From 3469d0989c7b32018c3afd6282ae35ad05b1fba0 Mon Sep 17 00:00:00 2001 From: Caleb Johnson Date: Wed, 15 Nov 2017 12:38:54 +0000 Subject: [PATCH] MINIFICPP-114 Consolidate JSON API use to RapidJSON Closes #191 --- CMakeLists.txt | 17 +- LICENSE | 36 + LibExample/CMakeLists.txt | 6 +- cmake/BuildTests.cmake | 4 +- extensions/bustache/CMakeLists.txt | 2 +- extensions/expression-language/CMakeLists.txt | 5 +- .../expression-language/noop/CMakeLists.txt | 4 +- extensions/gps/CMakeLists.txt | 5 +- extensions/http-curl/CMakeLists.txt | 4 +- extensions/http-curl/client/HTTPClient.cpp | 6 +- extensions/http-curl/client/HTTPClient.h | 2 + .../http-curl/protocols/RESTReceiver.cpp | 32 +- extensions/http-curl/protocols/RESTReceiver.h | 2 - extensions/http-curl/protocols/RESTSender.cpp | 36 +- extensions/http-curl/protocols/RESTSender.h | 2 - extensions/http-curl/sitetosite/PeersEntity.h | 113 +- extensions/http-curl/tests/HTTPHandlers.h | 1 - extensions/libarchive/ArchiveMetadata.cpp | 210 ++ extensions/libarchive/ArchiveMetadata.h | 97 + extensions/libarchive/CMakeLists.txt | 5 +- extensions/libarchive/FocusArchiveEntry.cpp | 78 +- extensions/libarchive/FocusArchiveEntry.h | 23 +- extensions/libarchive/ManipulateArchive.cpp | 38 +- extensions/libarchive/ManipulateArchive.h | 2 +- extensions/libarchive/UnfocusArchiveEntry.cpp | 100 +- extensions/libarchive/UnfocusArchiveEntry.h | 4 +- extensions/librdkafka/CMakeLists.txt | 5 +- extensions/mqtt/CMakeLists.txt | 3 +- extensions/pcap/CMakeLists.txt | 5 +- extensions/rocksdb-repos/CMakeLists.txt | 3 +- extensions/script/CMakeLists.txt | 5 +- extensions/tensorflow/CMakeLists.txt | 5 +- extensions/usb-camera/CMakeLists.txt | 5 +- libminifi/CMakeLists.txt | 6 +- libminifi/include/c2/protocols/RESTProtocol.h | 14 +- libminifi/include/utils/ByteArrayCallback.h | 2 - libminifi/include/utils/HTTPClient.h | 4 +- libminifi/src/RemoteProcessorGroupPort.cpp | 33 +- libminifi/src/c2/protocols/RESTProtocol.cpp | 174 +- .../SiteToSiteProvenanceReportingTask.cpp | 105 +- libminifi/test/unit/ProcessorTests.cpp | 2 +- main/CMakeLists.txt | 8 +- thirdparty/jsoncpp/AUTHORS | 1 - thirdparty/jsoncpp/CMakeLists.txt | 156 - thirdparty/jsoncpp/LICENSE | 55 - thirdparty/jsoncpp/NEWS.txt | 175 -- thirdparty/jsoncpp/README.md | 225 -- thirdparty/jsoncpp/SConstruct | 248 -- thirdparty/jsoncpp/amalgamate.py | 155 - thirdparty/jsoncpp/appveyor.yml | 35 - thirdparty/jsoncpp/dev.makefile | 35 - thirdparty/jsoncpp/doc/footer.html | 3 - thirdparty/jsoncpp/doc/header.html | 24 - thirdparty/jsoncpp/doc/jsoncpp.dox | 164 -- thirdparty/jsoncpp/doc/readme.txt | 1 - thirdparty/jsoncpp/doc/roadmap.dox | 3 - thirdparty/jsoncpp/doxybuild.py | 189 -- thirdparty/jsoncpp/include/CMakeLists.txt | 2 - thirdparty/jsoncpp/include/json/allocator.h | 98 - thirdparty/jsoncpp/include/json/assertions.h | 54 - thirdparty/jsoncpp/include/json/autolink.h | 25 - thirdparty/jsoncpp/include/json/config.h | 184 -- thirdparty/jsoncpp/include/json/features.h | 61 - thirdparty/jsoncpp/include/json/forwards.h | 37 - thirdparty/jsoncpp/include/json/json.h | 15 - thirdparty/jsoncpp/include/json/reader.h | 408 --- thirdparty/jsoncpp/include/json/value.h | 870 ------ thirdparty/jsoncpp/include/json/version.h | 20 - thirdparty/jsoncpp/include/json/writer.h | 335 --- .../jsoncpp/makefiles/msvc2010/jsoncpp.sln | 42 - .../makefiles/msvc2010/jsontest.vcxproj | 96 - .../msvc2010/jsontest.vcxproj.filters | 13 - .../makefiles/msvc2010/lib_json.vcxproj | 143 - .../msvc2010/lib_json.vcxproj.filters | 33 - .../makefiles/msvc2010/test_lib_json.vcxproj | 109 - .../msvc2010/test_lib_json.vcxproj.filters | 24 - thirdparty/jsoncpp/makefiles/vs71/jsoncpp.sln | 46 - .../jsoncpp/makefiles/vs71/jsontest.vcproj | 119 - .../jsoncpp/makefiles/vs71/lib_json.vcproj | 205 -- .../makefiles/vs71/test_lib_json.vcproj | 130 - thirdparty/jsoncpp/makerelease.py | 390 --- thirdparty/jsoncpp/pkg-config/jsoncpp.pc.in | 9 - thirdparty/jsoncpp/scons-tools/globtool.py | 58 - thirdparty/jsoncpp/scons-tools/srcdist.py | 183 -- thirdparty/jsoncpp/scons-tools/substinfile.py | 85 - thirdparty/jsoncpp/scons-tools/targz.py | 87 - thirdparty/jsoncpp/src/CMakeLists.txt | 5 - .../jsoncpp/src/jsontestrunner/CMakeLists.txt | 25 - .../jsoncpp/src/jsontestrunner/main.cpp | 326 --- .../jsoncpp/src/jsontestrunner/sconscript | 9 - .../jsoncpp/src/lib_json/CMakeLists.txt | 113 - .../jsoncpp/src/lib_json/json_reader.cpp | 2036 ------------- thirdparty/jsoncpp/src/lib_json/json_tool.h | 117 - .../jsoncpp/src/lib_json/json_value.cpp | 1617 ---------- .../src/lib_json/json_valueiterator.inl | 167 -- .../jsoncpp/src/lib_json/json_writer.cpp | 1224 -------- thirdparty/jsoncpp/src/lib_json/sconscript | 8 - thirdparty/jsoncpp/src/lib_json/version.h.in | 20 - .../jsoncpp/src/test_lib_json/CMakeLists.txt | 38 - .../jsoncpp/src/test_lib_json/jsontest.cpp | 457 --- .../jsoncpp/src/test_lib_json/jsontest.h | 286 -- thirdparty/jsoncpp/src/test_lib_json/main.cpp | 2589 ----------------- .../jsoncpp/src/test_lib_json/sconscript | 10 - thirdparty/jsoncpp/version | 1 - thirdparty/jsoncpp/version.in | 1 - thirdparty/rapidjson-1.1.0/.gitattributes | 22 + thirdparty/rapidjson-1.1.0/.gitignore | 25 + thirdparty/rapidjson-1.1.0/.gitmodules | 3 + thirdparty/rapidjson-1.1.0/.travis.yml | 98 + thirdparty/rapidjson-1.1.0/CHANGELOG.md | 158 + thirdparty/rapidjson-1.1.0/CMakeLists.txt | 173 ++ .../CMakeModules/FindGTestSrc.cmake | 30 + thirdparty/rapidjson-1.1.0/RapidJSON.pc.in | 7 + .../rapidjson-1.1.0/RapidJSONConfig.cmake.in | 3 + .../RapidJSONConfigVersion.cmake.in | 10 + thirdparty/rapidjson-1.1.0/appveyor.yml | 41 + thirdparty/rapidjson-1.1.0/doc/CMakeLists.txt | 25 + .../doc/Doxyfile.in} | 282 +- .../doc/Doxyfile.zh-cn.in} | 288 +- .../doc/diagram/architecture.dot | 50 + .../doc/diagram/architecture.png | Bin 0 -> 16569 bytes .../doc/diagram/insituparsing.dot | 65 + .../doc/diagram/insituparsing.png | Bin 0 -> 37281 bytes .../iterative-parser-states-diagram.dot | 62 + .../iterative-parser-states-diagram.png | Bin 0 -> 92378 bytes .../rapidjson-1.1.0/doc/diagram/makefile | 8 + .../rapidjson-1.1.0/doc/diagram/move1.dot | 47 + .../rapidjson-1.1.0/doc/diagram/move1.png | Bin 0 -> 16081 bytes .../rapidjson-1.1.0/doc/diagram/move2.dot | 62 + .../rapidjson-1.1.0/doc/diagram/move2.png | Bin 0 -> 41517 bytes .../rapidjson-1.1.0/doc/diagram/move3.dot | 60 + .../rapidjson-1.1.0/doc/diagram/move3.png | Bin 0 -> 36371 bytes .../doc/diagram/normalparsing.dot | 56 + .../doc/diagram/normalparsing.png | Bin 0 -> 32887 bytes .../rapidjson-1.1.0/doc/diagram/simpledom.dot | 54 + .../rapidjson-1.1.0/doc/diagram/simpledom.png | Bin 0 -> 43670 bytes .../rapidjson-1.1.0/doc/diagram/tutorial.dot | 58 + .../rapidjson-1.1.0/doc/diagram/tutorial.png | Bin 0 -> 44634 bytes .../doc/diagram/utilityclass.dot | 73 + .../doc/diagram/utilityclass.png | Bin 0 -> 99993 bytes thirdparty/rapidjson-1.1.0/doc/dom.md | 280 ++ thirdparty/rapidjson-1.1.0/doc/dom.zh-cn.md | 284 ++ thirdparty/rapidjson-1.1.0/doc/encoding.md | 146 + .../rapidjson-1.1.0/doc/encoding.zh-cn.md | 152 + thirdparty/rapidjson-1.1.0/doc/faq.md | 289 ++ thirdparty/rapidjson-1.1.0/doc/faq.zh-cn.md | 290 ++ thirdparty/rapidjson-1.1.0/doc/features.md | 104 + .../rapidjson-1.1.0/doc/features.zh-cn.md | 103 + thirdparty/rapidjson-1.1.0/doc/internals.md | 365 +++ .../rapidjson-1.1.0/doc/logo/rapidjson.png | Bin 0 -> 5259 bytes .../rapidjson-1.1.0/doc/logo/rapidjson.svg | 119 + .../doc/misc/DoxygenLayout.xml | 194 ++ .../rapidjson-1.1.0/doc/misc/doxygenextra.css | 274 ++ .../rapidjson-1.1.0/doc/misc/footer.html | 11 + .../rapidjson-1.1.0/doc/misc/header.html | 24 + thirdparty/rapidjson-1.1.0/doc/npm.md | 31 + thirdparty/rapidjson-1.1.0/doc/performance.md | 26 + .../rapidjson-1.1.0/doc/performance.zh-cn.md | 26 + thirdparty/rapidjson-1.1.0/doc/pointer.md | 234 ++ .../rapidjson-1.1.0/doc/pointer.zh-cn.md | 234 ++ thirdparty/rapidjson-1.1.0/doc/sax.md | 486 ++++ thirdparty/rapidjson-1.1.0/doc/sax.zh-cn.md | 487 ++++ thirdparty/rapidjson-1.1.0/doc/schema.md | 237 ++ .../rapidjson-1.1.0/doc/schema.zh-cn.md | 237 ++ thirdparty/rapidjson-1.1.0/doc/stream.md | 426 +++ .../rapidjson-1.1.0/doc/stream.zh-cn.md | 426 +++ thirdparty/rapidjson-1.1.0/doc/tutorial.md | 536 ++++ .../rapidjson-1.1.0/doc/tutorial.zh-cn.md | 534 ++++ .../rapidjson-1.1.0/docker/debian/Dockerfile | 8 + .../rapidjson-1.1.0/example/CMakeLists.txt | 42 + .../example/capitalize/capitalize.cpp | 67 + .../example/condense/condense.cpp | 32 + .../example/filterkey/filterkey.cpp | 135 + .../example/filterkeydom/filterkeydom.cpp | 170 ++ .../rapidjson-1.1.0/example/jsonx/jsonx.cpp | 207 ++ .../example/messagereader/messagereader.cpp | 105 + .../example/parsebyparts/parsebyparts.cpp | 173 ++ .../rapidjson-1.1.0/example/pretty/pretty.cpp | 30 + .../example/prettyauto/prettyauto.cpp | 56 + .../schemavalidator/schemavalidator.cpp | 72 + .../example/serialize/serialize.cpp | 173 ++ .../example/simpledom/simpledom.cpp | 29 + .../example/simplereader/simplereader.cpp | 42 + .../example/simplewriter/simplewriter.cpp | 36 + .../example/tutorial/tutorial.cpp | 151 + .../include/rapidjson/allocators.h | 271 ++ .../include/rapidjson/document.h | 2575 ++++++++++++++++ .../include/rapidjson/encodedstream.h | 299 ++ .../include/rapidjson/encodings.h | 716 +++++ .../include/rapidjson/error/en.h | 74 + .../include/rapidjson/error/error.h | 155 + .../include/rapidjson/filereadstream.h | 99 + .../include/rapidjson/filewritestream.h | 104 + .../rapidjson-1.1.0/include/rapidjson/fwd.h | 151 + .../include/rapidjson/internal/biginteger.h | 290 ++ .../include/rapidjson/internal/diyfp.h | 258 ++ .../include/rapidjson/internal/dtoa.h | 245 ++ .../include/rapidjson/internal/ieee754.h | 78 + .../include/rapidjson/internal/itoa.h | 304 ++ .../include/rapidjson/internal/meta.h | 181 ++ .../include/rapidjson/internal/pow10.h | 55 + .../include/rapidjson/internal/regex.h | 701 +++++ .../include/rapidjson/internal/stack.h | 230 ++ .../include/rapidjson/internal/strfunc.h | 55 + .../include/rapidjson/internal/strtod.h | 269 ++ .../include/rapidjson/internal/swap.h | 46 + .../include/rapidjson/istreamwrapper.h | 115 + .../include/rapidjson/memorybuffer.h | 70 + .../include/rapidjson/memorystream.h | 71 + .../include/rapidjson/msinttypes/inttypes.h | 316 ++ .../include/rapidjson/msinttypes/stdint.h | 300 ++ .../include/rapidjson/ostreamwrapper.h | 81 + .../include/rapidjson/pointer.h | 1358 +++++++++ .../include/rapidjson/prettywriter.h | 255 ++ .../include/rapidjson/rapidjson.h | 615 ++++ .../include/rapidjson/reader.h | 1879 ++++++++++++ .../include/rapidjson/schema.h | 2006 +++++++++++++ .../include/rapidjson/stream.h | 179 ++ .../include/rapidjson/stringbuffer.h | 117 + .../include/rapidjson/writer.h | 610 ++++ thirdparty/rapidjson-1.1.0/include_dirs.js | 2 + thirdparty/rapidjson-1.1.0/library.json | 12 + thirdparty/rapidjson-1.1.0/license.txt | 57 + thirdparty/rapidjson-1.1.0/package.json | 24 + thirdparty/rapidjson-1.1.0/rapidjson.autopkg | 75 + thirdparty/rapidjson-1.1.0/readme.md | 160 + thirdparty/rapidjson-1.1.0/readme.zh-cn.md | 152 + .../rapidjson-1.1.0/test/CMakeLists.txt | 20 + .../test/perftest/CMakeLists.txt | 26 + .../test/perftest/misctest.cpp | 974 +++++++ .../test/perftest/perftest.cpp | 24 + .../rapidjson-1.1.0/test/perftest/perftest.h | 182 ++ .../test/perftest/platformtest.cpp | 166 ++ .../test/perftest/rapidjsontest.cpp | 441 +++ .../test/perftest/schematest.cpp | 216 ++ .../test/unittest/CMakeLists.txt | 92 + .../test/unittest/allocatorstest.cpp | 102 + .../test/unittest/bigintegertest.cpp | 133 + .../test/unittest/documenttest.cpp | 652 +++++ .../test/unittest/dtoatest.cpp | 98 + .../test/unittest/encodedstreamtest.cpp | 313 ++ .../test/unittest/encodingstest.cpp | 451 +++ .../test/unittest/filestreamtest.cpp | 112 + .../rapidjson-1.1.0/test/unittest/fwdtest.cpp | 227 ++ .../test/unittest/istreamwrappertest.cpp | 181 ++ .../test/unittest/itoatest.cpp | 160 + .../test/unittest/jsoncheckertest.cpp | 99 + .../test/unittest/namespacetest.cpp | 70 + .../test/unittest/ostreamwrappertest.cpp | 91 + .../test/unittest/pointertest.cpp | 1524 ++++++++++ .../test/unittest/prettywritertest.cpp | 203 ++ .../test/unittest/readertest.cpp | 1844 ++++++++++++ .../test/unittest/regextest.cpp | 592 ++++ .../test/unittest/schematest.cpp | 1313 +++++++++ .../test/unittest/simdtest.cpp | 215 ++ .../test/unittest/strfunctest.cpp | 30 + .../test/unittest/stringbuffertest.cpp | 170 ++ .../test/unittest/strtodtest.cpp | 132 + .../test/unittest/unittest.cpp | 51 + .../rapidjson-1.1.0/test/unittest/unittest.h | 135 + .../test/unittest/valuetest.cpp | 1792 ++++++++++++ .../test/unittest/writertest.cpp | 497 ++++ thirdparty/rapidjson-1.1.0/travis-doxygen.sh | 122 + 263 files changed, 39447 insertions(+), 15068 deletions(-) create mode 100644 extensions/libarchive/ArchiveMetadata.cpp create mode 100644 extensions/libarchive/ArchiveMetadata.h delete mode 100644 thirdparty/jsoncpp/AUTHORS delete mode 100644 thirdparty/jsoncpp/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/LICENSE delete mode 100644 thirdparty/jsoncpp/NEWS.txt delete mode 100644 thirdparty/jsoncpp/README.md delete mode 100644 thirdparty/jsoncpp/SConstruct delete mode 100644 thirdparty/jsoncpp/amalgamate.py delete mode 100644 thirdparty/jsoncpp/appveyor.yml delete mode 100644 thirdparty/jsoncpp/dev.makefile delete mode 100644 thirdparty/jsoncpp/doc/footer.html delete mode 100644 thirdparty/jsoncpp/doc/header.html delete mode 100644 thirdparty/jsoncpp/doc/jsoncpp.dox delete mode 100644 thirdparty/jsoncpp/doc/readme.txt delete mode 100644 thirdparty/jsoncpp/doc/roadmap.dox delete mode 100644 thirdparty/jsoncpp/doxybuild.py delete mode 100644 thirdparty/jsoncpp/include/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/include/json/allocator.h delete mode 100644 thirdparty/jsoncpp/include/json/assertions.h delete mode 100644 thirdparty/jsoncpp/include/json/autolink.h delete mode 100644 thirdparty/jsoncpp/include/json/config.h delete mode 100644 thirdparty/jsoncpp/include/json/features.h delete mode 100644 thirdparty/jsoncpp/include/json/forwards.h delete mode 100644 thirdparty/jsoncpp/include/json/json.h delete mode 100644 thirdparty/jsoncpp/include/json/reader.h delete mode 100644 thirdparty/jsoncpp/include/json/value.h delete mode 100644 thirdparty/jsoncpp/include/json/version.h delete mode 100644 thirdparty/jsoncpp/include/json/writer.h delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/jsoncpp.sln delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj.filters delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj.filters delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj delete mode 100644 thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj.filters delete mode 100644 thirdparty/jsoncpp/makefiles/vs71/jsoncpp.sln delete mode 100644 thirdparty/jsoncpp/makefiles/vs71/jsontest.vcproj delete mode 100644 thirdparty/jsoncpp/makefiles/vs71/lib_json.vcproj delete mode 100644 thirdparty/jsoncpp/makefiles/vs71/test_lib_json.vcproj delete mode 100644 thirdparty/jsoncpp/makerelease.py delete mode 100644 thirdparty/jsoncpp/pkg-config/jsoncpp.pc.in delete mode 100644 thirdparty/jsoncpp/scons-tools/globtool.py delete mode 100644 thirdparty/jsoncpp/scons-tools/srcdist.py delete mode 100644 thirdparty/jsoncpp/scons-tools/substinfile.py delete mode 100644 thirdparty/jsoncpp/scons-tools/targz.py delete mode 100644 thirdparty/jsoncpp/src/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/src/jsontestrunner/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/src/jsontestrunner/main.cpp delete mode 100644 thirdparty/jsoncpp/src/jsontestrunner/sconscript delete mode 100644 thirdparty/jsoncpp/src/lib_json/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/src/lib_json/json_reader.cpp delete mode 100644 thirdparty/jsoncpp/src/lib_json/json_tool.h delete mode 100644 thirdparty/jsoncpp/src/lib_json/json_value.cpp delete mode 100644 thirdparty/jsoncpp/src/lib_json/json_valueiterator.inl delete mode 100644 thirdparty/jsoncpp/src/lib_json/json_writer.cpp delete mode 100644 thirdparty/jsoncpp/src/lib_json/sconscript delete mode 100644 thirdparty/jsoncpp/src/lib_json/version.h.in delete mode 100644 thirdparty/jsoncpp/src/test_lib_json/CMakeLists.txt delete mode 100644 thirdparty/jsoncpp/src/test_lib_json/jsontest.cpp delete mode 100644 thirdparty/jsoncpp/src/test_lib_json/jsontest.h delete mode 100644 thirdparty/jsoncpp/src/test_lib_json/main.cpp delete mode 100644 thirdparty/jsoncpp/src/test_lib_json/sconscript delete mode 100644 thirdparty/jsoncpp/version delete mode 100644 thirdparty/jsoncpp/version.in create mode 100644 thirdparty/rapidjson-1.1.0/.gitattributes create mode 100644 thirdparty/rapidjson-1.1.0/.gitignore create mode 100644 thirdparty/rapidjson-1.1.0/.gitmodules create mode 100644 thirdparty/rapidjson-1.1.0/.travis.yml create mode 100644 thirdparty/rapidjson-1.1.0/CHANGELOG.md create mode 100644 thirdparty/rapidjson-1.1.0/CMakeLists.txt create mode 100644 thirdparty/rapidjson-1.1.0/CMakeModules/FindGTestSrc.cmake create mode 100644 thirdparty/rapidjson-1.1.0/RapidJSON.pc.in create mode 100644 thirdparty/rapidjson-1.1.0/RapidJSONConfig.cmake.in create mode 100644 thirdparty/rapidjson-1.1.0/RapidJSONConfigVersion.cmake.in create mode 100644 thirdparty/rapidjson-1.1.0/appveyor.yml create mode 100644 thirdparty/rapidjson-1.1.0/doc/CMakeLists.txt rename thirdparty/{jsoncpp/doc/web_doxyfile.in => rapidjson-1.1.0/doc/Doxyfile.in} (92%) rename thirdparty/{jsoncpp/doc/doxyfile.in => rapidjson-1.1.0/doc/Doxyfile.zh-cn.in} (92%) create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/architecture.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/architecture.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/insituparsing.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/insituparsing.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/makefile create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move1.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move1.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move2.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move2.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move3.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/move3.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.dot create mode 100644 thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/dom.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/dom.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/encoding.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/encoding.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/faq.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/faq.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/features.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/features.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/internals.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/logo/rapidjson.png create mode 100644 thirdparty/rapidjson-1.1.0/doc/logo/rapidjson.svg create mode 100644 thirdparty/rapidjson-1.1.0/doc/misc/DoxygenLayout.xml create mode 100644 thirdparty/rapidjson-1.1.0/doc/misc/doxygenextra.css create mode 100644 thirdparty/rapidjson-1.1.0/doc/misc/footer.html create mode 100644 thirdparty/rapidjson-1.1.0/doc/misc/header.html create mode 100644 thirdparty/rapidjson-1.1.0/doc/npm.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/performance.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/performance.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/pointer.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/pointer.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/sax.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/sax.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/schema.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/schema.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/stream.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/stream.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/tutorial.md create mode 100644 thirdparty/rapidjson-1.1.0/doc/tutorial.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/docker/debian/Dockerfile create mode 100644 thirdparty/rapidjson-1.1.0/example/CMakeLists.txt create mode 100644 thirdparty/rapidjson-1.1.0/example/capitalize/capitalize.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/condense/condense.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/filterkey/filterkey.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/filterkeydom/filterkeydom.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/jsonx/jsonx.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/messagereader/messagereader.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/parsebyparts/parsebyparts.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/pretty/pretty.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/prettyauto/prettyauto.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/schemavalidator/schemavalidator.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/serialize/serialize.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/simpledom/simpledom.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/simplereader/simplereader.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/simplewriter/simplewriter.cpp create mode 100644 thirdparty/rapidjson-1.1.0/example/tutorial/tutorial.cpp create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/allocators.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/document.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/encodedstream.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/encodings.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/error/en.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/error/error.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/filereadstream.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/filewritestream.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/fwd.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/biginteger.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/diyfp.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/dtoa.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/ieee754.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/itoa.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/meta.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/pow10.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/regex.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/stack.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strfunc.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strtod.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/internal/swap.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/istreamwrapper.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/memorybuffer.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/memorystream.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/inttypes.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/stdint.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/ostreamwrapper.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/pointer.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/prettywriter.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/rapidjson.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/reader.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/schema.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/stream.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/stringbuffer.h create mode 100644 thirdparty/rapidjson-1.1.0/include/rapidjson/writer.h create mode 100644 thirdparty/rapidjson-1.1.0/include_dirs.js create mode 100644 thirdparty/rapidjson-1.1.0/library.json create mode 100644 thirdparty/rapidjson-1.1.0/license.txt create mode 100644 thirdparty/rapidjson-1.1.0/package.json create mode 100644 thirdparty/rapidjson-1.1.0/rapidjson.autopkg create mode 100644 thirdparty/rapidjson-1.1.0/readme.md create mode 100644 thirdparty/rapidjson-1.1.0/readme.zh-cn.md create mode 100644 thirdparty/rapidjson-1.1.0/test/CMakeLists.txt create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/CMakeLists.txt create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/misctest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/perftest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/perftest.h create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/platformtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/rapidjsontest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/perftest/schematest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/CMakeLists.txt create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/allocatorstest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/bigintegertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/documenttest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/dtoatest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/encodedstreamtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/encodingstest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/filestreamtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/fwdtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/istreamwrappertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/itoatest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/jsoncheckertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/namespacetest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/ostreamwrappertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/pointertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/prettywritertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/readertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/regextest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/schematest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/simdtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/strfunctest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/stringbuffertest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/strtodtest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/unittest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/unittest.h create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/valuetest.cpp create mode 100644 thirdparty/rapidjson-1.1.0/test/unittest/writertest.cpp create mode 100755 thirdparty/rapidjson-1.1.0/travis-doxygen.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 81fe21d244..ad6036f159 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,22 +95,6 @@ file(GLOB SPD_SOURCES "thirdparty/spdlog-20170710/include/spdlog/*") include(ExternalProject) -# Setup Jsoncpp as an external project -set(JSONCPP_LIB_DIR "${CMAKE_CURRENT_BINARY_DIR}/jsoncpp") - -externalproject_add(jsoncpp_project - SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/jsoncpp - CMAKE_ARGS - "-G${CMAKE_GENERATOR}" - "-DCMAKE_INSTALL_LIBDIR=${JSONCPP_LIB_DIR}/lib" - "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}" - "-DCMAKE_INSTALL_PREFIX=${JSONCPP_LIB_DIR}" - ) - -set(prefix "lib") -set(suffix ".a") -set(JSONCPP_LIB "${JSONCPP_LIB_DIR}/lib/${prefix}jsoncpp${suffix}") - set(CIVETWEB_ENABLE_SSL_DYNAMIC_LOADING OFF CACHE BOOL "Disable dynamic SSL library loading") set(CIVETWEB_ENABLE_CXX ON CACHE BOOL "Enable civet C++ library") SET(WITH_TOOLS OFF CACHE BOOL "Do not build RocksDB tools") @@ -122,6 +106,7 @@ add_subdirectory(thirdparty/yaml-cpp-yaml-cpp-20171024) include_directories(thirdparty/concurrentqueue) include_directories(thirdparty/yaml-cpp-yaml-cpp-20171024/include) +include_directories(thirdparty/rapidjson-1.1.0/include) ## Expression language extensions option(DISABLE_EXPRESSION_LANGUAGE "Disables the scripting extensions." OFF) diff --git a/LICENSE b/LICENSE index 8cde4ea730..cedd336ea2 100644 --- a/LICENSE +++ b/LICENSE @@ -1075,3 +1075,39 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +This product bundles RapidJSON: +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LibExample/CMakeLists.txt b/LibExample/CMakeLists.txt index 4ba26bde03..ddf1e2004f 100644 --- a/LibExample/CMakeLists.txt +++ b/LibExample/CMakeLists.txt @@ -23,7 +23,7 @@ IF(POLICY CMP0048) CMAKE_POLICY(SET CMP0048 OLD) ENDIF(POLICY CMP0048) -include_directories(../libminifi/include ../libminifi/include/c2 ../libminifi/include/c2/protocols/ ../libminifi/include/core/state ./libminifi/include/core/statemanagement/metrics ../libminifi/include/core/yaml ../libminifi/include/core ../thirdparty/spdlog-20170710/include ../thirdparty/concurrentqueue ../thirdparty/yaml-cpp-yaml-cpp-20171024/include ../thirdparty/civetweb-1.9.1/include ../thirdparty/jsoncpp/include ../thirdparty/) +include_directories(../libminifi/include ../libminifi/include/c2 ../libminifi/include/c2/protocols/ ../libminifi/include/core/state ./libminifi/include/core/statemanagement/metrics ../libminifi/include/core/yaml ../libminifi/include/core ../thirdparty/spdlog-20170710/include ../thirdparty/concurrentqueue ../thirdparty/yaml-cpp-yaml-cpp-20171024/include ../thirdparty/civetweb-1.9.1/include ../thirdparty/) include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) @@ -38,7 +38,7 @@ endif() add_executable(transmit_flow transmit_flow.c) -# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl, jsoncpp and rocksdb +# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl and rocksdb target_link_libraries(transmit_flow capi core-minifi minifi) if (APPLE) @@ -50,7 +50,7 @@ endif () add_executable(generate_flow generate_flow.c) -# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl, jsoncpp and rocksdb +# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl and rocksdb target_link_libraries(generate_flow capi core-minifi minifi) if (APPLE) diff --git a/cmake/BuildTests.cmake b/cmake/BuildTests.cmake index 42698981df..8bb83e701f 100644 --- a/cmake/BuildTests.cmake +++ b/cmake/BuildTests.cmake @@ -38,8 +38,6 @@ function(createTests testName) target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/thirdparty/catch") target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/thirdparty/spdlog-20170710/include") target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/thirdparty/yaml-cpp-yaml-cpp-0.5.3/include") - target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/thirdparty/jsoncpp/include") - target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/thirdparty/libarchive-3.3.2/libarchive") target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/include") target_include_directories(${testName} BEFORE PRIVATE "${CMAKE_SOURCE_DIR}/libminifi/include/") @@ -59,7 +57,7 @@ function(createTests testName) target_include_directories(${testName} BEFORE PRIVATE "${Boost_INCLUDE_DIRS}") endif() target_link_libraries(${testName} ${SPD_LIB} ${TEST_BASE_LIB}) - target_link_libraries(${testName} ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} core-minifi yaml-cpp ${JSON_CPP_LIB}) + target_link_libraries(${testName} ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} core-minifi yaml-cpp) if (APPLE) target_link_libraries (${testName} -Wl,-all_load minifi) else () diff --git a/extensions/bustache/CMakeLists.txt b/extensions/bustache/CMakeLists.txt index abdfb4d86f..b8cb0ce18b 100644 --- a/extensions/bustache/CMakeLists.txt +++ b/extensions/bustache/CMakeLists.txt @@ -22,7 +22,7 @@ cmake_minimum_required(VERSION 2.6) set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/civetweb-1.9.1/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/civetweb-1.9.1/include ../../thirdparty/) find_package(Boost COMPONENTS system filesystem iostreams REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) diff --git a/extensions/expression-language/CMakeLists.txt b/extensions/expression-language/CMakeLists.txt index 4053e8737f..53c87e6d8a 100644 --- a/extensions/expression-language/CMakeLists.txt +++ b/extensions/expression-language/CMakeLists.txt @@ -38,7 +38,7 @@ flex_target( add_flex_bison_dependency(el-scanner el-parser) -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(impl) file(GLOB SOURCES "*.cpp") @@ -53,8 +53,7 @@ if(CMAKE_THREAD_LIBS_INIT) endif() find_package(UUID REQUIRED) -target_link_libraries(minifi-expression-language-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-expression-language-extensions jsoncpp_project) +target_link_libraries(minifi-expression-language-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-expression-language-extensions ${CMAKE_DL_LIBS}) diff --git a/extensions/expression-language/noop/CMakeLists.txt b/extensions/expression-language/noop/CMakeLists.txt index 9df9f9706f..abf5e64fa9 100644 --- a/extensions/expression-language/noop/CMakeLists.txt +++ b/extensions/expression-language/noop/CMakeLists.txt @@ -19,5 +19,5 @@ message(STATUS "Expression language is disabled; using NoOp implementation") file(GLOB SOURCES "*.cpp") -include_directories(../../../libminifi/include ../../../libminifi/include/core ../../../thirdparty/spdlog-20170710/include ../../../thirdparty/concurrentqueue ../../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../../thirdparty/jsoncpp/include ../../../thirdparty/) -add_library(minifi-expression-language-extensions STATIC ${SOURCES}) \ No newline at end of file +include_directories(../../../libminifi/include ../../../libminifi/include/core ../../../thirdparty/spdlog-20170710/include ../../../thirdparty/concurrentqueue ../../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../../thirdparty/) +add_library(minifi-expression-language-extensions STATIC ${SOURCES}) diff --git a/extensions/gps/CMakeLists.txt b/extensions/gps/CMakeLists.txt index 0329dd3ed3..6b28d05511 100644 --- a/extensions/gps/CMakeLists.txt +++ b/extensions/gps/CMakeLists.txt @@ -23,7 +23,7 @@ cmake_minimum_required(VERSION 2.6) set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core/yaml ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core/yaml ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) find_package(LibGPS REQUIRED) @@ -43,8 +43,7 @@ endif() # Include UUID find_package(UUID REQUIRED) -target_link_libraries(minifi-gps ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB} ${LIBGPS_LIBRARIES}) -add_dependencies(minifi-gps jsoncpp_project) +target_link_libraries(minifi-gps ${LIBMINIFI} ${UUID_LIBRARIES} ${LIBGPS_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-gps ${CMAKE_DL_LIBS} ) diff --git a/extensions/http-curl/CMakeLists.txt b/extensions/http-curl/CMakeLists.txt index dfa4259ad1..d5e966a6a7 100644 --- a/extensions/http-curl/CMakeLists.txt +++ b/extensions/http-curl/CMakeLists.txt @@ -22,7 +22,7 @@ find_package(CURL REQUIRED) set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core/yaml ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT} ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core/yaml ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(protocols client processors sitetosite) file(GLOB SOURCES "*.cpp" "protocols/*.cpp" "client/*.cpp" "processors/*.cpp" "sitetosite/*.cpp") @@ -69,4 +69,4 @@ else () endif () SET (HTTP-CURL minifi-http-curl PARENT_SCOPE) -register_extension(minifi-http-curl) \ No newline at end of file +register_extension(minifi-http-curl) diff --git a/extensions/http-curl/client/HTTPClient.cpp b/extensions/http-curl/client/HTTPClient.cpp index a8643d549e..5ea9e95027 100644 --- a/extensions/http-curl/client/HTTPClient.cpp +++ b/extensions/http-curl/client/HTTPClient.cpp @@ -136,7 +136,7 @@ void HTTPClient::setDisablePeerVerification() { curl_easy_setopt(http_session_, CURLOPT_SSL_VERIFYPEER, 0L); } -void HTTPClient::setDisableHostVerification(){ +void HTTPClient::setDisableHostVerification() { logger_->log_debug("Disabling host verification"); curl_easy_setopt(http_session_, CURLOPT_SSL_VERIFYHOST, 0L); } @@ -192,6 +192,10 @@ void HTTPClient::setPostFields(std::string input) { curl_easy_setopt(http_session_, CURLOPT_POSTFIELDS, input.c_str()); } +void HTTPClient::setPostSize(size_t size) { + curl_easy_setopt(http_session_, CURLOPT_POSTFIELDSIZE, size); +} + void HTTPClient::setHeaders(struct curl_slist *list) { headers_ = list; } diff --git a/extensions/http-curl/client/HTTPClient.h b/extensions/http-curl/client/HTTPClient.h index 8f61ad355b..e5545c3cda 100644 --- a/extensions/http-curl/client/HTTPClient.h +++ b/extensions/http-curl/client/HTTPClient.h @@ -166,6 +166,8 @@ class HTTPClient : public BaseHTTPClient, public core::Connectable { return true; } + void setPostSize(size_t size); + protected: inline bool matches(const std::string &value, const std::string &sregex) override; diff --git a/extensions/http-curl/protocols/RESTReceiver.cpp b/extensions/http-curl/protocols/RESTReceiver.cpp index ac9d229903..fe4092ca85 100644 --- a/extensions/http-curl/protocols/RESTReceiver.cpp +++ b/extensions/http-curl/protocols/RESTReceiver.cpp @@ -64,38 +64,8 @@ void RESTReceiver::initialize(const std::shared_ptr 0) { - json_payload["operationid"] = payload.getIdentifier(); - } - const std::vector &content = payload.getContent(); - - for (const auto &payload_content : content) { - Json::Value payload_content_values; - bool use_sub_option = true; - if (payload_content.op == payload.getOperation()) { - for (auto content : payload_content.operation_arguments) { - if (payload_content.operation_arguments.size() == 1 && payload_content.name == content.first) { - json_payload[payload_content.name] = content.second; - use_sub_option = false; - } else { - payload_content_values[content.first] = content.second; - } - } - } - if (use_sub_option) - json_payload[payload_content.name] = payload_content_values; - } - - for (const auto &nested_payload : payload.getNestedPayloads()) { - json_payload[nested_payload.getLabel()] = serializeJsonPayload(json_payload, nested_payload); - } + std::string outputConfig = serializeJsonRootPayload(payload); - Json::StyledWriter writer; - outputConfig = writer.write(json_payload); if (handler != nullptr) { logger_->log_debug("Setting %s", outputConfig); handler->setResponse(outputConfig); diff --git a/extensions/http-curl/protocols/RESTReceiver.h b/extensions/http-curl/protocols/RESTReceiver.h index e19932c0a5..de97eae778 100644 --- a/extensions/http-curl/protocols/RESTReceiver.h +++ b/extensions/http-curl/protocols/RESTReceiver.h @@ -18,8 +18,6 @@ #ifndef LIBMINIFI_INCLUDE_C2_RESTRCVR_H_ #define LIBMINIFI_INCLUDE_C2_RESTRCVR_H_ -#include "json/json.h" -#include "json/writer.h" #include #include #include "core/Resource.h" diff --git a/extensions/http-curl/protocols/RESTSender.cpp b/extensions/http-curl/protocols/RESTSender.cpp index 5f8100572f..a98ba03cfb 100644 --- a/extensions/http-curl/protocols/RESTSender.cpp +++ b/extensions/http-curl/protocols/RESTSender.cpp @@ -45,40 +45,12 @@ void RESTSender::initialize(const std::shared_ptrlog_debug("Submitting to %s", rest_uri_); } + C2Payload RESTSender::consumePayload(const std::string &url, const C2Payload &payload, Direction direction, bool async) { - std::string operation_request_str = getOperation(payload); std::string outputConfig; - if (direction == Direction::TRANSMIT) { - Json::Value json_payload; - json_payload["operation"] = operation_request_str; - if (payload.getIdentifier().length() > 0) { - json_payload["operationid"] = payload.getIdentifier(); - } - const std::vector &content = payload.getContent(); - - for (const auto &payload_content : content) { - Json::Value payload_content_values; - bool use_sub_option = true; - if (payload_content.op == payload.getOperation()) { - for (auto content : payload_content.operation_arguments) { - if (payload_content.operation_arguments.size() == 1 && payload_content.name == content.first) { - json_payload[payload_content.name] = content.second; - use_sub_option = false; - } else { - payload_content_values[content.first] = content.second; - } - } - } - if (use_sub_option) - json_payload[payload_content.name] = payload_content_values; - } - - for (const auto &nested_payload : payload.getNestedPayloads()) { - json_payload[nested_payload.getLabel()] = serializeJsonPayload(json_payload, nested_payload); - } - Json::StyledWriter writer; - outputConfig = writer.write(json_payload); + if (direction == Direction::TRANSMIT) { + outputConfig = serializeJsonRootPayload(payload); } return sendPayload(url, direction, payload, outputConfig); @@ -111,11 +83,13 @@ const C2Payload RESTSender::sendPayload(const std::string url, const Direction d callback->pos = 0; client.set_request_method("POST"); client.setUploadCallback(callback.get()); + client.setPostSize(outputConfig.size()); } else { // we do not need to set the uplaod callback // since we are not uploading anything on a get client.set_request_method("GET"); } + client.appendHeader("Accept: application/json"); client.setContentType("application/json"); bool isOkay = client.submit(); int64_t respCode = client.getResponseCode(); diff --git a/extensions/http-curl/protocols/RESTSender.h b/extensions/http-curl/protocols/RESTSender.h index 450799c705..bc9102b8fd 100644 --- a/extensions/http-curl/protocols/RESTSender.h +++ b/extensions/http-curl/protocols/RESTSender.h @@ -18,8 +18,6 @@ #ifndef LIBMINIFI_INCLUDE_C2_RESTSENDER_H_ #define LIBMINIFI_INCLUDE_C2_RESTSENDER_H_ -#include "json/json.h" -#include "json/writer.h" #include #include diff --git a/extensions/http-curl/sitetosite/PeersEntity.h b/extensions/http-curl/sitetosite/PeersEntity.h index 54be488316..62cf20a976 100644 --- a/extensions/http-curl/sitetosite/PeersEntity.h +++ b/extensions/http-curl/sitetosite/PeersEntity.h @@ -18,9 +18,15 @@ #ifndef EXTENSIONS_HTTP_CURL_SITETOSITE_PEERSENTITY_H_ #define EXTENSIONS_HTTP_CURL_SITETOSITE_PEERSENTITY_H_ -#include "json/json.h" +#include +#include + +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" + #include "sitetosite/Peer.h" #include "utils/StringUtils.h" +#include "Exception.h" namespace org { namespace apache { @@ -35,63 +41,74 @@ class PeersEntity { public: static bool parse(const std::shared_ptr &logger, const std::string &entity, uuid_t id, std::vector &peer_statuses) { - - Json::Reader reader; - Json::Value root; try { - if (reader.parse(entity, root)) { - if (root.isMember("peers") && root["peers"].size() > 0) { - for (const auto &peer : root["peers"]) { + rapidjson::Document root; + rapidjson::ParseResult ok = root.Parse(entity.c_str()); - std::string hostname; - int port = 0, flowFileCount = 0; - bool secure = false; + if (!ok) { + std::stringstream ss; + ss << "Failed to parse archive lens stack from JSON string with reason: " + << rapidjson::GetParseError_En(ok.Code()) + << " at offset " << ok.Offset(); + std::string exception_msg = ss.str(); + + throw Exception(ExceptionType::GENERAL_EXCEPTION, exception_msg.c_str()); + } - if (peer.isMember("hostname") && peer.isMember("port")) { - hostname = peer["hostname"].asString(); - port = peer["port"].asInt(); - } - if (peer.isMember("secure")) { - // do not assume that secure parses incorrectly that we can continue without security - try { - secure = peer["secure"].asBool(); - } catch (...) { - logger->log_debug("Could not properly parse secure, so we're going to try it as a string"); - std::string secureStr = peer["secure"].asString(); - if (utils::StringUtils::equalsIgnoreCase(secureStr,"true")) - secure = true; - else if (utils::StringUtils::equalsIgnoreCase(secureStr,"false")) - secure = false; - else{ - logger->log_error("could not parse secure string %s",secureStr); - throw std::exception(); - } + if (root.HasMember("peers") && root["peers"].IsArray() && root["peers"].Size() > 0) { + for (const auto &peer : root["peers"].GetArray()) { + std::string hostname; + int port = 0, flowFileCount = 0; + bool secure = false; + if (peer.HasMember("hostname") && peer["hostname"].IsString() && + peer.HasMember("port") && peer["port"].IsNumber()) { + hostname = peer["hostname"].GetString(); + port = peer["port"].GetInt(); + } + + if (peer.HasMember("secure")) { + if (peer["secure"].IsBool()) { + secure = peer["secure"].GetBool(); + } else if (peer["secure"].IsString()) { + std::string secureStr = peer["secure"].GetString(); + + if (utils::StringUtils::equalsIgnoreCase(secureStr, "true")) { + secure = true; + } else if (utils::StringUtils::equalsIgnoreCase(secureStr, "false")) { + secure = false; + } else { + logger->log_error("could not parse secure string %s", secureStr); + throw std::exception(); } + } else { + logger->log_warn("Invalid value type for secure, assuming false (rapidjson type id %i)", + peer["secure"].GetType()); } - if (peer.isMember("flowFileCount")) { - // we can assume that if flowFileCount cannot parse as an integer that we CAN continue. - try { - flowFileCount = peer["flowFileCount"].asInt(); - } catch (...) { - logger->log_debug("Could not properly parse flowFileCount, so we're going to continue without it"); - } - } - // host name and port are required. - if (!IsNullOrEmpty(hostname) && port > 0) { - sitetosite::PeerStatus status(std::make_shared(id, hostname, port, secure), flowFileCount, true); - peer_statuses.push_back(std::move(status)); + } + + if (peer.HasMember("flowFileCount")) { + if (peer["flowFileCount"].IsNumber()) { + flowFileCount = peer["flowFileCount"].GetInt64(); } else { - logger->log_debug("hostname empty or port is zero. hostname: %s, port: %d", hostname, port); + logger->log_debug("Could not parse flowFileCount, so we're going to continue without it"); } } - } else { - logger->log_debug("Peers is either not a member or is empty. String to analyze: %s", entity); + + // host name and port are required. + if (!IsNullOrEmpty(hostname) && port > 0) { + sitetosite::PeerStatus status(std::make_shared(id, hostname, port, secure), flowFileCount, true); + peer_statuses.push_back(std::move(status)); + } else { + logger->log_debug("hostname empty or port is zero. hostname: %s, port: %d", hostname, port); + } } + } else { + logger->log_debug("Peers is either not a member or is empty. String to analyze: %s", entity); } return true; - } catch (Json::RuntimeError &er) { - logger->log_debug("JSON runtime error occurred. Message: %s", er.what()); + } catch (Exception &exception) { + logger->log_debug("Caught Exception %s", exception.what()); return false; } catch (...) { logger->log_debug("General exception occurred"); @@ -99,9 +116,7 @@ class PeersEntity { } } - -} -; +}; } /* namespace sitetosite */ } /* namespace minifi */ diff --git a/extensions/http-curl/tests/HTTPHandlers.h b/extensions/http-curl/tests/HTTPHandlers.h index 714090ad16..58bdd3a828 100644 --- a/extensions/http-curl/tests/HTTPHandlers.h +++ b/extensions/http-curl/tests/HTTPHandlers.h @@ -251,7 +251,6 @@ class FlowFileResponder : public CivetHandler { } auto ret = mg_write(conn, serializer.getBuffer(), total); } else { - std::cout << "Nothing to transfer feed" << std::endl; mg_printf(conn, "HTTP/1.1 200 OK\r\nConnection: " "close\r\nContent-Length: 0\r\n"); mg_printf(conn, "Content-Type: text/plain\r\n\r\n"); diff --git a/extensions/libarchive/ArchiveMetadata.cpp b/extensions/libarchive/ArchiveMetadata.cpp new file mode 100644 index 0000000000..0544b22b01 --- /dev/null +++ b/extensions/libarchive/ArchiveMetadata.cpp @@ -0,0 +1,210 @@ +/** + * @file ArchiveMetadata.cpp + * ArchiveMetadata class definition + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ArchiveMetadata.h" + +#include +#include + +#include +#include +#include +#include + +#include "utils/file/FileManager.h" +#include "Exception.h" + +using org::apache::nifi::minifi::Exception; +using org::apache::nifi::minifi::ExceptionType; + +rapidjson::Value ArchiveEntryMetadata::toJson(rapidjson::Document::AllocatorType &alloc) const { + rapidjson::Value entryVal(rapidjson::kObjectType); + + rapidjson::Value entryNameVal; + entryNameVal.SetString(entryName.c_str(), entryName.length()); + entryVal.AddMember("entry_name", entryNameVal, alloc); + + entryVal.AddMember("entry_type", entryType, alloc); + entryVal.AddMember("entry_perm", entryPerm, alloc); + entryVal.AddMember("entry_size", entrySize, alloc); + entryVal.AddMember("entry_uid", entryUID, alloc); + entryVal.AddMember("entry_gid", entryGID, alloc); + entryVal.AddMember("entry_mtime", entryMTime, alloc); + entryVal.AddMember("entry_mtime_nsec", entryMTimeNsec, alloc); + + if (entryType == AE_IFREG) { + rapidjson::Value stashKeyVal; + stashKeyVal.SetString(stashKey.c_str(), stashKey.length()); + entryVal.AddMember("stash_key", stashKeyVal, alloc); + } + + return entryVal; +} + +void ArchiveEntryMetadata::loadJson(const rapidjson::Value& entryVal) { + entryName.assign(entryVal["entry_name"].GetString()); + entryType = entryVal["entry_type"].GetUint64(); + entryPerm = entryVal["entry_perm"].GetUint64(); + entrySize = entryVal["entry_size"].GetUint64(); + entryUID = entryVal["entry_uid"].GetUint64(); + entryGID = entryVal["entry_gid"].GetUint64(); + entryMTime = entryVal["entry_mtime"].GetUint64(); + entryMTimeNsec = entryVal["entry_mtime_nsec"].GetInt64(); + + if (entryType == AE_IFREG) + stashKey.assign(entryVal["stash_key"].GetString()); +} + +ArchiveEntryMetadata ArchiveEntryMetadata::fromJson(const rapidjson::Value& entryVal) { + ArchiveEntryMetadata aem; + aem.loadJson(entryVal); + return aem; +} + +ArchiveEntryIterator ArchiveMetadata::find(const std::string& name) { + auto targetTest = [&](const ArchiveEntryMetadata& entry) -> bool { + return entry.entryName == name; + }; + + return std::find_if(entryMetadata.begin(), + entryMetadata.end(), + targetTest); +} + +ArchiveEntryIterator ArchiveMetadata::eraseEntry(ArchiveEntryIterator position) { + return entryMetadata.erase(position); +} + +ArchiveEntryIterator ArchiveMetadata::insertEntry( + ArchiveEntryIterator position, const ArchiveEntryMetadata& entry) { + return entryMetadata.insert(position, entry); +} + +rapidjson::Value ArchiveMetadata::toJson(rapidjson::Document::AllocatorType &alloc) const { + rapidjson::Value structVal(rapidjson::kArrayType); + + for (const auto &entry : entryMetadata) { + structVal.PushBack(entry.toJson(alloc), alloc); + } + + rapidjson::Value lensVal(rapidjson::kObjectType); + + rapidjson::Value archiveFormatNameVal; + archiveFormatNameVal.SetString(archiveFormatName.c_str(), archiveFormatName.length()); + lensVal.AddMember("archive_format_name", archiveFormatNameVal, alloc); + + lensVal.AddMember("archive_format", archiveFormat, alloc); + lensVal.AddMember("archive_structure", structVal, alloc); + + if (!archiveName.empty()) { + rapidjson::Value archiveNameVal; + archiveNameVal.SetString(archiveName.c_str(), archiveName.length()); + lensVal.AddMember("archive_name", archiveNameVal, alloc); + } + + rapidjson::Value focusedEntryVal; + focusedEntryVal.SetString(focusedEntry.c_str(), focusedEntry.length()); + lensVal.AddMember("focused_entry", focusedEntryVal, alloc); + + return lensVal; +} + +ArchiveMetadata ArchiveMetadata::fromJson(const rapidjson::Value& metadataDoc) { + ArchiveMetadata am; + am.loadJson(metadataDoc); + return am; +} + +void ArchiveMetadata::loadJson(const rapidjson::Value& metadataDoc) { + rapidjson::Value::ConstMemberIterator itr = metadataDoc.FindMember("archive_name"); + if (itr != metadataDoc.MemberEnd()) + archiveName.assign(itr->value.GetString()); + + archiveFormatName.assign(metadataDoc["archive_format_name"].GetString()); + archiveFormat = metadataDoc["archive_format"].GetUint64(); + + focusedEntry = metadataDoc["focused_entry"].GetString(); + + for (const auto &entryVal : metadataDoc["archive_structure"].GetArray()) { + entryMetadata.push_back(ArchiveEntryMetadata::fromJson(entryVal)); + } +} + +void ArchiveMetadata::seedTempPaths(fileutils::FileManager *file_man, bool keep = false) { + for (auto& entry : entryMetadata) + entry.tmpFileName.assign(file_man->unique_file("/tmp/", keep)); +} + +ArchiveStack ArchiveStack::fromJson(const rapidjson::Value& input) { + ArchiveStack as; + as.loadJson(input); + return as; +} + +ArchiveStack ArchiveStack::fromJsonString(const std::string& input) { + ArchiveStack as; + as.loadJsonString(input); + return as; +} + +void ArchiveStack::loadJson(const rapidjson::Value& lensStack) { + for (const auto& metadata : lensStack.GetArray()) { + stack_.push_back(ArchiveMetadata::fromJson(metadata)); + } +} + +void ArchiveStack::loadJsonString(const std::string& input) { + rapidjson::Document lensStack; + rapidjson::ParseResult ok = lensStack.Parse(input.c_str()); + + if (!ok) { + std::stringstream ss; + ss << "Failed to parse archive lens stack from JSON string with reason: " + << rapidjson::GetParseError_En(ok.Code()) + << " at offset " << ok.Offset(); + std::string exception_msg = ss.str(); + + throw Exception(ExceptionType::GENERAL_EXCEPTION, exception_msg.c_str()); + } + + loadJson(lensStack); +} + +rapidjson::Document ArchiveStack::toJson() const { + rapidjson::Document lensStack(rapidjson::kArrayType); + rapidjson::Document::AllocatorType &alloc = lensStack.GetAllocator(); + + for (const auto& metadata : stack_) { + lensStack.PushBack(metadata.toJson(alloc), alloc); + } + + return lensStack; +} + +std::string ArchiveStack::toJsonString() const { + rapidjson::Document d = toJson(); + + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + d.Accept(writer); + + std::string jsonString = buffer.GetString(); + return jsonString; +} diff --git a/extensions/libarchive/ArchiveMetadata.h b/extensions/libarchive/ArchiveMetadata.h new file mode 100644 index 0000000000..b44430988c --- /dev/null +++ b/extensions/libarchive/ArchiveMetadata.h @@ -0,0 +1,97 @@ +/** + * @file ArchiveMetadata.h + * ArchiveMetadata class declaration + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef EXTENSIONS_LIBARCHIVE_ARCHIVEMETADATA_H_ +#define EXTENSIONS_LIBARCHIVE_ARCHIVEMETADATA_H_ + +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/error/en.h" + +#include +#include +#include +#include + +#include "core/Core.h" +#include "utils/file/FileManager.h" + +class ArchiveEntryMetadata { +public: + std::string entryName; + mode_t entryType; + mode_t entryPerm; + uid_t entryUID; + gid_t entryGID; + uint64_t entryMTime; + uint64_t entryMTimeNsec; + uint64_t entrySize; + + std::string tmpFileName; + std::string stashKey; + + inline rapidjson::Value toJson(rapidjson::Document::AllocatorType &alloc) const; + static inline ArchiveEntryMetadata fromJson(const rapidjson::Value&); + +private: + inline void loadJson(const rapidjson::Value&); +}; + +using ArchiveEntryIterator = typename std::list::iterator; + +class ArchiveMetadata { +public: + std::string archiveName; + std::string archiveFormatName; + int archiveFormat; + std::list entryMetadata; + + std::string focusedEntry; + + ArchiveEntryIterator find(const std::string& name); + ArchiveEntryIterator eraseEntry(ArchiveEntryIterator position); + ArchiveEntryIterator insertEntry(ArchiveEntryIterator it, const ArchiveEntryMetadata& entry); + + void seedTempPaths(fileutils::FileManager* file_man, bool keep); + + rapidjson::Value toJson(rapidjson::Document::AllocatorType &alloc) const; + static ArchiveMetadata fromJson(const rapidjson::Value&); + +private: + void loadJson(const rapidjson::Value&); +}; + +class ArchiveStack { +public: + static ArchiveStack fromJsonString(const std::string& input); + static ArchiveStack fromJson(const rapidjson::Value& input); + void push(const ArchiveMetadata& metadata) { stack_.push_back(metadata); } + ArchiveMetadata pop() { auto x = top(); stack_.pop_back(); return x; } + ArchiveMetadata top() const { return stack_.back(); } + void loadJson(const rapidjson::Value& input); + void loadJsonString(const std::string& input); + std::string toJsonString() const; + rapidjson::Document toJson() const; + +private: + std::vector stack_; +}; + +#endif // EXTENSIONS_LIBARCHIVE_ARCHIVEMETADATA_H_ diff --git a/extensions/libarchive/CMakeLists.txt b/extensions/libarchive/CMakeLists.txt index 1ed8c5be90..4316049453 100644 --- a/extensions/libarchive/CMakeLists.txt +++ b/extensions/libarchive/CMakeLists.txt @@ -20,7 +20,7 @@ set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/) find_package(LibArchive) @@ -40,8 +40,7 @@ endif() # Include UUID find_package(UUID REQUIRED) -target_link_libraries(minifi-archive-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-archive-extensions jsoncpp_project) +target_link_libraries(minifi-archive-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-archive-extensions ${CMAKE_DL_LIBS} ) diff --git a/extensions/libarchive/FocusArchiveEntry.cpp b/extensions/libarchive/FocusArchiveEntry.cpp index 36b252c63f..5172dc6424 100644 --- a/extensions/libarchive/FocusArchiveEntry.cpp +++ b/extensions/libarchive/FocusArchiveEntry.cpp @@ -33,9 +33,7 @@ #include "core/ProcessContext.h" #include "core/ProcessSession.h" - -#include "json/json.h" -#include "json/writer.h" +#include "Exception.h" namespace org { namespace apache { @@ -76,17 +74,17 @@ void FocusArchiveEntry::onTrigger(core::ProcessContext *context, core::ProcessSe fileutils::FileManager file_man; - std::string targetEntry; - context->getProperty(Path.getName(), targetEntry); - // Extract archive contents ArchiveMetadata archiveMetadata; - archiveMetadata.focusedEntry = targetEntry; + context->getProperty(Path.getName(), archiveMetadata.focusedEntry); + flowFile->getAttribute("filename", archiveMetadata.archiveName); + ReadCallback cb(this, &file_man, &archiveMetadata); session->read(flowFile, &cb); // For each extracted entry, import & stash to key std::string targetEntryStashKey; + std::string targetEntry; for (auto &entryMetadata : archiveMetadata.entryMetadata) { if (entryMetadata.entryType == AE_IFREG) { @@ -99,7 +97,7 @@ void FocusArchiveEntry::onTrigger(core::ProcessContext *context, core::ProcessSe logger_->log_debug("FocusArchiveEntry generated stash key %s for entry %s", stashKey, entryMetadata.entryName); entryMetadata.stashKey.assign(stashKey); - if (entryMetadata.entryName == targetEntry) { + if (entryMetadata.entryName == archiveMetadata.focusedEntry) { targetEntryStashKey = entryMetadata.stashKey; } @@ -112,77 +110,45 @@ void FocusArchiveEntry::onTrigger(core::ProcessContext *context, core::ProcessSe if (targetEntryStashKey != "") { session->restore(targetEntryStashKey, flowFile); } else { - logger_->log_warn("FocusArchiveEntry failed to locate target entry: %s", targetEntry); + logger_->log_warn("FocusArchiveEntry failed to locate target entry: %s", + archiveMetadata.focusedEntry.c_str()); } // Set new/updated lens stack to attribute { - Json::Value lensStack; - Json::Reader reader; + ArchiveStack archiveStack; std::string existingLensStack; if (flowFile->getAttribute("lens.archive.stack", existingLensStack)) { logger_->log_info("FocusArchiveEntry loading existing lens context"); - if (!reader.parse(existingLensStack, lensStack)) { - logger_->log_error("FocusArchiveEntry JSON parse error: %s", reader.getFormattedErrorMessages()); + try { + archiveStack.loadJsonString(existingLensStack); + } catch (Exception &exception) { + logger_->log_debug(exception.what()); context->yield(); return; } - } else { - lensStack = Json::Value(Json::arrayValue); - } - - Json::Value structVal(Json::arrayValue); - - for (const auto &entryMetadata : archiveMetadata.entryMetadata) { - Json::Value entryVal(Json::objectValue); - entryVal["entry_name"] = Json::Value(entryMetadata.entryName); - entryVal["entry_type"] = Json::Value(entryMetadata.entryType); - entryVal["entry_perm"] = Json::Value(entryMetadata.entryPerm); - entryVal["entry_size"] = Json::Value(entryMetadata.entrySize); - entryVal["entry_uid"] = Json::Value(entryMetadata.entryUID); - entryVal["entry_gid"] = Json::Value(entryMetadata.entryGID); - entryVal["entry_mtime"] = Json::Value(entryMetadata.entryMTime); - entryVal["entry_mtime_nsec"] = Json::Value(entryMetadata.entryMTimeNsec); - - if (entryMetadata.entryType == AE_IFREG) { - entryVal["stash_key"] = Json::Value(entryMetadata.stashKey); - } - - structVal.append(entryVal); } - std::string archivenameStr; - Json::Value archiveName { Json::nullValue }; - - if (flowFile->getAttribute("filename", archivenameStr)) { - archiveName = Json::Value(archivenameStr); - } - - Json::Value lensVal(Json::objectValue); - lensVal["archive_format_name"] = Json::Value(archiveMetadata.archiveFormatName); - lensVal["archive_name"] = archiveName; - lensVal["focused_entry"] = Json::Value(archiveMetadata.focusedEntry); - lensVal["archive_format"] = Json::Value(archiveMetadata.archiveFormat); - lensVal["archive_structure"] = structVal; - lensStack.append(lensVal); - - Json::FastWriter writer; - std::string stackStr = writer.write(lensStack); + archiveStack.push(archiveMetadata); + //logger_->log_debug(archiveMetadata.toJsonString()); + std::string stackStr = archiveStack.toJsonString(); + if (!flowFile->updateAttribute("lens.archive.stack", stackStr)) { flowFile->addAttribute("lens.archive.stack", stackStr); } + } // Update filename attribute to that of focused entry - std::size_t found = targetEntry.find_last_of("/\\"); - std::string path = targetEntry.substr(0, found); - std::string name = targetEntry.substr(found + 1); + std::size_t found = archiveMetadata.focusedEntry.find_last_of("/\\"); + std::string path = archiveMetadata.focusedEntry.substr(0, found); + std::string name = archiveMetadata.focusedEntry.substr(found + 1); set_or_update_attr(flowFile, "filename", name); set_or_update_attr(flowFile, "path", path); - set_or_update_attr(flowFile, "absolute.path", targetEntry); + set_or_update_attr(flowFile, "absolute.path", archiveMetadata.focusedEntry); // Transfer to the relationship session->transfer(flowFile, Success); diff --git a/extensions/libarchive/FocusArchiveEntry.h b/extensions/libarchive/FocusArchiveEntry.h index 55b44cc643..174526c334 100644 --- a/extensions/libarchive/FocusArchiveEntry.h +++ b/extensions/libarchive/FocusArchiveEntry.h @@ -26,6 +26,7 @@ #include +#include "ArchiveMetadata.h" #include "FlowFileRecord.h" #include "core/Processor.h" #include "core/ProcessSession.h" @@ -69,29 +70,9 @@ class FocusArchiveEntry : public core::Processor { //! Initialize, over write by NiFi FocusArchiveEntry virtual void initialize(void); - typedef struct { - std::string entryName; - std::string tmpFileName; - std::string stashKey; - mode_t entryType; - mode_t entryPerm; - uid_t entryUID; - gid_t entryGID; - uint64_t entryMTime; - uint64_t entryMTimeNsec; - uint64_t entrySize; - } ArchiveEntryMetadata; - - typedef struct { - std::string archiveFormatName; - int archiveFormat; - std::string focusedEntry; - std::list entryMetadata; - } ArchiveMetadata; - class ReadCallback : public InputStreamCallback { public: - explicit ReadCallback(core::Processor*,fileutils::FileManager *file_man , ArchiveMetadata *archiveMetadata); + explicit ReadCallback(core::Processor*, fileutils::FileManager *file_man, ArchiveMetadata *archiveMetadata); ~ReadCallback(); virtual int64_t process(std::shared_ptr stream); bool isRunning() {return proc_->isRunning();} diff --git a/extensions/libarchive/ManipulateArchive.cpp b/extensions/libarchive/ManipulateArchive.cpp index c5c979fdf5..ac95c19518 100644 --- a/extensions/libarchive/ManipulateArchive.cpp +++ b/extensions/libarchive/ManipulateArchive.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include @@ -86,7 +85,6 @@ void ManipulateArchive::onSchedule(core::ProcessContext *context, core::ProcessS logger_->log_error("Invalid operation %s for ManipulateArchive.", operation_); invalid = true; } - context->getProperty(Target.getName(), targetEntry_); context->getProperty(Destination.getName(), destination_); @@ -123,7 +121,7 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe return; } - FocusArchiveEntry::ArchiveMetadata archiveMetadata; + ArchiveMetadata archiveMetadata; fileutils::FileManager file_man; FocusArchiveEntry::ReadCallback readCallback(this, &file_man, &archiveMetadata); @@ -131,7 +129,7 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe auto entries_end = archiveMetadata.entryMetadata.end(); - auto target_position = scanArchiveEntries(archiveMetadata, targetEntry_); + auto target_position = archiveMetadata.find(targetEntry_); if (target_position == entries_end && operation_ != OPERATION_TOUCH) { logger_->log_warn("ManipulateArchive could not find entry %s to %s!", @@ -144,7 +142,7 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe } if (!destination_.empty()) { - auto dest_position = scanArchiveEntries(archiveMetadata, destination_); + auto dest_position = archiveMetadata.find(destination_); if (dest_position != entries_end) { logger_->log_warn("ManipulateArchive cannot perform %s to existing destination_ %s!", operation_, destination_); @@ -153,14 +151,12 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe } } - std::list::iterator position; + auto position = entries_end; // Small speedup for when neither before or after are provided or needed - if ((before_.empty() && after_.empty()) || operation_ == OPERATION_REMOVE) { - position = entries_end; - } else { + if ((!before_.empty() || !after_.empty()) && operation_ != OPERATION_REMOVE) { std::string positionEntry = after_.empty() ? before_ : after_; - position = scanArchiveEntries(archiveMetadata, positionEntry); + position = archiveMetadata.find(positionEntry); if (position == entries_end) logger_->log_warn("ManipulateArchive could not find entry %s to " @@ -179,9 +175,9 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe if (operation_ == OPERATION_REMOVE) { std::remove((*target_position).tmpFileName.c_str()); - target_position = archiveMetadata.entryMetadata.erase(target_position); + target_position = archiveMetadata.eraseEntry(target_position); } else if (operation_ == OPERATION_COPY) { - FocusArchiveEntry::ArchiveEntryMetadata copy = *target_position; + ArchiveEntryMetadata copy = *target_position; // Copy tmp file const auto origTmpFileName = copy.tmpFileName; @@ -194,12 +190,12 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe archiveMetadata.entryMetadata.insert(position, copy); } else if (operation_ == OPERATION_MOVE) { - FocusArchiveEntry::ArchiveEntryMetadata moveEntry = *target_position; - target_position = archiveMetadata.entryMetadata.erase(target_position); + ArchiveEntryMetadata moveEntry = *target_position; + target_position = archiveMetadata.eraseEntry(target_position); moveEntry.entryName = destination_; archiveMetadata.entryMetadata.insert(position, moveEntry); } else if (operation_ == OPERATION_TOUCH) { - FocusArchiveEntry::ArchiveEntryMetadata touchEntry; + ArchiveEntryMetadata touchEntry; touchEntry.entryName = destination_; touchEntry.entryType = AE_IFREG; touchEntry.entrySize = 0; @@ -218,18 +214,6 @@ void ManipulateArchive::onTrigger(core::ProcessContext *context, core::ProcessSe session->transfer(flowFile, Success); } -std::list::iterator ManipulateArchive::scanArchiveEntries( - FocusArchiveEntry::ArchiveMetadata& archiveMetadata, - const std::string& target) { - auto targetTest = [&](const FocusArchiveEntry::ArchiveEntryMetadata& entry) -> bool { - return entry.entryName == target; - }; - - return std::find_if(archiveMetadata.entryMetadata.begin(), - archiveMetadata.entryMetadata.end(), - targetTest); -} - } /* namespace processors */ } /* namespace minifi */ } /* namespace nifi */ diff --git a/extensions/libarchive/ManipulateArchive.h b/extensions/libarchive/ManipulateArchive.h index 455044c4ec..6daca014dd 100644 --- a/extensions/libarchive/ManipulateArchive.h +++ b/extensions/libarchive/ManipulateArchive.h @@ -24,6 +24,7 @@ #include #include "FlowFileRecord.h" +#include "ArchiveMetadata.h" #include "core/Processor.h" #include "core/ProcessSession.h" @@ -83,7 +84,6 @@ class ManipulateArchive : public core::Processor { //! Logger std::shared_ptr logger_; std::string before_, after_, operation_, destination_, targetEntry_; - std::list::iterator scanArchiveEntries(FocusArchiveEntry::ArchiveMetadata&, const std::string&); }; REGISTER_RESOURCE(ManipulateArchive); diff --git a/extensions/libarchive/UnfocusArchiveEntry.cpp b/extensions/libarchive/UnfocusArchiveEntry.cpp index e904946b5b..64ffdebf2a 100644 --- a/extensions/libarchive/UnfocusArchiveEntry.cpp +++ b/extensions/libarchive/UnfocusArchiveEntry.cpp @@ -28,10 +28,9 @@ #include #include -#include "utils/file/FileManager.h" + #include "core/ProcessContext.h" #include "core/ProcessSession.h" -#include "json/json.h" namespace org { namespace apache { @@ -67,55 +66,41 @@ void UnfocusArchiveEntry::onTrigger(core::ProcessContext *context, core::Process } fileutils::FileManager file_man; - - // Get lens stack from attribute ArchiveMetadata lensArchiveMetadata; - Json::Value lensStack; - Json::Reader reader; - - std::string existingLensStack; - - if (flowFile->getAttribute("lens.archive.stack", existingLensStack)) { - logger_->log_info("UnfocusArchiveEntry loading existing lens context"); - - // TODO(calebj) handle any exceptions that might arise from working with JSON data - if (!reader.parse(existingLensStack, lensStack)) { - logger_->log_error("UnfocusArchiveEntry JSON parse error: %s", reader.getFormattedErrorMessages()); - context->yield(); - return; + // Get lens stack from attribute + { + ArchiveStack archiveStack; + { + std::string existingLensStack; + + if (flowFile->getAttribute("lens.archive.stack", existingLensStack)) { + logger_->log_info("FocusArchiveEntry loading existing lens context"); + + try { + archiveStack.loadJsonString(existingLensStack); + } catch (Exception &exception) { + logger_->log_debug(exception.what()); + context->yield(); + return; + } + } else { + logger_->log_error("UnfocusArchiveEntry lens metadata not found"); + context->yield(); + return; + } } - } else { - logger_->log_error("UnfocusArchiveEntry lens metadata not found"); - context->yield(); - return; - } + lensArchiveMetadata = archiveStack.pop(); + lensArchiveMetadata.seedTempPaths(&file_man, false); - Json::Value metadataDoc = lensStack[lensStack.size() - 1]; - lensStack.resize(lensStack.size() - 1); - - lensArchiveMetadata.archiveFormatName.assign(metadataDoc["archive_format_name"].asString()); - lensArchiveMetadata.archiveFormat = metadataDoc["archive_format"].asUInt64(); - lensArchiveMetadata.focusedEntry = metadataDoc["focused_entry"].asString(); - - for (auto itr = metadataDoc["archive_structure"].begin(); itr != metadataDoc["archive_structure"].end(); ++itr) { - const auto &entryVal = *itr; - ArchiveEntryMetadata metadata; - metadata.tmpFileName = file_man.unique_file("/tmp/", true); - metadata.entryName.assign(entryVal["entry_name"].asString()); - metadata.entryType = entryVal["entry_type"].asUInt64(); - metadata.entryPerm = entryVal["entry_perm"].asUInt64(); - metadata.entrySize = entryVal["entry_size"].asUInt64(); - metadata.entryUID = entryVal["entry_uid"].asUInt64(); - metadata.entryGID = entryVal["entry_gid"].asUInt64(); - metadata.entryMTime = entryVal["entry_mtime"].asUInt64(); - metadata.entryMTimeNsec = entryVal["entry_mtime_nsec"].asInt64(); - - if (metadata.entryType == AE_IFREG) - metadata.stashKey.assign(entryVal["stash_key"].asString()); - - lensArchiveMetadata.entryMetadata.push_back(metadata); + { + std::string stackStr = archiveStack.toJsonString(); + + if (!flowFile->updateAttribute("lens.archive.stack", stackStr)) { + flowFile->addAttribute("lens.archive.stack", stackStr); + } + } } // Export focused entry to tmp file @@ -146,27 +131,12 @@ void UnfocusArchiveEntry::onTrigger(core::ProcessContext *context, core::Process session->exportContent(entry.tmpFileName, flowFile, false); } - // Create archive by restoring each entry in the archive from tmp files - WriteCallback cb(&lensArchiveMetadata); - session->write(flowFile, &cb); - - // Set new/updated lens stack to attribute (already 'popped' with resize()) - Json::FastWriter writer; - std::string stackStr = writer.write(lensStack); - - if (!flowFile->updateAttribute("lens.archive.stack", stackStr)) { - flowFile->addAttribute("lens.archive.stack", stackStr); - } - - // Update filename to that of original archive - Json::Value archiveName = metadataDoc.get("archive_name", Json::Value(Json::nullValue)); - - if (archiveName.isNull()) { + if (lensArchiveMetadata.archiveName.empty()) { flowFile->removeAttribute("filename"); flowFile->removeAttribute("path"); flowFile->removeAttribute("absolute.path"); } else { - std::string abs_path = archiveName.asString(); + std::string abs_path = lensArchiveMetadata.archiveName; std::size_t found = abs_path.find_last_of("/\\"); std::string path = abs_path.substr(0, found); std::string name = abs_path.substr(found + 1); @@ -175,6 +145,10 @@ void UnfocusArchiveEntry::onTrigger(core::ProcessContext *context, core::Process set_or_update_attr(flowFile, "absolute.path", abs_path); } + // Create archive by restoring each entry in the archive from tmp files + WriteCallback cb(&lensArchiveMetadata); + session->write(flowFile, &cb); + // Transfer to the relationship session->transfer(flowFile, Success); } diff --git a/extensions/libarchive/UnfocusArchiveEntry.h b/extensions/libarchive/UnfocusArchiveEntry.h index 5fb29c5098..cc39b37462 100644 --- a/extensions/libarchive/UnfocusArchiveEntry.h +++ b/extensions/libarchive/UnfocusArchiveEntry.h @@ -27,6 +27,7 @@ #include "FocusArchiveEntry.h" #include "FlowFileRecord.h" +#include "ArchiveMetadata.h" #include "core/Processor.h" #include "core/ProcessSession.h" #include "core/Core.h" @@ -68,9 +69,6 @@ class UnfocusArchiveEntry : public core::Processor { //! Initialize, over write by NiFi UnfocusArchiveEntry virtual void initialize(void); - typedef FocusArchiveEntry::ArchiveEntryMetadata ArchiveEntryMetadata; - typedef FocusArchiveEntry::ArchiveMetadata ArchiveMetadata; - //! Write callback for reconstituting lensed archive into flow file content class WriteCallback : public OutputStreamCallback { public: diff --git a/extensions/librdkafka/CMakeLists.txt b/extensions/librdkafka/CMakeLists.txt index 1a5b0f4bb3..d37cf67e00 100644 --- a/extensions/librdkafka/CMakeLists.txt +++ b/extensions/librdkafka/CMakeLists.txt @@ -20,7 +20,7 @@ set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(../../thirdparty/librdkafka-0.11.1/src ./../thirdparty/librdkafka-0.11.1/src-cpp) @@ -38,8 +38,7 @@ endif() # Include UUID find_package(UUID REQUIRED) -target_link_libraries(minifi-rdkafka-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-rdkafka-extensions jsoncpp_project) +target_link_libraries(minifi-rdkafka-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-rdkafka-extensions ${CMAKE_DL_LIBS} ) diff --git a/extensions/mqtt/CMakeLists.txt b/extensions/mqtt/CMakeLists.txt index 7e186ba9e0..d248524d8e 100644 --- a/extensions/mqtt/CMakeLists.txt +++ b/extensions/mqtt/CMakeLists.txt @@ -20,7 +20,7 @@ set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(../../thirdparty/paho.mqtt.c/src) @@ -39,7 +39,6 @@ endif() # Include UUID find_package(UUID REQUIRED) target_link_libraries(minifi-mqtt-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-mqtt-extensions jsoncpp_project) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-mqtt-extensions ${CMAKE_DL_LIBS} ) diff --git a/extensions/pcap/CMakeLists.txt b/extensions/pcap/CMakeLists.txt index 69d9c8f2ed..c6dc980184 100644 --- a/extensions/pcap/CMakeLists.txt +++ b/extensions/pcap/CMakeLists.txt @@ -22,7 +22,7 @@ find_package(PCAP REQUIRED) set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/c2 ../../libminifi/include/c2/protocols/ ../../libminifi/include/core/state ./libminifi/include/core/statemanagement/metrics ../../libminifi/include/core/yaml ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(/usr/include/netinet) set(PCAPPLUSPLUS_TP_BASE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/pcap++/") @@ -80,8 +80,7 @@ endif () # Include UUID find_package(UUID REQUIRED) -target_link_libraries(minifi-pcap ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-pcap jsoncpp_project) +target_link_libraries(minifi-pcap ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-pcap ${CMAKE_DL_LIBS} ) diff --git a/extensions/rocksdb-repos/CMakeLists.txt b/extensions/rocksdb-repos/CMakeLists.txt index 5d459e5be1..6deb067d32 100644 --- a/extensions/rocksdb-repos/CMakeLists.txt +++ b/extensions/rocksdb-repos/CMakeLists.txt @@ -48,8 +48,7 @@ endif() # Include UUID find_package(UUID REQUIRED) -target_link_libraries(minifi-rocksdb-repos ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-rocksdb-repos jsoncpp_project) +target_link_libraries(minifi-rocksdb-repos ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-rocksdb-repos ${CMAKE_DL_LIBS} ) diff --git a/extensions/script/CMakeLists.txt b/extensions/script/CMakeLists.txt index 927d974bf5..86e41dddcc 100644 --- a/extensions/script/CMakeLists.txt +++ b/extensions/script/CMakeLists.txt @@ -37,7 +37,7 @@ endif() set(CMAKE_EXE_LINKER_FLAGS "-Wl,--export-all-symbols") set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--export-symbols") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ../../thirdparty/) file(GLOB SOURCES "*.cpp") @@ -51,8 +51,7 @@ if(CMAKE_THREAD_LIBS_INIT) endif() find_package(UUID REQUIRED) -target_link_libraries(minifi-script-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-script-extensions jsoncpp_project) +target_link_libraries(minifi-script-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-script-extensions ${CMAKE_DL_LIBS}) diff --git a/extensions/tensorflow/CMakeLists.txt b/extensions/tensorflow/CMakeLists.txt index a8ba8fb872..0efc93d71e 100644 --- a/extensions/tensorflow/CMakeLists.txt +++ b/extensions/tensorflow/CMakeLists.txt @@ -27,7 +27,7 @@ find_package(TensorFlow REQUIRED) message("-- Found TensorFlow: ${TENSORFLOW_INCLUDE_DIRS}") -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(${TENSORFLOW_INCLUDE_DIRS}) @@ -43,8 +43,7 @@ if(CMAKE_THREAD_LIBS_INIT) endif() find_package(UUID REQUIRED) -target_link_libraries(minifi-tensorflow-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-tensorflow-extensions jsoncpp_project) +target_link_libraries(minifi-tensorflow-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-tensorflow-extensions ${CMAKE_DL_LIBS}) diff --git a/extensions/usb-camera/CMakeLists.txt b/extensions/usb-camera/CMakeLists.txt index 480bc140f0..d807e8089f 100644 --- a/extensions/usb-camera/CMakeLists.txt +++ b/extensions/usb-camera/CMakeLists.txt @@ -44,7 +44,7 @@ if (NOT PNG_FOUND) message(FATAL_ERROR "A compatible PNG library is required to build GetUSBCamera.") endif() -include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/jsoncpp/include ../../thirdparty/) +include_directories(../../libminifi/include ../../libminifi/include/core ../../thirdparty/spdlog-20170710/include ../../thirdparty/concurrentqueue ../../thirdparty/yaml-cpp-yaml-cpp-0.5.3/include ${CIVET_THIRDPARTY_ROOT}/include ../../thirdparty/) include_directories(../../thirdparty/libuvc-0.0.6/include) @@ -60,8 +60,7 @@ if(CMAKE_THREAD_LIBS_INIT) endif() find_package(UUID REQUIRED) -target_link_libraries(minifi-usb-camera-extensions ${LIBMINIFI} ${UUID_LIBRARIES} ${JSONCPP_LIB}) -add_dependencies(minifi-usb-camera-extensions jsoncpp_project) +target_link_libraries(minifi-usb-camera-extensions ${LIBMINIFI} ${UUID_LIBRARIES}) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) target_link_libraries(minifi-usb-camera-extensions ${CMAKE_DL_LIBS} ) diff --git a/libminifi/CMakeLists.txt b/libminifi/CMakeLists.txt index a40f070a0b..ce0a0d930a 100644 --- a/libminifi/CMakeLists.txt +++ b/libminifi/CMakeLists.txt @@ -55,7 +55,7 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-reorder") include_directories(../thirdparty/spdlog-20170710/include) include_directories(../thirdparty/yaml-cpp-yaml-cpp-20171024/include) -include_directories(../thirdparty/jsoncpp/include) +include_directories(../thirdparty/rapidjson-1.1.0/include) include_directories(../thirdparty/concurrentqueue/) include_directories(include) @@ -71,8 +71,7 @@ file(GLOB SPD_SOURCES "../thirdparty/spdlog-20170710/include/spdlog/*") # header only library add_library(spdlog STATIC ${SPD_SOURCES}) add_library(core-minifi STATIC ${SOURCES}) -add_dependencies(core-minifi jsoncpp_project) -target_link_libraries(core-minifi ${UUID_LIBRARIES} ${JSONCPP_LIB} yaml-cpp dl) +target_link_libraries(core-minifi ${UUID_LIBRARIES} yaml-cpp) find_package(ZLIB REQUIRED) include_directories(${ZLIB_INCLUDE_DIRS}) @@ -91,7 +90,6 @@ endif (OPENSSL_FOUND) add_library(minifi STATIC ${PROCESSOR_SOURCES}) add_library(capi STATIC ${CAPI_SOURCES}) -target_link_libraries(minifi c-library civetweb-cpp) target_link_libraries(minifi core-minifi) diff --git a/libminifi/include/c2/protocols/RESTProtocol.h b/libminifi/include/c2/protocols/RESTProtocol.h index 823b5a9f0d..ed6d3eb352 100644 --- a/libminifi/include/c2/protocols/RESTProtocol.h +++ b/libminifi/include/c2/protocols/RESTProtocol.h @@ -18,8 +18,11 @@ #ifndef LIBMINIFI_INCLUDE_C2_PROTOCOLS_RESTPROTOCOL_H_ #define LIBMINIFI_INCLUDE_C2_PROTOCOLS_RESTPROTOCOL_H_ -#include "json/json.h" -#include "json/writer.h" +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/prettywriter.h" + #include #include @@ -28,6 +31,7 @@ #include "c2/HeartBeatReporter.h" #include "controllers/SSLContextService.h" #include "utils/HTTPClient.h" +#include "Exception.h" namespace org { namespace apache { @@ -55,7 +59,11 @@ class RESTProtocol { protected: - virtual Json::Value serializeJsonPayload(Json::Value &json_root, const C2Payload &payload); + virtual rapidjson::Value serializeJsonPayload(const C2Payload &payload, rapidjson::Document::AllocatorType &alloc); + + virtual std::string serializeJsonRootPayload(const C2Payload& payload); + + virtual void mergePayloadContent(rapidjson::Value &target, const C2Payload &payload, rapidjson::Document::AllocatorType &alloc); virtual const C2Payload parseJsonResponse(const C2Payload &payload, const std::vector &response); diff --git a/libminifi/include/utils/ByteArrayCallback.h b/libminifi/include/utils/ByteArrayCallback.h index f0a83eef55..9ccca4851c 100644 --- a/libminifi/include/utils/ByteArrayCallback.h +++ b/libminifi/include/utils/ByteArrayCallback.h @@ -61,8 +61,6 @@ class ByteInputCallBack : public InputStreamCallback { } virtual void write(std::string content) { - //vec.resize(content.length()); - //std::copy(content.begin(), content.end(), std::back_inserter(vec)); vec.assign(content.begin(), content.end()); ptr = &vec[0]; } diff --git a/libminifi/include/utils/HTTPClient.h b/libminifi/include/utils/HTTPClient.h index b09b450f98..3d1383c16f 100644 --- a/libminifi/include/utils/HTTPClient.h +++ b/libminifi/include/utils/HTTPClient.h @@ -147,7 +147,9 @@ class HTTPRequestResponse { if (callback->getPos() <= buffer_size) { size_t len = buffer_size - callback->pos; if (len <= 0) + { return 0; + } char *ptr = callback->ptr->getBuffer(callback->getPos()); if (ptr == nullptr) { @@ -155,6 +157,7 @@ class HTTPRequestResponse { } if (len > size * nmemb) len = size * nmemb; + auto strr = std::string(ptr,len); memcpy(data, ptr, len); callback->pos += len; callback->ptr->seek(callback->getPos()); @@ -163,7 +166,6 @@ class HTTPRequestResponse { } else { return 0x10000000; } - return 0; } diff --git a/libminifi/src/RemoteProcessorGroupPort.cpp b/libminifi/src/RemoteProcessorGroupPort.cpp index 332de0b681..c7cc1918a0 100644 --- a/libminifi/src/RemoteProcessorGroupPort.cpp +++ b/libminifi/src/RemoteProcessorGroupPort.cpp @@ -36,8 +36,8 @@ #include "sitetosite/Peer.h" #include "sitetosite/SiteToSiteFactory.h" -#include "json/json.h" -#include "json/writer.h" + +#include "rapidjson/document.h" #include "Exception.h" #include "core/logging/Logger.h" @@ -311,20 +311,25 @@ void RemoteProcessorGroupPort::refreshRemoteSite2SiteInfo() { if (!response_body.empty()) { std::string controller = std::string(response_body.begin(), response_body.end()); logger_->log_debug("controller config %s", controller); - Json::Value value; - Json::Reader reader; - bool parsingSuccessful = reader.parse(controller, value); - if (parsingSuccessful && !value.empty()) { - Json::Value controllerValue = value["controller"]; - if (!controllerValue.empty()) { - Json::Value port = controllerValue["remoteSiteListeningPort"]; - if (client_type_ == sitetosite::CLIENT_TYPE::RAW && !port.empty()) - this->site2site_port_ = port.asInt(); + rapidjson::Document doc; + rapidjson::ParseResult ok = doc.Parse(controller.c_str()); + + if (ok && doc.IsObject() && !doc.ObjectEmpty()) { + rapidjson::Value::MemberIterator itr = doc.FindMember("controller"); + + if (itr != doc.MemberEnd() && itr->value.IsObject()) { + rapidjson::Value controllerValue = itr->value.GetObject(); + rapidjson::Value::ConstMemberIterator end_itr = controllerValue.MemberEnd(); + rapidjson::Value::ConstMemberIterator port_itr = controllerValue.FindMember("remoteSiteListeningPort"); + rapidjson::Value::ConstMemberIterator secure_itr = controllerValue.FindMember("siteToSiteSecure"); + + if (client_type_ == sitetosite::CLIENT_TYPE::RAW && port_itr != end_itr && port_itr->value.IsNumber()) + this->site2site_port_ = port_itr->value.GetInt(); else this->site2site_port_ = port_; - Json::Value secure = controllerValue["siteToSiteSecure"]; - if (!secure.empty()) - this->site2site_secure_ = secure.asBool(); + + if (secure_itr != end_itr && secure_itr->value.IsBool()) + this->site2site_secure_ = secure_itr->value.GetBool(); } logger_->log_debug("process group remote site2site port %d, is secure %d", site2site_port_, site2site_secure_); } diff --git a/libminifi/src/c2/protocols/RESTProtocol.cpp b/libminifi/src/c2/protocols/RESTProtocol.cpp index 946e3c6522..b1cebb0e0c 100644 --- a/libminifi/src/c2/protocols/RESTProtocol.cpp +++ b/libminifi/src/c2/protocols/RESTProtocol.cpp @@ -24,6 +24,7 @@ #include #include #include +#include namespace org { namespace apache { @@ -32,46 +33,57 @@ namespace minifi { namespace c2 { const C2Payload RESTProtocol::parseJsonResponse(const C2Payload &payload, const std::vector &response) { - Json::Reader reader; - Json::Value root; + rapidjson::Document root; + try { - if (reader.parse(std::string(response.data(), response.size()), root)) { + rapidjson::ParseResult ok = root.Parse(response.data(), response.size()); + + if (ok) { std::string requested_operation = getOperation(payload); std::string identifier; - if (root.isMember("operationid")) { - identifier = root["operationid"].asString(); + if (root.HasMember("operationid")) { + identifier = root["operationid"].GetString(); } - if (root["operation"].asString() == requested_operation) { - if (root["requested_operations"].size() == 0) { + + if (root.HasMember("operation") && root["operation"].GetString() == requested_operation) { + if (root["requested_operations"].Size() == 0) return std::move(C2Payload(payload.getOperation(), state::UpdateState::READ_COMPLETE, true)); - } + C2Payload new_payload(payload.getOperation(), state::UpdateState::NESTED, true); new_payload.setIdentifier(identifier); - for (const Json::Value& request : root["requested_operations"]) { - Operation newOp = stringToOperation(request["operation"].asString()); + for (const rapidjson::Value& request : root["requested_operations"].GetArray()) { + Operation newOp = stringToOperation(request["operation"].GetString()); C2Payload nested_payload(newOp, state::UpdateState::READ_COMPLETE, true); C2ContentResponse new_command(newOp); new_command.delay = 0; new_command.required = true; new_command.ttl = -1; + // set the identifier if one exists - if (request.isMember("operationid")) { - new_command.ident = request["operationid"].asString(); + if (request.HasMember("operationid")) { + if (request["operationid"].IsNumber()) + new_command.ident = std::to_string(request["operationid"].GetInt64()); + else if (request["operationid"].IsString()) + new_command.ident = request["operationid"].GetString(); + else + throw(Exception(SITE2SITE_EXCEPTION, "Invalid type for operationid")); + nested_payload.setIdentifier(new_command.ident); } - new_command.name = request["name"].asString(); - if (request.isMember("content") && request["content"].size() > 0) { - for (const auto &name : request["content"].getMemberNames()) { - new_command.operation_arguments[name] = request["content"][name].asString(); - } - } + new_command.name = request["name"].GetString(); + + if (request.HasMember("content") && request["content"].MemberCount() > 0) + for (const auto &member : request["content"].GetObject()) + new_command.operation_arguments[member.name.GetString()] = member.value.GetString(); + nested_payload.addContent(std::move(new_command)); new_payload.addPayload(std::move(nested_payload)); } + // we have a response for this request return new_payload; } @@ -81,48 +93,116 @@ const C2Payload RESTProtocol::parseJsonResponse(const C2Payload &payload, const return std::move(C2Payload(payload.getOperation(), state::UpdateState::READ_ERROR, true)); } -Json::Value RESTProtocol::serializeJsonPayload(Json::Value &json_root, const C2Payload &payload) { - // get the name from the content - Json::Value json_payload; - std::map> children; - for (const auto &nested_payload : payload.getNestedPayloads()) { - Json::Value child_payload = serializeJsonPayload(json_payload, nested_payload); - children[nested_payload.getLabel()].push_back(child_payload); - } - for (auto child_vector : children) { - if (child_vector.second.size() > 1) { - Json::Value children_json(Json::arrayValue); - for (auto child : child_vector.second) { - json_payload[child_vector.first] = child; - } - } else { - if (child_vector.second.size() == 1) { - if (child_vector.second.at(0).isMember(child_vector.first)) { - json_payload[child_vector.first] = child_vector.second.at(0)[child_vector.first]; - } else { - json_payload[child_vector.first] = child_vector.second.at(0); - } - } - } - } +void setJsonStr(const std::string& key, const std::string& value, rapidjson::Value& parent, rapidjson::Document::AllocatorType& alloc) { // NOLINT + rapidjson::Value keyVal; + rapidjson::Value valueVal; + const char* c_key = key.c_str(); + const char* c_val = value.c_str(); + + keyVal.SetString(c_key, key.length(), alloc); + valueVal.SetString(c_val, value.length(), alloc); + parent.AddMember(keyVal, valueVal, alloc); +} + +rapidjson::Value getStringValue(const std::string& value, rapidjson::Document::AllocatorType& alloc) { // NOLINT + rapidjson::Value Val; + Val.SetString(value.c_str(), value.length(), alloc); + return Val; +} + +void RESTProtocol::mergePayloadContent(rapidjson::Value &target, const C2Payload &payload, rapidjson::Document::AllocatorType &alloc) { const std::vector &content = payload.getContent(); + for (const auto &payload_content : content) { - Json::Value payload_content_values; + rapidjson::Value payload_content_values(rapidjson::kObjectType); bool use_sub_option = true; + if (payload_content.op == payload.getOperation()) { for (auto content : payload_content.operation_arguments) { if (payload_content.operation_arguments.size() == 1 && payload_content.name == content.first) { - json_payload[payload_content.name] = content.second; + setJsonStr(payload_content.name, content.second, target, alloc); use_sub_option = false; } else { - payload_content_values[content.first] = content.second; + setJsonStr(content.first, content.second, payload_content_values, alloc); } } } - if (use_sub_option) - json_payload[payload_content.name] = payload_content_values; + if (use_sub_option) { + rapidjson::Value sub_key = getStringValue(payload_content.name, alloc); + target.AddMember(sub_key, payload_content_values, alloc); + } } +} + +std::string RESTProtocol::serializeJsonRootPayload(const C2Payload& payload) { + rapidjson::Document json_payload(rapidjson::kObjectType); + rapidjson::Document::AllocatorType &alloc = json_payload.GetAllocator(); + + rapidjson::Value opReqStrVal; + std::string operation_request_str = getOperation(payload); + opReqStrVal.SetString(operation_request_str.c_str(), operation_request_str.length(), alloc); + json_payload.AddMember("operation", opReqStrVal, alloc); + + std::string operationid = payload.getIdentifier(); + if (operationid.length() > 0) { + rapidjson::Value operationIdVal = getStringValue(operationid, alloc); + json_payload.AddMember("operationid", operationIdVal, alloc); + } + + mergePayloadContent(json_payload, payload, alloc); + + for (const auto &nested_payload : payload.getNestedPayloads()) { + rapidjson::Value np_key = getStringValue(nested_payload.getLabel(), alloc); + rapidjson::Value np_value = serializeJsonPayload(nested_payload, alloc); + json_payload.AddMember(np_key, np_value, alloc); + } + + rapidjson::StringBuffer buffer; + rapidjson::PrettyWriter writer(buffer); + json_payload.Accept(writer); + + // std::string ret = ; + return buffer.GetString(); +} + +rapidjson::Value RESTProtocol::serializeJsonPayload(const C2Payload &payload, rapidjson::Document::AllocatorType &alloc) { + // get the name from the content + rapidjson::Value json_payload(rapidjson::kObjectType); + + std::map> children; + + for (const auto &nested_payload : payload.getNestedPayloads()) { + rapidjson::Value* child_payload = new rapidjson::Value(serializeJsonPayload(nested_payload, alloc)); + children[nested_payload.getLabel()].push_back(child_payload); + } + + // child_vector is Pair> + for (auto child_vector : children) { + rapidjson::Value children_json; + rapidjson::Value newMemberKey = getStringValue(child_vector.first, alloc); + + if (child_vector.second.size() > 1) { + children_json.SetArray(); + for (auto child : child_vector.second) + children_json.PushBack(child->Move(), alloc); + + json_payload.AddMember(newMemberKey, children_json, alloc); + } else if (child_vector.second.size() == 1) { + rapidjson::Value* first = child_vector.second.front(); + + if (first->IsObject() && first->HasMember(newMemberKey)) + json_payload.AddMember(newMemberKey, (*first)[newMemberKey].Move(), alloc); + else + json_payload.AddMember(newMemberKey, first->Move(), alloc); + } + + for (rapidjson::Value* child : child_vector.second) + delete child; + } + + mergePayloadContent(json_payload, payload, alloc); + return json_payload; } diff --git a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp index 05fa6a8c8b..c25fa6401e 100644 --- a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp +++ b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp @@ -37,8 +37,11 @@ #include "provenance/Provenance.h" #include "FlowController.h" -#include "json/json.h" -#include "json/writer.h" +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/prettywriter.h" + namespace org { namespace apache { @@ -53,54 +56,92 @@ void SiteToSiteProvenanceReportingTask::initialize() { RemoteProcessorGroupPort::initialize(); } +void setJsonStr(const std::string& key, const std::string& value, rapidjson::Value& parent, rapidjson::Document::AllocatorType& alloc) { // NOLINT + rapidjson::Value keyVal; + rapidjson::Value valueVal; + const char* c_key = key.c_str(); + const char* c_val = value.c_str(); + + keyVal.SetString(c_key, key.length(), alloc); + valueVal.SetString(c_val, value.length(), alloc); + + parent.AddMember(keyVal, valueVal, alloc); +} + +rapidjson::Value getStringValue(const std::string& value, rapidjson::Document::AllocatorType& alloc) { // NOLINT + rapidjson::Value Val; + Val.SetString(value.c_str(), value.length(), alloc); + return Val; +} + +void appendJsonStr(const std::string& value, rapidjson::Value& parent, rapidjson::Document::AllocatorType& alloc) { // NOLINT + rapidjson::Value valueVal; + const char* c_val = value.c_str(); + valueVal.SetString(c_val, value.length(), alloc); + parent.PushBack(valueVal, alloc); +} + void SiteToSiteProvenanceReportingTask::getJsonReport(const std::shared_ptr &context, const std::shared_ptr &session, std::vector> &records, std::string &report) { - Json::Value array; + rapidjson::Document array(rapidjson::kArrayType); + rapidjson::Document::AllocatorType &alloc = array.GetAllocator(); + for (auto sercomp : records) { std::shared_ptr record = std::dynamic_pointer_cast(sercomp); if (nullptr == record) { break; } - Json::Value recordJson; - Json::Value updatedAttributesJson; - Json::Value parentUuidJson; - Json::Value childUuidJson; - recordJson["eventId"] = record->getEventId().c_str(); - recordJson["eventType"] = provenance::ProvenanceEventRecord::ProvenanceEventTypeStr[record->getEventType()]; - recordJson["timestampMillis"] = record->getEventTime(); - recordJson["durationMillis"] = record->getEventDuration(); - recordJson["lineageStart"] = record->getlineageStartDate(); - recordJson["details"] = record->getDetails().c_str(); - recordJson["componentId"] = record->getComponentId().c_str(); - recordJson["componentType"] = record->getComponentType().c_str(); - recordJson["entityId"] = record->getFlowFileUuid().c_str(); - recordJson["entityType"] = "org.apache.nifi.flowfile.FlowFile"; - recordJson["entitySize"] = record->getFileSize(); - recordJson["entityOffset"] = record->getFileOffset(); + + rapidjson::Value recordJson(rapidjson::kObjectType); + rapidjson::Value updatedAttributesJson(rapidjson::kObjectType); + rapidjson::Value parentUuidJson(rapidjson::kArrayType); + rapidjson::Value childUuidJson(rapidjson::kArrayType); + + recordJson.AddMember("timestampMillis", record->getEventTime(), alloc); + recordJson.AddMember("durationMillis", record->getEventDuration(), alloc); + recordJson.AddMember("lineageStart", record->getlineageStartDate(), alloc); + recordJson.AddMember("entitySize", record->getFileSize(), alloc); + recordJson.AddMember("entityOffset", record->getFileOffset(), alloc); + + recordJson.AddMember("entityType", "org.apache.nifi.flowfile.FlowFile", alloc); + + recordJson.AddMember("eventId", getStringValue(record->getEventId(), alloc), alloc); + recordJson.AddMember("eventType", getStringValue(provenance::ProvenanceEventRecord::ProvenanceEventTypeStr[record->getEventType()], alloc), alloc); + recordJson.AddMember("details", getStringValue(record->getDetails(), alloc), alloc); + recordJson.AddMember("componentId", getStringValue(record->getComponentId(), alloc), alloc); + recordJson.AddMember("componentType", getStringValue(record->getComponentType(), alloc), alloc); + recordJson.AddMember("entityId", getStringValue(record->getFlowFileUuid(), alloc), alloc); + recordJson.AddMember("transitUri", getStringValue(record->getTransitUri(), alloc), alloc); + recordJson.AddMember("remoteIdentifier", getStringValue(record->getSourceSystemFlowFileIdentifier(), alloc), alloc); + recordJson.AddMember("alternateIdentifier", getStringValue(record->getAlternateIdentifierUri(), alloc), alloc); for (auto attr : record->getAttributes()) { - updatedAttributesJson[attr.first] = attr.second; + setJsonStr(attr.first, attr.second, updatedAttributesJson, alloc); } - recordJson["updatedAttributes"] = updatedAttributesJson; + recordJson.AddMember("updatedAttributes", updatedAttributesJson, alloc); for (auto parentUUID : record->getParentUuids()) { - parentUuidJson.append(parentUUID.c_str()); + appendJsonStr(parentUUID, parentUuidJson, alloc); } - recordJson["parentIds"] = parentUuidJson; + recordJson.AddMember("parentIds", parentUuidJson, alloc); for (auto childUUID : record->getChildrenUuids()) { - childUuidJson.append(childUUID.c_str()); + appendJsonStr(childUUID, childUuidJson, alloc); } - recordJson["childIds"] = childUuidJson; - recordJson["transitUri"] = record->getTransitUri().c_str(); - recordJson["remoteIdentifier"] = record->getSourceSystemFlowFileIdentifier().c_str(); - recordJson["alternateIdentifier"] = record->getAlternateIdentifierUri().c_str(); - recordJson["application"] = ProvenanceAppStr; - array.append(recordJson); + recordJson.AddMember("childIds", childUuidJson, alloc); + + rapidjson::Value applicationVal; + applicationVal.SetString(ProvenanceAppStr, std::strlen(ProvenanceAppStr)); + recordJson.AddMember("application", applicationVal, alloc); + + array.PushBack(recordJson, alloc); } - Json::StyledWriter writer; - report = writer.write(array); + rapidjson::StringBuffer buffer; + rapidjson::PrettyWriter writer(buffer); + array.Accept(writer); + + report = buffer.GetString(); } void SiteToSiteProvenanceReportingTask::onSchedule(const std::shared_ptr &context, const std::shared_ptr &sessionFactory) { diff --git a/libminifi/test/unit/ProcessorTests.cpp b/libminifi/test/unit/ProcessorTests.cpp index 2b9102433a..6e9ae8373b 100644 --- a/libminifi/test/unit/ProcessorTests.cpp +++ b/libminifi/test/unit/ProcessorTests.cpp @@ -324,7 +324,7 @@ TEST_CASE("Test Find file", "[getfileCreate3]") { taskReport->getJsonReport(context, session, recordsReport, jsonStr); REQUIRE(recordsReport.size() == 1); REQUIRE(taskReport->getName() == std::string(org::apache::nifi::minifi::core::reporting::SiteToSiteProvenanceReportingTask::ReportTaskName)); - REQUIRE(jsonStr.find("\"componentType\" : \"getfileCreate2\"") != std::string::npos); + REQUIRE(jsonStr.find("\"componentType\": \"getfileCreate2\"") != std::string::npos); }; testController.runSession(plan, false, verifyReporter); diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 174853e71d..36d01e8d43 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -23,7 +23,7 @@ IF(POLICY CMP0048) CMAKE_POLICY(SET CMP0048 OLD) ENDIF(POLICY CMP0048) -include_directories(../libminifi/include ../libminifi/include/c2 ../libminifi/include/c2/protocols/ ../libminifi/include/core/state ./libminifi/include/core/statemanagement/metrics ../libminifi/include/core/yaml ../libminifi/include/core ../thirdparty/spdlog-20170710/include ../thirdparty/concurrentqueue ../thirdparty/yaml-cpp-yaml-cpp-20171024/include ${CIVET_THIRDPARTY_ROOT}/include ../thirdparty/jsoncpp/include ../thirdparty/) +include_directories(../libminifi/include ../thirdparty/spdlog-20170710/include ../thirdparty/concurrentqueue ../thirdparty/yaml-cpp-yaml-cpp-20171024/include ../thirdparty/rapidjson-1.1.0/include ../thirdparty/) include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) @@ -51,7 +51,7 @@ find_package(UUID REQUIRED) find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) -# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl, jsoncpp and rocksdb +# Link against minifi, yaml-cpp, civetweb-cpp, uuid, openssl, and rocksdb #target_link_libraries(minifiexe core-minifi) if (APPLE) @@ -66,9 +66,7 @@ else () target_link_libraries (minifiexe -Wl,--whole-archive minifi -Wl,--no-whole-archive) endif () - -target_link_libraries(minifiexe yaml-cpp ${JSON_CPP_LIB} ${UUID_LIBRARIES} ${OPENSSL_LIBRARIES}) - +target_link_libraries(minifiexe yaml-cpp ${UUID_LIBRARIES} ${OPENSSL_LIBRARIES}) if (APPLE) get_property(extensions GLOBAL PROPERTY EXTENSION-OPTIONS) diff --git a/thirdparty/jsoncpp/AUTHORS b/thirdparty/jsoncpp/AUTHORS deleted file mode 100644 index c0fbbeec11..0000000000 --- a/thirdparty/jsoncpp/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Baptiste Lepilleur diff --git a/thirdparty/jsoncpp/CMakeLists.txt b/thirdparty/jsoncpp/CMakeLists.txt deleted file mode 100644 index a6c0884803..0000000000 --- a/thirdparty/jsoncpp/CMakeLists.txt +++ /dev/null @@ -1,156 +0,0 @@ -# vim: et ts=4 sts=4 sw=4 tw=0 - -CMAKE_MINIMUM_REQUIRED(VERSION 3.1) -PROJECT(jsoncpp) -ENABLE_TESTING() - -OPTION(JSONCPP_WITH_TESTS "Compile and (for jsoncpp_check) run JsonCpp test executables" OFF) -OPTION(JSONCPP_WITH_POST_BUILD_UNITTEST "Automatically run unit-tests as a post build step" OFF) -OPTION(JSONCPP_WITH_WARNING_AS_ERROR "Force compilation to fail if a warning occurs" OFF) -OPTION(JSONCPP_WITH_STRICT_ISO "Issue all the warnings demanded by strict ISO C and ISO C++" ON) -OPTION(JSONCPP_WITH_PKGCONFIG_SUPPORT "Generate and install .pc files" ON) -OPTION(JSONCPP_WITH_CMAKE_PACKAGE "Generate and install cmake package files" OFF) -OPTION(BUILD_SHARED_LIBS "Build jsoncpp_lib as a shared library." OFF) -OPTION(BUILD_STATIC_LIBS "Build jsoncpp_lib static library." ON) - -# Ensures that CMAKE_BUILD_TYPE is visible in cmake-gui on Unix -IF(NOT WIN32) - IF(NOT CMAKE_BUILD_TYPE) - SET(CMAKE_BUILD_TYPE Release CACHE STRING - "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage." - FORCE) - ENDIF() -ENDIF() - -# Enable runtime search path support for dynamic libraries on OSX -IF(APPLE) - SET(CMAKE_MACOSX_RPATH 1) -ENDIF() - -# Adhere to GNU filesystem layout conventions -INCLUDE(GNUInstallDirs) - -SET(DEBUG_LIBNAME_SUFFIX "" CACHE STRING "Optional suffix to append to the library name for a debug build") - -# Set variable named ${VAR_NAME} to value ${VALUE} -FUNCTION(set_using_dynamic_name VAR_NAME VALUE) - SET( "${VAR_NAME}" "${VALUE}" PARENT_SCOPE) -ENDFUNCTION() - -# Extract major, minor, patch from version text -# Parse a version string "X.Y.Z" and outputs -# version parts in ${OUPUT_PREFIX}_MAJOR, _MINOR, _PATCH. -# If parse succeeds then ${OUPUT_PREFIX}_FOUND is TRUE. -MACRO(jsoncpp_parse_version VERSION_TEXT OUPUT_PREFIX) - SET(VERSION_REGEX "[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9_]+)?") - IF( ${VERSION_TEXT} MATCHES ${VERSION_REGEX} ) - STRING(REGEX MATCHALL "[0-9]+|-([A-Za-z0-9_]+)" VERSION_PARTS ${VERSION_TEXT}) - LIST(GET VERSION_PARTS 0 ${OUPUT_PREFIX}_MAJOR) - LIST(GET VERSION_PARTS 1 ${OUPUT_PREFIX}_MINOR) - LIST(GET VERSION_PARTS 2 ${OUPUT_PREFIX}_PATCH) - set_using_dynamic_name( "${OUPUT_PREFIX}_FOUND" TRUE ) - ELSE( ${VERSION_TEXT} MATCHES ${VERSION_REGEX} ) - set_using_dynamic_name( "${OUPUT_PREFIX}_FOUND" FALSE ) - ENDIF() -ENDMACRO() - -# Read out version from "version" file -#FILE(STRINGS "version" JSONCPP_VERSION) -#SET( JSONCPP_VERSION_MAJOR X ) -#SET( JSONCPP_VERSION_MINOR Y ) -#SET( JSONCPP_VERSION_PATCH Z ) -SET( JSONCPP_VERSION 1.8.0 ) -jsoncpp_parse_version( ${JSONCPP_VERSION} JSONCPP_VERSION ) -#IF(NOT JSONCPP_VERSION_FOUND) -# MESSAGE(FATAL_ERROR "Failed to parse version string properly. Expect X.Y.Z") -#ENDIF(NOT JSONCPP_VERSION_FOUND) -SET( JSONCPP_SOVERSION 11 ) -SET( JSONCPP_USE_SECURE_MEMORY "0" CACHE STRING "-D...=1 to use memory-wiping allocator for STL" ) - -MESSAGE(STATUS "JsonCpp Version: ${JSONCPP_VERSION_MAJOR}.${JSONCPP_VERSION_MINOR}.${JSONCPP_VERSION_PATCH}") -# File version.h is only regenerated on CMake configure step -CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/src/lib_json/version.h.in" - "${PROJECT_SOURCE_DIR}/include/json/version.h" - NEWLINE_STYLE UNIX ) -CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/version.in" - "${PROJECT_SOURCE_DIR}/version" - NEWLINE_STYLE UNIX ) - -MACRO(UseCompilationWarningAsError) - IF(MSVC) - # Only enabled in debug because some old versions of VS STL generate - # warnings when compiled in release configuration. - SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /WX ") - ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") - IF(JSONCPP_WITH_STRICT_ISO) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic-errors") - ENDIF() - ENDIF() -ENDMACRO() - -# Include our configuration header -INCLUDE_DIRECTORIES( ${jsoncpp_SOURCE_DIR}/include ) - -IF(MSVC) - # Only enabled in debug because some old versions of VS STL generate - # unreachable code warning when compiled in release configuration. - SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W4 ") -ENDIF() - -# Require C++11 support, prefer ISO C++ over GNU variants, -# as relying solely on ISO C++ is more portable. -SET(CMAKE_CXX_STANDARD 11) -SET(CMAKE_CXX_STANDARD_REQUIRED ON) -SET(CMAKE_CXX_EXTENSIONS OFF) - -IF(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - # using regular Clang or AppleClang - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Werror=conversion -Werror=sign-compare") -ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - # using GCC - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Wextra") - # not yet ready for -Wsign-conversion - - IF(JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=conversion -pedantic") - ENDIF() -ELSEIF(CMAKE_CXX_COMPILER_ID STREQUAL "Intel") - # using Intel compiler - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wconversion -Wshadow -Wextra -Werror=conversion") - - IF(JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic") - ENDIF() -ENDIF() - -FIND_PROGRAM(CCACHE_FOUND ccache) -IF(CCACHE_FOUND) - SET_PROPERTY(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) - SET_PROPERTY(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) -ENDIF(CCACHE_FOUND) - -IF(JSONCPP_WITH_WARNING_AS_ERROR) - UseCompilationWarningAsError() -ENDIF() - -IF(JSONCPP_WITH_PKGCONFIG_SUPPORT) - CONFIGURE_FILE( - "pkg-config/jsoncpp.pc.in" - "pkg-config/jsoncpp.pc" - @ONLY) - INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/pkg-config/jsoncpp.pc" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") -ENDIF() - -IF(JSONCPP_WITH_CMAKE_PACKAGE) - INSTALL(EXPORT jsoncpp - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/jsoncpp - FILE jsoncppConfig.cmake) -ENDIF() - -# Build the different applications -ADD_SUBDIRECTORY( src ) - -#install the includes -ADD_SUBDIRECTORY( include ) diff --git a/thirdparty/jsoncpp/LICENSE b/thirdparty/jsoncpp/LICENSE deleted file mode 100644 index ca2bfe1a03..0000000000 --- a/thirdparty/jsoncpp/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -The JsonCpp library's source code, including accompanying documentation, -tests and demonstration applications, are licensed under the following -conditions... - -The author (Baptiste Lepilleur) explicitly disclaims copyright in all -jurisdictions which recognize such a disclaimer. In such jurisdictions, -this software is released into the Public Domain. - -In jurisdictions which do not recognize Public Domain property (e.g. Germany as of -2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is -released under the terms of the MIT License (see below). - -In jurisdictions which recognize Public Domain property, the user of this -software may choose to accept it either as 1) Public Domain, 2) under the -conditions of the MIT License (see below), or 3) under the terms of dual -Public Domain/MIT License conditions described here, as they choose. - -The MIT License is about as close to Public Domain as a license can get, and is -described in clear, concise terms at: - - http://en.wikipedia.org/wiki/MIT_License - -The full text of the MIT License follows: - -======================================================================== -Copyright (c) 2007-2010 Baptiste Lepilleur - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, copy, -modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -======================================================================== -(END LICENSE TEXT) - -The MIT license is compatible with both the GPL and commercial -software, affording one all of the rights of Public Domain with the -minor nuisance of being required to keep the above copyright notice -and license text in the source code. Note also that by accepting the -Public Domain "license" you can re-license your copy using whatever -license you like. diff --git a/thirdparty/jsoncpp/NEWS.txt b/thirdparty/jsoncpp/NEWS.txt deleted file mode 100644 index 5733fcd5ef..0000000000 --- a/thirdparty/jsoncpp/NEWS.txt +++ /dev/null @@ -1,175 +0,0 @@ -New in SVN ----------- - - * Updated the type system's behavior, in order to better support backwards - compatibility with code that was written before 64-bit integer support was - introduced. Here's how it works now: - - * isInt, isInt64, isUInt, and isUInt64 return true if and only if the - value can be exactly represented as that type. In particular, a value - constructed with a double like 17.0 will now return true for all of - these methods. - - * isDouble and isFloat now return true for all numeric values, since all - numeric values can be converted to a double or float without - truncation. Note however that the conversion may not be exact -- for - example, doubles cannot exactly represent all integers above 2^53 + 1. - - * isBool, isNull, isString, isArray, and isObject now return true if and - only if the value is of that type. - - * isConvertibleTo(fooValue) indicates that it is safe to call asFoo. - (For each type foo, isFoo always implies isConvertibleTo(fooValue).) - asFoo returns an approximate or exact representation as appropriate. - For example, a double value may be truncated when asInt is called. - - * For backwards compatibility with old code, isConvertibleTo(intValue) - may return false even if type() == intValue. This is because the value - may have been constructed with a 64-bit integer larger than maxInt, - and calling asInt() would cause an exception. If you're writing new - code, use isInt64 to find out whether the value is exactly - representable using an Int64, or asDouble() combined with minInt64 and - maxInt64 to figure out whether it is approximately representable. - -* Value - - Patch #10: BOOST_FOREACH compatibility. Made Json::iterator more - standard compliant, added missing iterator_category and value_type - typedefs (contribued by Robert A. Iannucci). - -* Compilation - - - New CMake based build system. Based in part on contribution from - Igor Okulist and Damien Buhl (Patch #14). - - - New header json/version.h now contains version number macros - (JSONCPP_VERSION_MAJOR, JSONCPP_VERSION_MINOR, JSONCPP_VERSION_PATCH - and JSONCPP_VERSION_HEXA). - - - Patch #11: added missing JSON_API on some classes causing link issues - when building as a dynamic library on Windows - (contributed by Francis Bolduc). - - - Visual Studio DLL: suppressed warning "C4251: : - needs to have dll-interface to be used by..." via pragma push/pop - in json-cpp headers. - - - Added Travis CI intregration: https://travis-ci.org/blep/jsoncpp-mirror - -* Bug fixes - - Patch #15: Copy constructor does not initialize allocated_ for stringValue - (contributed by rmongia). - - - Patch #16: Missing field copy in Json::Value::iterator causing infinite - loop when using experimental internal map (#define JSON_VALUE_USE_INTERNAL_MAP) - (contributed by Ming-Lin Kao). - - - New in JsonCpp 0.6.0: - --------------------- - -* Compilation - - - LD_LIBRARY_PATH and LIBRARY_PATH environment variables are now - propagated to the build environment as this is required for some - compiler installation. - - - Added support for Microsoft Visual Studio 2008 (bug #2930462): - The platform "msvc90" has been added. - - Notes: you need to setup the environment by running vcvars32.bat - (e.g. MSVC 2008 command prompt in start menu) before running scons. - - - Added support for amalgamated source and header generation (a la sqlite). - Refer to README.md section "Generating amalgamated source and header" - for detail. - -* Value - - - Removed experimental ValueAllocator, it caused static - initialization/destruction order issues (bug #2934500). - The DefaultValueAllocator has been inlined in code. - - - Added support for 64 bits integer: - - Types Json::Int64 and Json::UInt64 have been added. They are aliased - to 64 bits integers on system that support them (based on __int64 on - Microsoft Visual Studio platform, and long long on other platforms). - - Types Json::LargestInt and Json::LargestUInt have been added. They are - aliased to the largest integer type supported: - either Json::Int/Json::UInt or Json::Int64/Json::UInt64 respectively. - - Json::Value::asInt() and Json::Value::asUInt() still returns plain - "int" based types, but asserts if an attempt is made to retrieve - a 64 bits value that can not represented as the return type. - - Json::Value::asInt64() and Json::Value::asUInt64() have been added - to obtain the 64 bits integer value. - - Json::Value::asLargestInt() and Json::Value::asLargestUInt() returns - the integer as a LargestInt/LargestUInt respectively. Those functions - functions are typically used when implementing writer. - - The reader attempts to read number as 64 bits integer, and fall back - to reading a double if the number is not in the range of 64 bits - integer. - - Warning: Json::Value::asInt() and Json::Value::asUInt() now returns - long long. This changes break code that was passing the return value - to *printf() function. - - Support for 64 bits integer can be disabled by defining the macro - JSON_NO_INT64 (uncomment it in json/config.h for example), though - it should have no impact on existing usage. - - - The type Json::ArrayIndex is used for indexes of a JSON value array. It - is an unsigned int (typically 32 bits). - - - Array index can be passed as int to operator[], allowing use of literal: - Json::Value array; - array.append( 1234 ); - int value = array[0].asInt(); // did not compile previously - - - Added float Json::Value::asFloat() to obtain a floating point value as a - float (avoid lost of precision warning caused by used of asDouble() - to initialize a float). - -* Reader - - - Renamed Reader::getFormatedErrorMessages() to getFormattedErrorMessages. - Bug #3023708 (Formatted has 2 't'). The old member function is deprecated - but still present for backward compatibility. - -* Tests - - - Added test to ensure that the escape sequence "\/" is corrected handled - by the parser. - -* Bug fixes - - - Bug #3139677: JSON [1 2 3] was incorrectly parsed as [1, 3]. Error is now - correctly detected. - - - Bug #3139678: stack buffer overflow when parsing a double with a - length of 32 characters. - - - Fixed Value::operator <= implementation (had the semantic of operator >=). - Found when adding unit tests for comparison operators. - - - Value::compare() is now const and has an actual implementation with - unit tests. - - - Bug #2407932: strpbrk() can fail for NULL pointer. - - - Bug #3306345: Fixed minor typo in Path::resolve(). - - - Bug #3314841/#3306896: errors in amalgamate.py - - - Fixed some Coverity warnings and line-endings. - -* License - - - See file LICENSE for details. Basically JsonCpp is now licensed under - MIT license, or public domain if desired and recognized in your jurisdiction. - Thanks to Stephan G. Beal [http://wanderinghorse.net/home/stephan/]) who - helped figuring out the solution to the public domain issue. diff --git a/thirdparty/jsoncpp/README.md b/thirdparty/jsoncpp/README.md deleted file mode 100644 index 038ccd2f78..0000000000 --- a/thirdparty/jsoncpp/README.md +++ /dev/null @@ -1,225 +0,0 @@ -# JsonCpp - -[JSON][json-org] is a lightweight data-interchange format. It can represent -numbers, strings, ordered sequences of values, and collections of name/value -pairs. - -[json-org]: http://json.org/ - -JsonCpp is a C++ library that allows manipulating JSON values, including -serialization and deserialization to and from strings. It can also preserve -existing comment in unserialization/serialization steps, making it a convenient -format to store user input files. - - -## Documentation - -[JsonCpp documentation][JsonCpp-documentation] is generated using [Doxygen][]. - -[JsonCpp-documentation]: http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html -[Doxygen]: http://www.doxygen.org - - -## A note on backward-compatibility - -* `1.y.z` is built with C++11. -* `0.y.z` can be used with older compilers. -* Major versions maintain binary-compatibility. - - -## Using JsonCpp in your project - -The recommended approach to integrating JsonCpp in your project is to include -the [amalgamated source](#generating-amalgamated-source-and-header) (a single -`.cpp` file and two `.h` files) in your project, and compile and build as you -would any other source file. This ensures consistency of compilation flags and -ABI compatibility, issues which arise when building shared or static -libraries. See the next section for instructions. - -The `include/` should be added to your compiler include path. JsonCpp headers -should be included as follow: - - #include - -If JsonCpp was built as a dynamic library on Windows, then your project needs to define the macro `JSON_DLL`. - -### Generating amalgamated source and header - -JsonCpp is provided with a script to generate a single header and a single -source file to ease inclusion into an existing project. The amalgamated source -can be generated at any time by running the following command from the -top-directory (this requires Python 2.6): - - python amalgamate.py - -It is possible to specify header name. See the `-h` option for detail. - -By default, the following files are generated: - -* `dist/jsoncpp.cpp`: source file that needs to be added to your project. -* `dist/json/json.h`: corresponding header file for use in your project. It is - equivalent to including `json/json.h` in non-amalgamated source. This header - only depends on standard headers. -* `dist/json/json-forwards.h`: header that provides forward declaration of all - JsonCpp types. - -The amalgamated sources are generated by concatenating JsonCpp source in the -correct order and defining the macro `JSON_IS_AMALGAMATION` to prevent inclusion of other headers. - - -## Contributing to JsonCpp - -### Building and testing with CMake - -[CMake][] is a C++ Makefiles/Solution generator. It is usually available on most Linux system as package. On Ubuntu: - - sudo apt-get install cmake - -[CMake]: http://www.cmake.org - -Note that Python is also required to run the JSON reader/writer tests. If -missing, the build will skip running those tests. - -When running CMake, a few parameters are required: - -* A build directory where the makefiles/solution are generated. It is also used - to store objects, libraries and executables files. -* The generator to use: makefiles or Visual Studio solution? What version or - Visual Studio, 32 or 64 bits solution? - -Steps for generating solution/makefiles using `cmake-gui`: - -* Make "source code" point to the source directory. -* Make "where to build the binary" point to the directory to use for the build. -* Click on the "Grouped" check box. -* Review JsonCpp build options (tick `BUILD_SHARED_LIBS` to build as a - dynamic library). -* Click the configure button at the bottom, then the generate button. -* The generated solution/makefiles can be found in the binary directory. - -Alternatively, from the command-line on Unix in the source directory: - - mkdir -p build/debug - cd build/debug - cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../.. - make - -For a good pkg-config file, add: - - -DCMAKE_INSTALL_INCLUDEDIR=include/jsoncpp - -Running `cmake -h` will display the list of available generators (passed using -the `-G` option). - -By default CMake hides compilation commands. This can be modified by specifying -`-DCMAKE_VERBOSE_MAKEFILE=true` when generating makefiles. - -### Building and testing with SCons - -**Note:** The SCons-based build system is deprecated. Please use CMake (see the -section above). - -JsonCpp can use [Scons][] as a build system. Note that SCons requires Python to -be installed. - -[SCons]: http://www.scons.org/ - -Invoke SCons as follows: - - scons platform=$PLATFORM [TARGET] - -where `$PLATFORM` may be one of: - -* `suncc`: Sun C++ (Solaris) -* `vacpp`: Visual Age C++ (AIX) -* `mingw` -* `msvc6`: Microsoft Visual Studio 6 service pack 5-6 -* `msvc70`: Microsoft Visual Studio 2002 -* `msvc71`: Microsoft Visual Studio 2003 -* `msvc80`: Microsoft Visual Studio 2005 -* `msvc90`: Microsoft Visual Studio 2008 -* `linux-gcc`: Gnu C++ (linux, also reported to work for Mac OS X) - -If you are building with Microsoft Visual Studio 2008, you need to set up the -environment by running `vcvars32.bat` (e.g. MSVC 2008 command prompt) before -running SCons. - -### Running the tests manually - -You need to run tests manually only if you are troubleshooting an issue. - -In the instructions below, replace `path/to/jsontest` with the path of the -`jsontest` executable that was compiled on your platform. - - cd test - # This will run the Reader/Writer tests - python runjsontests.py path/to/jsontest - - # This will run the Reader/Writer tests, using JSONChecker test suite - # (http://www.json.org/JSON_checker/). - # Notes: not all tests pass: JsonCpp is too lenient (for example, - # it allows an integer to start with '0'). The goal is to improve - # strict mode parsing to get all tests to pass. - python runjsontests.py --with-json-checker path/to/jsontest - - # This will run the unit tests (mostly Value) - python rununittests.py path/to/test_lib_json - - # You can run the tests using valgrind: - python rununittests.py --valgrind path/to/test_lib_json - -### Running the tests using SCons - -Note that tests can be run using SCons using the `check` target: - - scons platform=$PLATFORM check - -### Building the documentation - -Run the Python script `doxybuild.py` from the top directory: - - python doxybuild.py --doxygen=$(which doxygen) --open --with-dot - -See `doxybuild.py --help` for options. - -### Adding a reader/writer test - -To add a test, you need to create two files in test/data: - -* a `TESTNAME.json` file, that contains the input document in JSON format. -* a `TESTNAME.expected` file, that contains a flatened representation of the - input document. - -The `TESTNAME.expected` file format is as follows: - -* Each line represents a JSON element of the element tree represented by the - input document. -* Each line has two parts: the path to access the element separated from the - element value by `=`. Array and object values are always empty (i.e. - represented by either `[]` or `{}`). -* Element path `.` represents the root element, and is used to separate object - members. `[N]` is used to specify the value of an array element at index `N`. - -See the examples `test_complex_01.json` and `test_complex_01.expected` to better understand element paths. - -### Understanding reader/writer test output - -When a test is run, output files are generated beside the input test files. Below is a short description of the content of each file: - -* `test_complex_01.json`: input JSON document. -* `test_complex_01.expected`: flattened JSON element tree used to check if - parsing was corrected. -* `test_complex_01.actual`: flattened JSON element tree produced by `jsontest` - from reading `test_complex_01.json`. -* `test_complex_01.rewrite`: JSON document written by `jsontest` using the - `Json::Value` parsed from `test_complex_01.json` and serialized using - `Json::StyledWritter`. -* `test_complex_01.actual-rewrite`: flattened JSON element tree produced by - `jsontest` from reading `test_complex_01.rewrite`. -* `test_complex_01.process-output`: `jsontest` output, typically useful for - understanding parsing errors. - -## License - -See the `LICENSE` file for details. In summary, JsonCpp is licensed under the -MIT license, or public domain if desired and recognized in your jurisdiction. diff --git a/thirdparty/jsoncpp/SConstruct b/thirdparty/jsoncpp/SConstruct deleted file mode 100644 index f3a73f773b..0000000000 --- a/thirdparty/jsoncpp/SConstruct +++ /dev/null @@ -1,248 +0,0 @@ -""" -Notes: -- shared library support is buggy: it assumes that a static and dynamic library can be build from the same object files. This is not true on many platforms. For this reason it is only enabled on linux-gcc at the current time. - -To add a platform: -- add its name in options allowed_values below -- add tool initialization for this platform. Search for "if platform == 'suncc'" as an example. -""" - -import os -import os.path -import sys - -JSONCPP_VERSION = open(File('#version').abspath,'rt').read().strip() -DIST_DIR = '#dist' - -options = Variables() -options.Add( EnumVariable('platform', - 'Platform (compiler/stl) used to build the project', - 'msvc71', - allowed_values='suncc vacpp mingw msvc6 msvc7 msvc71 msvc80 msvc90 linux-gcc'.split(), - ignorecase=2) ) - -try: - platform = ARGUMENTS['platform'] - if platform == 'linux-gcc': - CXX = 'g++' # not quite right, but env is not yet available. - import commands - version = commands.getoutput('%s -dumpversion' %CXX) - platform = 'linux-gcc-%s' %version - print "Using platform '%s'" %platform - LD_LIBRARY_PATH = os.environ.get('LD_LIBRARY_PATH', '') - LD_LIBRARY_PATH = "%s:libs/%s" %(LD_LIBRARY_PATH, platform) - os.environ['LD_LIBRARY_PATH'] = LD_LIBRARY_PATH - print "LD_LIBRARY_PATH =", LD_LIBRARY_PATH -except KeyError: - print 'You must specify a "platform"' - sys.exit(2) - -print "Building using PLATFORM =", platform - -rootbuild_dir = Dir('#buildscons') -build_dir = os.path.join( '#buildscons', platform ) -bin_dir = os.path.join( '#bin', platform ) -lib_dir = os.path.join( '#libs', platform ) -sconsign_dir_path = Dir(build_dir).abspath -sconsign_path = os.path.join( sconsign_dir_path, '.sconsign.dbm' ) - -# Ensure build directory exist (SConsignFile fail otherwise!) -if not os.path.exists( sconsign_dir_path ): - os.makedirs( sconsign_dir_path ) - -# Store all dependencies signature in a database -SConsignFile( sconsign_path ) - -def make_environ_vars(): - """Returns a dictionnary with environment variable to use when compiling.""" - # PATH is required to find the compiler - # TEMP is required for at least mingw - # LD_LIBRARY_PATH & co is required on some system for the compiler - vars = {} - for name in ('PATH', 'TEMP', 'TMP', 'LD_LIBRARY_PATH', 'LIBRARY_PATH'): - if name in os.environ: - vars[name] = os.environ[name] - return vars - - -env = Environment( ENV = make_environ_vars(), - toolpath = ['scons-tools'], - tools=[] ) #, tools=['default'] ) - -if platform == 'suncc': - env.Tool( 'sunc++' ) - env.Tool( 'sunlink' ) - env.Tool( 'sunar' ) - env.Append( CCFLAGS = ['-mt'] ) -elif platform == 'vacpp': - env.Tool( 'default' ) - env.Tool( 'aixcc' ) - env['CXX'] = 'xlC_r' #scons does not pick-up the correct one ! - # using xlC_r ensure multi-threading is enabled: - # http://publib.boulder.ibm.com/infocenter/pseries/index.jsp?topic=/com.ibm.vacpp7a.doc/compiler/ref/cuselect.htm - env.Append( CCFLAGS = '-qrtti=all', - LINKFLAGS='-bh:5' ) # -bh:5 remove duplicate symbol warning -elif platform == 'msvc6': - env['MSVS_VERSION']='6.0' - for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']: - env.Tool( tool ) - env['CXXFLAGS']='-GR -GX /nologo /MT' -elif platform == 'msvc70': - env['MSVS_VERSION']='7.0' - for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']: - env.Tool( tool ) - env['CXXFLAGS']='-GR -GX /nologo /MT' -elif platform == 'msvc71': - env['MSVS_VERSION']='7.1' - for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']: - env.Tool( tool ) - env['CXXFLAGS']='-GR -GX /nologo /MT' -elif platform == 'msvc80': - env['MSVS_VERSION']='8.0' - for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']: - env.Tool( tool ) - env['CXXFLAGS']='-GR -EHsc /nologo /MT' -elif platform == 'msvc90': - env['MSVS_VERSION']='9.0' - # Scons 1.2 fails to detect the correct location of the platform SDK. - # So we propagate those from the environment. This requires that the - # user run vcvars32.bat before compiling. - if 'INCLUDE' in os.environ: - env['ENV']['INCLUDE'] = os.environ['INCLUDE'] - if 'LIB' in os.environ: - env['ENV']['LIB'] = os.environ['LIB'] - for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']: - env.Tool( tool ) - env['CXXFLAGS']='-GR -EHsc /nologo /MT' -elif platform == 'mingw': - env.Tool( 'mingw' ) - env.Append( CPPDEFINES=[ "WIN32", "NDEBUG", "_MT" ] ) -elif platform.startswith('linux-gcc'): - env.Tool( 'default' ) - env.Append( LIBS = ['pthread'], CCFLAGS = os.environ.get("CXXFLAGS", "-Wall"), LINKFLAGS=os.environ.get("LDFLAGS", "") ) - env['SHARED_LIB_ENABLED'] = True -else: - print "UNSUPPORTED PLATFORM." - env.Exit(1) - -env.Tool('targz') -env.Tool('srcdist') -env.Tool('globtool') - -env.Append( CPPPATH = ['#include'], - LIBPATH = lib_dir ) -short_platform = platform -if short_platform.startswith('msvc'): - short_platform = short_platform[2:] -# Notes: on Windows you need to rebuild the source for each variant -# Build script does not support that yet so we only build static libraries. -# This also fails on AIX because both dynamic and static library ends with -# extension .a. -env['SHARED_LIB_ENABLED'] = env.get('SHARED_LIB_ENABLED', False) -env['LIB_PLATFORM'] = short_platform -env['LIB_LINK_TYPE'] = 'lib' # static -env['LIB_CRUNTIME'] = 'mt' -env['LIB_NAME_SUFFIX'] = '${LIB_PLATFORM}_${LIB_LINK_TYPE}${LIB_CRUNTIME}' # must match autolink naming convention -env['JSONCPP_VERSION'] = JSONCPP_VERSION -env['BUILD_DIR'] = env.Dir(build_dir) -env['ROOTBUILD_DIR'] = env.Dir(rootbuild_dir) -env['DIST_DIR'] = DIST_DIR -if 'TarGz' in env['BUILDERS']: - class SrcDistAdder: - def __init__( self, env ): - self.env = env - def __call__( self, *args, **kw ): - apply( self.env.SrcDist, (self.env['SRCDIST_TARGET'],) + args, kw ) - env['SRCDIST_BUILDER'] = env.TarGz -else: # If tarfile module is missing - class SrcDistAdder: - def __init__( self, env ): - pass - def __call__( self, *args, **kw ): - pass -env['SRCDIST_ADD'] = SrcDistAdder( env ) -env['SRCDIST_TARGET'] = os.path.join( DIST_DIR, 'jsoncpp-src-%s.tar.gz' % env['JSONCPP_VERSION'] ) - -env_testing = env.Clone( ) -env_testing.Append( LIBS = ['json_${LIB_NAME_SUFFIX}'] ) - -def buildJSONExample( env, target_sources, target_name ): - env = env.Clone() - env.Append( CPPPATH = ['#'] ) - exe = env.Program( target=target_name, - source=target_sources ) - env['SRCDIST_ADD']( source=[target_sources] ) - global bin_dir - return env.Install( bin_dir, exe ) - -def buildJSONTests( env, target_sources, target_name ): - jsontests_node = buildJSONExample( env, target_sources, target_name ) - check_alias_target = env.Alias( 'check', jsontests_node, RunJSONTests( jsontests_node, jsontests_node ) ) - env.AlwaysBuild( check_alias_target ) - -def buildUnitTests( env, target_sources, target_name ): - jsontests_node = buildJSONExample( env, target_sources, target_name ) - check_alias_target = env.Alias( 'check', jsontests_node, - RunUnitTests( jsontests_node, jsontests_node ) ) - env.AlwaysBuild( check_alias_target ) - -def buildLibrary( env, target_sources, target_name ): - static_lib = env.StaticLibrary( target=target_name + '_${LIB_NAME_SUFFIX}', - source=target_sources ) - global lib_dir - env.Install( lib_dir, static_lib ) - if env['SHARED_LIB_ENABLED']: - shared_lib = env.SharedLibrary( target=target_name + '_${LIB_NAME_SUFFIX}', - source=target_sources ) - env.Install( lib_dir, shared_lib ) - env['SRCDIST_ADD']( source=[target_sources] ) - -Export( 'env env_testing buildJSONExample buildLibrary buildJSONTests buildUnitTests' ) - -def buildProjectInDirectory( target_directory ): - global build_dir - target_build_dir = os.path.join( build_dir, target_directory ) - target = os.path.join( target_directory, 'sconscript' ) - SConscript( target, build_dir=target_build_dir, duplicate=0 ) - env['SRCDIST_ADD']( source=[target] ) - - -def runJSONTests_action( target, source = None, env = None ): - # Add test scripts to python path - jsontest_path = Dir( '#test' ).abspath - sys.path.insert( 0, jsontest_path ) - data_path = os.path.join( jsontest_path, 'data' ) - import runjsontests - return runjsontests.runAllTests( os.path.abspath(source[0].path), data_path ) - -def runJSONTests_string( target, source = None, env = None ): - return 'RunJSONTests("%s")' % source[0] - -import SCons.Action -ActionFactory = SCons.Action.ActionFactory -RunJSONTests = ActionFactory(runJSONTests_action, runJSONTests_string ) - -def runUnitTests_action( target, source = None, env = None ): - # Add test scripts to python path - jsontest_path = Dir( '#test' ).abspath - sys.path.insert( 0, jsontest_path ) - import rununittests - return rununittests.runAllTests( os.path.abspath(source[0].path) ) - -def runUnitTests_string( target, source = None, env = None ): - return 'RunUnitTests("%s")' % source[0] - -RunUnitTests = ActionFactory(runUnitTests_action, runUnitTests_string ) - -env.Alias( 'check' ) - -srcdist_cmd = env['SRCDIST_ADD']( source = """ - AUTHORS README.md SConstruct - """.split() ) -env.Alias( 'src-dist', srcdist_cmd ) - -buildProjectInDirectory( 'src/jsontestrunner' ) -buildProjectInDirectory( 'src/lib_json' ) -buildProjectInDirectory( 'src/test_lib_json' ) -#print env.Dump() - diff --git a/thirdparty/jsoncpp/amalgamate.py b/thirdparty/jsoncpp/amalgamate.py deleted file mode 100644 index 9cb2d08ccd..0000000000 --- a/thirdparty/jsoncpp/amalgamate.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Amalgate json-cpp library sources into a single source and header file. - -Works with python2.6+ and python3.4+. - -Example of invocation (must be invoked from json-cpp top directory): -python amalgate.py -""" -import os -import os.path -import sys - -class AmalgamationFile: - def __init__(self, top_dir): - self.top_dir = top_dir - self.blocks = [] - - def add_text(self, text): - if not text.endswith("\n"): - text += "\n" - self.blocks.append(text) - - def add_file(self, relative_input_path, wrap_in_comment=False): - def add_marker(prefix): - self.add_text("") - self.add_text("// " + "/"*70) - self.add_text("// %s of content of file: %s" % (prefix, relative_input_path.replace("\\","/"))) - self.add_text("// " + "/"*70) - self.add_text("") - add_marker("Beginning") - f = open(os.path.join(self.top_dir, relative_input_path), "rt") - content = f.read() - if wrap_in_comment: - content = "/*\n" + content + "\n*/" - self.add_text(content) - f.close() - add_marker("End") - self.add_text("\n\n\n\n") - - def get_value(self): - return "".join(self.blocks).replace("\r\n","\n") - - def write_to(self, output_path): - output_dir = os.path.dirname(output_path) - if output_dir and not os.path.isdir(output_dir): - os.makedirs(output_dir) - f = open(output_path, "wb") - f.write(str.encode(self.get_value(), 'UTF-8')) - f.close() - -def amalgamate_source(source_top_dir=None, - target_source_path=None, - header_include_path=None): - """Produces amalgated source. - Parameters: - source_top_dir: top-directory - target_source_path: output .cpp path - header_include_path: generated header path relative to target_source_path. - """ - print("Amalgating header...") - header = AmalgamationFile(source_top_dir) - header.add_text("/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).") - header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) - header.add_file("LICENSE", wrap_in_comment=True) - header.add_text("#ifndef JSON_AMALGATED_H_INCLUDED") - header.add_text("# define JSON_AMALGATED_H_INCLUDED") - header.add_text("/// If defined, indicates that the source file is amalgated") - header.add_text("/// to prevent private header inclusion.") - header.add_text("#define JSON_IS_AMALGAMATION") - header.add_file("include/json/version.h") - #header.add_file("include/json/allocator.h") # Not available here. - header.add_file("include/json/config.h") - header.add_file("include/json/forwards.h") - header.add_file("include/json/features.h") - header.add_file("include/json/value.h") - header.add_file("include/json/reader.h") - header.add_file("include/json/writer.h") - header.add_file("include/json/assertions.h") - header.add_text("#endif //ifndef JSON_AMALGATED_H_INCLUDED") - - target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) - print("Writing amalgated header to %r" % target_header_path) - header.write_to(target_header_path) - - base, ext = os.path.splitext(header_include_path) - forward_header_include_path = base + "-forwards" + ext - print("Amalgating forward header...") - header = AmalgamationFile(source_top_dir) - header.add_text("/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).") - header.add_text('/// It is intended to be used with #include "%s"' % forward_header_include_path) - header.add_text("/// This header provides forward declaration for all JsonCpp types.") - header.add_file("LICENSE", wrap_in_comment=True) - header.add_text("#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED") - header.add_text("# define JSON_FORWARD_AMALGATED_H_INCLUDED") - header.add_text("/// If defined, indicates that the source file is amalgated") - header.add_text("/// to prevent private header inclusion.") - header.add_text("#define JSON_IS_AMALGAMATION") - header.add_file("include/json/config.h") - header.add_file("include/json/forwards.h") - header.add_text("#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED") - - target_forward_header_path = os.path.join(os.path.dirname(target_source_path), - forward_header_include_path) - print("Writing amalgated forward header to %r" % target_forward_header_path) - header.write_to(target_forward_header_path) - - print("Amalgating source...") - source = AmalgamationFile(source_top_dir) - source.add_text("/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).") - source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) - source.add_file("LICENSE", wrap_in_comment=True) - source.add_text("") - source.add_text('#include "%s"' % header_include_path) - source.add_text(""" -#ifndef JSON_IS_AMALGAMATION -#error "Compile with -I PATH_TO_JSON_DIRECTORY" -#endif -""") - source.add_text("") - lib_json = "src/lib_json" - source.add_file(os.path.join(lib_json, "json_tool.h")) - source.add_file(os.path.join(lib_json, "json_reader.cpp")) - source.add_file(os.path.join(lib_json, "json_valueiterator.inl")) - source.add_file(os.path.join(lib_json, "json_value.cpp")) - source.add_file(os.path.join(lib_json, "json_writer.cpp")) - - print("Writing amalgated source to %r" % target_source_path) - source.write_to(target_source_path) - -def main(): - usage = """%prog [options] -Generate a single amalgated source and header file from the sources. -""" - from optparse import OptionParser - parser = OptionParser(usage=usage) - parser.allow_interspersed_args = False - parser.add_option("-s", "--source", dest="target_source_path", action="store", default="dist/jsoncpp.cpp", - help="""Output .cpp source path. [Default: %default]""") - parser.add_option("-i", "--include", dest="header_include_path", action="store", default="json/json.h", - help="""Header include path. Used to include the header from the amalgated source file. [Default: %default]""") - parser.add_option("-t", "--top-dir", dest="top_dir", action="store", default=os.getcwd(), - help="""Source top-directory. [Default: %default]""") - parser.enable_interspersed_args() - options, args = parser.parse_args() - - msg = amalgamate_source(source_top_dir=options.top_dir, - target_source_path=options.target_source_path, - header_include_path=options.header_include_path) - if msg: - sys.stderr.write(msg + "\n") - sys.exit(1) - else: - print("Source succesfully amalagated") - -if __name__ == "__main__": - main() diff --git a/thirdparty/jsoncpp/appveyor.yml b/thirdparty/jsoncpp/appveyor.yml deleted file mode 100644 index f4966a34d6..0000000000 --- a/thirdparty/jsoncpp/appveyor.yml +++ /dev/null @@ -1,35 +0,0 @@ -# This is a comment. - -version: build.{build} - -os: Windows Server 2012 R2 - -clone_folder: c:\projects\jsoncpp - -platform: - - Win32 - - x64 - -configuration: - - Debug - - Release - -# scripts to run before build -before_build: - - echo "Running cmake..." - - cd c:\projects\jsoncpp - - cmake --version - - set PATH=C:\Program Files (x86)\MSBuild\14.0\Bin;%PATH% - - if %PLATFORM% == Win32 cmake . - - if %PLATFORM% == x64 cmake -G "Visual Studio 12 2013 Win64" . - -build: - project: jsoncpp.sln # path to Visual Studio solution or project - -deploy: - provider: GitHub - auth_token: - secure: K2Tp1q8pIZ7rs0Ot24ZMWuwr12Ev6Tc6QkhMjGQxoQG3ng1pXtgPasiJ45IDXGdg - on: - branch: master - appveyor_repo_tag: true diff --git a/thirdparty/jsoncpp/dev.makefile b/thirdparty/jsoncpp/dev.makefile deleted file mode 100644 index d288b16658..0000000000 --- a/thirdparty/jsoncpp/dev.makefile +++ /dev/null @@ -1,35 +0,0 @@ -# This is only for jsoncpp developers/contributors. -# We use this to sign releases, generate documentation, etc. -VER?=$(shell cat version) - -default: - @echo "VER=${VER}" -sign: jsoncpp-${VER}.tar.gz - gpg --armor --detach-sign $< - gpg --verify $<.asc - # Then upload .asc to the release. -jsoncpp-%.tar.gz: - curl https://github.com/open-source-parsers/jsoncpp/archive/$*.tar.gz -o $@ -dox: - python doxybuild.py --doxygen=$$(which doxygen) --in doc/web_doxyfile.in - rsync -va --delete dist/doxygen/jsoncpp-api-html-${VER}/ ../jsoncpp-docs/doxygen/ - # Then 'git add -A' and 'git push' in jsoncpp-docs. -build: - mkdir -p build/debug - cd build/debug; cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_SHARED_LIBS=ON -G "Unix Makefiles" ../.. - make -C build/debug - -# Currently, this depends on include/json/version.h generated -# by cmake. -test-amalgamate: - python2.7 amalgamate.py - python3.4 amalgamate.py - cd dist; gcc -I. -c jsoncpp.cpp - -valgrind: - valgrind --error-exitcode=42 --leak-check=full ./build/debug/src/test_lib_json/jsoncpp_test - -clean: - \rm -rf *.gz *.asc dist/ - -.PHONY: build diff --git a/thirdparty/jsoncpp/doc/footer.html b/thirdparty/jsoncpp/doc/footer.html deleted file mode 100644 index c83e5bcc0e..0000000000 --- a/thirdparty/jsoncpp/doc/footer.html +++ /dev/null @@ -1,3 +0,0 @@ -
- - diff --git a/thirdparty/jsoncpp/doc/header.html b/thirdparty/jsoncpp/doc/header.html deleted file mode 100644 index 4b2a5e9219..0000000000 --- a/thirdparty/jsoncpp/doc/header.html +++ /dev/null @@ -1,24 +0,0 @@ - - - -JsonCpp - JSON data format manipulation library - - - - - - - - - - - -
- - JsonCpp project page - - - JsonCpp home page -
- -
diff --git a/thirdparty/jsoncpp/doc/jsoncpp.dox b/thirdparty/jsoncpp/doc/jsoncpp.dox deleted file mode 100644 index 47efc8a357..0000000000 --- a/thirdparty/jsoncpp/doc/jsoncpp.dox +++ /dev/null @@ -1,164 +0,0 @@ -/** -\mainpage -\section _intro Introduction - -JSON (JavaScript Object Notation) - is a lightweight data-interchange format. - -Here is an example of JSON data: -\verbatim -{ - "encoding" : "UTF-8", - "plug-ins" : [ - "python", - "c++", - "ruby" - ], - "indent" : { "length" : 3, "use_space": true } -} -\endverbatim -JsonCpp supports comments as meta-data: -\code -// Configuration options -{ - // Default encoding for text - "encoding" : "UTF-8", - - // Plug-ins loaded at start-up - "plug-ins" : [ - "python", - "c++", // trailing comment - "ruby" - ], - - // Tab indent size - // (multi-line comment) - "indent" : { /*embedded comment*/ "length" : 3, "use_space": true } -} -\endcode - -\section _features Features -- read and write JSON document -- attach C++ style comments to element during parsing -- rewrite JSON document preserving original comments - -Notes: Comments used to be supported in JSON but were removed for -portability (C like comments are not supported in Python). Since -comments are useful in configuration/input file, this feature was -preserved. - -\section _example Code example - -\code -Json::Value root; // 'root' will contain the root value after parsing. -std::cin >> root; - -// You can also read into a particular sub-value. -std::cin >> root["subtree"]; - -// Get the value of the member of root named 'encoding', -// and return 'UTF-8' if there is no such member. -std::string encoding = root.get("encoding", "UTF-8" ).asString(); - -// Get the value of the member of root named 'plug-ins'; return a 'null' value if -// there is no such member. -const Json::Value plugins = root["plug-ins"]; - -// Iterate over the sequence elements. -for ( int index = 0; index < plugins.size(); ++index ) - loadPlugIn( plugins[index].asString() ); - -// Try other datatypes. Some are auto-convertible to others. -foo::setIndentLength( root["indent"].get("length", 3).asInt() ); -foo::setIndentUseSpace( root["indent"].get("use_space", true).asBool() ); - -// Since Json::Value has an implicit constructor for all value types, it is not -// necessary to explicitly construct the Json::Value object. -root["encoding"] = foo::getCurrentEncoding(); -root["indent"]["length"] = foo::getCurrentIndentLength(); -root["indent"]["use_space"] = foo::getCurrentIndentUseSpace(); - -// If you like the defaults, you can insert directly into a stream. -std::cout << root; -// Of course, you can write to `std::ostringstream` if you prefer. - -// If desired, remember to add a linefeed and flush. -std::cout << std::endl; -\endcode - -\section _advanced Advanced usage - -Configure *builders* to create *readers* and *writers*. For -configuration, we use our own `Json::Value` (rather than -standard setters/getters) so that we can add -features without losing binary-compatibility. - -\code -// For convenience, use `writeString()` with a specialized builder. -Json::StreamWriterBuilder wbuilder; -wbuilder["indentation"] = "\t"; -std::string document = Json::writeString(wbuilder, root); - -// Here, using a specialized Builder, we discard comments and -// record errors as we parse. -Json::CharReaderBuilder rbuilder; -rbuilder["collectComments"] = false; -std::string errs; -bool ok = Json::parseFromStream(rbuilder, std::cin, &root, &errs); -\endcode - -Yes, compile-time configuration-checking would be helpful, -but `Json::Value` lets you -write and read the builder configuration, which is better! In other words, -you can configure your JSON parser using JSON. - -CharReaders and StreamWriters are not thread-safe, but they are re-usable. -\code -Json::CharReaderBuilder rbuilder; -cfg >> rbuilder.settings_; -std::unique_ptr const reader(rbuilder.newCharReader()); -reader->parse(start, stop, &value1, &errs); -// ... -reader->parse(start, stop, &value2, &errs); -// etc. -\endcode - -\section _pbuild Build instructions -The build instructions are located in the file -README.md in the top-directory of the project. - -The latest version of the source is available in the project's GitHub repository: - -jsoncpp - -\section _news What's New? -The description of latest changes can be found in - - the NEWS wiki -. - -\section _rlinks Related links -- JSON Specification and alternate language implementations. -- YAML A data format designed for human readability. -- UTF-8 and Unicode FAQ. - -\section _plinks Old project links -- https://sourceforge.net/projects/jsoncpp/ -- http://jsoncpp.sourceforge.net -- http://sourceforge.net/projects/jsoncpp/files/ -- http://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/trunk/ -- http://jsoncpp.sourceforge.net/old.html - -\section _license License -See file LICENSE in the top-directory of the project. - -Basically JsonCpp is licensed under MIT license, or public domain if desired -and recognized in your jurisdiction. - -\author Baptiste Lepilleur (originator) -\author Christopher Dunn (primary maintainer) -\version \include version -We make strong guarantees about binary-compatibility, consistent with -the Apache versioning scheme. -\sa version.h -*/ diff --git a/thirdparty/jsoncpp/doc/readme.txt b/thirdparty/jsoncpp/doc/readme.txt deleted file mode 100644 index 0e42cdfb4c..0000000000 --- a/thirdparty/jsoncpp/doc/readme.txt +++ /dev/null @@ -1 +0,0 @@ -The documentation is generated using doxygen (http://www.doxygen.org). diff --git a/thirdparty/jsoncpp/doc/roadmap.dox b/thirdparty/jsoncpp/doc/roadmap.dox deleted file mode 100644 index 12294bbbd2..0000000000 --- a/thirdparty/jsoncpp/doc/roadmap.dox +++ /dev/null @@ -1,3 +0,0 @@ -/*! \page roadmap JsonCpp roadmap - Moved to: https://github.com/open-source-parsers/jsoncpp/wiki/Roadmap -*/ diff --git a/thirdparty/jsoncpp/doxybuild.py b/thirdparty/jsoncpp/doxybuild.py deleted file mode 100644 index f18c9c0697..0000000000 --- a/thirdparty/jsoncpp/doxybuild.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Script to generate doxygen documentation. -""" -from __future__ import print_function -from __future__ import unicode_literals -from devtools import tarball -from contextlib import contextmanager -import subprocess -import traceback -import re -import os -import sys -import shutil - -@contextmanager -def cd(newdir): - """ - http://stackoverflow.com/questions/431684/how-do-i-cd-in-python - """ - prevdir = os.getcwd() - os.chdir(newdir) - try: - yield - finally: - os.chdir(prevdir) - -def find_program(*filenames): - """find a program in folders path_lst, and sets env[var] - @param filenames: a list of possible names of the program to search for - @return: the full path of the filename if found, or '' if filename could not be found -""" - paths = os.environ.get('PATH', '').split(os.pathsep) - suffixes = ('win32' in sys.platform) and '.exe .com .bat .cmd' or '' - for filename in filenames: - for name in [filename+ext for ext in suffixes.split(' ')]: - for directory in paths: - full_path = os.path.join(directory, name) - if os.path.isfile(full_path): - return full_path - return '' - -def do_subst_in_file(targetfile, sourcefile, dict): - """Replace all instances of the keys of dict with their values. - For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'}, - then all instances of %VERSION% in the file will be replaced with 1.2345 etc. - """ - with open(sourcefile, 'r') as f: - contents = f.read() - for (k,v) in list(dict.items()): - v = v.replace('\\','\\\\') - contents = re.sub(k, v, contents) - with open(targetfile, 'w') as f: - f.write(contents) - -def getstatusoutput(cmd): - """cmd is a list. - """ - try: - process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - output, _ = process.communicate() - status = process.returncode - except: - status = -1 - output = traceback.format_exc() - return status, output - -def run_cmd(cmd, silent=False): - """Raise exception on failure. - """ - info = 'Running: %r in %r' %(' '.join(cmd), os.getcwd()) - print(info) - sys.stdout.flush() - if silent: - status, output = getstatusoutput(cmd) - else: - status, output = subprocess.call(cmd), '' - if status: - msg = 'Error while %s ...\n\terror=%d, output="""%s"""' %(info, status, output) - raise Exception(msg) - -def assert_is_exe(path): - if not path: - raise Exception('path is empty.') - if not os.path.isfile(path): - raise Exception('%r is not a file.' %path) - if not os.access(path, os.X_OK): - raise Exception('%r is not executable by this user.' %path) - -def run_doxygen(doxygen_path, config_file, working_dir, is_silent): - assert_is_exe(doxygen_path) - config_file = os.path.abspath(config_file) - with cd(working_dir): - cmd = [doxygen_path, config_file] - run_cmd(cmd, is_silent) - -def build_doc(options, make_release=False): - if make_release: - options.make_tarball = True - options.with_dot = True - options.with_html_help = True - options.with_uml_look = True - options.open = False - options.silent = True - - version = open('version', 'rt').read().strip() - output_dir = 'dist/doxygen' # relative to doc/doxyfile location. - if not os.path.isdir(output_dir): - os.makedirs(output_dir) - top_dir = os.path.abspath('.') - html_output_dirname = 'jsoncpp-api-html-' + version - tarball_path = os.path.join('dist', html_output_dirname + '.tar.gz') - warning_log_path = os.path.join(output_dir, '../jsoncpp-doxygen-warning.log') - html_output_path = os.path.join(output_dir, html_output_dirname) - def yesno(bool): - return bool and 'YES' or 'NO' - subst_keys = { - '%JSONCPP_VERSION%': version, - '%DOC_TOPDIR%': '', - '%TOPDIR%': top_dir, - '%HTML_OUTPUT%': os.path.join('..', output_dir, html_output_dirname), - '%HAVE_DOT%': yesno(options.with_dot), - '%DOT_PATH%': os.path.split(options.dot_path)[0], - '%HTML_HELP%': yesno(options.with_html_help), - '%UML_LOOK%': yesno(options.with_uml_look), - '%WARNING_LOG_PATH%': os.path.join('..', warning_log_path) - } - - if os.path.isdir(output_dir): - print('Deleting directory:', output_dir) - shutil.rmtree(output_dir) - if not os.path.isdir(output_dir): - os.makedirs(output_dir) - - do_subst_in_file('doc/doxyfile', options.doxyfile_input_path, subst_keys) - run_doxygen(options.doxygen_path, 'doc/doxyfile', 'doc', is_silent=options.silent) - if not options.silent: - print(open(warning_log_path, 'r').read()) - index_path = os.path.abspath(os.path.join('doc', subst_keys['%HTML_OUTPUT%'], 'index.html')) - print('Generated documentation can be found in:') - print(index_path) - if options.open: - import webbrowser - webbrowser.open('file://' + index_path) - if options.make_tarball: - print('Generating doc tarball to', tarball_path) - tarball_sources = [ - output_dir, - 'README.md', - 'LICENSE', - 'NEWS.txt', - 'version' - ] - tarball_basedir = os.path.join(output_dir, html_output_dirname) - tarball.make_tarball(tarball_path, tarball_sources, tarball_basedir, html_output_dirname) - return tarball_path, html_output_dirname - -def main(): - usage = """%prog - Generates doxygen documentation in build/doxygen. - Optionaly makes a tarball of the documentation to dist/. - - Must be started in the project top directory. - """ - from optparse import OptionParser - parser = OptionParser(usage=usage) - parser.allow_interspersed_args = False - parser.add_option('--with-dot', dest="with_dot", action='store_true', default=False, - help="""Enable usage of DOT to generate collaboration diagram""") - parser.add_option('--dot', dest="dot_path", action='store', default=find_program('dot'), - help="""Path to GraphViz dot tool. Must be full qualified path. [Default: %default]""") - parser.add_option('--doxygen', dest="doxygen_path", action='store', default=find_program('doxygen'), - help="""Path to Doxygen tool. [Default: %default]""") - parser.add_option('--in', dest="doxyfile_input_path", action='store', default='doc/doxyfile.in', - help="""Path to doxygen inputs. [Default: %default]""") - parser.add_option('--with-html-help', dest="with_html_help", action='store_true', default=False, - help="""Enable generation of Microsoft HTML HELP""") - parser.add_option('--no-uml-look', dest="with_uml_look", action='store_false', default=True, - help="""Generates DOT graph without UML look [Default: False]""") - parser.add_option('--open', dest="open", action='store_true', default=False, - help="""Open the HTML index in the web browser after generation""") - parser.add_option('--tarball', dest="make_tarball", action='store_true', default=False, - help="""Generates a tarball of the documentation in dist/ directory""") - parser.add_option('-s', '--silent', dest="silent", action='store_true', default=False, - help="""Hides doxygen output""") - parser.enable_interspersed_args() - options, args = parser.parse_args() - build_doc(options) - -if __name__ == '__main__': - main() diff --git a/thirdparty/jsoncpp/include/CMakeLists.txt b/thirdparty/jsoncpp/include/CMakeLists.txt deleted file mode 100644 index cc866f173d..0000000000 --- a/thirdparty/jsoncpp/include/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -FILE(GLOB INCLUDE_FILES "json/*.h") -INSTALL(FILES ${INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/json) diff --git a/thirdparty/jsoncpp/include/json/allocator.h b/thirdparty/jsoncpp/include/json/allocator.h deleted file mode 100644 index 2492758cd7..0000000000 --- a/thirdparty/jsoncpp/include/json/allocator.h +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef CPPTL_JSON_ALLOCATOR_H_INCLUDED -#define CPPTL_JSON_ALLOCATOR_H_INCLUDED - -#include -#include - -#pragma pack(push, 8) - -namespace Json { -template -class SecureAllocator { - public: - // Type definitions - using value_type = T; - using pointer = T*; - using const_pointer = const T*; - using reference = T&; - using const_reference = const T&; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - - /** - * Allocate memory for N items using the standard allocator. - */ - pointer allocate(size_type n) { - // allocate using "global operator new" - return static_cast(::operator new(n * sizeof(T))); - } - - /** - * Release memory which was allocated for N items at pointer P. - * - * The memory block is filled with zeroes before being released. - * The pointer argument is tagged as "volatile" to prevent the - * compiler optimizing out this critical step. - */ - void deallocate(volatile pointer p, size_type n) { - std::memset(p, 0, n * sizeof(T)); - // free using "global operator delete" - ::operator delete(p); - } - - /** - * Construct an item in-place at pointer P. - */ - template - void construct(pointer p, Args&&... args) { - // construct using "placement new" and "perfect forwarding" - ::new (static_cast(p)) T(std::forward(args)...); - } - - size_type max_size() const { - return size_t(-1) / sizeof(T); - } - - pointer address( reference x ) const { - return std::addressof(x); - } - - const_pointer address( const_reference x ) const { - return std::addressof(x); - } - - /** - * Destroy an item in-place at pointer P. - */ - void destroy(pointer p) { - // destroy using "explicit destructor" - p->~T(); - } - - // Boilerplate - SecureAllocator() {} - template SecureAllocator(const SecureAllocator&) {} - template struct rebind { using other = SecureAllocator; }; -}; - - -template -bool operator==(const SecureAllocator&, const SecureAllocator&) { - return true; -} - -template -bool operator!=(const SecureAllocator&, const SecureAllocator&) { - return false; -} - -} //namespace Json - -#pragma pack(pop) - -#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/assertions.h b/thirdparty/jsoncpp/include/json/assertions.h deleted file mode 100644 index 9c5f8bc0fe..0000000000 --- a/thirdparty/jsoncpp/include/json/assertions.h +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED -#define CPPTL_JSON_ASSERTIONS_H_INCLUDED - -#include -#include - -#if !defined(JSON_IS_AMALGAMATION) -#include "config.h" -#endif // if !defined(JSON_IS_AMALGAMATION) - -/** It should not be possible for a maliciously designed file to - * cause an abort() or seg-fault, so these macros are used only - * for pre-condition violations and internal logic errors. - */ -#if JSON_USE_EXCEPTION - -// @todo <= add detail about condition in exception -# define JSON_ASSERT(condition) \ - {if (!(condition)) {Json::throwLogicError( "assert json failed" );}} - -# define JSON_FAIL_MESSAGE(message) \ - { \ - JSONCPP_OSTRINGSTREAM oss; oss << message; \ - Json::throwLogicError(oss.str()); \ - abort(); \ - } - -#else // JSON_USE_EXCEPTION - -# define JSON_ASSERT(condition) assert(condition) - -// The call to assert() will show the failure message in debug builds. In -// release builds we abort, for a core-dump or debugger. -# define JSON_FAIL_MESSAGE(message) \ - { \ - JSONCPP_OSTRINGSTREAM oss; oss << message; \ - assert(false && oss.str().c_str()); \ - abort(); \ - } - - -#endif - -#define JSON_ASSERT_MESSAGE(condition, message) \ - if (!(condition)) { \ - JSON_FAIL_MESSAGE(message); \ - } - -#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/autolink.h b/thirdparty/jsoncpp/include/json/autolink.h deleted file mode 100644 index 6fcc8afac5..0000000000 --- a/thirdparty/jsoncpp/include/json/autolink.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_AUTOLINK_H_INCLUDED -#define JSON_AUTOLINK_H_INCLUDED - -#include "config.h" - -#ifdef JSON_IN_CPPTL -#include -#endif - -#if !defined(JSON_NO_AUTOLINK) && !defined(JSON_DLL_BUILD) && \ - !defined(JSON_IN_CPPTL) -#define CPPTL_AUTOLINK_NAME "json" -#undef CPPTL_AUTOLINK_DLL -#ifdef JSON_DLL -#define CPPTL_AUTOLINK_DLL -#endif -#include "autolink.h" -#endif - -#endif // JSON_AUTOLINK_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/config.h b/thirdparty/jsoncpp/include/json/config.h deleted file mode 100644 index 6e3f3ac647..0000000000 --- a/thirdparty/jsoncpp/include/json/config.h +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_CONFIG_H_INCLUDED -#define JSON_CONFIG_H_INCLUDED -#include -#include //typedef String -#include //typedef int64_t, uint64_t - -/// If defined, indicates that json library is embedded in CppTL library. -//# define JSON_IN_CPPTL 1 - -/// If defined, indicates that json may leverage CppTL library -//# define JSON_USE_CPPTL 1 -/// If defined, indicates that cpptl vector based map should be used instead of -/// std::map -/// as Value container. -//# define JSON_USE_CPPTL_SMALLMAP 1 - -// If non-zero, the library uses exceptions to report bad input instead of C -// assertion macros. The default is to use exceptions. -#ifndef JSON_USE_EXCEPTION -#define JSON_USE_EXCEPTION 1 -#endif - -/// If defined, indicates that the source file is amalgated -/// to prevent private header inclusion. -/// Remarks: it is automatically defined in the generated amalgated header. -// #define JSON_IS_AMALGAMATION - -#ifdef JSON_IN_CPPTL -#include -#ifndef JSON_USE_CPPTL -#define JSON_USE_CPPTL 1 -#endif -#endif - -#ifdef JSON_IN_CPPTL -#define JSON_API CPPTL_API -#elif defined(JSON_DLL_BUILD) -#if defined(_MSC_VER) || defined(__MINGW32__) -#define JSON_API __declspec(dllexport) -#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING -#endif // if defined(_MSC_VER) -#elif defined(JSON_DLL) -#if defined(_MSC_VER) || defined(__MINGW32__) -#define JSON_API __declspec(dllimport) -#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING -#endif // if defined(_MSC_VER) -#endif // ifdef JSON_IN_CPPTL -#if !defined(JSON_API) -#define JSON_API -#endif - -// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for -// integer -// Storages, and 64 bits integer support is disabled. -// #define JSON_NO_INT64 1 - -#if defined(_MSC_VER) // MSVC -# if _MSC_VER <= 1200 // MSVC 6 - // Microsoft Visual Studio 6 only support conversion from __int64 to double - // (no conversion from unsigned __int64). -# define JSON_USE_INT64_DOUBLE_CONVERSION 1 - // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255' - // characters in the debug information) - // All projects I've ever seen with VS6 were using this globally (not bothering - // with pragma push/pop). -# pragma warning(disable : 4786) -# endif // MSVC 6 - -# if _MSC_VER >= 1500 // MSVC 2008 - /// Indicates that the following function is deprecated. -# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) -# endif - -#endif // defined(_MSC_VER) - -// In c++11 the override keyword allows you to explicity define that a function -// is intended to override the base-class version. This makes the code more -// managable and fixes a set of common hard-to-find bugs. -#if __cplusplus >= 201103L -# define JSONCPP_OVERRIDE override -# define JSONCPP_NOEXCEPT noexcept -#elif defined(_MSC_VER) && _MSC_VER > 1600 && _MSC_VER < 1900 -# define JSONCPP_OVERRIDE override -# define JSONCPP_NOEXCEPT throw() -#elif defined(_MSC_VER) && _MSC_VER >= 1900 -# define JSONCPP_OVERRIDE override -# define JSONCPP_NOEXCEPT noexcept -#else -# define JSONCPP_OVERRIDE -# define JSONCPP_NOEXCEPT throw() -#endif - -#ifndef JSON_HAS_RVALUE_REFERENCES - -#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010 -#define JSON_HAS_RVALUE_REFERENCES 1 -#endif // MSVC >= 2010 - -#ifdef __clang__ -#if __has_feature(cxx_rvalue_references) -#define JSON_HAS_RVALUE_REFERENCES 1 -#endif // has_feature - -#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) -#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L) -#define JSON_HAS_RVALUE_REFERENCES 1 -#endif // GXX_EXPERIMENTAL - -#endif // __clang__ || __GNUC__ - -#endif // not defined JSON_HAS_RVALUE_REFERENCES - -#ifndef JSON_HAS_RVALUE_REFERENCES -#define JSON_HAS_RVALUE_REFERENCES 0 -#endif - -#ifdef __clang__ -#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc) -# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) -# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message))) -# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) -# endif // GNUC version -#endif // __clang__ || __GNUC__ - -#if !defined(JSONCPP_DEPRECATED) -#define JSONCPP_DEPRECATED(message) -#endif // if !defined(JSONCPP_DEPRECATED) - -#if __GNUC__ >= 6 -# define JSON_USE_INT64_DOUBLE_CONVERSION 1 -#endif - -#if !defined(JSON_IS_AMALGAMATION) - -# include "version.h" - -# if JSONCPP_USING_SECURE_MEMORY -# include "allocator.h" //typedef Allocator -# endif - -#endif // if !defined(JSON_IS_AMALGAMATION) - -namespace Json { -typedef int Int; -typedef unsigned int UInt; -#if defined(JSON_NO_INT64) -typedef int LargestInt; -typedef unsigned int LargestUInt; -#undef JSON_HAS_INT64 -#else // if defined(JSON_NO_INT64) -// For Microsoft Visual use specific types as long long is not supported -#if defined(_MSC_VER) // Microsoft Visual Studio -typedef __int64 Int64; -typedef unsigned __int64 UInt64; -#else // if defined(_MSC_VER) // Other platforms, use long long -typedef int64_t Int64; -typedef uint64_t UInt64; -#endif // if defined(_MSC_VER) -typedef Int64 LargestInt; -typedef UInt64 LargestUInt; -#define JSON_HAS_INT64 -#endif // if defined(JSON_NO_INT64) -#if JSONCPP_USING_SECURE_MEMORY -#define JSONCPP_STRING std::basic_string, Json::SecureAllocator > -#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream, Json::SecureAllocator > -#define JSONCPP_OSTREAM std::basic_ostream> -#define JSONCPP_ISTRINGSTREAM std::basic_istringstream, Json::SecureAllocator > -#define JSONCPP_ISTREAM std::istream -#else -#define JSONCPP_STRING std::string -#define JSONCPP_OSTRINGSTREAM std::ostringstream -#define JSONCPP_OSTREAM std::ostream -#define JSONCPP_ISTRINGSTREAM std::istringstream -#define JSONCPP_ISTREAM std::istream -#endif // if JSONCPP_USING_SECURE_MEMORY -} // end namespace Json - -#endif // JSON_CONFIG_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/features.h b/thirdparty/jsoncpp/include/json/features.h deleted file mode 100644 index de45248fb3..0000000000 --- a/thirdparty/jsoncpp/include/json/features.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef CPPTL_JSON_FEATURES_H_INCLUDED -#define CPPTL_JSON_FEATURES_H_INCLUDED - -#if !defined(JSON_IS_AMALGAMATION) -#include "forwards.h" -#endif // if !defined(JSON_IS_AMALGAMATION) - -#pragma pack(push, 8) - -namespace Json { - -/** \brief Configuration passed to reader and writer. - * This configuration object can be used to force the Reader or Writer - * to behave in a standard conforming way. - */ -class JSON_API Features { -public: - /** \brief A configuration that allows all features and assumes all strings - * are UTF-8. - * - C & C++ comments are allowed - * - Root object can be any JSON value - * - Assumes Value strings are encoded in UTF-8 - */ - static Features all(); - - /** \brief A configuration that is strictly compatible with the JSON - * specification. - * - Comments are forbidden. - * - Root object must be either an array or an object value. - * - Assumes Value strings are encoded in UTF-8 - */ - static Features strictMode(); - - /** \brief Initialize the configuration like JsonConfig::allFeatures; - */ - Features(); - - /// \c true if comments are allowed. Default: \c true. - bool allowComments_; - - /// \c true if root must be either an array or an object value. Default: \c - /// false. - bool strictRoot_; - - /// \c true if dropped null placeholders are allowed. Default: \c false. - bool allowDroppedNullPlaceholders_; - - /// \c true if numeric object key are allowed. Default: \c false. - bool allowNumericKeys_; -}; - -} // namespace Json - -#pragma pack(pop) - -#endif // CPPTL_JSON_FEATURES_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/forwards.h b/thirdparty/jsoncpp/include/json/forwards.h deleted file mode 100644 index ccfe09abf4..0000000000 --- a/thirdparty/jsoncpp/include/json/forwards.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_FORWARDS_H_INCLUDED -#define JSON_FORWARDS_H_INCLUDED - -#if !defined(JSON_IS_AMALGAMATION) -#include "config.h" -#endif // if !defined(JSON_IS_AMALGAMATION) - -namespace Json { - -// writer.h -class FastWriter; -class StyledWriter; - -// reader.h -class Reader; - -// features.h -class Features; - -// value.h -typedef unsigned int ArrayIndex; -class StaticString; -class Path; -class PathArgument; -class Value; -class ValueIteratorBase; -class ValueIterator; -class ValueConstIterator; - -} // namespace Json - -#endif // JSON_FORWARDS_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/json.h b/thirdparty/jsoncpp/include/json/json.h deleted file mode 100644 index 8f10ac2bf7..0000000000 --- a/thirdparty/jsoncpp/include/json/json.h +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_JSON_H_INCLUDED -#define JSON_JSON_H_INCLUDED - -#include "autolink.h" -#include "value.h" -#include "reader.h" -#include "writer.h" -#include "features.h" - -#endif // JSON_JSON_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/reader.h b/thirdparty/jsoncpp/include/json/reader.h deleted file mode 100644 index 6ab5bdbf79..0000000000 --- a/thirdparty/jsoncpp/include/json/reader.h +++ /dev/null @@ -1,408 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef CPPTL_JSON_READER_H_INCLUDED -#define CPPTL_JSON_READER_H_INCLUDED - -#if !defined(JSON_IS_AMALGAMATION) -#include "features.h" -#include "value.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#include -#include - -// Disable warning C4251: : needs to have dll-interface to -// be used by... -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(push) -#pragma warning(disable : 4251) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#pragma pack(push, 8) - -namespace Json { - -/** \brief Unserialize a JSON document into a - *Value. - * - * \deprecated Use CharReader and CharReaderBuilder. - */ -class JSON_API Reader { -public: - typedef char Char; - typedef const Char* Location; - - /** \brief An error tagged with where in the JSON text it was encountered. - * - * The offsets give the [start, limit) range of bytes within the text. Note - * that this is bytes, not codepoints. - * - */ - struct StructuredError { - ptrdiff_t offset_start; - ptrdiff_t offset_limit; - JSONCPP_STRING message; - }; - - /** \brief Constructs a Reader allowing all features - * for parsing. - */ - Reader(); - - /** \brief Constructs a Reader allowing the specified feature set - * for parsing. - */ - Reader(const Features& features); - - /** \brief Read a Value from a JSON - * document. - * \param document UTF-8 encoded string containing the document to read. - * \param root [out] Contains the root value of the document if it was - * successfully parsed. - * \param collectComments \c true to collect comment and allow writing them - * back during - * serialization, \c false to discard comments. - * This parameter is ignored if - * Features::allowComments_ - * is \c false. - * \return \c true if the document was successfully parsed, \c false if an - * error occurred. - */ - bool - parse(const std::string& document, Value& root, bool collectComments = true); - - /** \brief Read a Value from a JSON - document. - * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the - document to read. - * \param endDoc Pointer on the end of the UTF-8 encoded string of the - document to read. - * Must be >= beginDoc. - * \param root [out] Contains the root value of the document if it was - * successfully parsed. - * \param collectComments \c true to collect comment and allow writing them - back during - * serialization, \c false to discard comments. - * This parameter is ignored if - Features::allowComments_ - * is \c false. - * \return \c true if the document was successfully parsed, \c false if an - error occurred. - */ - bool parse(const char* beginDoc, - const char* endDoc, - Value& root, - bool collectComments = true); - - /// \brief Parse from input stream. - /// \see Json::operator>>(std::istream&, Json::Value&). - bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true); - - /** \brief Returns a user friendly string that list errors in the parsed - * document. - * \return Formatted error message with the list of errors with their location - * in - * the parsed document. An empty string is returned if no error - * occurred - * during parsing. - * \deprecated Use getFormattedErrorMessages() instead (typo fix). - */ - JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") - JSONCPP_STRING getFormatedErrorMessages() const; - - /** \brief Returns a user friendly string that list errors in the parsed - * document. - * \return Formatted error message with the list of errors with their location - * in - * the parsed document. An empty string is returned if no error - * occurred - * during parsing. - */ - JSONCPP_STRING getFormattedErrorMessages() const; - - /** \brief Returns a vector of structured erros encounted while parsing. - * \return A (possibly empty) vector of StructuredError objects. Currently - * only one error can be returned, but the caller should tolerate - * multiple - * errors. This can occur if the parser recovers from a non-fatal - * parse error and then encounters additional errors. - */ - std::vector getStructuredErrors() const; - - /** \brief Add a semantic error message. - * \param value JSON Value location associated with the error - * \param message The error message. - * \return \c true if the error was successfully added, \c false if the - * Value offset exceeds the document size. - */ - bool pushError(const Value& value, const JSONCPP_STRING& message); - - /** \brief Add a semantic error message with extra context. - * \param value JSON Value location associated with the error - * \param message The error message. - * \param extra Additional JSON Value location to contextualize the error - * \return \c true if the error was successfully added, \c false if either - * Value offset exceeds the document size. - */ - bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra); - - /** \brief Return whether there are any errors. - * \return \c true if there are no errors to report \c false if - * errors have occurred. - */ - bool good() const; - -private: - enum TokenType { - tokenEndOfStream = 0, - tokenObjectBegin, - tokenObjectEnd, - tokenArrayBegin, - tokenArrayEnd, - tokenString, - tokenNumber, - tokenTrue, - tokenFalse, - tokenNull, - tokenArraySeparator, - tokenMemberSeparator, - tokenComment, - tokenError - }; - - class Token { - public: - TokenType type_; - Location start_; - Location end_; - }; - - class ErrorInfo { - public: - Token token_; - JSONCPP_STRING message_; - Location extra_; - }; - - typedef std::deque Errors; - - bool readToken(Token& token); - void skipSpaces(); - bool match(Location pattern, int patternLength); - bool readComment(); - bool readCStyleComment(); - bool readCppStyleComment(); - bool readString(); - void readNumber(); - bool readValue(); - bool readObject(Token& token); - bool readArray(Token& token); - bool decodeNumber(Token& token); - bool decodeNumber(Token& token, Value& decoded); - bool decodeString(Token& token); - bool decodeString(Token& token, JSONCPP_STRING& decoded); - bool decodeDouble(Token& token); - bool decodeDouble(Token& token, Value& decoded); - bool decodeUnicodeCodePoint(Token& token, - Location& current, - Location end, - unsigned int& unicode); - bool decodeUnicodeEscapeSequence(Token& token, - Location& current, - Location end, - unsigned int& unicode); - bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0); - bool recoverFromError(TokenType skipUntilToken); - bool addErrorAndRecover(const JSONCPP_STRING& message, - Token& token, - TokenType skipUntilToken); - void skipUntilSpace(); - Value& currentValue(); - Char getNextChar(); - void - getLocationLineAndColumn(Location location, int& line, int& column) const; - JSONCPP_STRING getLocationLineAndColumn(Location location) const; - void addComment(Location begin, Location end, CommentPlacement placement); - void skipCommentTokens(Token& token); - - typedef std::stack Nodes; - Nodes nodes_; - Errors errors_; - JSONCPP_STRING document_; - Location begin_; - Location end_; - Location current_; - Location lastValueEnd_; - Value* lastValue_; - JSONCPP_STRING commentsBefore_; - Features features_; - bool collectComments_; -}; // Reader - -/** Interface for reading JSON from a char array. - */ -class JSON_API CharReader { -public: - virtual ~CharReader() {} - /** \brief Read a Value from a JSON - document. - * The document must be a UTF-8 encoded string containing the document to read. - * - * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the - document to read. - * \param endDoc Pointer on the end of the UTF-8 encoded string of the - document to read. - * Must be >= beginDoc. - * \param root [out] Contains the root value of the document if it was - * successfully parsed. - * \param errs [out] Formatted error messages (if not NULL) - * a user friendly string that lists errors in the parsed - * document. - * \return \c true if the document was successfully parsed, \c false if an - error occurred. - */ - virtual bool parse( - char const* beginDoc, char const* endDoc, - Value* root, JSONCPP_STRING* errs) = 0; - - class JSON_API Factory { - public: - virtual ~Factory() {} - /** \brief Allocate a CharReader via operator new(). - * \throw std::exception if something goes wrong (e.g. invalid settings) - */ - virtual CharReader* newCharReader() const = 0; - }; // Factory -}; // CharReader - -/** \brief Build a CharReader implementation. - -Usage: -\code - using namespace Json; - CharReaderBuilder builder; - builder["collectComments"] = false; - Value value; - JSONCPP_STRING errs; - bool ok = parseFromStream(builder, std::cin, &value, &errs); -\endcode -*/ -class JSON_API CharReaderBuilder : public CharReader::Factory { -public: - // Note: We use a Json::Value so that we can add data-members to this class - // without a major version bump. - /** Configuration of this builder. - These are case-sensitive. - Available settings (case-sensitive): - - `"collectComments": false or true` - - true to collect comment and allow writing them - back during serialization, false to discard comments. - This parameter is ignored if allowComments is false. - - `"allowComments": false or true` - - true if comments are allowed. - - `"strictRoot": false or true` - - true if root must be either an array or an object value - - `"allowDroppedNullPlaceholders": false or true` - - true if dropped null placeholders are allowed. (See StreamWriterBuilder.) - - `"allowNumericKeys": false or true` - - true if numeric object keys are allowed. - - `"allowSingleQuotes": false or true` - - true if '' are allowed for strings (both keys and values) - - `"stackLimit": integer` - - Exceeding stackLimit (recursive depth of `readValue()`) will - cause an exception. - - This is a security issue (seg-faults caused by deeply nested JSON), - so the default is low. - - `"failIfExtra": false or true` - - If true, `parse()` returns false when extra non-whitespace trails - the JSON value in the input string. - - `"rejectDupKeys": false or true` - - If true, `parse()` returns false when a key is duplicated within an object. - - `"allowSpecialFloats": false or true` - - If true, special float values (NaNs and infinities) are allowed - and their values are lossfree restorable. - - You can examine 'settings_` yourself - to see the defaults. You can also write and read them just like any - JSON Value. - \sa setDefaults() - */ - Json::Value settings_; - - CharReaderBuilder(); - ~CharReaderBuilder() JSONCPP_OVERRIDE; - - CharReader* newCharReader() const JSONCPP_OVERRIDE; - - /** \return true if 'settings' are legal and consistent; - * otherwise, indicate bad settings via 'invalid'. - */ - bool validate(Json::Value* invalid) const; - - /** A simple way to update a specific setting. - */ - Value& operator[](JSONCPP_STRING key); - - /** Called by ctor, but you can use this to reset settings_. - * \pre 'settings' != NULL (but Json::null is fine) - * \remark Defaults: - * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults - */ - static void setDefaults(Json::Value* settings); - /** Same as old Features::strictMode(). - * \pre 'settings' != NULL (but Json::null is fine) - * \remark Defaults: - * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode - */ - static void strictMode(Json::Value* settings); -}; - -/** Consume entire stream and use its begin/end. - * Someday we might have a real StreamReader, but for now this - * is convenient. - */ -bool JSON_API parseFromStream( - CharReader::Factory const&, - JSONCPP_ISTREAM&, - Value* root, std::string* errs); - -/** \brief Read from 'sin' into 'root'. - - Always keep comments from the input JSON. - - This can be used to read a file into a particular sub-object. - For example: - \code - Json::Value root; - cin >> root["dir"]["file"]; - cout << root; - \endcode - Result: - \verbatim - { - "dir": { - "file": { - // The input stream JSON would be nested here. - } - } - } - \endverbatim - \throw std::exception on parse error. - \see Json::operator<<() -*/ -JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&); - -} // namespace Json - -#pragma pack(pop) - -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(pop) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#endif // CPPTL_JSON_READER_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/value.h b/thirdparty/jsoncpp/include/json/value.h deleted file mode 100644 index c39f423fa5..0000000000 --- a/thirdparty/jsoncpp/include/json/value.h +++ /dev/null @@ -1,870 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef CPPTL_JSON_H_INCLUDED -#define CPPTL_JSON_H_INCLUDED - -#if !defined(JSON_IS_AMALGAMATION) -#include "forwards.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include - -#ifndef JSON_USE_CPPTL_SMALLMAP -#include -#else -#include -#endif -#ifdef JSON_USE_CPPTL -#include -#endif - -//Conditional NORETURN attribute on the throw functions would: -// a) suppress false positives from static code analysis -// b) possibly improve optimization opportunities. -#if !defined(JSONCPP_NORETURN) -# if defined(_MSC_VER) -# define JSONCPP_NORETURN __declspec(noreturn) -# elif defined(__GNUC__) -# define JSONCPP_NORETURN __attribute__ ((__noreturn__)) -# else -# define JSONCPP_NORETURN -# endif -#endif - -// Disable warning C4251: : needs to have dll-interface to -// be used by... -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(push) -#pragma warning(disable : 4251) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#pragma pack(push, 8) - -/** \brief JSON (JavaScript Object Notation). - */ -namespace Json { - -/** Base class for all exceptions we throw. - * - * We use nothing but these internally. Of course, STL can throw others. - */ -class JSON_API Exception : public std::exception { -public: - Exception(JSONCPP_STRING const& msg); - ~Exception() JSONCPP_NOEXCEPT JSONCPP_OVERRIDE; - char const* what() const JSONCPP_NOEXCEPT JSONCPP_OVERRIDE; -protected: - JSONCPP_STRING msg_; -}; - -/** Exceptions which the user cannot easily avoid. - * - * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input - * - * \remark derived from Json::Exception - */ -class JSON_API RuntimeError : public Exception { -public: - RuntimeError(JSONCPP_STRING const& msg); -}; - -/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. - * - * These are precondition-violations (user bugs) and internal errors (our bugs). - * - * \remark derived from Json::Exception - */ -class JSON_API LogicError : public Exception { -public: - LogicError(JSONCPP_STRING const& msg); -}; - -/// used internally -JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg); -/// used internally -JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg); - -/** \brief Type of the value held by a Value object. - */ -enum ValueType { - nullValue = 0, ///< 'null' value - intValue, ///< signed integer value - uintValue, ///< unsigned integer value - realValue, ///< double value - stringValue, ///< UTF-8 string value - booleanValue, ///< bool value - arrayValue, ///< array value (ordered list) - objectValue ///< object value (collection of name/value pairs). -}; - -enum CommentPlacement { - commentBefore = 0, ///< a comment placed on the line before a value - commentAfterOnSameLine, ///< a comment just after a value on the same line - commentAfter, ///< a comment on the line after a value (only make sense for - /// root value) - numberOfCommentPlacement -}; - -//# ifdef JSON_USE_CPPTL -// typedef CppTL::AnyEnumerator EnumMemberNames; -// typedef CppTL::AnyEnumerator EnumValues; -//# endif - -/** \brief Lightweight wrapper to tag static string. - * - * Value constructor and objectValue member assignement takes advantage of the - * StaticString and avoid the cost of string duplication when storing the - * string or the member name. - * - * Example of usage: - * \code - * Json::Value aValue( StaticString("some text") ); - * Json::Value object; - * static const StaticString code("code"); - * object[code] = 1234; - * \endcode - */ -class JSON_API StaticString { -public: - explicit StaticString(const char* czstring) : c_str_(czstring) {} - - operator const char*() const { return c_str_; } - - const char* c_str() const { return c_str_; } - -private: - const char* c_str_; -}; - -/** \brief Represents a JSON value. - * - * This class is a discriminated union wrapper that can represents a: - * - signed integer [range: Value::minInt - Value::maxInt] - * - unsigned integer (range: 0 - Value::maxUInt) - * - double - * - UTF-8 string - * - boolean - * - 'null' - * - an ordered list of Value - * - collection of name/value pairs (javascript object) - * - * The type of the held value is represented by a #ValueType and - * can be obtained using type(). - * - * Values of an #objectValue or #arrayValue can be accessed using operator[]() - * methods. - * Non-const methods will automatically create the a #nullValue element - * if it does not exist. - * The sequence of an #arrayValue will be automatically resized and initialized - * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. - * - * The get() methods can be used to obtain default value in the case the - * required element does not exist. - * - * It is possible to iterate over the list of a #objectValue values using - * the getMemberNames() method. - * - * \note #Value string-length fit in size_t, but keys must be < 2^30. - * (The reason is an implementation detail.) A #CharReader will raise an - * exception if a bound is exceeded to avoid security holes in your app, - * but the Value API does *not* check bounds. That is the responsibility - * of the caller. - */ -class JSON_API Value { - friend class ValueIteratorBase; -public: - typedef std::vector Members; - typedef ValueIterator iterator; - typedef ValueConstIterator const_iterator; - typedef Json::UInt UInt; - typedef Json::Int Int; -#if defined(JSON_HAS_INT64) - typedef Json::UInt64 UInt64; - typedef Json::Int64 Int64; -#endif // defined(JSON_HAS_INT64) - typedef Json::LargestInt LargestInt; - typedef Json::LargestUInt LargestUInt; - typedef Json::ArrayIndex ArrayIndex; - - static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value(). - static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null - static Value const& nullSingleton(); ///< Prefer this to null or nullRef. - - /// Minimum signed integer value that can be stored in a Json::Value. - static const LargestInt minLargestInt; - /// Maximum signed integer value that can be stored in a Json::Value. - static const LargestInt maxLargestInt; - /// Maximum unsigned integer value that can be stored in a Json::Value. - static const LargestUInt maxLargestUInt; - - /// Minimum signed int value that can be stored in a Json::Value. - static const Int minInt; - /// Maximum signed int value that can be stored in a Json::Value. - static const Int maxInt; - /// Maximum unsigned int value that can be stored in a Json::Value. - static const UInt maxUInt; - -#if defined(JSON_HAS_INT64) - /// Minimum signed 64 bits int value that can be stored in a Json::Value. - static const Int64 minInt64; - /// Maximum signed 64 bits int value that can be stored in a Json::Value. - static const Int64 maxInt64; - /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. - static const UInt64 maxUInt64; -#endif // defined(JSON_HAS_INT64) - -private: -#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION - class CZString { - public: - enum DuplicationPolicy { - noDuplication = 0, - duplicate, - duplicateOnCopy - }; - CZString(ArrayIndex index); - CZString(char const* str, unsigned length, DuplicationPolicy allocate); - CZString(CZString const& other); -#if JSON_HAS_RVALUE_REFERENCES - CZString(CZString&& other); -#endif - ~CZString(); - CZString& operator=(CZString other); - bool operator<(CZString const& other) const; - bool operator==(CZString const& other) const; - ArrayIndex index() const; - //const char* c_str() const; ///< \deprecated - char const* data() const; - unsigned length() const; - bool isStaticString() const; - - private: - void swap(CZString& other); - - struct StringStorage { - unsigned policy_: 2; - unsigned length_: 30; // 1GB max - }; - - char const* cstr_; // actually, a prefixed string, unless policy is noDup - union { - ArrayIndex index_; - StringStorage storage_; - }; - }; - -public: -#ifndef JSON_USE_CPPTL_SMALLMAP - typedef std::map ObjectValues; -#else - typedef CppTL::SmallMap ObjectValues; -#endif // ifndef JSON_USE_CPPTL_SMALLMAP -#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION - -public: - /** \brief Create a default Value of the given type. - - This is a very useful constructor. - To create an empty array, pass arrayValue. - To create an empty object, pass objectValue. - Another Value can then be set to this one by assignment. -This is useful since clear() and resize() will not alter types. - - Examples: -\code -Json::Value null_value; // null -Json::Value arr_value(Json::arrayValue); // [] -Json::Value obj_value(Json::objectValue); // {} -\endcode - */ - Value(ValueType type = nullValue); - Value(Int value); - Value(UInt value); -#if defined(JSON_HAS_INT64) - Value(Int64 value); - Value(UInt64 value); -#endif // if defined(JSON_HAS_INT64) - Value(double value); - Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) - Value(const char* begin, const char* end); ///< Copy all, incl zeroes. - /** \brief Constructs a value from a static string. - - * Like other value string constructor but do not duplicate the string for - * internal storage. The given string must remain alive after the call to this - * constructor. - * \note This works only for null-terminated strings. (We cannot change the - * size of this class, so we have nowhere to store the length, - * which might be computed later for various operations.) - * - * Example of usage: - * \code - * static StaticString foo("some text"); - * Json::Value aValue(foo); - * \endcode - */ - Value(const StaticString& value); - Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too. -#ifdef JSON_USE_CPPTL - Value(const CppTL::ConstString& value); -#endif - Value(bool value); - /// Deep copy. - Value(const Value& other); -#if JSON_HAS_RVALUE_REFERENCES - /// Move constructor - Value(Value&& other); -#endif - ~Value(); - - /// Deep copy, then swap(other). - /// \note Over-write existing comments. To preserve comments, use #swapPayload(). - Value& operator=(Value other); - /// Swap everything. - void swap(Value& other); - /// Swap values but leave comments and source offsets in place. - void swapPayload(Value& other); - - ValueType type() const; - - /// Compare payload only, not comments etc. - bool operator<(const Value& other) const; - bool operator<=(const Value& other) const; - bool operator>=(const Value& other) const; - bool operator>(const Value& other) const; - bool operator==(const Value& other) const; - bool operator!=(const Value& other) const; - int compare(const Value& other) const; - - const char* asCString() const; ///< Embedded zeroes could cause you trouble! -#if JSONCPP_USING_SECURE_MEMORY - unsigned getCStringLength() const; //Allows you to understand the length of the CString -#endif - JSONCPP_STRING asString() const; ///< Embedded zeroes are possible. - /** Get raw char* of string-value. - * \return false if !string. (Seg-fault if str or end are NULL.) - */ - bool getString( - char const** begin, char const** end) const; -#ifdef JSON_USE_CPPTL - CppTL::ConstString asConstString() const; -#endif - Int asInt() const; - UInt asUInt() const; -#if defined(JSON_HAS_INT64) - Int64 asInt64() const; - UInt64 asUInt64() const; -#endif // if defined(JSON_HAS_INT64) - LargestInt asLargestInt() const; - LargestUInt asLargestUInt() const; - float asFloat() const; - double asDouble() const; - bool asBool() const; - - bool isNull() const; - bool isBool() const; - bool isInt() const; - bool isInt64() const; - bool isUInt() const; - bool isUInt64() const; - bool isIntegral() const; - bool isDouble() const; - bool isNumeric() const; - bool isString() const; - bool isArray() const; - bool isObject() const; - - bool isConvertibleTo(ValueType other) const; - - /// Number of values in array or object - ArrayIndex size() const; - - /// \brief Return true if empty array, empty object, or null; - /// otherwise, false. - bool empty() const; - - /// Return isNull() - bool operator!() const; - - /// Remove all object members and array elements. - /// \pre type() is arrayValue, objectValue, or nullValue - /// \post type() is unchanged - void clear(); - - /// Resize the array to size elements. - /// New elements are initialized to null. - /// May only be called on nullValue or arrayValue. - /// \pre type() is arrayValue or nullValue - /// \post type() is arrayValue - void resize(ArrayIndex size); - - /// Access an array element (zero based index ). - /// If the array contains less than index element, then null value are - /// inserted - /// in the array so that its size is index+1. - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - Value& operator[](ArrayIndex index); - - /// Access an array element (zero based index ). - /// If the array contains less than index element, then null value are - /// inserted - /// in the array so that its size is index+1. - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - Value& operator[](int index); - - /// Access an array element (zero based index ) - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - const Value& operator[](ArrayIndex index) const; - - /// Access an array element (zero based index ) - /// (You may need to say 'value[0u]' to get your compiler to distinguish - /// this from the operator[] which takes a string.) - const Value& operator[](int index) const; - - /// If the array contains at least index+1 elements, returns the element - /// value, - /// otherwise returns defaultValue. - Value get(ArrayIndex index, const Value& defaultValue) const; - /// Return true if index < size(). - bool isValidIndex(ArrayIndex index) const; - /// \brief Append value to array at the end. - /// - /// Equivalent to jsonvalue[jsonvalue.size()] = value; - Value& append(const Value& value); - - /// Access an object value by name, create a null member if it does not exist. - /// \note Because of our implementation, keys are limited to 2^30 -1 chars. - /// Exceeding that will cause an exception. - Value& operator[](const char* key); - /// Access an object value by name, returns null if there is no member with - /// that name. - const Value& operator[](const char* key) const; - /// Access an object value by name, create a null member if it does not exist. - /// \param key may contain embedded nulls. - Value& operator[](const JSONCPP_STRING& key); - /// Access an object value by name, returns null if there is no member with - /// that name. - /// \param key may contain embedded nulls. - const Value& operator[](const JSONCPP_STRING& key) const; - /** \brief Access an object value by name, create a null member if it does not - exist. - - * If the object has no entry for that name, then the member name used to store - * the new entry is not duplicated. - * Example of use: - * \code - * Json::Value object; - * static const StaticString code("code"); - * object[code] = 1234; - * \endcode - */ - Value& operator[](const StaticString& key); -#ifdef JSON_USE_CPPTL - /// Access an object value by name, create a null member if it does not exist. - Value& operator[](const CppTL::ConstString& key); - /// Access an object value by name, returns null if there is no member with - /// that name. - const Value& operator[](const CppTL::ConstString& key) const; -#endif - /// Return the member named key if it exist, defaultValue otherwise. - /// \note deep copy - Value get(const char* key, const Value& defaultValue) const; - /// Return the member named key if it exist, defaultValue otherwise. - /// \note deep copy - /// \note key may contain embedded nulls. - Value get(const char* begin, const char* end, const Value& defaultValue) const; - /// Return the member named key if it exist, defaultValue otherwise. - /// \note deep copy - /// \param key may contain embedded nulls. - Value get(const JSONCPP_STRING& key, const Value& defaultValue) const; -#ifdef JSON_USE_CPPTL - /// Return the member named key if it exist, defaultValue otherwise. - /// \note deep copy - Value get(const CppTL::ConstString& key, const Value& defaultValue) const; -#endif - /// Most general and efficient version of isMember()const, get()const, - /// and operator[]const - /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 - Value const* find(char const* begin, char const* end) const; - /// Most general and efficient version of object-mutators. - /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 - /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. - Value const* demand(char const* begin, char const* end); - /// \brief Remove and return the named member. - /// - /// Do nothing if it did not exist. - /// \return the removed Value, or null. - /// \pre type() is objectValue or nullValue - /// \post type() is unchanged - /// \deprecated - Value removeMember(const char* key); - /// Same as removeMember(const char*) - /// \param key may contain embedded nulls. - /// \deprecated - Value removeMember(const JSONCPP_STRING& key); - /// Same as removeMember(const char* begin, const char* end, Value* removed), - /// but 'key' is null-terminated. - bool removeMember(const char* key, Value* removed); - /** \brief Remove the named map member. - - Update 'removed' iff removed. - \param key may contain embedded nulls. - \return true iff removed (no exceptions) - */ - bool removeMember(JSONCPP_STRING const& key, Value* removed); - /// Same as removeMember(JSONCPP_STRING const& key, Value* removed) - bool removeMember(const char* begin, const char* end, Value* removed); - /** \brief Remove the indexed array element. - - O(n) expensive operations. - Update 'removed' iff removed. - \return true iff removed (no exceptions) - */ - bool removeIndex(ArrayIndex i, Value* removed); - - /// Return true if the object has a member named key. - /// \note 'key' must be null-terminated. - bool isMember(const char* key) const; - /// Return true if the object has a member named key. - /// \param key may contain embedded nulls. - bool isMember(const JSONCPP_STRING& key) const; - /// Same as isMember(JSONCPP_STRING const& key)const - bool isMember(const char* begin, const char* end) const; -#ifdef JSON_USE_CPPTL - /// Return true if the object has a member named key. - bool isMember(const CppTL::ConstString& key) const; -#endif - - /// \brief Return a list of the member names. - /// - /// If null, return an empty list. - /// \pre type() is objectValue or nullValue - /// \post if type() was nullValue, it remains nullValue - Members getMemberNames() const; - - //# ifdef JSON_USE_CPPTL - // EnumMemberNames enumMemberNames() const; - // EnumValues enumValues() const; - //# endif - - /// \deprecated Always pass len. - JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.") - void setComment(const char* comment, CommentPlacement placement); - /// Comments must be //... or /* ... */ - void setComment(const char* comment, size_t len, CommentPlacement placement); - /// Comments must be //... or /* ... */ - void setComment(const JSONCPP_STRING& comment, CommentPlacement placement); - bool hasComment(CommentPlacement placement) const; - /// Include delimiters and embedded newlines. - JSONCPP_STRING getComment(CommentPlacement placement) const; - - JSONCPP_STRING toStyledString() const; - - const_iterator begin() const; - const_iterator end() const; - - iterator begin(); - iterator end(); - - // Accessors for the [start, limit) range of bytes within the JSON text from - // which this value was parsed, if any. - void setOffsetStart(ptrdiff_t start); - void setOffsetLimit(ptrdiff_t limit); - ptrdiff_t getOffsetStart() const; - ptrdiff_t getOffsetLimit() const; - -private: - void initBasic(ValueType type, bool allocated = false); - - Value& resolveReference(const char* key); - Value& resolveReference(const char* key, const char* end); - - struct CommentInfo { - CommentInfo(); - ~CommentInfo(); - - void setComment(const char* text, size_t len); - - char* comment_; - }; - - // struct MemberNamesTransform - //{ - // typedef const char *result_type; - // const char *operator()( const CZString &name ) const - // { - // return name.c_str(); - // } - //}; - - union ValueHolder { - LargestInt int_; - LargestUInt uint_; - double real_; - bool bool_; - char* string_; // actually ptr to unsigned, followed by str, unless !allocated_ - ObjectValues* map_; - } value_; - ValueType type_ : 8; - unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. - // If not allocated_, string_ must be null-terminated. - CommentInfo* comments_; - - // [start, limit) byte offsets in the source JSON text from which this Value - // was extracted. - ptrdiff_t start_; - ptrdiff_t limit_; -}; - -/** \brief Experimental and untested: represents an element of the "path" to - * access a node. - */ -class JSON_API PathArgument { -public: - friend class Path; - - PathArgument(); - PathArgument(ArrayIndex index); - PathArgument(const char* key); - PathArgument(const JSONCPP_STRING& key); - -private: - enum Kind { - kindNone = 0, - kindIndex, - kindKey - }; - JSONCPP_STRING key_; - ArrayIndex index_; - Kind kind_; -}; - -/** \brief Experimental and untested: represents a "path" to access a node. - * - * Syntax: - * - "." => root node - * - ".[n]" => elements at index 'n' of root node (an array value) - * - ".name" => member named 'name' of root node (an object value) - * - ".name1.name2.name3" - * - ".[0][1][2].name1[3]" - * - ".%" => member name is provided as parameter - * - ".[%]" => index is provied as parameter - */ -class JSON_API Path { -public: - Path(const JSONCPP_STRING& path, - const PathArgument& a1 = PathArgument(), - const PathArgument& a2 = PathArgument(), - const PathArgument& a3 = PathArgument(), - const PathArgument& a4 = PathArgument(), - const PathArgument& a5 = PathArgument()); - - const Value& resolve(const Value& root) const; - Value resolve(const Value& root, const Value& defaultValue) const; - /// Creates the "path" to access the specified node and returns a reference on - /// the node. - Value& make(Value& root) const; - -private: - typedef std::vector InArgs; - typedef std::vector Args; - - void makePath(const JSONCPP_STRING& path, const InArgs& in); - void addPathInArg(const JSONCPP_STRING& path, - const InArgs& in, - InArgs::const_iterator& itInArg, - PathArgument::Kind kind); - void invalidPath(const JSONCPP_STRING& path, int location); - - Args args_; -}; - -/** \brief base class for Value iterators. - * - */ -class JSON_API ValueIteratorBase { -public: - typedef std::bidirectional_iterator_tag iterator_category; - typedef unsigned int size_t; - typedef int difference_type; - typedef ValueIteratorBase SelfType; - - bool operator==(const SelfType& other) const { return isEqual(other); } - - bool operator!=(const SelfType& other) const { return !isEqual(other); } - - difference_type operator-(const SelfType& other) const { - return other.computeDistance(*this); - } - - /// Return either the index or the member name of the referenced value as a - /// Value. - Value key() const; - - /// Return the index of the referenced Value, or -1 if it is not an arrayValue. - UInt index() const; - - /// Return the member name of the referenced Value, or "" if it is not an - /// objectValue. - /// \note Avoid `c_str()` on result, as embedded zeroes are possible. - JSONCPP_STRING name() const; - - /// Return the member name of the referenced Value. "" if it is not an - /// objectValue. - /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls. - JSONCPP_DEPRECATED("Use `key = name();` instead.") - char const* memberName() const; - /// Return the member name of the referenced Value, or NULL if it is not an - /// objectValue. - /// \note Better version than memberName(). Allows embedded nulls. - char const* memberName(char const** end) const; - -protected: - Value& deref() const; - - void increment(); - - void decrement(); - - difference_type computeDistance(const SelfType& other) const; - - bool isEqual(const SelfType& other) const; - - void copy(const SelfType& other); - -private: - Value::ObjectValues::iterator current_; - // Indicates that iterator is for a null value. - bool isNull_; - -public: - // For some reason, BORLAND needs these at the end, rather - // than earlier. No idea why. - ValueIteratorBase(); - explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); -}; - -/** \brief const iterator for object and array value. - * - */ -class JSON_API ValueConstIterator : public ValueIteratorBase { - friend class Value; - -public: - typedef const Value value_type; - //typedef unsigned int size_t; - //typedef int difference_type; - typedef const Value& reference; - typedef const Value* pointer; - typedef ValueConstIterator SelfType; - - ValueConstIterator(); - ValueConstIterator(ValueIterator const& other); - -private: -/*! \internal Use by Value to create an iterator. - */ - explicit ValueConstIterator(const Value::ObjectValues::iterator& current); -public: - SelfType& operator=(const ValueIteratorBase& other); - - SelfType operator++(int) { - SelfType temp(*this); - ++*this; - return temp; - } - - SelfType operator--(int) { - SelfType temp(*this); - --*this; - return temp; - } - - SelfType& operator--() { - decrement(); - return *this; - } - - SelfType& operator++() { - increment(); - return *this; - } - - reference operator*() const { return deref(); } - - pointer operator->() const { return &deref(); } -}; - -/** \brief Iterator for object and array value. - */ -class JSON_API ValueIterator : public ValueIteratorBase { - friend class Value; - -public: - typedef Value value_type; - typedef unsigned int size_t; - typedef int difference_type; - typedef Value& reference; - typedef Value* pointer; - typedef ValueIterator SelfType; - - ValueIterator(); - explicit ValueIterator(const ValueConstIterator& other); - ValueIterator(const ValueIterator& other); - -private: -/*! \internal Use by Value to create an iterator. - */ - explicit ValueIterator(const Value::ObjectValues::iterator& current); -public: - SelfType& operator=(const SelfType& other); - - SelfType operator++(int) { - SelfType temp(*this); - ++*this; - return temp; - } - - SelfType operator--(int) { - SelfType temp(*this); - --*this; - return temp; - } - - SelfType& operator--() { - decrement(); - return *this; - } - - SelfType& operator++() { - increment(); - return *this; - } - - reference operator*() const { return deref(); } - - pointer operator->() const { return &deref(); } -}; - -} // namespace Json - - -namespace std { -/// Specialize std::swap() for Json::Value. -template<> -inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); } -} - -#pragma pack(pop) - -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(pop) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#endif // CPPTL_JSON_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/version.h b/thirdparty/jsoncpp/include/json/version.h deleted file mode 100644 index 9e5a66ee6e..0000000000 --- a/thirdparty/jsoncpp/include/json/version.h +++ /dev/null @@ -1,20 +0,0 @@ -// DO NOT EDIT. This file (and "version") is generated by CMake. -// Run CMake configure step to update it. -#ifndef JSON_VERSION_H_INCLUDED -# define JSON_VERSION_H_INCLUDED - -# define JSONCPP_VERSION_STRING "1.8.0" -# define JSONCPP_VERSION_MAJOR 1 -# define JSONCPP_VERSION_MINOR 8 -# define JSONCPP_VERSION_PATCH 0 -# define JSONCPP_VERSION_QUALIFIER -# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) - -#ifdef JSONCPP_USING_SECURE_MEMORY -#undef JSONCPP_USING_SECURE_MEMORY -#endif -#define JSONCPP_USING_SECURE_MEMORY 0 -// If non-zero, the library zeroes any memory that it has allocated before -// it frees its memory. - -#endif // JSON_VERSION_H_INCLUDED diff --git a/thirdparty/jsoncpp/include/json/writer.h b/thirdparty/jsoncpp/include/json/writer.h deleted file mode 100644 index d0944eeb88..0000000000 --- a/thirdparty/jsoncpp/include/json/writer.h +++ /dev/null @@ -1,335 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSON_WRITER_H_INCLUDED -#define JSON_WRITER_H_INCLUDED - -#if !defined(JSON_IS_AMALGAMATION) -#include "value.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include - -// Disable warning C4251: : needs to have dll-interface to -// be used by... -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(push) -#pragma warning(disable : 4251) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#pragma pack(push, 8) - -namespace Json { - -class Value; - -/** - -Usage: -\code - using namespace Json; - void writeToStdout(StreamWriter::Factory const& factory, Value const& value) { - std::unique_ptr const writer( - factory.newStreamWriter()); - writer->write(value, &std::cout); - std::cout << std::endl; // add lf and flush - } -\endcode -*/ -class JSON_API StreamWriter { -protected: - JSONCPP_OSTREAM* sout_; // not owned; will not delete -public: - StreamWriter(); - virtual ~StreamWriter(); - /** Write Value into document as configured in sub-class. - Do not take ownership of sout, but maintain a reference during function. - \pre sout != NULL - \return zero on success (For now, we always return zero, so check the stream instead.) - \throw std::exception possibly, depending on configuration - */ - virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0; - - /** \brief A simple abstract factory. - */ - class JSON_API Factory { - public: - virtual ~Factory(); - /** \brief Allocate a CharReader via operator new(). - * \throw std::exception if something goes wrong (e.g. invalid settings) - */ - virtual StreamWriter* newStreamWriter() const = 0; - }; // Factory -}; // StreamWriter - -/** \brief Write into stringstream, then return string, for convenience. - * A StreamWriter will be created from the factory, used, and then deleted. - */ -JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); - - -/** \brief Build a StreamWriter implementation. - -Usage: -\code - using namespace Json; - Value value = ...; - StreamWriterBuilder builder; - builder["commentStyle"] = "None"; - builder["indentation"] = " "; // or whatever you like - std::unique_ptr writer( - builder.newStreamWriter()); - writer->write(value, &std::cout); - std::cout << std::endl; // add lf and flush -\endcode -*/ -class JSON_API StreamWriterBuilder : public StreamWriter::Factory { -public: - // Note: We use a Json::Value so that we can add data-members to this class - // without a major version bump. - /** Configuration of this builder. - Available settings (case-sensitive): - - "commentStyle": "None" or "All" - - "indentation": "" - - "enableYAMLCompatibility": false or true - - slightly change the whitespace around colons - - "dropNullPlaceholders": false or true - - Drop the "null" string from the writer's output for nullValues. - Strictly speaking, this is not valid JSON. But when the output is being - fed to a browser's Javascript, it makes for smaller output and the - browser can handle the output just fine. - - "useSpecialFloats": false or true - - If true, outputs non-finite floating point values in the following way: - NaN values as "NaN", positive infinity as "Infinity", and negative infinity - as "-Infinity". - - You can examine 'settings_` yourself - to see the defaults. You can also write and read them just like any - JSON Value. - \sa setDefaults() - */ - Json::Value settings_; - - StreamWriterBuilder(); - ~StreamWriterBuilder() JSONCPP_OVERRIDE; - - /** - * \throw std::exception if something goes wrong (e.g. invalid settings) - */ - StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE; - - /** \return true if 'settings' are legal and consistent; - * otherwise, indicate bad settings via 'invalid'. - */ - bool validate(Json::Value* invalid) const; - /** A simple way to update a specific setting. - */ - Value& operator[](JSONCPP_STRING key); - - /** Called by ctor, but you can use this to reset settings_. - * \pre 'settings' != NULL (but Json::null is fine) - * \remark Defaults: - * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults - */ - static void setDefaults(Json::Value* settings); -}; - -/** \brief Abstract class for writers. - * \deprecated Use StreamWriter. (And really, this is an implementation detail.) - */ -class JSON_API Writer { -public: - virtual ~Writer(); - - virtual JSONCPP_STRING write(const Value& root) = 0; -}; - -/** \brief Outputs a Value in JSON format - *without formatting (not human friendly). - * - * The JSON document is written in a single line. It is not intended for 'human' - *consumption, - * but may be usefull to support feature such as RPC where bandwith is limited. - * \sa Reader, Value - * \deprecated Use StreamWriterBuilder. - */ -class JSON_API FastWriter : public Writer { - -public: - FastWriter(); - ~FastWriter() JSONCPP_OVERRIDE {} - - void enableYAMLCompatibility(); - - /** \brief Drop the "null" string from the writer's output for nullValues. - * Strictly speaking, this is not valid JSON. But when the output is being - * fed to a browser's Javascript, it makes for smaller output and the - * browser can handle the output just fine. - */ - void dropNullPlaceholders(); - - void omitEndingLineFeed(); - -public: // overridden from Writer - JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; - -private: - void writeValue(const Value& value); - - JSONCPP_STRING document_; - bool yamlCompatiblityEnabled_; - bool dropNullPlaceholders_; - bool omitEndingLineFeed_; -}; - -/** \brief Writes a Value in JSON format in a - *human friendly way. - * - * The rules for line break and indent are as follow: - * - Object value: - * - if empty then print {} without indent and line break - * - if not empty the print '{', line break & indent, print one value per - *line - * and then unindent and line break and print '}'. - * - Array value: - * - if empty then print [] without indent and line break - * - if the array contains no object value, empty array or some other value - *types, - * and all the values fit on one lines, then print the array on a single - *line. - * - otherwise, it the values do not fit on one line, or the array contains - * object or non empty array, then print one value per line. - * - * If the Value have comments then they are outputed according to their - *#CommentPlacement. - * - * \sa Reader, Value, Value::setComment() - * \deprecated Use StreamWriterBuilder. - */ -class JSON_API StyledWriter : public Writer { -public: - StyledWriter(); - ~StyledWriter() JSONCPP_OVERRIDE {} - -public: // overridden from Writer - /** \brief Serialize a Value in JSON format. - * \param root Value to serialize. - * \return String containing the JSON document that represents the root value. - */ - JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE; - -private: - void writeValue(const Value& value); - void writeArrayValue(const Value& value); - bool isMultineArray(const Value& value); - void pushValue(const JSONCPP_STRING& value); - void writeIndent(); - void writeWithIndent(const JSONCPP_STRING& value); - void indent(); - void unindent(); - void writeCommentBeforeValue(const Value& root); - void writeCommentAfterValueOnSameLine(const Value& root); - bool hasCommentForValue(const Value& value); - static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); - - typedef std::vector ChildValues; - - ChildValues childValues_; - JSONCPP_STRING document_; - JSONCPP_STRING indentString_; - unsigned int rightMargin_; - unsigned int indentSize_; - bool addChildValues_; -}; - -/** \brief Writes a Value in JSON format in a - human friendly way, - to a stream rather than to a string. - * - * The rules for line break and indent are as follow: - * - Object value: - * - if empty then print {} without indent and line break - * - if not empty the print '{', line break & indent, print one value per - line - * and then unindent and line break and print '}'. - * - Array value: - * - if empty then print [] without indent and line break - * - if the array contains no object value, empty array or some other value - types, - * and all the values fit on one lines, then print the array on a single - line. - * - otherwise, it the values do not fit on one line, or the array contains - * object or non empty array, then print one value per line. - * - * If the Value have comments then they are outputed according to their - #CommentPlacement. - * - * \param indentation Each level will be indented by this amount extra. - * \sa Reader, Value, Value::setComment() - * \deprecated Use StreamWriterBuilder. - */ -class JSON_API StyledStreamWriter { -public: - StyledStreamWriter(JSONCPP_STRING indentation = "\t"); - ~StyledStreamWriter() {} - -public: - /** \brief Serialize a Value in JSON format. - * \param out Stream to write to. (Can be ostringstream, e.g.) - * \param root Value to serialize. - * \note There is no point in deriving from Writer, since write() should not - * return a value. - */ - void write(JSONCPP_OSTREAM& out, const Value& root); - -private: - void writeValue(const Value& value); - void writeArrayValue(const Value& value); - bool isMultineArray(const Value& value); - void pushValue(const JSONCPP_STRING& value); - void writeIndent(); - void writeWithIndent(const JSONCPP_STRING& value); - void indent(); - void unindent(); - void writeCommentBeforeValue(const Value& root); - void writeCommentAfterValueOnSameLine(const Value& root); - bool hasCommentForValue(const Value& value); - static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text); - - typedef std::vector ChildValues; - - ChildValues childValues_; - JSONCPP_OSTREAM* document_; - JSONCPP_STRING indentString_; - unsigned int rightMargin_; - JSONCPP_STRING indentation_; - bool addChildValues_ : 1; - bool indented_ : 1; -}; - -#if defined(JSON_HAS_INT64) -JSONCPP_STRING JSON_API valueToString(Int value); -JSONCPP_STRING JSON_API valueToString(UInt value); -#endif // if defined(JSON_HAS_INT64) -JSONCPP_STRING JSON_API valueToString(LargestInt value); -JSONCPP_STRING JSON_API valueToString(LargestUInt value); -JSONCPP_STRING JSON_API valueToString(double value); -JSONCPP_STRING JSON_API valueToString(bool value); -JSONCPP_STRING JSON_API valueToQuotedString(const char* value); - -/// \brief Output using the StyledStreamWriter. -/// \see Json::operator>>() -JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root); - -} // namespace Json - -#pragma pack(pop) - -#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) -#pragma warning(pop) -#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) - -#endif // JSON_WRITER_H_INCLUDED diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/jsoncpp.sln b/thirdparty/jsoncpp/makefiles/msvc2010/jsoncpp.sln deleted file mode 100644 index fb18898104..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/jsoncpp.sln +++ /dev/null @@ -1,42 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_json", "lib_json.vcxproj", "{1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsontest", "jsontest.vcxproj", "{25AF2DD2-D396-4668-B188-488C33B8E620}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_lib_json", "test_lib_json.vcxproj", "{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Debug|Win32.ActiveCfg = Debug|Win32 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Debug|Win32.Build.0 = Debug|Win32 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Debug|x64.ActiveCfg = Debug|x64 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Debug|x64.Build.0 = Debug|x64 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Release|Win32.ActiveCfg = Release|Win32 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Release|Win32.Build.0 = Release|Win32 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Release|x64.ActiveCfg = Release|x64 - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89}.Release|x64.Build.0 = Release|x64 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Debug|Win32.ActiveCfg = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Debug|Win32.Build.0 = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Debug|x64.ActiveCfg = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Release|Win32.ActiveCfg = Release|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Release|Win32.Build.0 = Release|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Release|x64.ActiveCfg = Release|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug|Win32.ActiveCfg = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug|Win32.Build.0 = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug|x64.ActiveCfg = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release|Win32.ActiveCfg = Release|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release|Win32.Build.0 = Release|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release|x64.ActiveCfg = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj b/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj deleted file mode 100644 index 4c301e50a9..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {25AF2DD2-D396-4668-B188-488C33B8E620} - Win32Proj - - - - Application - MultiByte - - - Application - MultiByte - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - ../../build/vs71/debug/jsontest\ - ../../build/vs71/debug/jsontest\ - true - ../../build/vs71/release/jsontest\ - ../../build/vs71/release/jsontest\ - false - - - - Disabled - ../../include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebug - - - Level3 - EditAndContinue - - - $(OutDir)jsontest.exe - true - $(OutDir)jsontest.pdb - Console - MachineX86 - - - - - ../../include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreaded - - - Level3 - ProgramDatabase - - - $(OutDir)jsontest.exe - true - Console - true - true - MachineX86 - - - - - - - - {1e6c2c1c-6453-4129-ae3f-0ee8e6599c89} - - - - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj.filters b/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj.filters deleted file mode 100644 index 610b540ea5..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/jsontest.vcxproj.filters +++ /dev/null @@ -1,13 +0,0 @@ - - - - - {903591b3-ade3-4ce4-b1f9-1e175e62b014} - - - - - Source Files - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj b/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj deleted file mode 100644 index e435f86851..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj +++ /dev/null @@ -1,143 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - - - - - - - - - - - {1E6C2C1C-6453-4129-AE3F-0EE8E6599C89} - Win32Proj - jsoncpp - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - true - Unicode - - - StaticLibrary - false - true - Unicode - - - - - - - - - - - - - - - - - - - - - NotUsing - Level3 - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ../../include - MultiThreadedDebug - - - Windows - true - - - - - NotUsing - Level3 - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - ../../include - MultiThreadedDebug - - - Windows - true - - - - - Level3 - NotUsing - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ../../include - MultiThreaded - - - Windows - true - true - true - - - - - Level3 - NotUsing - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - ../../include - MultiThreaded - - - Windows - true - true - true - - - - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj.filters b/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj.filters deleted file mode 100644 index 63c740331e..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/lib_json.vcxproj.filters +++ /dev/null @@ -1,33 +0,0 @@ - - - - - {c110bc57-c46e-476c-97ea-84d8014f431c} - - - {ed718592-5acf-47b5-8f2b-b8224590da6a} - - - - - Source Files - - - Source Files - - - Source Files - - - - - Header Files - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj b/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj deleted file mode 100644 index 08c4d44ec8..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj +++ /dev/null @@ -1,109 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D} - test_lib_json - Win32Proj - - - - Application - MultiByte - - - Application - MultiByte - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - ../../build/vs71/debug/test_lib_json\ - ../../build/vs71/debug/test_lib_json\ - true - ../../build/vs71/release/test_lib_json\ - ../../build/vs71/release/test_lib_json\ - false - - - - Disabled - ../../include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebug - - - Level3 - EditAndContinue - - - $(OutDir)test_lib_json.exe - true - $(OutDir)test_lib_json.pdb - Console - MachineX86 - - - Running all unit tests - $(TargetPath) - - - - - ../../include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreaded - - - Level3 - ProgramDatabase - - - $(OutDir)test_lib_json.exe - true - Console - true - true - MachineX86 - - - Running all unit tests - $(TargetPath) - - - - - - - - - - - - {1e6c2c1c-6453-4129-ae3f-0ee8e6599c89} - - - - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj.filters b/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj.filters deleted file mode 100644 index 8f0a17b995..0000000000 --- a/thirdparty/jsoncpp/makefiles/msvc2010/test_lib_json.vcxproj.filters +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Source Filter - - - Source Filter - - - - - {bf40cbfc-8e98-40b4-b9f3-7e8d579cbae2} - - - {5fd39074-89e6-4939-aa3f-694fefd296b1} - - - - - Header Files - - - \ No newline at end of file diff --git a/thirdparty/jsoncpp/makefiles/vs71/jsoncpp.sln b/thirdparty/jsoncpp/makefiles/vs71/jsoncpp.sln deleted file mode 100644 index 5bfa366547..0000000000 --- a/thirdparty/jsoncpp/makefiles/vs71/jsoncpp.sln +++ /dev/null @@ -1,46 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 8.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_json", "lib_json.vcproj", "{B84F7231-16CE-41D8-8C08-7B523FF4225B}" - ProjectSection(ProjectDependencies) = postProject - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsontest", "jsontest.vcproj", "{25AF2DD2-D396-4668-B188-488C33B8E620}" - ProjectSection(ProjectDependencies) = postProject - {B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_lib_json", "test_lib_json.vcproj", "{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}" - ProjectSection(ProjectDependencies) = postProject - {B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - Debug = Debug - dummy = dummy - Release = Release - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.ActiveCfg = Debug|Win32 - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.Build.0 = Debug|Win32 - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.ActiveCfg = dummy|Win32 - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.Build.0 = dummy|Win32 - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.ActiveCfg = Release|Win32 - {B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.Build.0 = Release|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.ActiveCfg = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.Build.0 = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.ActiveCfg = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.Build.0 = Debug|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Release.ActiveCfg = Release|Win32 - {25AF2DD2-D396-4668-B188-488C33B8E620}.Release.Build.0 = Release|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.ActiveCfg = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.Build.0 = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.ActiveCfg = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.Build.0 = Debug|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.ActiveCfg = Release|Win32 - {B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal diff --git a/thirdparty/jsoncpp/makefiles/vs71/jsontest.vcproj b/thirdparty/jsoncpp/makefiles/vs71/jsontest.vcproj deleted file mode 100644 index 99a4dd6971..0000000000 --- a/thirdparty/jsoncpp/makefiles/vs71/jsontest.vcproj +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/thirdparty/jsoncpp/makefiles/vs71/lib_json.vcproj b/thirdparty/jsoncpp/makefiles/vs71/lib_json.vcproj deleted file mode 100644 index fe66d8ac58..0000000000 --- a/thirdparty/jsoncpp/makefiles/vs71/lib_json.vcproj +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/thirdparty/jsoncpp/makefiles/vs71/test_lib_json.vcproj b/thirdparty/jsoncpp/makefiles/vs71/test_lib_json.vcproj deleted file mode 100644 index df36700bdc..0000000000 --- a/thirdparty/jsoncpp/makefiles/vs71/test_lib_json.vcproj +++ /dev/null @@ -1,130 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/thirdparty/jsoncpp/makerelease.py b/thirdparty/jsoncpp/makerelease.py deleted file mode 100644 index ea3722de44..0000000000 --- a/thirdparty/jsoncpp/makerelease.py +++ /dev/null @@ -1,390 +0,0 @@ -# Copyright 2010 Baptiste Lepilleur -# Distributed under MIT license, or public domain if desired and -# recognized in your jurisdiction. -# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -"""Tag the sandbox for release, make source and doc tarballs. - -Requires Python 2.6 - -Example of invocation (use to test the script): -python makerelease.py --platform=msvc6,msvc71,msvc80,msvc90,mingw -ublep 0.6.0 0.7.0-dev - -When testing this script: -python makerelease.py --force --retag --platform=msvc6,msvc71,msvc80,mingw -ublep test-0.6.0 test-0.6.1-dev - -Example of invocation when doing a release: -python makerelease.py 0.5.0 0.6.0-dev - -Note: This was for Subversion. Now that we are in GitHub, we do not -need to build versioned tarballs anymore, so makerelease.py is defunct. -""" - -from __future__ import print_function -import os.path -import subprocess -import sys -import doxybuild -import subprocess -import xml.etree.ElementTree as ElementTree -import shutil -import urllib2 -import tempfile -import os -import time -from devtools import antglob, fixeol, tarball -import amalgamate - -SVN_ROOT = 'https://jsoncpp.svn.sourceforge.net/svnroot/jsoncpp/' -SVN_TAG_ROOT = SVN_ROOT + 'tags/jsoncpp' -SCONS_LOCAL_URL = 'http://sourceforge.net/projects/scons/files/scons-local/1.2.0/scons-local-1.2.0.tar.gz/download' -SOURCEFORGE_PROJECT = 'jsoncpp' - -def set_version(version): - with open('version','wb') as f: - f.write(version.strip()) - -def rmdir_if_exist(dir_path): - if os.path.isdir(dir_path): - shutil.rmtree(dir_path) - -class SVNError(Exception): - pass - -def svn_command(command, *args): - cmd = ['svn', '--non-interactive', command] + list(args) - print('Running:', ' '.join(cmd)) - process = subprocess.Popen(cmd, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - stdout = process.communicate()[0] - if process.returncode: - error = SVNError('SVN command failed:\n' + stdout) - error.returncode = process.returncode - raise error - return stdout - -def check_no_pending_commit(): - """Checks that there is no pending commit in the sandbox.""" - stdout = svn_command('status', '--xml') - etree = ElementTree.fromstring(stdout) - msg = [] - for entry in etree.getiterator('entry'): - path = entry.get('path') - status = entry.find('wc-status').get('item') - if status != 'unversioned' and path != 'version': - msg.append('File "%s" has pending change (status="%s")' % (path, status)) - if msg: - msg.insert(0, 'Pending change to commit found in sandbox. Commit them first!') - return '\n'.join(msg) - -def svn_join_url(base_url, suffix): - if not base_url.endswith('/'): - base_url += '/' - if suffix.startswith('/'): - suffix = suffix[1:] - return base_url + suffix - -def svn_check_if_tag_exist(tag_url): - """Checks if a tag exist. - Returns: True if the tag exist, False otherwise. - """ - try: - list_stdout = svn_command('list', tag_url) - except SVNError as e: - if e.returncode != 1 or not str(e).find('tag_url'): - raise e - # otherwise ignore error, meaning tag does not exist - return False - return True - -def svn_commit(message): - """Commit the sandbox, providing the specified comment. - """ - svn_command('ci', '-m', message) - -def svn_tag_sandbox(tag_url, message): - """Makes a tag based on the sandbox revisions. - """ - svn_command('copy', '-m', message, '.', tag_url) - -def svn_remove_tag(tag_url, message): - """Removes an existing tag. - """ - svn_command('delete', '-m', message, tag_url) - -def svn_export(tag_url, export_dir): - """Exports the tag_url revision to export_dir. - Target directory, including its parent is created if it does not exist. - If the directory export_dir exist, it is deleted before export proceed. - """ - rmdir_if_exist(export_dir) - svn_command('export', tag_url, export_dir) - -def fix_sources_eol(dist_dir): - """Set file EOL for tarball distribution. - """ - print('Preparing exported source file EOL for distribution...') - prune_dirs = antglob.prune_dirs + 'scons-local* ./build* ./libs ./dist' - win_sources = antglob.glob(dist_dir, - includes = '**/*.sln **/*.vcproj', - prune_dirs = prune_dirs) - unix_sources = antglob.glob(dist_dir, - includes = '''**/*.h **/*.cpp **/*.inl **/*.txt **/*.dox **/*.py **/*.html **/*.in - sconscript *.json *.expected AUTHORS LICENSE''', - excludes = antglob.default_excludes + 'scons.py sconsign.py scons-*', - prune_dirs = prune_dirs) - for path in win_sources: - fixeol.fix_source_eol(path, is_dry_run = False, verbose = True, eol = '\r\n') - for path in unix_sources: - fixeol.fix_source_eol(path, is_dry_run = False, verbose = True, eol = '\n') - -def download(url, target_path): - """Download file represented by url to target_path. - """ - f = urllib2.urlopen(url) - try: - data = f.read() - finally: - f.close() - fout = open(target_path, 'wb') - try: - fout.write(data) - finally: - fout.close() - -def check_compile(distcheck_top_dir, platform): - cmd = [sys.executable, 'scons.py', 'platform=%s' % platform, 'check'] - print('Running:', ' '.join(cmd)) - log_path = os.path.join(distcheck_top_dir, 'build-%s.log' % platform) - flog = open(log_path, 'wb') - try: - process = subprocess.Popen(cmd, - stdout=flog, - stderr=subprocess.STDOUT, - cwd=distcheck_top_dir) - stdout = process.communicate()[0] - status = (process.returncode == 0) - finally: - flog.close() - return (status, log_path) - -def write_tempfile(content, **kwargs): - fd, path = tempfile.mkstemp(**kwargs) - f = os.fdopen(fd, 'wt') - try: - f.write(content) - finally: - f.close() - return path - -class SFTPError(Exception): - pass - -def run_sftp_batch(userhost, sftp, batch, retry=0): - path = write_tempfile(batch, suffix='.sftp', text=True) - # psftp -agent -C blep,jsoncpp@web.sourceforge.net -batch -b batch.sftp -bc - cmd = [sftp, '-agent', '-C', '-batch', '-b', path, '-bc', userhost] - error = None - for retry_index in range(0, max(1,retry)): - heading = retry_index == 0 and 'Running:' or 'Retrying:' - print(heading, ' '.join(cmd)) - process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - stdout = process.communicate()[0] - if process.returncode != 0: - error = SFTPError('SFTP batch failed:\n' + stdout) - else: - break - if error: - raise error - return stdout - -def sourceforge_web_synchro(sourceforge_project, doc_dir, - user=None, sftp='sftp'): - """Notes: does not synchronize sub-directory of doc-dir. - """ - userhost = '%s,%s@web.sourceforge.net' % (user, sourceforge_project) - stdout = run_sftp_batch(userhost, sftp, """ -cd htdocs -dir -exit -""") - existing_paths = set() - collect = 0 - for line in stdout.split('\n'): - line = line.strip() - if not collect and line.endswith('> dir'): - collect = True - elif collect and line.endswith('> exit'): - break - elif collect == 1: - collect = 2 - elif collect == 2: - path = line.strip().split()[-1:] - if path and path[0] not in ('.', '..'): - existing_paths.add(path[0]) - upload_paths = set([os.path.basename(p) for p in antglob.glob(doc_dir)]) - paths_to_remove = existing_paths - upload_paths - if paths_to_remove: - print('Removing the following file from web:') - print('\n'.join(paths_to_remove)) - stdout = run_sftp_batch(userhost, sftp, """cd htdocs -rm %s -exit""" % ' '.join(paths_to_remove)) - print('Uploading %d files:' % len(upload_paths)) - batch_size = 10 - upload_paths = list(upload_paths) - start_time = time.time() - for index in range(0,len(upload_paths),batch_size): - paths = upload_paths[index:index+batch_size] - file_per_sec = (time.time() - start_time) / (index+1) - remaining_files = len(upload_paths) - index - remaining_sec = file_per_sec * remaining_files - print('%d/%d, ETA=%.1fs' % (index+1, len(upload_paths), remaining_sec)) - run_sftp_batch(userhost, sftp, """cd htdocs -lcd %s -mput %s -exit""" % (doc_dir, ' '.join(paths)), retry=3) - -def sourceforge_release_tarball(sourceforge_project, paths, user=None, sftp='sftp'): - userhost = '%s,%s@frs.sourceforge.net' % (user, sourceforge_project) - run_sftp_batch(userhost, sftp, """ -mput %s -exit -""" % (' '.join(paths),)) - - -def main(): - usage = """%prog release_version next_dev_version -Update 'version' file to release_version and commit. -Generates the document tarball. -Tags the sandbox revision with release_version. -Update 'version' file to next_dev_version and commit. - -Performs an svn export of tag release version, and build a source tarball. - -Must be started in the project top directory. - -Warning: --force should only be used when developping/testing the release script. -""" - from optparse import OptionParser - parser = OptionParser(usage=usage) - parser.allow_interspersed_args = False - parser.add_option('--dot', dest="dot_path", action='store', default=doxybuild.find_program('dot'), - help="""Path to GraphViz dot tool. Must be full qualified path. [Default: %default]""") - parser.add_option('--doxygen', dest="doxygen_path", action='store', default=doxybuild.find_program('doxygen'), - help="""Path to Doxygen tool. [Default: %default]""") - parser.add_option('--force', dest="ignore_pending_commit", action='store_true', default=False, - help="""Ignore pending commit. [Default: %default]""") - parser.add_option('--retag', dest="retag_release", action='store_true', default=False, - help="""Overwrite release existing tag if it exist. [Default: %default]""") - parser.add_option('-p', '--platforms', dest="platforms", action='store', default='', - help="""Comma separated list of platform passed to scons for build check.""") - parser.add_option('--no-test', dest="no_test", action='store_true', default=False, - help="""Skips build check.""") - parser.add_option('--no-web', dest="no_web", action='store_true', default=False, - help="""Do not update web site.""") - parser.add_option('-u', '--upload-user', dest="user", action='store', - help="""Sourceforge user for SFTP documentation upload.""") - parser.add_option('--sftp', dest='sftp', action='store', default=doxybuild.find_program('psftp', 'sftp'), - help="""Path of the SFTP compatible binary used to upload the documentation.""") - parser.enable_interspersed_args() - options, args = parser.parse_args() - - if len(args) != 2: - parser.error('release_version missing on command-line.') - release_version = args[0] - next_version = args[1] - - if not options.platforms and not options.no_test: - parser.error('You must specify either --platform or --no-test option.') - - if options.ignore_pending_commit: - msg = '' - else: - msg = check_no_pending_commit() - if not msg: - print('Setting version to', release_version) - set_version(release_version) - svn_commit('Release ' + release_version) - tag_url = svn_join_url(SVN_TAG_ROOT, release_version) - if svn_check_if_tag_exist(tag_url): - if options.retag_release: - svn_remove_tag(tag_url, 'Overwriting previous tag') - else: - print('Aborting, tag %s already exist. Use --retag to overwrite it!' % tag_url) - sys.exit(1) - svn_tag_sandbox(tag_url, 'Release ' + release_version) - - print('Generated doxygen document...') -## doc_dirname = r'jsoncpp-api-html-0.5.0' -## doc_tarball_path = r'e:\prg\vc\Lib\jsoncpp-trunk\dist\jsoncpp-api-html-0.5.0.tar.gz' - doc_tarball_path, doc_dirname = doxybuild.build_doc(options, make_release=True) - doc_distcheck_dir = 'dist/doccheck' - tarball.decompress(doc_tarball_path, doc_distcheck_dir) - doc_distcheck_top_dir = os.path.join(doc_distcheck_dir, doc_dirname) - - export_dir = 'dist/export' - svn_export(tag_url, export_dir) - fix_sources_eol(export_dir) - - source_dir = 'jsoncpp-src-' + release_version - source_tarball_path = 'dist/%s.tar.gz' % source_dir - print('Generating source tarball to', source_tarball_path) - tarball.make_tarball(source_tarball_path, [export_dir], export_dir, prefix_dir=source_dir) - - amalgamation_tarball_path = 'dist/%s-amalgamation.tar.gz' % source_dir - print('Generating amalgamation source tarball to', amalgamation_tarball_path) - amalgamation_dir = 'dist/amalgamation' - amalgamate.amalgamate_source(export_dir, '%s/jsoncpp.cpp' % amalgamation_dir, 'json/json.h') - amalgamation_source_dir = 'jsoncpp-src-amalgamation' + release_version - tarball.make_tarball(amalgamation_tarball_path, [amalgamation_dir], - amalgamation_dir, prefix_dir=amalgamation_source_dir) - - # Decompress source tarball, download and install scons-local - distcheck_dir = 'dist/distcheck' - distcheck_top_dir = distcheck_dir + '/' + source_dir - print('Decompressing source tarball to', distcheck_dir) - rmdir_if_exist(distcheck_dir) - tarball.decompress(source_tarball_path, distcheck_dir) - scons_local_path = 'dist/scons-local.tar.gz' - print('Downloading scons-local to', scons_local_path) - download(SCONS_LOCAL_URL, scons_local_path) - print('Decompressing scons-local to', distcheck_top_dir) - tarball.decompress(scons_local_path, distcheck_top_dir) - - # Run compilation - print('Compiling decompressed tarball') - all_build_status = True - for platform in options.platforms.split(','): - print('Testing platform:', platform) - build_status, log_path = check_compile(distcheck_top_dir, platform) - print('see build log:', log_path) - print(build_status and '=> ok' or '=> FAILED') - all_build_status = all_build_status and build_status - if not build_status: - print('Testing failed on at least one platform, aborting...') - svn_remove_tag(tag_url, 'Removing tag due to failed testing') - sys.exit(1) - if options.user: - if not options.no_web: - print('Uploading documentation using user', options.user) - sourceforge_web_synchro(SOURCEFORGE_PROJECT, doc_distcheck_top_dir, user=options.user, sftp=options.sftp) - print('Completed documentation upload') - print('Uploading source and documentation tarballs for release using user', options.user) - sourceforge_release_tarball(SOURCEFORGE_PROJECT, - [source_tarball_path, doc_tarball_path], - user=options.user, sftp=options.sftp) - print('Source and doc release tarballs uploaded') - else: - print('No upload user specified. Web site and download tarbal were not uploaded.') - print('Tarball can be found at:', doc_tarball_path) - - # Set next version number and commit - set_version(next_version) - svn_commit('Released ' + release_version) - else: - sys.stderr.write(msg + '\n') - -if __name__ == '__main__': - main() diff --git a/thirdparty/jsoncpp/pkg-config/jsoncpp.pc.in b/thirdparty/jsoncpp/pkg-config/jsoncpp.pc.in deleted file mode 100644 index dea51f5125..0000000000 --- a/thirdparty/jsoncpp/pkg-config/jsoncpp.pc.in +++ /dev/null @@ -1,9 +0,0 @@ -libdir=@CMAKE_INSTALL_FULL_LIBDIR@ -includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ - -Name: jsoncpp -Description: A C++ library for interacting with JSON -Version: @JSONCPP_VERSION@ -URL: https://github.com/open-source-parsers/jsoncpp -Libs: -L${libdir} -ljsoncpp -Cflags: -I${includedir} diff --git a/thirdparty/jsoncpp/scons-tools/globtool.py b/thirdparty/jsoncpp/scons-tools/globtool.py deleted file mode 100644 index 890f1b7b1f..0000000000 --- a/thirdparty/jsoncpp/scons-tools/globtool.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2009 Baptiste Lepilleur -# Distributed under MIT license, or public domain if desired and -# recognized in your jurisdiction. -# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -import fnmatch -import os - -def generate(env): - def Glob(env, includes = None, excludes = None, dir = '.'): - """Adds Glob(includes = Split('*'), excludes = None, dir = '.') - helper function to environment. - - Glob both the file-system files. - - includes: list of file name pattern included in the return list when matched. - excludes: list of file name pattern exluced from the return list. - - Example: - sources = env.Glob(("*.cpp", '*.h'), "~*.cpp", "#src") - """ - def filterFilename(path): - abs_path = os.path.join(dir, path) - if not os.path.isfile(abs_path): - return 0 - fn = os.path.basename(path) - match = 0 - for include in includes: - if fnmatch.fnmatchcase(fn, include): - match = 1 - break - if match == 1 and not excludes is None: - for exclude in excludes: - if fnmatch.fnmatchcase(fn, exclude): - match = 0 - break - return match - if includes is None: - includes = ('*',) - elif type(includes) in (type(''), type(u'')): - includes = (includes,) - if type(excludes) in (type(''), type(u'')): - excludes = (excludes,) - dir = env.Dir(dir).abspath - paths = os.listdir(dir) - def makeAbsFileNode(path): - return env.File(os.path.join(dir, path)) - nodes = filter(filterFilename, paths) - return map(makeAbsFileNode, nodes) - - from SCons.Script import Environment - Environment.Glob = Glob - -def exists(env): - """ - Tool always exists. - """ - return True diff --git a/thirdparty/jsoncpp/scons-tools/srcdist.py b/thirdparty/jsoncpp/scons-tools/srcdist.py deleted file mode 100644 index fe1d74695a..0000000000 --- a/thirdparty/jsoncpp/scons-tools/srcdist.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright 2007 Baptiste Lepilleur -# Distributed under MIT license, or public domain if desired and -# recognized in your jurisdiction. -# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -import os -import os.path -from fnmatch import fnmatch -import targz - -##def DoxyfileParse(file_contents): -## """ -## Parse a Doxygen source file and return a dictionary of all the values. -## Values will be strings and lists of strings. -## """ -## data = {} -## -## import shlex -## lex = shlex.shlex(instream = file_contents, posix = True) -## lex.wordchars += "*+./-:" -## lex.whitespace = lex.whitespace.replace("\n", "") -## lex.escape = "" -## -## lineno = lex.lineno -## last_backslash_lineno = lineno -## token = lex.get_token() -## key = token # the first token should be a key -## last_token = "" -## key_token = False -## next_key = False -## new_data = True -## -## def append_data(data, key, new_data, token): -## if new_data or len(data[key]) == 0: -## data[key].append(token) -## else: -## data[key][-1] += token -## -## while token: -## if token in ['\n']: -## if last_token not in ['\\']: -## key_token = True -## elif token in ['\\']: -## pass -## elif key_token: -## key = token -## key_token = False -## else: -## if token == "+=": -## if not data.has_key(key): -## data[key] = list() -## elif token == "=": -## data[key] = list() -## else: -## append_data(data, key, new_data, token) -## new_data = True -## -## last_token = token -## token = lex.get_token() -## -## if last_token == '\\' and token != '\n': -## new_data = False -## append_data(data, key, new_data, '\\') -## -## # compress lists of len 1 into single strings -## for (k, v) in data.items(): -## if len(v) == 0: -## data.pop(k) -## -## # items in the following list will be kept as lists and not converted to strings -## if k in ["INPUT", "FILE_PATTERNS", "EXCLUDE_PATTERNS"]: -## continue -## -## if len(v) == 1: -## data[k] = v[0] -## -## return data -## -##def DoxySourceScan(node, env, path): -## """ -## Doxygen Doxyfile source scanner. This should scan the Doxygen file and add -## any files used to generate docs to the list of source files. -## """ -## default_file_patterns = [ -## '*.c', '*.cc', '*.cxx', '*.cpp', '*.c++', '*.java', '*.ii', '*.ixx', -## '*.ipp', '*.i++', '*.inl', '*.h', '*.hh ', '*.hxx', '*.hpp', '*.h++', -## '*.idl', '*.odl', '*.cs', '*.php', '*.php3', '*.inc', '*.m', '*.mm', -## '*.py', -## ] -## -## default_exclude_patterns = [ -## '*~', -## ] -## -## sources = [] -## -## data = DoxyfileParse(node.get_contents()) -## -## if data.get("RECURSIVE", "NO") == "YES": -## recursive = True -## else: -## recursive = False -## -## file_patterns = data.get("FILE_PATTERNS", default_file_patterns) -## exclude_patterns = data.get("EXCLUDE_PATTERNS", default_exclude_patterns) -## -## for node in data.get("INPUT", []): -## if os.path.isfile(node): -## sources.add(node) -## elif os.path.isdir(node): -## if recursive: -## for root, dirs, files in os.walk(node): -## for f in files: -## filename = os.path.join(root, f) -## -## pattern_check = reduce(lambda x, y: x or bool(fnmatch(filename, y)), file_patterns, False) -## exclude_check = reduce(lambda x, y: x and fnmatch(filename, y), exclude_patterns, True) -## -## if pattern_check and not exclude_check: -## sources.append(filename) -## else: -## for pattern in file_patterns: -## sources.extend(glob.glob("/".join([node, pattern]))) -## sources = map(lambda path: env.File(path), sources) -## return sources -## -## -##def DoxySourceScanCheck(node, env): -## """Check if we should scan this file""" -## return os.path.isfile(node.path) - -def srcDistEmitter(source, target, env): -## """Doxygen Doxyfile emitter""" -## # possible output formats and their default values and output locations -## output_formats = { -## "HTML": ("YES", "html"), -## "LATEX": ("YES", "latex"), -## "RTF": ("NO", "rtf"), -## "MAN": ("YES", "man"), -## "XML": ("NO", "xml"), -## } -## -## data = DoxyfileParse(source[0].get_contents()) -## -## targets = [] -## out_dir = data.get("OUTPUT_DIRECTORY", ".") -## -## # add our output locations -## for (k, v) in output_formats.items(): -## if data.get("GENERATE_" + k, v[0]) == "YES": -## targets.append(env.Dir(os.path.join(out_dir, data.get(k + "_OUTPUT", v[1])))) -## -## # don't clobber targets -## for node in targets: -## env.Precious(node) -## -## # set up cleaning stuff -## for node in targets: -## env.Clean(node, node) -## -## return (targets, source) - return (target,source) - -def generate(env): - """ - Add builders and construction variables for the - SrcDist tool. - """ -## doxyfile_scanner = env.Scanner(## DoxySourceScan, -## "DoxySourceScan", -## scan_check = DoxySourceScanCheck, -##) - - if targz.exists(env): - srcdist_builder = targz.makeBuilder(srcDistEmitter) - - env['BUILDERS']['SrcDist'] = srcdist_builder - -def exists(env): - """ - Make sure srcdist exists. - """ - return targz.exists(env) diff --git a/thirdparty/jsoncpp/scons-tools/substinfile.py b/thirdparty/jsoncpp/scons-tools/substinfile.py deleted file mode 100644 index c620442d57..0000000000 --- a/thirdparty/jsoncpp/scons-tools/substinfile.py +++ /dev/null @@ -1,85 +0,0 @@ -# Copyright 2010 Baptiste Lepilleur -# Distributed under MIT license, or public domain if desired and -# recognized in your jurisdiction. -# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -import re -from SCons.Script import * # the usual scons stuff you get in a SConscript -import collections - -def generate(env): - """ - Add builders and construction variables for the - SubstInFile tool. - - Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT - from the source to the target. - The values of SUBST_DICT first have any construction variables expanded - (its keys are not expanded). - If a value of SUBST_DICT is a python callable function, it is called and - the result is expanded as the value. - If there's more than one source and more than one target, each target gets - substituted from the corresponding source. - """ - def do_subst_in_file(targetfile, sourcefile, dict): - """Replace all instances of the keys of dict with their values. - For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'}, - then all instances of %VERSION% in the file will be replaced with 1.2345 etc. - """ - try: - f = open(sourcefile, 'rb') - contents = f.read() - f.close() - except: - raise SCons.Errors.UserError("Can't read source file %s"%sourcefile) - for (k,v) in list(dict.items()): - contents = re.sub(k, v, contents) - try: - f = open(targetfile, 'wb') - f.write(contents) - f.close() - except: - raise SCons.Errors.UserError("Can't write target file %s"%targetfile) - return 0 # success - - def subst_in_file(target, source, env): - if 'SUBST_DICT' not in env: - raise SCons.Errors.UserError("SubstInFile requires SUBST_DICT to be set.") - d = dict(env['SUBST_DICT']) # copy it - for (k,v) in list(d.items()): - if isinstance(v, collections.Callable): - d[k] = env.subst(v()).replace('\\','\\\\') - elif SCons.Util.is_String(v): - d[k] = env.subst(v).replace('\\','\\\\') - else: - raise SCons.Errors.UserError("SubstInFile: key %s: %s must be a string or callable"%(k, repr(v))) - for (t,s) in zip(target, source): - return do_subst_in_file(str(t), str(s), d) - - def subst_in_file_string(target, source, env): - """This is what gets printed on the console.""" - return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t)) - for (t,s) in zip(target, source)]) - - def subst_emitter(target, source, env): - """Add dependency from substituted SUBST_DICT to target. - Returns original target, source tuple unchanged. - """ - d = env['SUBST_DICT'].copy() # copy it - for (k,v) in list(d.items()): - if isinstance(v, collections.Callable): - d[k] = env.subst(v()) - elif SCons.Util.is_String(v): - d[k]=env.subst(v) - Depends(target, SCons.Node.Python.Value(d)) - return target, source - -## env.Append(TOOLS = 'substinfile') # this should be automaticaly done by Scons ?!? - subst_action = SCons.Action.Action(subst_in_file, subst_in_file_string) - env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter) - -def exists(env): - """ - Make sure tool exists. - """ - return True diff --git a/thirdparty/jsoncpp/scons-tools/targz.py b/thirdparty/jsoncpp/scons-tools/targz.py deleted file mode 100644 index 8e5ba83003..0000000000 --- a/thirdparty/jsoncpp/scons-tools/targz.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2007 Baptiste Lepilleur -# Distributed under MIT license, or public domain if desired and -# recognized in your jurisdiction. -# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -"""tarball - -Tool-specific initialization for tarball. - -""" - -## Commands to tackle a command based implementation: -##to unpack on the fly... -##gunzip < FILE.tar.gz | tar xvf - -##to pack on the fly... -##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz - -import os.path - -import SCons.Builder -import SCons.Node.FS -import SCons.Util - -try: - import gzip - import tarfile - internal_targz = 1 -except ImportError: - internal_targz = 0 - -TARGZ_DEFAULT_COMPRESSION_LEVEL = 9 - -if internal_targz: - def targz(target, source, env): - def archive_name(path): - path = os.path.normpath(os.path.abspath(path)) - common_path = os.path.commonprefix((base_dir, path)) - archive_name = path[len(common_path):] - return archive_name - - def visit(tar, dirname, names): - for name in names: - path = os.path.join(dirname, name) - if os.path.isfile(path): - tar.add(path, archive_name(path)) - compression = env.get('TARGZ_COMPRESSION_LEVEL',TARGZ_DEFAULT_COMPRESSION_LEVEL) - base_dir = os.path.normpath(env.get('TARGZ_BASEDIR', env.Dir('.')).abspath) - target_path = str(target[0]) - fileobj = gzip.GzipFile(target_path, 'wb', compression) - tar = tarfile.TarFile(os.path.splitext(target_path)[0], 'w', fileobj) - for source in source: - source_path = str(source) - if source.isdir(): - os.path.walk(source_path, visit, tar) - else: - tar.add(source_path, archive_name(source_path)) # filename, arcname - tar.close() - - targzAction = SCons.Action.Action(targz, varlist=['TARGZ_COMPRESSION_LEVEL','TARGZ_BASEDIR']) - - def makeBuilder(emitter = None): - return SCons.Builder.Builder(action = SCons.Action.Action('$TARGZ_COM', '$TARGZ_COMSTR'), - source_factory = SCons.Node.FS.Entry, - source_scanner = SCons.Defaults.DirScanner, - suffix = '$TARGZ_SUFFIX', - multi = 1) - TarGzBuilder = makeBuilder() - - def generate(env): - """Add Builders and construction variables for zip to an Environment. - The following environnement variables may be set: - TARGZ_COMPRESSION_LEVEL: integer, [0-9]. 0: no compression, 9: best compression (same as gzip compression level). - TARGZ_BASEDIR: base-directory used to determine archive name (this allow archive name to be relative - to something other than top-dir). - """ - env['BUILDERS']['TarGz'] = TarGzBuilder - env['TARGZ_COM'] = targzAction - env['TARGZ_COMPRESSION_LEVEL'] = TARGZ_DEFAULT_COMPRESSION_LEVEL # range 0-9 - env['TARGZ_SUFFIX'] = '.tar.gz' - env['TARGZ_BASEDIR'] = env.Dir('.') # Sources archive name are made relative to that directory. -else: - def generate(env): - pass - - -def exists(env): - return internal_targz diff --git a/thirdparty/jsoncpp/src/CMakeLists.txt b/thirdparty/jsoncpp/src/CMakeLists.txt deleted file mode 100644 index ca8ac15e28..0000000000 --- a/thirdparty/jsoncpp/src/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -ADD_SUBDIRECTORY(lib_json) -IF(JSONCPP_WITH_TESTS) - ADD_SUBDIRECTORY(jsontestrunner) - ADD_SUBDIRECTORY(test_lib_json) -ENDIF() diff --git a/thirdparty/jsoncpp/src/jsontestrunner/CMakeLists.txt b/thirdparty/jsoncpp/src/jsontestrunner/CMakeLists.txt deleted file mode 100644 index 20d01e6268..0000000000 --- a/thirdparty/jsoncpp/src/jsontestrunner/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -FIND_PACKAGE(PythonInterp 2.6) - -ADD_EXECUTABLE(jsontestrunner_exe - main.cpp - ) - -IF(BUILD_SHARED_LIBS) - ADD_DEFINITIONS( -DJSON_DLL ) - TARGET_LINK_LIBRARIES(jsontestrunner_exe jsoncpp_lib) -ELSE(BUILD_SHARED_LIBS) - TARGET_LINK_LIBRARIES(jsontestrunner_exe jsoncpp_lib_static) -ENDIF() - -SET_TARGET_PROPERTIES(jsontestrunner_exe PROPERTIES OUTPUT_NAME jsontestrunner_exe) - -IF(PYTHONINTERP_FOUND) - # Run end to end parser/writer tests - SET(TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../test) - SET(RUNJSONTESTS_PATH ${TEST_DIR}/runjsontests.py) - ADD_CUSTOM_TARGET(jsoncpp_readerwriter_tests - "${PYTHON_EXECUTABLE}" -B "${RUNJSONTESTS_PATH}" $ "${TEST_DIR}/data" - DEPENDS jsontestrunner_exe jsoncpp_test - ) - ADD_CUSTOM_TARGET(jsoncpp_check DEPENDS jsoncpp_readerwriter_tests) -ENDIF() diff --git a/thirdparty/jsoncpp/src/jsontestrunner/main.cpp b/thirdparty/jsoncpp/src/jsontestrunner/main.cpp deleted file mode 100644 index 45db464a18..0000000000 --- a/thirdparty/jsoncpp/src/jsontestrunner/main.cpp +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -/* This executable is used for testing parser/writer using real JSON files. - */ - -#include -#include // sort -#include -#include - -#if defined(_MSC_VER) && _MSC_VER >= 1310 -#pragma warning(disable : 4996) // disable fopen deprecation warning -#endif - -struct Options -{ - JSONCPP_STRING path; - Json::Features features; - bool parseOnly; - typedef JSONCPP_STRING (*writeFuncType)(Json::Value const&); - writeFuncType write; -}; - -static JSONCPP_STRING normalizeFloatingPointStr(double value) { - char buffer[32]; -#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) - sprintf_s(buffer, sizeof(buffer), "%.16g", value); -#else - snprintf(buffer, sizeof(buffer), "%.16g", value); -#endif - buffer[sizeof(buffer) - 1] = 0; - JSONCPP_STRING s(buffer); - JSONCPP_STRING::size_type index = s.find_last_of("eE"); - if (index != JSONCPP_STRING::npos) { - JSONCPP_STRING::size_type hasSign = - (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0; - JSONCPP_STRING::size_type exponentStartIndex = index + 1 + hasSign; - JSONCPP_STRING normalized = s.substr(0, exponentStartIndex); - JSONCPP_STRING::size_type indexDigit = - s.find_first_not_of('0', exponentStartIndex); - JSONCPP_STRING exponent = "0"; - if (indexDigit != - JSONCPP_STRING::npos) // There is an exponent different from 0 - { - exponent = s.substr(indexDigit); - } - return normalized + exponent; - } - return s; -} - -static JSONCPP_STRING readInputTestFile(const char* path) { - FILE* file = fopen(path, "rb"); - if (!file) - return JSONCPP_STRING(""); - fseek(file, 0, SEEK_END); - long const size = ftell(file); - unsigned long const usize = static_cast(size); - fseek(file, 0, SEEK_SET); - JSONCPP_STRING text; - char* buffer = new char[size + 1]; - buffer[size] = 0; - if (fread(buffer, 1, usize, file) == usize) - text = buffer; - fclose(file); - delete[] buffer; - return text; -} - -static void -printValueTree(FILE* fout, Json::Value& value, const JSONCPP_STRING& path = ".") { - if (value.hasComment(Json::commentBefore)) { - fprintf(fout, "%s\n", value.getComment(Json::commentBefore).c_str()); - } - switch (value.type()) { - case Json::nullValue: - fprintf(fout, "%s=null\n", path.c_str()); - break; - case Json::intValue: - fprintf(fout, - "%s=%s\n", - path.c_str(), - Json::valueToString(value.asLargestInt()).c_str()); - break; - case Json::uintValue: - fprintf(fout, - "%s=%s\n", - path.c_str(), - Json::valueToString(value.asLargestUInt()).c_str()); - break; - case Json::realValue: - fprintf(fout, - "%s=%s\n", - path.c_str(), - normalizeFloatingPointStr(value.asDouble()).c_str()); - break; - case Json::stringValue: - fprintf(fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str()); - break; - case Json::booleanValue: - fprintf(fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false"); - break; - case Json::arrayValue: { - fprintf(fout, "%s=[]\n", path.c_str()); - Json::ArrayIndex size = value.size(); - for (Json::ArrayIndex index = 0; index < size; ++index) { - static char buffer[16]; -#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) - sprintf_s(buffer, sizeof(buffer), "[%d]", index); -#else - snprintf(buffer, sizeof(buffer), "[%d]", index); -#endif - printValueTree(fout, value[index], path + buffer); - } - } break; - case Json::objectValue: { - fprintf(fout, "%s={}\n", path.c_str()); - Json::Value::Members members(value.getMemberNames()); - std::sort(members.begin(), members.end()); - JSONCPP_STRING suffix = *(path.end() - 1) == '.' ? "" : "."; - for (Json::Value::Members::iterator it = members.begin(); - it != members.end(); - ++it) { - const JSONCPP_STRING name = *it; - printValueTree(fout, value[name], path + suffix + name); - } - } break; - default: - break; - } - - if (value.hasComment(Json::commentAfter)) { - fprintf(fout, "%s\n", value.getComment(Json::commentAfter).c_str()); - } -} - -static int parseAndSaveValueTree(const JSONCPP_STRING& input, - const JSONCPP_STRING& actual, - const JSONCPP_STRING& kind, - const Json::Features& features, - bool parseOnly, - Json::Value* root) -{ - Json::Reader reader(features); - bool parsingSuccessful = reader.parse(input.data(), input.data() + input.size(), *root); - if (!parsingSuccessful) { - printf("Failed to parse %s file: \n%s\n", - kind.c_str(), - reader.getFormattedErrorMessages().c_str()); - return 1; - } - if (!parseOnly) { - FILE* factual = fopen(actual.c_str(), "wt"); - if (!factual) { - printf("Failed to create %s actual file.\n", kind.c_str()); - return 2; - } - printValueTree(factual, *root); - fclose(factual); - } - return 0; -} -// static JSONCPP_STRING useFastWriter(Json::Value const& root) { -// Json::FastWriter writer; -// writer.enableYAMLCompatibility(); -// return writer.write(root); -// } -static JSONCPP_STRING useStyledWriter( - Json::Value const& root) -{ - Json::StyledWriter writer; - return writer.write(root); -} -static JSONCPP_STRING useStyledStreamWriter( - Json::Value const& root) -{ - Json::StyledStreamWriter writer; - JSONCPP_OSTRINGSTREAM sout; - writer.write(sout, root); - return sout.str(); -} -static JSONCPP_STRING useBuiltStyledStreamWriter( - Json::Value const& root) -{ - Json::StreamWriterBuilder builder; - return Json::writeString(builder, root); -} -static int rewriteValueTree( - const JSONCPP_STRING& rewritePath, - const Json::Value& root, - Options::writeFuncType write, - JSONCPP_STRING* rewrite) -{ - *rewrite = write(root); - FILE* fout = fopen(rewritePath.c_str(), "wt"); - if (!fout) { - printf("Failed to create rewrite file: %s\n", rewritePath.c_str()); - return 2; - } - fprintf(fout, "%s\n", rewrite->c_str()); - fclose(fout); - return 0; -} - -static JSONCPP_STRING removeSuffix(const JSONCPP_STRING& path, - const JSONCPP_STRING& extension) { - if (extension.length() >= path.length()) - return JSONCPP_STRING(""); - JSONCPP_STRING suffix = path.substr(path.length() - extension.length()); - if (suffix != extension) - return JSONCPP_STRING(""); - return path.substr(0, path.length() - extension.length()); -} - -static void printConfig() { -// Print the configuration used to compile JsonCpp -#if defined(JSON_NO_INT64) - printf("JSON_NO_INT64=1\n"); -#else - printf("JSON_NO_INT64=0\n"); -#endif -} - -static int printUsage(const char* argv[]) { - printf("Usage: %s [--strict] input-json-file", argv[0]); - return 3; -} - -static int parseCommandLine( - int argc, const char* argv[], Options* opts) -{ - opts->parseOnly = false; - opts->write = &useStyledWriter; - if (argc < 2) { - return printUsage(argv); - } - int index = 1; - if (JSONCPP_STRING(argv[index]) == "--json-checker") { - opts->features = Json::Features::strictMode(); - opts->parseOnly = true; - ++index; - } - if (JSONCPP_STRING(argv[index]) == "--json-config") { - printConfig(); - return 3; - } - if (JSONCPP_STRING(argv[index]) == "--json-writer") { - ++index; - JSONCPP_STRING const writerName(argv[index++]); - if (writerName == "StyledWriter") { - opts->write = &useStyledWriter; - } else if (writerName == "StyledStreamWriter") { - opts->write = &useStyledStreamWriter; - } else if (writerName == "BuiltStyledStreamWriter") { - opts->write = &useBuiltStyledStreamWriter; - } else { - printf("Unknown '--json-writer %s'\n", writerName.c_str()); - return 4; - } - } - if (index == argc || index + 1 < argc) { - return printUsage(argv); - } - opts->path = argv[index]; - return 0; -} -static int runTest(Options const& opts) -{ - int exitCode = 0; - - JSONCPP_STRING input = readInputTestFile(opts.path.c_str()); - if (input.empty()) { - printf("Failed to read input or empty input: %s\n", opts.path.c_str()); - return 3; - } - - JSONCPP_STRING basePath = removeSuffix(opts.path, ".json"); - if (!opts.parseOnly && basePath.empty()) { - printf("Bad input path. Path does not end with '.expected':\n%s\n", - opts.path.c_str()); - return 3; - } - - JSONCPP_STRING const actualPath = basePath + ".actual"; - JSONCPP_STRING const rewritePath = basePath + ".rewrite"; - JSONCPP_STRING const rewriteActualPath = basePath + ".actual-rewrite"; - - Json::Value root; - exitCode = parseAndSaveValueTree( - input, actualPath, "input", - opts.features, opts.parseOnly, &root); - if (exitCode || opts.parseOnly) { - return exitCode; - } - JSONCPP_STRING rewrite; - exitCode = rewriteValueTree(rewritePath, root, opts.write, &rewrite); - if (exitCode) { - return exitCode; - } - Json::Value rewriteRoot; - exitCode = parseAndSaveValueTree( - rewrite, rewriteActualPath, "rewrite", - opts.features, opts.parseOnly, &rewriteRoot); - if (exitCode) { - return exitCode; - } - return 0; -} -int main(int argc, const char* argv[]) { - Options opts; - try { - int exitCode = parseCommandLine(argc, argv, &opts); - if (exitCode != 0) { - printf("Failed to parse command-line."); - return exitCode; - } - return runTest(opts); - } - catch (const std::exception& e) { - printf("Unhandled exception:\n%s\n", e.what()); - return 1; - } -} diff --git a/thirdparty/jsoncpp/src/jsontestrunner/sconscript b/thirdparty/jsoncpp/src/jsontestrunner/sconscript deleted file mode 100644 index 6e68e31533..0000000000 --- a/thirdparty/jsoncpp/src/jsontestrunner/sconscript +++ /dev/null @@ -1,9 +0,0 @@ -Import( 'env_testing buildJSONTests' ) - -buildJSONTests( env_testing, Split( """ - main.cpp - """ ), - 'jsontestrunner' ) - -# For 'check' to work, 'libs' must be built first. -env_testing.Depends('jsontestrunner', '#libs') diff --git a/thirdparty/jsoncpp/src/lib_json/CMakeLists.txt b/thirdparty/jsoncpp/src/lib_json/CMakeLists.txt deleted file mode 100644 index c64aab2efa..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/CMakeLists.txt +++ /dev/null @@ -1,113 +0,0 @@ -IF( CMAKE_COMPILER_IS_GNUCXX ) - #Get compiler version. - EXECUTE_PROCESS( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion - OUTPUT_VARIABLE GNUCXX_VERSION ) - - #-Werror=* was introduced -after- GCC 4.1.2 - IF( GNUCXX_VERSION VERSION_GREATER 4.1.2 ) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=strict-aliasing") - ENDIF() -ENDIF( CMAKE_COMPILER_IS_GNUCXX ) - -INCLUDE(CheckIncludeFileCXX) -INCLUDE(CheckTypeSize) -INCLUDE(CheckStructHasMember) -INCLUDE(CheckCXXSymbolExists) - -check_include_file_cxx(clocale HAVE_CLOCALE) -check_cxx_symbol_exists(localeconv clocale HAVE_LOCALECONV) - -IF(CMAKE_VERSION VERSION_LESS 3.0.0) - # The "LANGUAGE CXX" parameter is not supported in CMake versions below 3, - # so the C compiler and header has to be used. - check_include_file(locale.h HAVE_LOCALE_H) - SET(CMAKE_EXTRA_INCLUDE_FILES locale.h) - check_type_size("struct lconv" LCONV_SIZE) - UNSET(CMAKE_EXTRA_INCLUDE_FILES) - check_struct_has_member("struct lconv" decimal_point locale.h HAVE_DECIMAL_POINT) -ELSE() - SET(CMAKE_EXTRA_INCLUDE_FILES clocale) - check_type_size(lconv LCONV_SIZE LANGUAGE CXX) - UNSET(CMAKE_EXTRA_INCLUDE_FILES) - check_struct_has_member(lconv decimal_point clocale HAVE_DECIMAL_POINT LANGUAGE CXX) -ENDIF() - -IF(NOT (HAVE_CLOCALE AND HAVE_LCONV_SIZE AND HAVE_DECIMAL_POINT AND HAVE_LOCALECONV)) - MESSAGE(WARNING "Locale functionality is not supported") - ADD_DEFINITIONS(-DJSONCPP_NO_LOCALE_SUPPORT) -ENDIF() - -SET( JSONCPP_INCLUDE_DIR ../../include ) - -SET( PUBLIC_HEADERS - ${JSONCPP_INCLUDE_DIR}/json/config.h - ${JSONCPP_INCLUDE_DIR}/json/forwards.h - ${JSONCPP_INCLUDE_DIR}/json/features.h - ${JSONCPP_INCLUDE_DIR}/json/value.h - ${JSONCPP_INCLUDE_DIR}/json/reader.h - ${JSONCPP_INCLUDE_DIR}/json/writer.h - ${JSONCPP_INCLUDE_DIR}/json/assertions.h - ${JSONCPP_INCLUDE_DIR}/json/version.h - ) - -SOURCE_GROUP( "Public API" FILES ${PUBLIC_HEADERS} ) - -SET(jsoncpp_sources - json_tool.h - json_reader.cpp - json_valueiterator.inl - json_value.cpp - json_writer.cpp - version.h.in) - -# Install instructions for this target -IF(JSONCPP_WITH_CMAKE_PACKAGE) - SET(INSTALL_EXPORT EXPORT jsoncpp) -ELSE(JSONCPP_WITH_CMAKE_PACKAGE) - SET(INSTALL_EXPORT) -ENDIF() - -IF(BUILD_SHARED_LIBS) - ADD_DEFINITIONS( -DJSON_DLL_BUILD ) - ADD_LIBRARY(jsoncpp_lib SHARED ${PUBLIC_HEADERS} ${jsoncpp_sources}) - SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES VERSION ${JSONCPP_VERSION} SOVERSION ${JSONCPP_SOVERSION}) - SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES OUTPUT_NAME jsoncpp - DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} ) - - # Set library's runtime search path on OSX - IF(APPLE) - SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES INSTALL_RPATH "@loader_path/." ) - ENDIF() - - INSTALL( TARGETS jsoncpp_lib ${INSTALL_EXPORT} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) - - IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11) - TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib PUBLIC - $ - $) - ENDIF() - -ENDIF() - -IF(BUILD_STATIC_LIBS) - ADD_LIBRARY(jsoncpp_lib_static STATIC ${PUBLIC_HEADERS} ${jsoncpp_sources}) - SET_TARGET_PROPERTIES( jsoncpp_lib_static PROPERTIES VERSION ${JSONCPP_VERSION} SOVERSION ${JSONCPP_SOVERSION}) - SET_TARGET_PROPERTIES( jsoncpp_lib_static PROPERTIES OUTPUT_NAME jsoncpp - DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} ) - - INSTALL( TARGETS jsoncpp_lib_static ${INSTALL_EXPORT} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) - - IF(NOT CMAKE_VERSION VERSION_LESS 2.8.11) - TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib_static PUBLIC - $ - $ - ) - ENDIF() - -ENDIF() diff --git a/thirdparty/jsoncpp/src/lib_json/json_reader.cpp b/thirdparty/jsoncpp/src/lib_json/json_reader.cpp deleted file mode 100644 index 6de6a31ade..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/json_reader.cpp +++ /dev/null @@ -1,2036 +0,0 @@ -// Copyright 2007-2011 Baptiste Lepilleur -// Copyright (C) 2016 InfoTeCS JSC. All rights reserved. -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#include "json_tool.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_MSC_VER) -#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above -#define snprintf sprintf_s -#elif _MSC_VER >= 1900 // VC++ 14.0 and above -#define snprintf std::snprintf -#else -#define snprintf _snprintf -#endif -#elif defined(__ANDROID__) || defined(__QNXNTO__) -#define snprintf snprintf -#elif __cplusplus >= 201103L -#if !defined(__MINGW32__) && !defined(__CYGWIN__) -#define snprintf std::snprintf -#endif -#endif - -#if defined(__QNXNTO__) -#define sscanf std::sscanf -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0 -// Disable warning about strdup being deprecated. -#pragma warning(disable : 4996) -#endif - -// Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile time to change the stack limit -#if !defined(JSONCPP_DEPRECATED_STACK_LIMIT) -#define JSONCPP_DEPRECATED_STACK_LIMIT 1000 -#endif - -static size_t const stackLimit_g = JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue() - -namespace Json { - -#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520) -typedef std::unique_ptr CharReaderPtr; -#else -typedef std::auto_ptr CharReaderPtr; -#endif - -// Implementation of class Features -// //////////////////////////////// - -Features::Features() - : allowComments_(true), strictRoot_(false), - allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {} - -Features Features::all() { return Features(); } - -Features Features::strictMode() { - Features features; - features.allowComments_ = false; - features.strictRoot_ = true; - features.allowDroppedNullPlaceholders_ = false; - features.allowNumericKeys_ = false; - return features; -} - -// Implementation of class Reader -// //////////////////////////////// - -static bool containsNewLine(Reader::Location begin, Reader::Location end) { - for (; begin < end; ++begin) - if (*begin == '\n' || *begin == '\r') - return true; - return false; -} - -// Class Reader -// ////////////////////////////////////////////////////////////////// - -Reader::Reader() - : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), - lastValue_(), commentsBefore_(), features_(Features::all()), - collectComments_() {} - -Reader::Reader(const Features& features) - : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), - lastValue_(), commentsBefore_(), features_(features), collectComments_() { -} - -bool -Reader::parse(const std::string& document, Value& root, bool collectComments) { - JSONCPP_STRING documentCopy(document.data(), document.data() + document.capacity()); - std::swap(documentCopy, document_); - const char* begin = document_.c_str(); - const char* end = begin + document_.length(); - return parse(begin, end, root, collectComments); -} - -bool Reader::parse(std::istream& sin, Value& root, bool collectComments) { - // std::istream_iterator begin(sin); - // std::istream_iterator end; - // Those would allow streamed input from a file, if parse() were a - // template function. - - // Since JSONCPP_STRING is reference-counted, this at least does not - // create an extra copy. - JSONCPP_STRING doc; - std::getline(sin, doc, (char)EOF); - return parse(doc.data(), doc.data() + doc.size(), root, collectComments); -} - -bool Reader::parse(const char* beginDoc, - const char* endDoc, - Value& root, - bool collectComments) { - if (!features_.allowComments_) { - collectComments = false; - } - - begin_ = beginDoc; - end_ = endDoc; - collectComments_ = collectComments; - current_ = begin_; - lastValueEnd_ = 0; - lastValue_ = 0; - commentsBefore_ = ""; - errors_.clear(); - while (!nodes_.empty()) - nodes_.pop(); - nodes_.push(&root); - - bool successful = readValue(); - Token token; - skipCommentTokens(token); - if (collectComments_ && !commentsBefore_.empty()) - root.setComment(commentsBefore_, commentAfter); - if (features_.strictRoot_) { - if (!root.isArray() && !root.isObject()) { - // Set error location to start of doc, ideally should be first token found - // in doc - token.type_ = tokenError; - token.start_ = beginDoc; - token.end_ = endDoc; - addError( - "A valid JSON document must be either an array or an object value.", - token); - return false; - } - } - return successful; -} - -bool Reader::readValue() { - // readValue() may call itself only if it calls readObject() or ReadArray(). - // These methods execute nodes_.push() just before and nodes_.pop)() just after calling readValue(). - // parse() executes one nodes_.push(), so > instead of >=. - if (nodes_.size() > stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue()."); - - Token token; - skipCommentTokens(token); - bool successful = true; - - if (collectComments_ && !commentsBefore_.empty()) { - currentValue().setComment(commentsBefore_, commentBefore); - commentsBefore_ = ""; - } - - switch (token.type_) { - case tokenObjectBegin: - successful = readObject(token); - currentValue().setOffsetLimit(current_ - begin_); - break; - case tokenArrayBegin: - successful = readArray(token); - currentValue().setOffsetLimit(current_ - begin_); - break; - case tokenNumber: - successful = decodeNumber(token); - break; - case tokenString: - successful = decodeString(token); - break; - case tokenTrue: - { - Value v(true); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenFalse: - { - Value v(false); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenNull: - { - Value v; - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenArraySeparator: - case tokenObjectEnd: - case tokenArrayEnd: - if (features_.allowDroppedNullPlaceholders_) { - // "Un-read" the current token and mark the current value as a null - // token. - current_--; - Value v; - currentValue().swapPayload(v); - currentValue().setOffsetStart(current_ - begin_ - 1); - currentValue().setOffsetLimit(current_ - begin_); - break; - } // Else, fall through... - default: - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return addError("Syntax error: value, object or array expected.", token); - } - - if (collectComments_) { - lastValueEnd_ = current_; - lastValue_ = ¤tValue(); - } - - return successful; -} - -void Reader::skipCommentTokens(Token& token) { - if (features_.allowComments_) { - do { - readToken(token); - } while (token.type_ == tokenComment); - } else { - readToken(token); - } -} - -bool Reader::readToken(Token& token) { - skipSpaces(); - token.start_ = current_; - Char c = getNextChar(); - bool ok = true; - switch (c) { - case '{': - token.type_ = tokenObjectBegin; - break; - case '}': - token.type_ = tokenObjectEnd; - break; - case '[': - token.type_ = tokenArrayBegin; - break; - case ']': - token.type_ = tokenArrayEnd; - break; - case '"': - token.type_ = tokenString; - ok = readString(); - break; - case '/': - token.type_ = tokenComment; - ok = readComment(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - token.type_ = tokenNumber; - readNumber(); - break; - case 't': - token.type_ = tokenTrue; - ok = match("rue", 3); - break; - case 'f': - token.type_ = tokenFalse; - ok = match("alse", 4); - break; - case 'n': - token.type_ = tokenNull; - ok = match("ull", 3); - break; - case ',': - token.type_ = tokenArraySeparator; - break; - case ':': - token.type_ = tokenMemberSeparator; - break; - case 0: - token.type_ = tokenEndOfStream; - break; - default: - ok = false; - break; - } - if (!ok) - token.type_ = tokenError; - token.end_ = current_; - return true; -} - -void Reader::skipSpaces() { - while (current_ != end_) { - Char c = *current_; - if (c == ' ' || c == '\t' || c == '\r' || c == '\n') - ++current_; - else - break; - } -} - -bool Reader::match(Location pattern, int patternLength) { - if (end_ - current_ < patternLength) - return false; - int index = patternLength; - while (index--) - if (current_[index] != pattern[index]) - return false; - current_ += patternLength; - return true; -} - -bool Reader::readComment() { - Location commentBegin = current_ - 1; - Char c = getNextChar(); - bool successful = false; - if (c == '*') - successful = readCStyleComment(); - else if (c == '/') - successful = readCppStyleComment(); - if (!successful) - return false; - - if (collectComments_) { - CommentPlacement placement = commentBefore; - if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { - if (c != '*' || !containsNewLine(commentBegin, current_)) - placement = commentAfterOnSameLine; - } - - addComment(commentBegin, current_, placement); - } - return true; -} - -static JSONCPP_STRING normalizeEOL(Reader::Location begin, Reader::Location end) { - JSONCPP_STRING normalized; - normalized.reserve(static_cast(end - begin)); - Reader::Location current = begin; - while (current != end) { - char c = *current++; - if (c == '\r') { - if (current != end && *current == '\n') - // convert dos EOL - ++current; - // convert Mac EOL - normalized += '\n'; - } else { - normalized += c; - } - } - return normalized; -} - -void -Reader::addComment(Location begin, Location end, CommentPlacement placement) { - assert(collectComments_); - const JSONCPP_STRING& normalized = normalizeEOL(begin, end); - if (placement == commentAfterOnSameLine) { - assert(lastValue_ != 0); - lastValue_->setComment(normalized, placement); - } else { - commentsBefore_ += normalized; - } -} - -bool Reader::readCStyleComment() { - while ((current_ + 1) < end_) { - Char c = getNextChar(); - if (c == '*' && *current_ == '/') - break; - } - return getNextChar() == '/'; -} - -bool Reader::readCppStyleComment() { - while (current_ != end_) { - Char c = getNextChar(); - if (c == '\n') - break; - if (c == '\r') { - // Consume DOS EOL. It will be normalized in addComment. - if (current_ != end_ && *current_ == '\n') - getNextChar(); - // Break on Moc OS 9 EOL. - break; - } - } - return true; -} - -void Reader::readNumber() { - const char *p = current_; - char c = '0'; // stopgap for already consumed character - // integral part - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - // fractional part - if (c == '.') { - c = (current_ = p) < end_ ? *p++ : '\0'; - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - } - // exponential part - if (c == 'e' || c == 'E') { - c = (current_ = p) < end_ ? *p++ : '\0'; - if (c == '+' || c == '-') - c = (current_ = p) < end_ ? *p++ : '\0'; - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - } -} - -bool Reader::readString() { - Char c = '\0'; - while (current_ != end_) { - c = getNextChar(); - if (c == '\\') - getNextChar(); - else if (c == '"') - break; - } - return c == '"'; -} - -bool Reader::readObject(Token& tokenStart) { - Token tokenName; - JSONCPP_STRING name; - Value init(objectValue); - currentValue().swapPayload(init); - currentValue().setOffsetStart(tokenStart.start_ - begin_); - while (readToken(tokenName)) { - bool initialTokenOk = true; - while (tokenName.type_ == tokenComment && initialTokenOk) - initialTokenOk = readToken(tokenName); - if (!initialTokenOk) - break; - if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object - return true; - name = ""; - if (tokenName.type_ == tokenString) { - if (!decodeString(tokenName, name)) - return recoverFromError(tokenObjectEnd); - } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { - Value numberName; - if (!decodeNumber(tokenName, numberName)) - return recoverFromError(tokenObjectEnd); - name = JSONCPP_STRING(numberName.asCString()); - } else { - break; - } - - Token colon; - if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { - return addErrorAndRecover( - "Missing ':' after object member name", colon, tokenObjectEnd); - } - Value& value = currentValue()[name]; - nodes_.push(&value); - bool ok = readValue(); - nodes_.pop(); - if (!ok) // error already set - return recoverFromError(tokenObjectEnd); - - Token comma; - if (!readToken(comma) || - (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && - comma.type_ != tokenComment)) { - return addErrorAndRecover( - "Missing ',' or '}' in object declaration", comma, tokenObjectEnd); - } - bool finalizeTokenOk = true; - while (comma.type_ == tokenComment && finalizeTokenOk) - finalizeTokenOk = readToken(comma); - if (comma.type_ == tokenObjectEnd) - return true; - } - return addErrorAndRecover( - "Missing '}' or object member name", tokenName, tokenObjectEnd); -} - -bool Reader::readArray(Token& tokenStart) { - Value init(arrayValue); - currentValue().swapPayload(init); - currentValue().setOffsetStart(tokenStart.start_ - begin_); - skipSpaces(); - if (current_ != end_ && *current_ == ']') // empty array - { - Token endArray; - readToken(endArray); - return true; - } - int index = 0; - for (;;) { - Value& value = currentValue()[index++]; - nodes_.push(&value); - bool ok = readValue(); - nodes_.pop(); - if (!ok) // error already set - return recoverFromError(tokenArrayEnd); - - Token token; - // Accept Comment after last item in the array. - ok = readToken(token); - while (token.type_ == tokenComment && ok) { - ok = readToken(token); - } - bool badTokenType = - (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); - if (!ok || badTokenType) { - return addErrorAndRecover( - "Missing ',' or ']' in array declaration", token, tokenArrayEnd); - } - if (token.type_ == tokenArrayEnd) - break; - } - return true; -} - -bool Reader::decodeNumber(Token& token) { - Value decoded; - if (!decodeNumber(token, decoded)) - return false; - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool Reader::decodeNumber(Token& token, Value& decoded) { - // Attempts to parse the number as an integer. If the number is - // larger than the maximum supported value of an integer then - // we decode the number as a double. - Location current = token.start_; - bool isNegative = *current == '-'; - if (isNegative) - ++current; - // TODO: Help the compiler do the div and mod at compile time or get rid of them. - Value::LargestUInt maxIntegerValue = - isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1 - : Value::maxLargestUInt; - Value::LargestUInt threshold = maxIntegerValue / 10; - Value::LargestUInt value = 0; - while (current < token.end_) { - Char c = *current++; - if (c < '0' || c > '9') - return decodeDouble(token, decoded); - Value::UInt digit(static_cast(c - '0')); - if (value >= threshold) { - // We've hit or exceeded the max value divided by 10 (rounded down). If - // a) we've only just touched the limit, b) this is the last digit, and - // c) it's small enough to fit in that rounding delta, we're okay. - // Otherwise treat this number as a double to avoid overflow. - if (value > threshold || current != token.end_ || - digit > maxIntegerValue % 10) { - return decodeDouble(token, decoded); - } - } - value = value * 10 + digit; - } - if (isNegative && value == maxIntegerValue) - decoded = Value::minLargestInt; - else if (isNegative) - decoded = -Value::LargestInt(value); - else if (value <= Value::LargestUInt(Value::maxInt)) - decoded = Value::LargestInt(value); - else - decoded = value; - return true; -} - -bool Reader::decodeDouble(Token& token) { - Value decoded; - if (!decodeDouble(token, decoded)) - return false; - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool Reader::decodeDouble(Token& token, Value& decoded) { - double value = 0; - JSONCPP_STRING buffer(token.start_, token.end_); - JSONCPP_ISTRINGSTREAM is(buffer); - if (!(is >> value)) - return addError("'" + JSONCPP_STRING(token.start_, token.end_) + - "' is not a number.", - token); - decoded = value; - return true; -} - -bool Reader::decodeString(Token& token) { - JSONCPP_STRING decoded_string; - if (!decodeString(token, decoded_string)) - return false; - Value decoded(decoded_string); - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) { - decoded.reserve(static_cast(token.end_ - token.start_ - 2)); - Location current = token.start_ + 1; // skip '"' - Location end = token.end_ - 1; // do not include '"' - while (current != end) { - Char c = *current++; - if (c == '"') - break; - else if (c == '\\') { - if (current == end) - return addError("Empty escape sequence in string", token, current); - Char escape = *current++; - switch (escape) { - case '"': - decoded += '"'; - break; - case '/': - decoded += '/'; - break; - case '\\': - decoded += '\\'; - break; - case 'b': - decoded += '\b'; - break; - case 'f': - decoded += '\f'; - break; - case 'n': - decoded += '\n'; - break; - case 'r': - decoded += '\r'; - break; - case 't': - decoded += '\t'; - break; - case 'u': { - unsigned int unicode; - if (!decodeUnicodeCodePoint(token, current, end, unicode)) - return false; - decoded += codePointToUTF8(unicode); - } break; - default: - return addError("Bad escape sequence in string", token, current); - } - } else { - decoded += c; - } - } - return true; -} - -bool Reader::decodeUnicodeCodePoint(Token& token, - Location& current, - Location end, - unsigned int& unicode) { - - if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) - return false; - if (unicode >= 0xD800 && unicode <= 0xDBFF) { - // surrogate pairs - if (end - current < 6) - return addError( - "additional six characters expected to parse unicode surrogate pair.", - token, - current); - unsigned int surrogatePair; - if (*(current++) == '\\' && *(current++) == 'u') { - if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { - unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); - } else - return false; - } else - return addError("expecting another \\u token to begin the second half of " - "a unicode surrogate pair", - token, - current); - } - return true; -} - -bool Reader::decodeUnicodeEscapeSequence(Token& token, - Location& current, - Location end, - unsigned int& ret_unicode) { - if (end - current < 4) - return addError( - "Bad unicode escape sequence in string: four digits expected.", - token, - current); - int unicode = 0; - for (int index = 0; index < 4; ++index) { - Char c = *current++; - unicode *= 16; - if (c >= '0' && c <= '9') - unicode += c - '0'; - else if (c >= 'a' && c <= 'f') - unicode += c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - unicode += c - 'A' + 10; - else - return addError( - "Bad unicode escape sequence in string: hexadecimal digit expected.", - token, - current); - } - ret_unicode = static_cast(unicode); - return true; -} - -bool -Reader::addError(const JSONCPP_STRING& message, Token& token, Location extra) { - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = extra; - errors_.push_back(info); - return false; -} - -bool Reader::recoverFromError(TokenType skipUntilToken) { - size_t const errorCount = errors_.size(); - Token skip; - for (;;) { - if (!readToken(skip)) - errors_.resize(errorCount); // discard errors caused by recovery - if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) - break; - } - errors_.resize(errorCount); - return false; -} - -bool Reader::addErrorAndRecover(const JSONCPP_STRING& message, - Token& token, - TokenType skipUntilToken) { - addError(message, token); - return recoverFromError(skipUntilToken); -} - -Value& Reader::currentValue() { return *(nodes_.top()); } - -Reader::Char Reader::getNextChar() { - if (current_ == end_) - return 0; - return *current_++; -} - -void Reader::getLocationLineAndColumn(Location location, - int& line, - int& column) const { - Location current = begin_; - Location lastLineStart = current; - line = 0; - while (current < location && current != end_) { - Char c = *current++; - if (c == '\r') { - if (*current == '\n') - ++current; - lastLineStart = current; - ++line; - } else if (c == '\n') { - lastLineStart = current; - ++line; - } - } - // column & line start at 1 - column = int(location - lastLineStart) + 1; - ++line; -} - -JSONCPP_STRING Reader::getLocationLineAndColumn(Location location) const { - int line, column; - getLocationLineAndColumn(location, line, column); - char buffer[18 + 16 + 16 + 1]; - snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); - return buffer; -} - -// Deprecated. Preserved for backward compatibility -JSONCPP_STRING Reader::getFormatedErrorMessages() const { - return getFormattedErrorMessages(); -} - -JSONCPP_STRING Reader::getFormattedErrorMessages() const { - JSONCPP_STRING formattedMessage; - for (Errors::const_iterator itError = errors_.begin(); - itError != errors_.end(); - ++itError) { - const ErrorInfo& error = *itError; - formattedMessage += - "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; - formattedMessage += " " + error.message_ + "\n"; - if (error.extra_) - formattedMessage += - "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; - } - return formattedMessage; -} - -std::vector Reader::getStructuredErrors() const { - std::vector allErrors; - for (Errors::const_iterator itError = errors_.begin(); - itError != errors_.end(); - ++itError) { - const ErrorInfo& error = *itError; - Reader::StructuredError structured; - structured.offset_start = error.token_.start_ - begin_; - structured.offset_limit = error.token_.end_ - begin_; - structured.message = error.message_; - allErrors.push_back(structured); - } - return allErrors; -} - -bool Reader::pushError(const Value& value, const JSONCPP_STRING& message) { - ptrdiff_t const length = end_ - begin_; - if(value.getOffsetStart() > length - || value.getOffsetLimit() > length) - return false; - Token token; - token.type_ = tokenError; - token.start_ = begin_ + value.getOffsetStart(); - token.end_ = end_ + value.getOffsetLimit(); - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = 0; - errors_.push_back(info); - return true; -} - -bool Reader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) { - ptrdiff_t const length = end_ - begin_; - if(value.getOffsetStart() > length - || value.getOffsetLimit() > length - || extra.getOffsetLimit() > length) - return false; - Token token; - token.type_ = tokenError; - token.start_ = begin_ + value.getOffsetStart(); - token.end_ = begin_ + value.getOffsetLimit(); - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = begin_ + extra.getOffsetStart(); - errors_.push_back(info); - return true; -} - -bool Reader::good() const { - return !errors_.size(); -} - -// exact copy of Features -class OurFeatures { -public: - static OurFeatures all(); - bool allowComments_; - bool strictRoot_; - bool allowDroppedNullPlaceholders_; - bool allowNumericKeys_; - bool allowSingleQuotes_; - bool failIfExtra_; - bool rejectDupKeys_; - bool allowSpecialFloats_; - int stackLimit_; -}; // OurFeatures - -// exact copy of Implementation of class Features -// //////////////////////////////// - -OurFeatures OurFeatures::all() { return OurFeatures(); } - -// Implementation of class Reader -// //////////////////////////////// - -// exact copy of Reader, renamed to OurReader -class OurReader { -public: - typedef char Char; - typedef const Char* Location; - struct StructuredError { - ptrdiff_t offset_start; - ptrdiff_t offset_limit; - JSONCPP_STRING message; - }; - - OurReader(OurFeatures const& features); - bool parse(const char* beginDoc, - const char* endDoc, - Value& root, - bool collectComments = true); - JSONCPP_STRING getFormattedErrorMessages() const; - std::vector getStructuredErrors() const; - bool pushError(const Value& value, const JSONCPP_STRING& message); - bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra); - bool good() const; - -private: - OurReader(OurReader const&); // no impl - void operator=(OurReader const&); // no impl - - enum TokenType { - tokenEndOfStream = 0, - tokenObjectBegin, - tokenObjectEnd, - tokenArrayBegin, - tokenArrayEnd, - tokenString, - tokenNumber, - tokenTrue, - tokenFalse, - tokenNull, - tokenNaN, - tokenPosInf, - tokenNegInf, - tokenArraySeparator, - tokenMemberSeparator, - tokenComment, - tokenError - }; - - class Token { - public: - TokenType type_; - Location start_; - Location end_; - }; - - class ErrorInfo { - public: - Token token_; - JSONCPP_STRING message_; - Location extra_; - }; - - typedef std::deque Errors; - - bool readToken(Token& token); - void skipSpaces(); - bool match(Location pattern, int patternLength); - bool readComment(); - bool readCStyleComment(); - bool readCppStyleComment(); - bool readString(); - bool readStringSingleQuote(); - bool readNumber(bool checkInf); - bool readValue(); - bool readObject(Token& token); - bool readArray(Token& token); - bool decodeNumber(Token& token); - bool decodeNumber(Token& token, Value& decoded); - bool decodeString(Token& token); - bool decodeString(Token& token, JSONCPP_STRING& decoded); - bool decodeDouble(Token& token); - bool decodeDouble(Token& token, Value& decoded); - bool decodeUnicodeCodePoint(Token& token, - Location& current, - Location end, - unsigned int& unicode); - bool decodeUnicodeEscapeSequence(Token& token, - Location& current, - Location end, - unsigned int& unicode); - bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0); - bool recoverFromError(TokenType skipUntilToken); - bool addErrorAndRecover(const JSONCPP_STRING& message, - Token& token, - TokenType skipUntilToken); - void skipUntilSpace(); - Value& currentValue(); - Char getNextChar(); - void - getLocationLineAndColumn(Location location, int& line, int& column) const; - JSONCPP_STRING getLocationLineAndColumn(Location location) const; - void addComment(Location begin, Location end, CommentPlacement placement); - void skipCommentTokens(Token& token); - - typedef std::stack Nodes; - Nodes nodes_; - Errors errors_; - JSONCPP_STRING document_; - Location begin_; - Location end_; - Location current_; - Location lastValueEnd_; - Value* lastValue_; - JSONCPP_STRING commentsBefore_; - - OurFeatures const features_; - bool collectComments_; -}; // OurReader - -// complete copy of Read impl, for OurReader - -OurReader::OurReader(OurFeatures const& features) - : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(), - lastValue_(), commentsBefore_(), - features_(features), collectComments_() { -} - -bool OurReader::parse(const char* beginDoc, - const char* endDoc, - Value& root, - bool collectComments) { - if (!features_.allowComments_) { - collectComments = false; - } - - begin_ = beginDoc; - end_ = endDoc; - collectComments_ = collectComments; - current_ = begin_; - lastValueEnd_ = 0; - lastValue_ = 0; - commentsBefore_ = ""; - errors_.clear(); - while (!nodes_.empty()) - nodes_.pop(); - nodes_.push(&root); - - bool successful = readValue(); - Token token; - skipCommentTokens(token); - if (features_.failIfExtra_) { - if ((features_.strictRoot_ || token.type_ != tokenError) && token.type_ != tokenEndOfStream) { - addError("Extra non-whitespace after JSON value.", token); - return false; - } - } - if (collectComments_ && !commentsBefore_.empty()) - root.setComment(commentsBefore_, commentAfter); - if (features_.strictRoot_) { - if (!root.isArray() && !root.isObject()) { - // Set error location to start of doc, ideally should be first token found - // in doc - token.type_ = tokenError; - token.start_ = beginDoc; - token.end_ = endDoc; - addError( - "A valid JSON document must be either an array or an object value.", - token); - return false; - } - } - return successful; -} - -bool OurReader::readValue() { - // To preserve the old behaviour we cast size_t to int. - if (static_cast(nodes_.size()) > features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue()."); - Token token; - skipCommentTokens(token); - bool successful = true; - - if (collectComments_ && !commentsBefore_.empty()) { - currentValue().setComment(commentsBefore_, commentBefore); - commentsBefore_ = ""; - } - - switch (token.type_) { - case tokenObjectBegin: - successful = readObject(token); - currentValue().setOffsetLimit(current_ - begin_); - break; - case tokenArrayBegin: - successful = readArray(token); - currentValue().setOffsetLimit(current_ - begin_); - break; - case tokenNumber: - successful = decodeNumber(token); - break; - case tokenString: - successful = decodeString(token); - break; - case tokenTrue: - { - Value v(true); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenFalse: - { - Value v(false); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenNull: - { - Value v; - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenNaN: - { - Value v(std::numeric_limits::quiet_NaN()); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenPosInf: - { - Value v(std::numeric_limits::infinity()); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenNegInf: - { - Value v(-std::numeric_limits::infinity()); - currentValue().swapPayload(v); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - } - break; - case tokenArraySeparator: - case tokenObjectEnd: - case tokenArrayEnd: - if (features_.allowDroppedNullPlaceholders_) { - // "Un-read" the current token and mark the current value as a null - // token. - current_--; - Value v; - currentValue().swapPayload(v); - currentValue().setOffsetStart(current_ - begin_ - 1); - currentValue().setOffsetLimit(current_ - begin_); - break; - } // else, fall through ... - default: - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return addError("Syntax error: value, object or array expected.", token); - } - - if (collectComments_) { - lastValueEnd_ = current_; - lastValue_ = ¤tValue(); - } - - return successful; -} - -void OurReader::skipCommentTokens(Token& token) { - if (features_.allowComments_) { - do { - readToken(token); - } while (token.type_ == tokenComment); - } else { - readToken(token); - } -} - -bool OurReader::readToken(Token& token) { - skipSpaces(); - token.start_ = current_; - Char c = getNextChar(); - bool ok = true; - switch (c) { - case '{': - token.type_ = tokenObjectBegin; - break; - case '}': - token.type_ = tokenObjectEnd; - break; - case '[': - token.type_ = tokenArrayBegin; - break; - case ']': - token.type_ = tokenArrayEnd; - break; - case '"': - token.type_ = tokenString; - ok = readString(); - break; - case '\'': - if (features_.allowSingleQuotes_) { - token.type_ = tokenString; - ok = readStringSingleQuote(); - break; - } // else continue - case '/': - token.type_ = tokenComment; - ok = readComment(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - token.type_ = tokenNumber; - readNumber(false); - break; - case '-': - if (readNumber(true)) { - token.type_ = tokenNumber; - } else { - token.type_ = tokenNegInf; - ok = features_.allowSpecialFloats_ && match("nfinity", 7); - } - break; - case 't': - token.type_ = tokenTrue; - ok = match("rue", 3); - break; - case 'f': - token.type_ = tokenFalse; - ok = match("alse", 4); - break; - case 'n': - token.type_ = tokenNull; - ok = match("ull", 3); - break; - case 'N': - if (features_.allowSpecialFloats_) { - token.type_ = tokenNaN; - ok = match("aN", 2); - } else { - ok = false; - } - break; - case 'I': - if (features_.allowSpecialFloats_) { - token.type_ = tokenPosInf; - ok = match("nfinity", 7); - } else { - ok = false; - } - break; - case ',': - token.type_ = tokenArraySeparator; - break; - case ':': - token.type_ = tokenMemberSeparator; - break; - case 0: - token.type_ = tokenEndOfStream; - break; - default: - ok = false; - break; - } - if (!ok) - token.type_ = tokenError; - token.end_ = current_; - return true; -} - -void OurReader::skipSpaces() { - while (current_ != end_) { - Char c = *current_; - if (c == ' ' || c == '\t' || c == '\r' || c == '\n') - ++current_; - else - break; - } -} - -bool OurReader::match(Location pattern, int patternLength) { - if (end_ - current_ < patternLength) - return false; - int index = patternLength; - while (index--) - if (current_[index] != pattern[index]) - return false; - current_ += patternLength; - return true; -} - -bool OurReader::readComment() { - Location commentBegin = current_ - 1; - Char c = getNextChar(); - bool successful = false; - if (c == '*') - successful = readCStyleComment(); - else if (c == '/') - successful = readCppStyleComment(); - if (!successful) - return false; - - if (collectComments_) { - CommentPlacement placement = commentBefore; - if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { - if (c != '*' || !containsNewLine(commentBegin, current_)) - placement = commentAfterOnSameLine; - } - - addComment(commentBegin, current_, placement); - } - return true; -} - -void -OurReader::addComment(Location begin, Location end, CommentPlacement placement) { - assert(collectComments_); - const JSONCPP_STRING& normalized = normalizeEOL(begin, end); - if (placement == commentAfterOnSameLine) { - assert(lastValue_ != 0); - lastValue_->setComment(normalized, placement); - } else { - commentsBefore_ += normalized; - } -} - -bool OurReader::readCStyleComment() { - while ((current_ + 1) < end_) { - Char c = getNextChar(); - if (c == '*' && *current_ == '/') - break; - } - return getNextChar() == '/'; -} - -bool OurReader::readCppStyleComment() { - while (current_ != end_) { - Char c = getNextChar(); - if (c == '\n') - break; - if (c == '\r') { - // Consume DOS EOL. It will be normalized in addComment. - if (current_ != end_ && *current_ == '\n') - getNextChar(); - // Break on Moc OS 9 EOL. - break; - } - } - return true; -} - -bool OurReader::readNumber(bool checkInf) { - const char *p = current_; - if (checkInf && p != end_ && *p == 'I') { - current_ = ++p; - return false; - } - char c = '0'; // stopgap for already consumed character - // integral part - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - // fractional part - if (c == '.') { - c = (current_ = p) < end_ ? *p++ : '\0'; - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - } - // exponential part - if (c == 'e' || c == 'E') { - c = (current_ = p) < end_ ? *p++ : '\0'; - if (c == '+' || c == '-') - c = (current_ = p) < end_ ? *p++ : '\0'; - while (c >= '0' && c <= '9') - c = (current_ = p) < end_ ? *p++ : '\0'; - } - return true; -} -bool OurReader::readString() { - Char c = 0; - while (current_ != end_) { - c = getNextChar(); - if (c == '\\') - getNextChar(); - else if (c == '"') - break; - } - return c == '"'; -} - - -bool OurReader::readStringSingleQuote() { - Char c = 0; - while (current_ != end_) { - c = getNextChar(); - if (c == '\\') - getNextChar(); - else if (c == '\'') - break; - } - return c == '\''; -} - -bool OurReader::readObject(Token& tokenStart) { - Token tokenName; - JSONCPP_STRING name; - Value init(objectValue); - currentValue().swapPayload(init); - currentValue().setOffsetStart(tokenStart.start_ - begin_); - while (readToken(tokenName)) { - bool initialTokenOk = true; - while (tokenName.type_ == tokenComment && initialTokenOk) - initialTokenOk = readToken(tokenName); - if (!initialTokenOk) - break; - if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object - return true; - name = ""; - if (tokenName.type_ == tokenString) { - if (!decodeString(tokenName, name)) - return recoverFromError(tokenObjectEnd); - } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { - Value numberName; - if (!decodeNumber(tokenName, numberName)) - return recoverFromError(tokenObjectEnd); - name = numberName.asString(); - } else { - break; - } - - Token colon; - if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { - return addErrorAndRecover( - "Missing ':' after object member name", colon, tokenObjectEnd); - } - if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30"); - if (features_.rejectDupKeys_ && currentValue().isMember(name)) { - JSONCPP_STRING msg = "Duplicate key: '" + name + "'"; - return addErrorAndRecover( - msg, tokenName, tokenObjectEnd); - } - Value& value = currentValue()[name]; - nodes_.push(&value); - bool ok = readValue(); - nodes_.pop(); - if (!ok) // error already set - return recoverFromError(tokenObjectEnd); - - Token comma; - if (!readToken(comma) || - (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && - comma.type_ != tokenComment)) { - return addErrorAndRecover( - "Missing ',' or '}' in object declaration", comma, tokenObjectEnd); - } - bool finalizeTokenOk = true; - while (comma.type_ == tokenComment && finalizeTokenOk) - finalizeTokenOk = readToken(comma); - if (comma.type_ == tokenObjectEnd) - return true; - } - return addErrorAndRecover( - "Missing '}' or object member name", tokenName, tokenObjectEnd); -} - -bool OurReader::readArray(Token& tokenStart) { - Value init(arrayValue); - currentValue().swapPayload(init); - currentValue().setOffsetStart(tokenStart.start_ - begin_); - skipSpaces(); - if (current_ != end_ && *current_ == ']') // empty array - { - Token endArray; - readToken(endArray); - return true; - } - int index = 0; - for (;;) { - Value& value = currentValue()[index++]; - nodes_.push(&value); - bool ok = readValue(); - nodes_.pop(); - if (!ok) // error already set - return recoverFromError(tokenArrayEnd); - - Token token; - // Accept Comment after last item in the array. - ok = readToken(token); - while (token.type_ == tokenComment && ok) { - ok = readToken(token); - } - bool badTokenType = - (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd); - if (!ok || badTokenType) { - return addErrorAndRecover( - "Missing ',' or ']' in array declaration", token, tokenArrayEnd); - } - if (token.type_ == tokenArrayEnd) - break; - } - return true; -} - -bool OurReader::decodeNumber(Token& token) { - Value decoded; - if (!decodeNumber(token, decoded)) - return false; - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool OurReader::decodeNumber(Token& token, Value& decoded) { - // Attempts to parse the number as an integer. If the number is - // larger than the maximum supported value of an integer then - // we decode the number as a double. - Location current = token.start_; - bool isNegative = *current == '-'; - if (isNegative) - ++current; - // TODO: Help the compiler do the div and mod at compile time or get rid of them. - Value::LargestUInt maxIntegerValue = - isNegative ? Value::LargestUInt(-Value::minLargestInt) - : Value::maxLargestUInt; - Value::LargestUInt threshold = maxIntegerValue / 10; - Value::LargestUInt value = 0; - while (current < token.end_) { - Char c = *current++; - if (c < '0' || c > '9') - return decodeDouble(token, decoded); - Value::UInt digit(static_cast(c - '0')); - if (value >= threshold) { - // We've hit or exceeded the max value divided by 10 (rounded down). If - // a) we've only just touched the limit, b) this is the last digit, and - // c) it's small enough to fit in that rounding delta, we're okay. - // Otherwise treat this number as a double to avoid overflow. - if (value > threshold || current != token.end_ || - digit > maxIntegerValue % 10) { - return decodeDouble(token, decoded); - } - } - value = value * 10 + digit; - } - if (isNegative) - decoded = -Value::LargestInt(value); - else if (value <= Value::LargestUInt(Value::maxInt)) - decoded = Value::LargestInt(value); - else - decoded = value; - return true; -} - -bool OurReader::decodeDouble(Token& token) { - Value decoded; - if (!decodeDouble(token, decoded)) - return false; - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool OurReader::decodeDouble(Token& token, Value& decoded) { - double value = 0; - const int bufferSize = 32; - int count; - ptrdiff_t const length = token.end_ - token.start_; - - // Sanity check to avoid buffer overflow exploits. - if (length < 0) { - return addError("Unable to parse token length", token); - } - size_t const ulength = static_cast(length); - - // Avoid using a string constant for the format control string given to - // sscanf, as this can cause hard to debug crashes on OS X. See here for more - // info: - // - // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html - char format[] = "%lf"; - - if (length <= bufferSize) { - Char buffer[bufferSize + 1]; - memcpy(buffer, token.start_, ulength); - buffer[length] = 0; - fixNumericLocaleInput(buffer, buffer + length); - count = sscanf(buffer, format, &value); - } else { - JSONCPP_STRING buffer(token.start_, token.end_); - count = sscanf(buffer.c_str(), format, &value); - } - - if (count != 1) - return addError("'" + JSONCPP_STRING(token.start_, token.end_) + - "' is not a number.", - token); - decoded = value; - return true; -} - -bool OurReader::decodeString(Token& token) { - JSONCPP_STRING decoded_string; - if (!decodeString(token, decoded_string)) - return false; - Value decoded(decoded_string); - currentValue().swapPayload(decoded); - currentValue().setOffsetStart(token.start_ - begin_); - currentValue().setOffsetLimit(token.end_ - begin_); - return true; -} - -bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) { - decoded.reserve(static_cast(token.end_ - token.start_ - 2)); - Location current = token.start_ + 1; // skip '"' - Location end = token.end_ - 1; // do not include '"' - while (current != end) { - Char c = *current++; - if (c == '"') - break; - else if (c == '\\') { - if (current == end) - return addError("Empty escape sequence in string", token, current); - Char escape = *current++; - switch (escape) { - case '"': - decoded += '"'; - break; - case '/': - decoded += '/'; - break; - case '\\': - decoded += '\\'; - break; - case 'b': - decoded += '\b'; - break; - case 'f': - decoded += '\f'; - break; - case 'n': - decoded += '\n'; - break; - case 'r': - decoded += '\r'; - break; - case 't': - decoded += '\t'; - break; - case 'u': { - unsigned int unicode; - if (!decodeUnicodeCodePoint(token, current, end, unicode)) - return false; - decoded += codePointToUTF8(unicode); - } break; - default: - return addError("Bad escape sequence in string", token, current); - } - } else { - decoded += c; - } - } - return true; -} - -bool OurReader::decodeUnicodeCodePoint(Token& token, - Location& current, - Location end, - unsigned int& unicode) { - - if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) - return false; - if (unicode >= 0xD800 && unicode <= 0xDBFF) { - // surrogate pairs - if (end - current < 6) - return addError( - "additional six characters expected to parse unicode surrogate pair.", - token, - current); - unsigned int surrogatePair; - if (*(current++) == '\\' && *(current++) == 'u') { - if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { - unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); - } else - return false; - } else - return addError("expecting another \\u token to begin the second half of " - "a unicode surrogate pair", - token, - current); - } - return true; -} - -bool OurReader::decodeUnicodeEscapeSequence(Token& token, - Location& current, - Location end, - unsigned int& ret_unicode) { - if (end - current < 4) - return addError( - "Bad unicode escape sequence in string: four digits expected.", - token, - current); - int unicode = 0; - for (int index = 0; index < 4; ++index) { - Char c = *current++; - unicode *= 16; - if (c >= '0' && c <= '9') - unicode += c - '0'; - else if (c >= 'a' && c <= 'f') - unicode += c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - unicode += c - 'A' + 10; - else - return addError( - "Bad unicode escape sequence in string: hexadecimal digit expected.", - token, - current); - } - ret_unicode = static_cast(unicode); - return true; -} - -bool -OurReader::addError(const JSONCPP_STRING& message, Token& token, Location extra) { - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = extra; - errors_.push_back(info); - return false; -} - -bool OurReader::recoverFromError(TokenType skipUntilToken) { - size_t errorCount = errors_.size(); - Token skip; - for (;;) { - if (!readToken(skip)) - errors_.resize(errorCount); // discard errors caused by recovery - if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) - break; - } - errors_.resize(errorCount); - return false; -} - -bool OurReader::addErrorAndRecover(const JSONCPP_STRING& message, - Token& token, - TokenType skipUntilToken) { - addError(message, token); - return recoverFromError(skipUntilToken); -} - -Value& OurReader::currentValue() { return *(nodes_.top()); } - -OurReader::Char OurReader::getNextChar() { - if (current_ == end_) - return 0; - return *current_++; -} - -void OurReader::getLocationLineAndColumn(Location location, - int& line, - int& column) const { - Location current = begin_; - Location lastLineStart = current; - line = 0; - while (current < location && current != end_) { - Char c = *current++; - if (c == '\r') { - if (*current == '\n') - ++current; - lastLineStart = current; - ++line; - } else if (c == '\n') { - lastLineStart = current; - ++line; - } - } - // column & line start at 1 - column = int(location - lastLineStart) + 1; - ++line; -} - -JSONCPP_STRING OurReader::getLocationLineAndColumn(Location location) const { - int line, column; - getLocationLineAndColumn(location, line, column); - char buffer[18 + 16 + 16 + 1]; - snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); - return buffer; -} - -JSONCPP_STRING OurReader::getFormattedErrorMessages() const { - JSONCPP_STRING formattedMessage; - for (Errors::const_iterator itError = errors_.begin(); - itError != errors_.end(); - ++itError) { - const ErrorInfo& error = *itError; - formattedMessage += - "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; - formattedMessage += " " + error.message_ + "\n"; - if (error.extra_) - formattedMessage += - "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; - } - return formattedMessage; -} - -std::vector OurReader::getStructuredErrors() const { - std::vector allErrors; - for (Errors::const_iterator itError = errors_.begin(); - itError != errors_.end(); - ++itError) { - const ErrorInfo& error = *itError; - OurReader::StructuredError structured; - structured.offset_start = error.token_.start_ - begin_; - structured.offset_limit = error.token_.end_ - begin_; - structured.message = error.message_; - allErrors.push_back(structured); - } - return allErrors; -} - -bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message) { - ptrdiff_t length = end_ - begin_; - if(value.getOffsetStart() > length - || value.getOffsetLimit() > length) - return false; - Token token; - token.type_ = tokenError; - token.start_ = begin_ + value.getOffsetStart(); - token.end_ = end_ + value.getOffsetLimit(); - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = 0; - errors_.push_back(info); - return true; -} - -bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) { - ptrdiff_t length = end_ - begin_; - if(value.getOffsetStart() > length - || value.getOffsetLimit() > length - || extra.getOffsetLimit() > length) - return false; - Token token; - token.type_ = tokenError; - token.start_ = begin_ + value.getOffsetStart(); - token.end_ = begin_ + value.getOffsetLimit(); - ErrorInfo info; - info.token_ = token; - info.message_ = message; - info.extra_ = begin_ + extra.getOffsetStart(); - errors_.push_back(info); - return true; -} - -bool OurReader::good() const { - return !errors_.size(); -} - - -class OurCharReader : public CharReader { - bool const collectComments_; - OurReader reader_; -public: - OurCharReader( - bool collectComments, - OurFeatures const& features) - : collectComments_(collectComments) - , reader_(features) - {} - bool parse( - char const* beginDoc, char const* endDoc, - Value* root, JSONCPP_STRING* errs) JSONCPP_OVERRIDE { - bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_); - if (errs) { - *errs = reader_.getFormattedErrorMessages(); - } - return ok; - } -}; - -CharReaderBuilder::CharReaderBuilder() -{ - setDefaults(&settings_); -} -CharReaderBuilder::~CharReaderBuilder() -{} -CharReader* CharReaderBuilder::newCharReader() const -{ - bool collectComments = settings_["collectComments"].asBool(); - OurFeatures features = OurFeatures::all(); - features.allowComments_ = settings_["allowComments"].asBool(); - features.strictRoot_ = settings_["strictRoot"].asBool(); - features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool(); - features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool(); - features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool(); - features.stackLimit_ = settings_["stackLimit"].asInt(); - features.failIfExtra_ = settings_["failIfExtra"].asBool(); - features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool(); - features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool(); - return new OurCharReader(collectComments, features); -} -static void getValidReaderKeys(std::set* valid_keys) -{ - valid_keys->clear(); - valid_keys->insert("collectComments"); - valid_keys->insert("allowComments"); - valid_keys->insert("strictRoot"); - valid_keys->insert("allowDroppedNullPlaceholders"); - valid_keys->insert("allowNumericKeys"); - valid_keys->insert("allowSingleQuotes"); - valid_keys->insert("stackLimit"); - valid_keys->insert("failIfExtra"); - valid_keys->insert("rejectDupKeys"); - valid_keys->insert("allowSpecialFloats"); -} -bool CharReaderBuilder::validate(Json::Value* invalid) const -{ - Json::Value my_invalid; - if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL - Json::Value& inv = *invalid; - std::set valid_keys; - getValidReaderKeys(&valid_keys); - Value::Members keys = settings_.getMemberNames(); - size_t n = keys.size(); - for (size_t i = 0; i < n; ++i) { - JSONCPP_STRING const& key = keys[i]; - if (valid_keys.find(key) == valid_keys.end()) { - inv[key] = settings_[key]; - } - } - return 0u == inv.size(); -} -Value& CharReaderBuilder::operator[](JSONCPP_STRING key) -{ - return settings_[key]; -} -// static -void CharReaderBuilder::strictMode(Json::Value* settings) -{ -//! [CharReaderBuilderStrictMode] - (*settings)["allowComments"] = false; - (*settings)["strictRoot"] = true; - (*settings)["allowDroppedNullPlaceholders"] = false; - (*settings)["allowNumericKeys"] = false; - (*settings)["allowSingleQuotes"] = false; - (*settings)["stackLimit"] = 1000; - (*settings)["failIfExtra"] = true; - (*settings)["rejectDupKeys"] = true; - (*settings)["allowSpecialFloats"] = false; -//! [CharReaderBuilderStrictMode] -} -// static -void CharReaderBuilder::setDefaults(Json::Value* settings) -{ -//! [CharReaderBuilderDefaults] - (*settings)["collectComments"] = true; - (*settings)["allowComments"] = true; - (*settings)["strictRoot"] = false; - (*settings)["allowDroppedNullPlaceholders"] = false; - (*settings)["allowNumericKeys"] = false; - (*settings)["allowSingleQuotes"] = false; - (*settings)["stackLimit"] = 1000; - (*settings)["failIfExtra"] = false; - (*settings)["rejectDupKeys"] = false; - (*settings)["allowSpecialFloats"] = false; -//! [CharReaderBuilderDefaults] -} - -////////////////////////////////// -// global functions - -bool parseFromStream( - CharReader::Factory const& fact, JSONCPP_ISTREAM& sin, - Value* root, JSONCPP_STRING* errs) -{ - JSONCPP_OSTRINGSTREAM ssin; - ssin << sin.rdbuf(); - JSONCPP_STRING doc = ssin.str(); - char const* begin = doc.data(); - char const* end = begin + doc.size(); - // Note that we do not actually need a null-terminator. - CharReaderPtr const reader(fact.newCharReader()); - return reader->parse(begin, end, root, errs); -} - -JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM& sin, Value& root) { - CharReaderBuilder b; - JSONCPP_STRING errs; - bool ok = parseFromStream(b, sin, &root, &errs); - if (!ok) { - fprintf(stderr, - "Error from reader: %s", - errs.c_str()); - - throwRuntimeError(errs); - } - return sin; -} - -} // namespace Json diff --git a/thirdparty/jsoncpp/src/lib_json/json_tool.h b/thirdparty/jsoncpp/src/lib_json/json_tool.h deleted file mode 100644 index 41d0f49d21..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/json_tool.h +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED -#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED - - -// Also support old flag NO_LOCALE_SUPPORT -#ifdef NO_LOCALE_SUPPORT -#define JSONCPP_NO_LOCALE_SUPPORT -#endif - -#ifndef JSONCPP_NO_LOCALE_SUPPORT -#include -#endif - -/* This header provides common string manipulation support, such as UTF-8, - * portable conversion from/to string... - * - * It is an internal header that must not be exposed. - */ - -namespace Json { -static char getDecimalPoint() { -#ifdef JSONCPP_NO_LOCALE_SUPPORT - return '\0'; -#else - struct lconv* lc = localeconv(); - return lc ? *(lc->decimal_point) : '\0'; -#endif -} - -/// Converts a unicode code-point to UTF-8. -static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) { - JSONCPP_STRING result; - - // based on description from http://en.wikipedia.org/wiki/UTF-8 - - if (cp <= 0x7f) { - result.resize(1); - result[0] = static_cast(cp); - } else if (cp <= 0x7FF) { - result.resize(2); - result[1] = static_cast(0x80 | (0x3f & cp)); - result[0] = static_cast(0xC0 | (0x1f & (cp >> 6))); - } else if (cp <= 0xFFFF) { - result.resize(3); - result[2] = static_cast(0x80 | (0x3f & cp)); - result[1] = static_cast(0x80 | (0x3f & (cp >> 6))); - result[0] = static_cast(0xE0 | (0xf & (cp >> 12))); - } else if (cp <= 0x10FFFF) { - result.resize(4); - result[3] = static_cast(0x80 | (0x3f & cp)); - result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); - result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); - result[0] = static_cast(0xF0 | (0x7 & (cp >> 18))); - } - - return result; -} - -/// Returns true if ch is a control character (in range [1,31]). -static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; } - -enum { - /// Constant that specify the size of the buffer that must be passed to - /// uintToString. - uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1 -}; - -// Defines a char buffer for use with uintToString(). -typedef char UIntToStringBuffer[uintToStringBufferSize]; - -/** Converts an unsigned integer to string. - * @param value Unsigned interger to convert to string - * @param current Input/Output string buffer. - * Must have at least uintToStringBufferSize chars free. - */ -static inline void uintToString(LargestUInt value, char*& current) { - *--current = 0; - do { - *--current = static_cast(value % 10U + static_cast('0')); - value /= 10; - } while (value != 0); -} - -/** Change ',' to '.' everywhere in buffer. - * - * We had a sophisticated way, but it did not work in WinCE. - * @see https://github.com/open-source-parsers/jsoncpp/pull/9 - */ -static inline void fixNumericLocale(char* begin, char* end) { - while (begin < end) { - if (*begin == ',') { - *begin = '.'; - } - ++begin; - } -} - -static inline void fixNumericLocaleInput(char* begin, char* end) { - char decimalPoint = getDecimalPoint(); - if (decimalPoint != '\0' && decimalPoint != '.') { - while (begin < end) { - if (*begin == '.') { - *begin = decimalPoint; - } - ++begin; - } - } -} - -} // namespace Json { - -#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED diff --git a/thirdparty/jsoncpp/src/lib_json/json_value.cpp b/thirdparty/jsoncpp/src/lib_json/json_value.cpp deleted file mode 100644 index 391c20f4a7..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/json_value.cpp +++ /dev/null @@ -1,1617 +0,0 @@ -// Copyright 2011 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#include -#include -#ifdef JSON_USE_CPPTL -#include -#endif -#include // size_t -#include // min() - -#define JSON_ASSERT_UNREACHABLE assert(false) - -namespace Json { - -// This is a walkaround to avoid the static initialization of Value::null. -// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of -// 8 (instead of 4) as a bit of future-proofing. -#if defined(__ARMEL__) -#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment))) -#else -#define ALIGNAS(byte_alignment) -#endif -//static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 }; -//const unsigned char& kNullRef = kNull[0]; -//const Value& Value::null = reinterpret_cast(kNullRef); -//const Value& Value::nullRef = null; - -// static -Value const& Value::nullSingleton() -{ - static Value const nullStatic; - return nullStatic; -} - -// for backwards compatibility, we'll leave these global references around, but DO NOT -// use them in JSONCPP library code any more! -Value const& Value::null = Value::nullSingleton(); -Value const& Value::nullRef = Value::nullSingleton(); - -const Int Value::minInt = Int(~(UInt(-1) / 2)); -const Int Value::maxInt = Int(UInt(-1) / 2); -const UInt Value::maxUInt = UInt(-1); -#if defined(JSON_HAS_INT64) -const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2)); -const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2); -const UInt64 Value::maxUInt64 = UInt64(-1); -// The constant is hard-coded because some compiler have trouble -// converting Value::maxUInt64 to a double correctly (AIX/xlC). -// Assumes that UInt64 is a 64 bits integer. -static const double maxUInt64AsDouble = 18446744073709551615.0; -#endif // defined(JSON_HAS_INT64) -const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2)); -const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2); -const LargestUInt Value::maxLargestUInt = LargestUInt(-1); - -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) -template -static inline bool InRange(double d, T min, U max) { - // The casts can lose precision, but we are looking only for - // an approximate range. Might fail on edge cases though. ~cdunn - //return d >= static_cast(min) && d <= static_cast(max); - return d >= min && d <= max; -} -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) -static inline double integerToDouble(Json::UInt64 value) { - return static_cast(Int64(value / 2)) * 2.0 + static_cast(Int64(value & 1)); -} - -template static inline double integerToDouble(T value) { - return static_cast(value); -} - -template -static inline bool InRange(double d, T min, U max) { - return d >= integerToDouble(min) && d <= integerToDouble(max); -} -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - -/** Duplicates the specified string value. - * @param value Pointer to the string to duplicate. Must be zero-terminated if - * length is "unknown". - * @param length Length of the value. if equals to unknown, then it will be - * computed using strlen(value). - * @return Pointer on the duplicate instance of string. - */ -static inline char* duplicateStringValue(const char* value, - size_t length) -{ - // Avoid an integer overflow in the call to malloc below by limiting length - // to a sane value. - if (length >= static_cast(Value::maxInt)) - length = Value::maxInt - 1; - - char* newString = static_cast(malloc(length + 1)); - if (newString == NULL) { - throwRuntimeError( - "in Json::Value::duplicateStringValue(): " - "Failed to allocate string value buffer"); - } - memcpy(newString, value, length); - newString[length] = 0; - return newString; -} - -/* Record the length as a prefix. - */ -static inline char* duplicateAndPrefixStringValue( - const char* value, - unsigned int length) -{ - // Avoid an integer overflow in the call to malloc below by limiting length - // to a sane value. - JSON_ASSERT_MESSAGE(length <= static_cast(Value::maxInt) - sizeof(unsigned) - 1U, - "in Json::Value::duplicateAndPrefixStringValue(): " - "length too big for prefixing"); - unsigned actualLength = length + static_cast(sizeof(unsigned)) + 1U; - char* newString = static_cast(malloc(actualLength)); - if (newString == 0) { - throwRuntimeError( - "in Json::Value::duplicateAndPrefixStringValue(): " - "Failed to allocate string value buffer"); - } - *reinterpret_cast(newString) = length; - memcpy(newString + sizeof(unsigned), value, length); - newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later - return newString; -} -inline static void decodePrefixedString( - bool isPrefixed, char const* prefixed, - unsigned* length, char const** value) -{ - if (!isPrefixed) { - *length = static_cast(strlen(prefixed)); - *value = prefixed; - } else { - *length = *reinterpret_cast(prefixed); - *value = prefixed + sizeof(unsigned); - } -} -/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue(). - */ -#if JSONCPP_USING_SECURE_MEMORY -static inline void releasePrefixedStringValue(char* value) { - unsigned length = 0; - char const* valueDecoded; - decodePrefixedString(true, value, &length, &valueDecoded); - size_t const size = sizeof(unsigned) + length + 1U; - memset(value, 0, size); - free(value); -} -static inline void releaseStringValue(char* value, unsigned length) { - // length==0 => we allocated the strings memory - size_t size = (length==0) ? strlen(value) : length; - memset(value, 0, size); - free(value); -} -#else // !JSONCPP_USING_SECURE_MEMORY -static inline void releasePrefixedStringValue(char* value) { - free(value); -} -static inline void releaseStringValue(char* value, unsigned) { - free(value); -} -#endif // JSONCPP_USING_SECURE_MEMORY - -} // namespace Json - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ValueInternals... -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -#if !defined(JSON_IS_AMALGAMATION) - -#include "json_valueiterator.inl" -#endif // if !defined(JSON_IS_AMALGAMATION) - -namespace Json { - -Exception::Exception(JSONCPP_STRING const& msg) - : msg_(msg) -{} -Exception::~Exception() JSONCPP_NOEXCEPT -{} -char const* Exception::what() const JSONCPP_NOEXCEPT -{ - return msg_.c_str(); -} -RuntimeError::RuntimeError(JSONCPP_STRING const& msg) - : Exception(msg) -{} -LogicError::LogicError(JSONCPP_STRING const& msg) - : Exception(msg) -{} -JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg) -{ - throw RuntimeError(msg); -} -JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg) -{ - throw LogicError(msg); -} - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class Value::CommentInfo -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -Value::CommentInfo::CommentInfo() : comment_(0) -{} - -Value::CommentInfo::~CommentInfo() { - if (comment_) - releaseStringValue(comment_, 0u); -} - -void Value::CommentInfo::setComment(const char* text, size_t len) { - if (comment_) { - releaseStringValue(comment_, 0u); - comment_ = 0; - } - JSON_ASSERT(text != 0); - JSON_ASSERT_MESSAGE( - text[0] == '\0' || text[0] == '/', - "in Json::Value::setComment(): Comments must start with /"); - // It seems that /**/ style comments are acceptable as well. - comment_ = duplicateStringValue(text, len); -} - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class Value::CZString -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -// Notes: policy_ indicates if the string was allocated when -// a string is stored. - -Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {} - -Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate) - : cstr_(str) { - // allocate != duplicate - storage_.policy_ = allocate & 0x3; - storage_.length_ = ulength & 0x3FFFFFFF; -} - -Value::CZString::CZString(const CZString& other) { - cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != 0 - ? duplicateStringValue(other.cstr_, other.storage_.length_) - : other.cstr_); - storage_.policy_ = static_cast(other.cstr_ - ? (static_cast(other.storage_.policy_) == noDuplication - ? noDuplication : duplicate) - : static_cast(other.storage_.policy_)) & 3U; - storage_.length_ = other.storage_.length_; -} - -#if JSON_HAS_RVALUE_REFERENCES -Value::CZString::CZString(CZString&& other) - : cstr_(other.cstr_), index_(other.index_) { - other.cstr_ = nullptr; -} -#endif - -Value::CZString::~CZString() { - if (cstr_ && storage_.policy_ == duplicate) { - releaseStringValue(const_cast(cstr_), storage_.length_ + 1u); //+1 for null terminating character for sake of completeness but not actually necessary - } -} - -void Value::CZString::swap(CZString& other) { - std::swap(cstr_, other.cstr_); - std::swap(index_, other.index_); -} - -Value::CZString& Value::CZString::operator=(CZString other) { - swap(other); - return *this; -} - -bool Value::CZString::operator<(const CZString& other) const { - if (!cstr_) return index_ < other.index_; - //return strcmp(cstr_, other.cstr_) < 0; - // Assume both are strings. - unsigned this_len = this->storage_.length_; - unsigned other_len = other.storage_.length_; - unsigned min_len = std::min(this_len, other_len); - JSON_ASSERT(this->cstr_ && other.cstr_); - int comp = memcmp(this->cstr_, other.cstr_, min_len); - if (comp < 0) return true; - if (comp > 0) return false; - return (this_len < other_len); -} - -bool Value::CZString::operator==(const CZString& other) const { - if (!cstr_) return index_ == other.index_; - //return strcmp(cstr_, other.cstr_) == 0; - // Assume both are strings. - unsigned this_len = this->storage_.length_; - unsigned other_len = other.storage_.length_; - if (this_len != other_len) return false; - JSON_ASSERT(this->cstr_ && other.cstr_); - int comp = memcmp(this->cstr_, other.cstr_, this_len); - return comp == 0; -} - -ArrayIndex Value::CZString::index() const { return index_; } - -//const char* Value::CZString::c_str() const { return cstr_; } -const char* Value::CZString::data() const { return cstr_; } -unsigned Value::CZString::length() const { return storage_.length_; } -bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; } - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class Value::Value -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -/*! \internal Default constructor initialization must be equivalent to: - * memset( this, 0, sizeof(Value) ) - * This optimization is used in ValueInternalMap fast allocator. - */ -Value::Value(ValueType vtype) { - static char const emptyString[] = ""; - initBasic(vtype); - switch (vtype) { - case nullValue: - break; - case intValue: - case uintValue: - value_.int_ = 0; - break; - case realValue: - value_.real_ = 0.0; - break; - case stringValue: - // allocated_ == false, so this is safe. - value_.string_ = const_cast(static_cast(emptyString)); - break; - case arrayValue: - case objectValue: - value_.map_ = new ObjectValues(); - break; - case booleanValue: - value_.bool_ = false; - break; - default: - JSON_ASSERT_UNREACHABLE; - } -} - -Value::Value(Int value) { - initBasic(intValue); - value_.int_ = value; -} - -Value::Value(UInt value) { - initBasic(uintValue); - value_.uint_ = value; -} -#if defined(JSON_HAS_INT64) -Value::Value(Int64 value) { - initBasic(intValue); - value_.int_ = value; -} -Value::Value(UInt64 value) { - initBasic(uintValue); - value_.uint_ = value; -} -#endif // defined(JSON_HAS_INT64) - -Value::Value(double value) { - initBasic(realValue); - value_.real_ = value; -} - -Value::Value(const char* value) { - initBasic(stringValue, true); - JSON_ASSERT_MESSAGE(value != NULL, "Null Value Passed to Value Constructor"); - value_.string_ = duplicateAndPrefixStringValue(value, static_cast(strlen(value))); -} - -Value::Value(const char* beginValue, const char* endValue) { - initBasic(stringValue, true); - value_.string_ = - duplicateAndPrefixStringValue(beginValue, static_cast(endValue - beginValue)); -} - -Value::Value(const JSONCPP_STRING& value) { - initBasic(stringValue, true); - value_.string_ = - duplicateAndPrefixStringValue(value.data(), static_cast(value.length())); -} - -Value::Value(const StaticString& value) { - initBasic(stringValue); - value_.string_ = const_cast(value.c_str()); -} - -#ifdef JSON_USE_CPPTL -Value::Value(const CppTL::ConstString& value) { - initBasic(stringValue, true); - value_.string_ = duplicateAndPrefixStringValue(value, static_cast(value.length())); -} -#endif - -Value::Value(bool value) { - initBasic(booleanValue); - value_.bool_ = value; -} - -Value::Value(Value const& other) - : type_(other.type_), allocated_(false) - , - comments_(0), start_(other.start_), limit_(other.limit_) -{ - switch (type_) { - case nullValue: - case intValue: - case uintValue: - case realValue: - case booleanValue: - value_ = other.value_; - break; - case stringValue: - if (other.value_.string_ && other.allocated_) { - unsigned len; - char const* str; - decodePrefixedString(other.allocated_, other.value_.string_, - &len, &str); - value_.string_ = duplicateAndPrefixStringValue(str, len); - allocated_ = true; - } else { - value_.string_ = other.value_.string_; - allocated_ = false; - } - break; - case arrayValue: - case objectValue: - value_.map_ = new ObjectValues(*other.value_.map_); - break; - default: - JSON_ASSERT_UNREACHABLE; - } - if (other.comments_) { - comments_ = new CommentInfo[numberOfCommentPlacement]; - for (int comment = 0; comment < numberOfCommentPlacement; ++comment) { - const CommentInfo& otherComment = other.comments_[comment]; - if (otherComment.comment_) - comments_[comment].setComment( - otherComment.comment_, strlen(otherComment.comment_)); - } - } -} - -#if JSON_HAS_RVALUE_REFERENCES -// Move constructor -Value::Value(Value&& other) { - initBasic(nullValue); - swap(other); -} -#endif - -Value::~Value() { - switch (type_) { - case nullValue: - case intValue: - case uintValue: - case realValue: - case booleanValue: - break; - case stringValue: - if (allocated_) - releasePrefixedStringValue(value_.string_); - break; - case arrayValue: - case objectValue: - delete value_.map_; - break; - default: - JSON_ASSERT_UNREACHABLE; - } - - delete[] comments_; - - value_.uint_ = 0; -} - -Value& Value::operator=(Value other) { - swap(other); - return *this; -} - -void Value::swapPayload(Value& other) { - ValueType temp = type_; - type_ = other.type_; - other.type_ = temp; - std::swap(value_, other.value_); - int temp2 = allocated_; - allocated_ = other.allocated_; - other.allocated_ = temp2 & 0x1; -} - -void Value::swap(Value& other) { - swapPayload(other); - std::swap(comments_, other.comments_); - std::swap(start_, other.start_); - std::swap(limit_, other.limit_); -} - -ValueType Value::type() const { return type_; } - -int Value::compare(const Value& other) const { - if (*this < other) - return -1; - if (*this > other) - return 1; - return 0; -} - -bool Value::operator<(const Value& other) const { - int typeDelta = type_ - other.type_; - if (typeDelta) - return typeDelta < 0 ? true : false; - switch (type_) { - case nullValue: - return false; - case intValue: - return value_.int_ < other.value_.int_; - case uintValue: - return value_.uint_ < other.value_.uint_; - case realValue: - return value_.real_ < other.value_.real_; - case booleanValue: - return value_.bool_ < other.value_.bool_; - case stringValue: - { - if ((value_.string_ == 0) || (other.value_.string_ == 0)) { - if (other.value_.string_) return true; - else return false; - } - unsigned this_len; - unsigned other_len; - char const* this_str; - char const* other_str; - decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); - decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str); - unsigned min_len = std::min(this_len, other_len); - JSON_ASSERT(this_str && other_str); - int comp = memcmp(this_str, other_str, min_len); - if (comp < 0) return true; - if (comp > 0) return false; - return (this_len < other_len); - } - case arrayValue: - case objectValue: { - int delta = int(value_.map_->size() - other.value_.map_->size()); - if (delta) - return delta < 0; - return (*value_.map_) < (*other.value_.map_); - } - default: - JSON_ASSERT_UNREACHABLE; - } - return false; // unreachable -} - -bool Value::operator<=(const Value& other) const { return !(other < *this); } - -bool Value::operator>=(const Value& other) const { return !(*this < other); } - -bool Value::operator>(const Value& other) const { return other < *this; } - -bool Value::operator==(const Value& other) const { - // if ( type_ != other.type_ ) - // GCC 2.95.3 says: - // attempt to take address of bit-field structure member `Json::Value::type_' - // Beats me, but a temp solves the problem. - int temp = other.type_; - if (type_ != temp) - return false; - switch (type_) { - case nullValue: - return true; - case intValue: - return value_.int_ == other.value_.int_; - case uintValue: - return value_.uint_ == other.value_.uint_; - case realValue: - return value_.real_ == other.value_.real_; - case booleanValue: - return value_.bool_ == other.value_.bool_; - case stringValue: - { - if ((value_.string_ == 0) || (other.value_.string_ == 0)) { - return (value_.string_ == other.value_.string_); - } - unsigned this_len; - unsigned other_len; - char const* this_str; - char const* other_str; - decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); - decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str); - if (this_len != other_len) return false; - JSON_ASSERT(this_str && other_str); - int comp = memcmp(this_str, other_str, this_len); - return comp == 0; - } - case arrayValue: - case objectValue: - return value_.map_->size() == other.value_.map_->size() && - (*value_.map_) == (*other.value_.map_); - default: - JSON_ASSERT_UNREACHABLE; - } - return false; // unreachable -} - -bool Value::operator!=(const Value& other) const { return !(*this == other); } - -const char* Value::asCString() const { - JSON_ASSERT_MESSAGE(type_ == stringValue, - "in Json::Value::asCString(): requires stringValue"); - if (value_.string_ == 0) return 0; - unsigned this_len; - char const* this_str; - decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); - return this_str; -} - -#if JSONCPP_USING_SECURE_MEMORY -unsigned Value::getCStringLength() const { - JSON_ASSERT_MESSAGE(type_ == stringValue, - "in Json::Value::asCString(): requires stringValue"); - if (value_.string_ == 0) return 0; - unsigned this_len; - char const* this_str; - decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); - return this_len; -} -#endif - -bool Value::getString(char const** str, char const** cend) const { - if (type_ != stringValue) return false; - if (value_.string_ == 0) return false; - unsigned length; - decodePrefixedString(this->allocated_, this->value_.string_, &length, str); - *cend = *str + length; - return true; -} - -JSONCPP_STRING Value::asString() const { - switch (type_) { - case nullValue: - return ""; - case stringValue: - { - if (value_.string_ == 0) return ""; - unsigned this_len; - char const* this_str; - decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str); - return JSONCPP_STRING(this_str, this_len); - } - case booleanValue: - return value_.bool_ ? "true" : "false"; - case intValue: - return valueToString(value_.int_); - case uintValue: - return valueToString(value_.uint_); - case realValue: - return valueToString(value_.real_); - default: - JSON_FAIL_MESSAGE("Type is not convertible to string"); - } -} - -#ifdef JSON_USE_CPPTL -CppTL::ConstString Value::asConstString() const { - unsigned len; - char const* str; - decodePrefixedString(allocated_, value_.string_, - &len, &str); - return CppTL::ConstString(str, len); -} -#endif - -Value::Int Value::asInt() const { - switch (type_) { - case intValue: - JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range"); - return Int(value_.int_); - case uintValue: - JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range"); - return Int(value_.uint_); - case realValue: - JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt), - "double out of Int range"); - return Int(value_.real_); - case nullValue: - return 0; - case booleanValue: - return value_.bool_ ? 1 : 0; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to Int."); -} - -Value::UInt Value::asUInt() const { - switch (type_) { - case intValue: - JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range"); - return UInt(value_.int_); - case uintValue: - JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range"); - return UInt(value_.uint_); - case realValue: - JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt), - "double out of UInt range"); - return UInt(value_.real_); - case nullValue: - return 0; - case booleanValue: - return value_.bool_ ? 1 : 0; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to UInt."); -} - -#if defined(JSON_HAS_INT64) - -Value::Int64 Value::asInt64() const { - switch (type_) { - case intValue: - return Int64(value_.int_); - case uintValue: - JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range"); - return Int64(value_.uint_); - case realValue: - JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64), - "double out of Int64 range"); - return Int64(value_.real_); - case nullValue: - return 0; - case booleanValue: - return value_.bool_ ? 1 : 0; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to Int64."); -} - -Value::UInt64 Value::asUInt64() const { - switch (type_) { - case intValue: - JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range"); - return UInt64(value_.int_); - case uintValue: - return UInt64(value_.uint_); - case realValue: - JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64), - "double out of UInt64 range"); - return UInt64(value_.real_); - case nullValue: - return 0; - case booleanValue: - return value_.bool_ ? 1 : 0; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to UInt64."); -} -#endif // if defined(JSON_HAS_INT64) - -LargestInt Value::asLargestInt() const { -#if defined(JSON_NO_INT64) - return asInt(); -#else - return asInt64(); -#endif -} - -LargestUInt Value::asLargestUInt() const { -#if defined(JSON_NO_INT64) - return asUInt(); -#else - return asUInt64(); -#endif -} - -double Value::asDouble() const { - switch (type_) { - case intValue: - return static_cast(value_.int_); - case uintValue: -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast(value_.uint_); -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return integerToDouble(value_.uint_); -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - case realValue: - return value_.real_; - case nullValue: - return 0.0; - case booleanValue: - return value_.bool_ ? 1.0 : 0.0; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to double."); -} - -float Value::asFloat() const { - switch (type_) { - case intValue: - return static_cast(value_.int_); - case uintValue: -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - return static_cast(value_.uint_); -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - // This can fail (silently?) if the value is bigger than MAX_FLOAT. - return static_cast(integerToDouble(value_.uint_)); -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - case realValue: - return static_cast(value_.real_); - case nullValue: - return 0.0; - case booleanValue: - return value_.bool_ ? 1.0f : 0.0f; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to float."); -} - -bool Value::asBool() const { - switch (type_) { - case booleanValue: - return value_.bool_; - case nullValue: - return false; - case intValue: - return value_.int_ ? true : false; - case uintValue: - return value_.uint_ ? true : false; - case realValue: - // This is kind of strange. Not recommended. - return (value_.real_ != 0.0) ? true : false; - default: - break; - } - JSON_FAIL_MESSAGE("Value is not convertible to bool."); -} - -bool Value::isConvertibleTo(ValueType other) const { - switch (other) { - case nullValue: - return (isNumeric() && asDouble() == 0.0) || - (type_ == booleanValue && value_.bool_ == false) || - (type_ == stringValue && asString() == "") || - (type_ == arrayValue && value_.map_->size() == 0) || - (type_ == objectValue && value_.map_->size() == 0) || - type_ == nullValue; - case intValue: - return isInt() || - (type_ == realValue && InRange(value_.real_, minInt, maxInt)) || - type_ == booleanValue || type_ == nullValue; - case uintValue: - return isUInt() || - (type_ == realValue && InRange(value_.real_, 0, maxUInt)) || - type_ == booleanValue || type_ == nullValue; - case realValue: - return isNumeric() || type_ == booleanValue || type_ == nullValue; - case booleanValue: - return isNumeric() || type_ == booleanValue || type_ == nullValue; - case stringValue: - return isNumeric() || type_ == booleanValue || type_ == stringValue || - type_ == nullValue; - case arrayValue: - return type_ == arrayValue || type_ == nullValue; - case objectValue: - return type_ == objectValue || type_ == nullValue; - } - JSON_ASSERT_UNREACHABLE; - return false; -} - -/// Number of values in array or object -ArrayIndex Value::size() const { - switch (type_) { - case nullValue: - case intValue: - case uintValue: - case realValue: - case booleanValue: - case stringValue: - return 0; - case arrayValue: // size of the array is highest index + 1 - if (!value_.map_->empty()) { - ObjectValues::const_iterator itLast = value_.map_->end(); - --itLast; - return (*itLast).first.index() + 1; - } - return 0; - case objectValue: - return ArrayIndex(value_.map_->size()); - } - JSON_ASSERT_UNREACHABLE; - return 0; // unreachable; -} - -bool Value::empty() const { - if (isNull() || isArray() || isObject()) - return size() == 0u; - else - return false; -} - -bool Value::operator!() const { return isNull(); } - -void Value::clear() { - JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue || - type_ == objectValue, - "in Json::Value::clear(): requires complex value"); - start_ = 0; - limit_ = 0; - switch (type_) { - case arrayValue: - case objectValue: - value_.map_->clear(); - break; - default: - break; - } -} - -void Value::resize(ArrayIndex newSize) { - JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue, - "in Json::Value::resize(): requires arrayValue"); - if (type_ == nullValue) - *this = Value(arrayValue); - ArrayIndex oldSize = size(); - if (newSize == 0) - clear(); - else if (newSize > oldSize) - (*this)[newSize - 1]; - else { - for (ArrayIndex index = newSize; index < oldSize; ++index) { - value_.map_->erase(index); - } - JSON_ASSERT(size() == newSize); - } -} - -Value& Value::operator[](ArrayIndex index) { - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == arrayValue, - "in Json::Value::operator[](ArrayIndex): requires arrayValue"); - if (type_ == nullValue) - *this = Value(arrayValue); - CZString key(index); - ObjectValues::iterator it = value_.map_->lower_bound(key); - if (it != value_.map_->end() && (*it).first == key) - return (*it).second; - - ObjectValues::value_type defaultValue(key, nullSingleton()); - it = value_.map_->insert(it, defaultValue); - return (*it).second; -} - -Value& Value::operator[](int index) { - JSON_ASSERT_MESSAGE( - index >= 0, - "in Json::Value::operator[](int index): index cannot be negative"); - return (*this)[ArrayIndex(index)]; -} - -const Value& Value::operator[](ArrayIndex index) const { - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == arrayValue, - "in Json::Value::operator[](ArrayIndex)const: requires arrayValue"); - if (type_ == nullValue) - return nullSingleton(); - CZString key(index); - ObjectValues::const_iterator it = value_.map_->find(key); - if (it == value_.map_->end()) - return nullSingleton(); - return (*it).second; -} - -const Value& Value::operator[](int index) const { - JSON_ASSERT_MESSAGE( - index >= 0, - "in Json::Value::operator[](int index) const: index cannot be negative"); - return (*this)[ArrayIndex(index)]; -} - -void Value::initBasic(ValueType vtype, bool allocated) { - type_ = vtype; - allocated_ = allocated; - comments_ = 0; - start_ = 0; - limit_ = 0; -} - -// Access an object value by name, create a null member if it does not exist. -// @pre Type of '*this' is object or null. -// @param key is null-terminated. -Value& Value::resolveReference(const char* key) { - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == objectValue, - "in Json::Value::resolveReference(): requires objectValue"); - if (type_ == nullValue) - *this = Value(objectValue); - CZString actualKey( - key, static_cast(strlen(key)), CZString::noDuplication); // NOTE! - ObjectValues::iterator it = value_.map_->lower_bound(actualKey); - if (it != value_.map_->end() && (*it).first == actualKey) - return (*it).second; - - ObjectValues::value_type defaultValue(actualKey, nullSingleton()); - it = value_.map_->insert(it, defaultValue); - Value& value = (*it).second; - return value; -} - -// @param key is not null-terminated. -Value& Value::resolveReference(char const* key, char const* cend) -{ - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == objectValue, - "in Json::Value::resolveReference(key, end): requires objectValue"); - if (type_ == nullValue) - *this = Value(objectValue); - CZString actualKey( - key, static_cast(cend-key), CZString::duplicateOnCopy); - ObjectValues::iterator it = value_.map_->lower_bound(actualKey); - if (it != value_.map_->end() && (*it).first == actualKey) - return (*it).second; - - ObjectValues::value_type defaultValue(actualKey, nullSingleton()); - it = value_.map_->insert(it, defaultValue); - Value& value = (*it).second; - return value; -} - -Value Value::get(ArrayIndex index, const Value& defaultValue) const { - const Value* value = &((*this)[index]); - return value == &nullSingleton() ? defaultValue : *value; -} - -bool Value::isValidIndex(ArrayIndex index) const { return index < size(); } - -Value const* Value::find(char const* key, char const* cend) const -{ - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == objectValue, - "in Json::Value::find(key, end, found): requires objectValue or nullValue"); - if (type_ == nullValue) return NULL; - CZString actualKey(key, static_cast(cend-key), CZString::noDuplication); - ObjectValues::const_iterator it = value_.map_->find(actualKey); - if (it == value_.map_->end()) return NULL; - return &(*it).second; -} -const Value& Value::operator[](const char* key) const -{ - Value const* found = find(key, key + strlen(key)); - if (!found) return nullSingleton(); - return *found; -} -Value const& Value::operator[](JSONCPP_STRING const& key) const -{ - Value const* found = find(key.data(), key.data() + key.length()); - if (!found) return nullSingleton(); - return *found; -} - -Value& Value::operator[](const char* key) { - return resolveReference(key, key + strlen(key)); -} - -Value& Value::operator[](const JSONCPP_STRING& key) { - return resolveReference(key.data(), key.data() + key.length()); -} - -Value& Value::operator[](const StaticString& key) { - return resolveReference(key.c_str()); -} - -#ifdef JSON_USE_CPPTL -Value& Value::operator[](const CppTL::ConstString& key) { - return resolveReference(key.c_str(), key.end_c_str()); -} -Value const& Value::operator[](CppTL::ConstString const& key) const -{ - Value const* found = find(key.c_str(), key.end_c_str()); - if (!found) return nullSingleton(); - return *found; -} -#endif - -Value& Value::append(const Value& value) { return (*this)[size()] = value; } - -Value Value::get(char const* key, char const* cend, Value const& defaultValue) const -{ - Value const* found = find(key, cend); - return !found ? defaultValue : *found; -} -Value Value::get(char const* key, Value const& defaultValue) const -{ - return get(key, key + strlen(key), defaultValue); -} -Value Value::get(JSONCPP_STRING const& key, Value const& defaultValue) const -{ - return get(key.data(), key.data() + key.length(), defaultValue); -} - - -bool Value::removeMember(const char* key, const char* cend, Value* removed) -{ - if (type_ != objectValue) { - return false; - } - CZString actualKey(key, static_cast(cend-key), CZString::noDuplication); - ObjectValues::iterator it = value_.map_->find(actualKey); - if (it == value_.map_->end()) - return false; - *removed = it->second; - value_.map_->erase(it); - return true; -} -bool Value::removeMember(const char* key, Value* removed) -{ - return removeMember(key, key + strlen(key), removed); -} -bool Value::removeMember(JSONCPP_STRING const& key, Value* removed) -{ - return removeMember(key.data(), key.data() + key.length(), removed); -} -Value Value::removeMember(const char* key) -{ - JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue, - "in Json::Value::removeMember(): requires objectValue"); - if (type_ == nullValue) - return nullSingleton(); - - Value removed; // null - removeMember(key, key + strlen(key), &removed); - return removed; // still null if removeMember() did nothing -} -Value Value::removeMember(const JSONCPP_STRING& key) -{ - return removeMember(key.c_str()); -} - -bool Value::removeIndex(ArrayIndex index, Value* removed) { - if (type_ != arrayValue) { - return false; - } - CZString key(index); - ObjectValues::iterator it = value_.map_->find(key); - if (it == value_.map_->end()) { - return false; - } - *removed = it->second; - ArrayIndex oldSize = size(); - // shift left all items left, into the place of the "removed" - for (ArrayIndex i = index; i < (oldSize - 1); ++i){ - CZString keey(i); - (*value_.map_)[keey] = (*this)[i + 1]; - } - // erase the last one ("leftover") - CZString keyLast(oldSize - 1); - ObjectValues::iterator itLast = value_.map_->find(keyLast); - value_.map_->erase(itLast); - return true; -} - -#ifdef JSON_USE_CPPTL -Value Value::get(const CppTL::ConstString& key, - const Value& defaultValue) const { - return get(key.c_str(), key.end_c_str(), defaultValue); -} -#endif - -bool Value::isMember(char const* key, char const* cend) const -{ - Value const* value = find(key, cend); - return NULL != value; -} -bool Value::isMember(char const* key) const -{ - return isMember(key, key + strlen(key)); -} -bool Value::isMember(JSONCPP_STRING const& key) const -{ - return isMember(key.data(), key.data() + key.length()); -} - -#ifdef JSON_USE_CPPTL -bool Value::isMember(const CppTL::ConstString& key) const { - return isMember(key.c_str(), key.end_c_str()); -} -#endif - -Value::Members Value::getMemberNames() const { - JSON_ASSERT_MESSAGE( - type_ == nullValue || type_ == objectValue, - "in Json::Value::getMemberNames(), value must be objectValue"); - if (type_ == nullValue) - return Value::Members(); - Members members; - members.reserve(value_.map_->size()); - ObjectValues::const_iterator it = value_.map_->begin(); - ObjectValues::const_iterator itEnd = value_.map_->end(); - for (; it != itEnd; ++it) { - members.push_back(JSONCPP_STRING((*it).first.data(), - (*it).first.length())); - } - return members; -} -// -//# ifdef JSON_USE_CPPTL -// EnumMemberNames -// Value::enumMemberNames() const -//{ -// if ( type_ == objectValue ) -// { -// return CppTL::Enum::any( CppTL::Enum::transform( -// CppTL::Enum::keys( *(value_.map_), CppTL::Type() ), -// MemberNamesTransform() ) ); -// } -// return EnumMemberNames(); -//} -// -// -// EnumValues -// Value::enumValues() const -//{ -// if ( type_ == objectValue || type_ == arrayValue ) -// return CppTL::Enum::anyValues( *(value_.map_), -// CppTL::Type() ); -// return EnumValues(); -//} -// -//# endif - -static bool IsIntegral(double d) { - double integral_part; - return modf(d, &integral_part) == 0.0; -} - -bool Value::isNull() const { return type_ == nullValue; } - -bool Value::isBool() const { return type_ == booleanValue; } - -bool Value::isInt() const { - switch (type_) { - case intValue: -#if defined(JSON_HAS_INT64) - return value_.int_ >= minInt && value_.int_ <= maxInt; -#else - return true; -#endif - case uintValue: - return value_.uint_ <= UInt(maxInt); - case realValue: - return value_.real_ >= minInt && value_.real_ <= maxInt && - IsIntegral(value_.real_); - default: - break; - } - return false; -} - -bool Value::isUInt() const { - switch (type_) { - case intValue: -#if defined(JSON_HAS_INT64) - return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt); -#else - return value_.int_ >= 0; -#endif - case uintValue: -#if defined(JSON_HAS_INT64) - return value_.uint_ <= maxUInt; -#else - return true; -#endif - case realValue: - return value_.real_ >= 0 && value_.real_ <= maxUInt && - IsIntegral(value_.real_); - default: - break; - } - return false; -} - -bool Value::isInt64() const { -#if defined(JSON_HAS_INT64) - switch (type_) { - case intValue: - return true; - case uintValue: - return value_.uint_ <= UInt64(maxInt64); - case realValue: - // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a - // double, so double(maxInt64) will be rounded up to 2^63. Therefore we - // require the value to be strictly less than the limit. - return value_.real_ >= double(minInt64) && - value_.real_ < double(maxInt64) && IsIntegral(value_.real_); - default: - break; - } -#endif // JSON_HAS_INT64 - return false; -} - -bool Value::isUInt64() const { -#if defined(JSON_HAS_INT64) - switch (type_) { - case intValue: - return value_.int_ >= 0; - case uintValue: - return true; - case realValue: - // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a - // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we - // require the value to be strictly less than the limit. - return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble && - IsIntegral(value_.real_); - default: - break; - } -#endif // JSON_HAS_INT64 - return false; -} - -bool Value::isIntegral() const { -#if defined(JSON_HAS_INT64) - return isInt64() || isUInt64(); -#else - return isInt() || isUInt(); -#endif -} - -bool Value::isDouble() const { return type_ == intValue || type_ == uintValue || type_ == realValue; } - -bool Value::isNumeric() const { return isDouble(); } - -bool Value::isString() const { return type_ == stringValue; } - -bool Value::isArray() const { return type_ == arrayValue; } - -bool Value::isObject() const { return type_ == objectValue; } - -void Value::setComment(const char* comment, size_t len, CommentPlacement placement) { - if (!comments_) - comments_ = new CommentInfo[numberOfCommentPlacement]; - if ((len > 0) && (comment[len-1] == '\n')) { - // Always discard trailing newline, to aid indentation. - len -= 1; - } - comments_[placement].setComment(comment, len); -} - -void Value::setComment(const char* comment, CommentPlacement placement) { - setComment(comment, strlen(comment), placement); -} - -void Value::setComment(const JSONCPP_STRING& comment, CommentPlacement placement) { - setComment(comment.c_str(), comment.length(), placement); -} - -bool Value::hasComment(CommentPlacement placement) const { - return comments_ != 0 && comments_[placement].comment_ != 0; -} - -JSONCPP_STRING Value::getComment(CommentPlacement placement) const { - if (hasComment(placement)) - return comments_[placement].comment_; - return ""; -} - -void Value::setOffsetStart(ptrdiff_t start) { start_ = start; } - -void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; } - -ptrdiff_t Value::getOffsetStart() const { return start_; } - -ptrdiff_t Value::getOffsetLimit() const { return limit_; } - -JSONCPP_STRING Value::toStyledString() const { - StyledWriter writer; - return writer.write(*this); -} - -Value::const_iterator Value::begin() const { - switch (type_) { - case arrayValue: - case objectValue: - if (value_.map_) - return const_iterator(value_.map_->begin()); - break; - default: - break; - } - return const_iterator(); -} - -Value::const_iterator Value::end() const { - switch (type_) { - case arrayValue: - case objectValue: - if (value_.map_) - return const_iterator(value_.map_->end()); - break; - default: - break; - } - return const_iterator(); -} - -Value::iterator Value::begin() { - switch (type_) { - case arrayValue: - case objectValue: - if (value_.map_) - return iterator(value_.map_->begin()); - break; - default: - break; - } - return iterator(); -} - -Value::iterator Value::end() { - switch (type_) { - case arrayValue: - case objectValue: - if (value_.map_) - return iterator(value_.map_->end()); - break; - default: - break; - } - return iterator(); -} - -// class PathArgument -// ////////////////////////////////////////////////////////////////// - -PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {} - -PathArgument::PathArgument(ArrayIndex index) - : key_(), index_(index), kind_(kindIndex) {} - -PathArgument::PathArgument(const char* key) - : key_(key), index_(), kind_(kindKey) {} - -PathArgument::PathArgument(const JSONCPP_STRING& key) - : key_(key.c_str()), index_(), kind_(kindKey) {} - -// class Path -// ////////////////////////////////////////////////////////////////// - -Path::Path(const JSONCPP_STRING& path, - const PathArgument& a1, - const PathArgument& a2, - const PathArgument& a3, - const PathArgument& a4, - const PathArgument& a5) { - InArgs in; - in.push_back(&a1); - in.push_back(&a2); - in.push_back(&a3); - in.push_back(&a4); - in.push_back(&a5); - makePath(path, in); -} - -void Path::makePath(const JSONCPP_STRING& path, const InArgs& in) { - const char* current = path.c_str(); - const char* end = current + path.length(); - InArgs::const_iterator itInArg = in.begin(); - while (current != end) { - if (*current == '[') { - ++current; - if (*current == '%') - addPathInArg(path, in, itInArg, PathArgument::kindIndex); - else { - ArrayIndex index = 0; - for (; current != end && *current >= '0' && *current <= '9'; ++current) - index = index * 10 + ArrayIndex(*current - '0'); - args_.push_back(index); - } - if (current == end || *++current != ']') - invalidPath(path, int(current - path.c_str())); - } else if (*current == '%') { - addPathInArg(path, in, itInArg, PathArgument::kindKey); - ++current; - } else if (*current == '.' || *current == ']') { - ++current; - } else { - const char* beginName = current; - while (current != end && !strchr("[.", *current)) - ++current; - args_.push_back(JSONCPP_STRING(beginName, current)); - } - } -} - -void Path::addPathInArg(const JSONCPP_STRING& /*path*/, - const InArgs& in, - InArgs::const_iterator& itInArg, - PathArgument::Kind kind) { - if (itInArg == in.end()) { - // Error: missing argument %d - } else if ((*itInArg)->kind_ != kind) { - // Error: bad argument type - } else { - args_.push_back(**itInArg++); - } -} - -void Path::invalidPath(const JSONCPP_STRING& /*path*/, int /*location*/) { - // Error: invalid path. -} - -const Value& Path::resolve(const Value& root) const { - const Value* node = &root; - for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { - const PathArgument& arg = *it; - if (arg.kind_ == PathArgument::kindIndex) { - if (!node->isArray() || !node->isValidIndex(arg.index_)) { - // Error: unable to resolve path (array value expected at position... - return Value::null; - } - node = &((*node)[arg.index_]); - } else if (arg.kind_ == PathArgument::kindKey) { - if (!node->isObject()) { - // Error: unable to resolve path (object value expected at position...) - return Value::null; - } - node = &((*node)[arg.key_]); - if (node == &Value::nullSingleton()) { - // Error: unable to resolve path (object has no member named '' at - // position...) - return Value::null; - } - } - } - return *node; -} - -Value Path::resolve(const Value& root, const Value& defaultValue) const { - const Value* node = &root; - for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { - const PathArgument& arg = *it; - if (arg.kind_ == PathArgument::kindIndex) { - if (!node->isArray() || !node->isValidIndex(arg.index_)) - return defaultValue; - node = &((*node)[arg.index_]); - } else if (arg.kind_ == PathArgument::kindKey) { - if (!node->isObject()) - return defaultValue; - node = &((*node)[arg.key_]); - if (node == &Value::nullSingleton()) - return defaultValue; - } - } - return *node; -} - -Value& Path::make(Value& root) const { - Value* node = &root; - for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) { - const PathArgument& arg = *it; - if (arg.kind_ == PathArgument::kindIndex) { - if (!node->isArray()) { - // Error: node is not an array at position ... - } - node = &((*node)[arg.index_]); - } else if (arg.kind_ == PathArgument::kindKey) { - if (!node->isObject()) { - // Error: node is not an object at position... - } - node = &((*node)[arg.key_]); - } - } - return *node; -} - -} // namespace Json diff --git a/thirdparty/jsoncpp/src/lib_json/json_valueiterator.inl b/thirdparty/jsoncpp/src/lib_json/json_valueiterator.inl deleted file mode 100644 index b45162b4a6..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/json_valueiterator.inl +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -// included by json_value.cpp - -namespace Json { - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class ValueIteratorBase -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -ValueIteratorBase::ValueIteratorBase() - : current_(), isNull_(true) { -} - -ValueIteratorBase::ValueIteratorBase( - const Value::ObjectValues::iterator& current) - : current_(current), isNull_(false) {} - -Value& ValueIteratorBase::deref() const { - return current_->second; -} - -void ValueIteratorBase::increment() { - ++current_; -} - -void ValueIteratorBase::decrement() { - --current_; -} - -ValueIteratorBase::difference_type -ValueIteratorBase::computeDistance(const SelfType& other) const { -#ifdef JSON_USE_CPPTL_SMALLMAP - return other.current_ - current_; -#else - // Iterator for null value are initialized using the default - // constructor, which initialize current_ to the default - // std::map::iterator. As begin() and end() are two instance - // of the default std::map::iterator, they can not be compared. - // To allow this, we handle this comparison specifically. - if (isNull_ && other.isNull_) { - return 0; - } - - // Usage of std::distance is not portable (does not compile with Sun Studio 12 - // RogueWave STL, - // which is the one used by default). - // Using a portable hand-made version for non random iterator instead: - // return difference_type( std::distance( current_, other.current_ ) ); - difference_type myDistance = 0; - for (Value::ObjectValues::iterator it = current_; it != other.current_; - ++it) { - ++myDistance; - } - return myDistance; -#endif -} - -bool ValueIteratorBase::isEqual(const SelfType& other) const { - if (isNull_) { - return other.isNull_; - } - return current_ == other.current_; -} - -void ValueIteratorBase::copy(const SelfType& other) { - current_ = other.current_; - isNull_ = other.isNull_; -} - -Value ValueIteratorBase::key() const { - const Value::CZString czstring = (*current_).first; - if (czstring.data()) { - if (czstring.isStaticString()) - return Value(StaticString(czstring.data())); - return Value(czstring.data(), czstring.data() + czstring.length()); - } - return Value(czstring.index()); -} - -UInt ValueIteratorBase::index() const { - const Value::CZString czstring = (*current_).first; - if (!czstring.data()) - return czstring.index(); - return Value::UInt(-1); -} - -JSONCPP_STRING ValueIteratorBase::name() const { - char const* keey; - char const* end; - keey = memberName(&end); - if (!keey) return JSONCPP_STRING(); - return JSONCPP_STRING(keey, end); -} - -char const* ValueIteratorBase::memberName() const { - const char* cname = (*current_).first.data(); - return cname ? cname : ""; -} - -char const* ValueIteratorBase::memberName(char const** end) const { - const char* cname = (*current_).first.data(); - if (!cname) { - *end = NULL; - return NULL; - } - *end = cname + (*current_).first.length(); - return cname; -} - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class ValueConstIterator -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -ValueConstIterator::ValueConstIterator() {} - -ValueConstIterator::ValueConstIterator( - const Value::ObjectValues::iterator& current) - : ValueIteratorBase(current) {} - -ValueConstIterator::ValueConstIterator(ValueIterator const& other) - : ValueIteratorBase(other) {} - -ValueConstIterator& ValueConstIterator:: -operator=(const ValueIteratorBase& other) { - copy(other); - return *this; -} - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// class ValueIterator -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -ValueIterator::ValueIterator() {} - -ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current) - : ValueIteratorBase(current) {} - -ValueIterator::ValueIterator(const ValueConstIterator& other) - : ValueIteratorBase(other) { - throwRuntimeError("ConstIterator to Iterator should never be allowed."); -} - -ValueIterator::ValueIterator(const ValueIterator& other) - : ValueIteratorBase(other) {} - -ValueIterator& ValueIterator::operator=(const SelfType& other) { - copy(other); - return *this; -} - -} // namespace Json diff --git a/thirdparty/jsoncpp/src/lib_json/json_writer.cpp b/thirdparty/jsoncpp/src/lib_json/json_writer.cpp deleted file mode 100644 index a03f0ebcd0..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/json_writer.cpp +++ /dev/null @@ -1,1224 +0,0 @@ -// Copyright 2011 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#if !defined(JSON_IS_AMALGAMATION) -#include -#include "json_tool.h" -#endif // if !defined(JSON_IS_AMALGAMATION) -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0 -#include -#define isfinite _finite -#elif defined(__sun) && defined(__SVR4) //Solaris -#if !defined(isfinite) -#include -#define isfinite finite -#endif -#elif defined(_AIX) -#if !defined(isfinite) -#include -#define isfinite finite -#endif -#elif defined(__hpux) -#if !defined(isfinite) -#if defined(__ia64) && !defined(finite) -#define isfinite(x) ((sizeof(x) == sizeof(float) ? \ - _Isfinitef(x) : _IsFinite(x))) -#else -#include -#define isfinite finite -#endif -#endif -#else -#include -#if !(defined(__QNXNTO__)) // QNX already defines isfinite -#define isfinite std::isfinite -#endif -#endif - -#if defined(_MSC_VER) -#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above -#define snprintf sprintf_s -#elif _MSC_VER >= 1900 // VC++ 14.0 and above -#define snprintf std::snprintf -#else -#define snprintf _snprintf -#endif -#elif defined(__ANDROID__) || defined(__QNXNTO__) -#define snprintf snprintf -#elif __cplusplus >= 201103L -#if !defined(__MINGW32__) && !defined(__CYGWIN__) -#define snprintf std::snprintf -#endif -#endif - -#if defined(__BORLANDC__) -#include -#define isfinite _finite -#define snprintf _snprintf -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0 -// Disable warning about strdup being deprecated. -#pragma warning(disable : 4996) -#endif - -namespace Json { - -#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520) -typedef std::unique_ptr StreamWriterPtr; -#else -typedef std::auto_ptr StreamWriterPtr; -#endif - -static bool containsControlCharacter(const char* str) { - while (*str) { - if (isControlCharacter(*(str++))) - return true; - } - return false; -} - -static bool containsControlCharacter0(const char* str, unsigned len) { - char const* end = str + len; - while (end != str) { - if (isControlCharacter(*str) || 0==*str) - return true; - ++str; - } - return false; -} - -JSONCPP_STRING valueToString(LargestInt value) { - UIntToStringBuffer buffer; - char* current = buffer + sizeof(buffer); - if (value == Value::minLargestInt) { - uintToString(LargestUInt(Value::maxLargestInt) + 1, current); - *--current = '-'; - } else if (value < 0) { - uintToString(LargestUInt(-value), current); - *--current = '-'; - } else { - uintToString(LargestUInt(value), current); - } - assert(current >= buffer); - return current; -} - -JSONCPP_STRING valueToString(LargestUInt value) { - UIntToStringBuffer buffer; - char* current = buffer + sizeof(buffer); - uintToString(value, current); - assert(current >= buffer); - return current; -} - -#if defined(JSON_HAS_INT64) - -JSONCPP_STRING valueToString(Int value) { - return valueToString(LargestInt(value)); -} - -JSONCPP_STRING valueToString(UInt value) { - return valueToString(LargestUInt(value)); -} - -#endif // # if defined(JSON_HAS_INT64) - -namespace { -JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) { - // Allocate a buffer that is more than large enough to store the 16 digits of - // precision requested below. - char buffer[36]; - int len = -1; - - char formatString[6]; - sprintf(formatString, "%%.%dg", precision); - - // Print into the buffer. We need not request the alternative representation - // that always has a decimal point because JSON doesn't distingish the - // concepts of reals and integers. - if (isfinite(value)) { - len = snprintf(buffer, sizeof(buffer), formatString, value); - - // try to ensure we preserve the fact that this was given to us as a double on input - if (!strstr(buffer, ".") && !strstr(buffer, "e")) { - strcat(buffer, ".0"); - } - - } else { - // IEEE standard states that NaN values will not compare to themselves - if (value != value) { - len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null"); - } else if (value < 0) { - len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999"); - } else { - len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999"); - } - // For those, we do not need to call fixNumLoc, but it is fast. - } - assert(len >= 0); - fixNumericLocale(buffer, buffer + len); - return buffer; -} -} - -JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); } - -JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; } - -JSONCPP_STRING valueToQuotedString(const char* value) { - if (value == NULL) - return ""; - // Not sure how to handle unicode... - if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && - !containsControlCharacter(value)) - return JSONCPP_STRING("\"") + value + "\""; - // We have to walk value and escape any special characters. - // Appending to JSONCPP_STRING is not efficient, but this should be rare. - // (Note: forward slashes are *not* rare, but I am not escaping them.) - JSONCPP_STRING::size_type maxsize = - strlen(value) * 2 + 3; // allescaped+quotes+NULL - JSONCPP_STRING result; - result.reserve(maxsize); // to avoid lots of mallocs - result += "\""; - for (const char* c = value; *c != 0; ++c) { - switch (*c) { - case '\"': - result += "\\\""; - break; - case '\\': - result += "\\\\"; - break; - case '\b': - result += "\\b"; - break; - case '\f': - result += "\\f"; - break; - case '\n': - result += "\\n"; - break; - case '\r': - result += "\\r"; - break; - case '\t': - result += "\\t"; - break; - // case '/': - // Even though \/ is considered a legal escape in JSON, a bare - // slash is also legal, so I see no reason to escape it. - // (I hope I am not misunderstanding something. - // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); - result += oss.str(); - } else { - result += *c; - } - break; - } - } - result += "\""; - return result; -} - -// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp -static char const* strnpbrk(char const* s, char const* accept, size_t n) { - assert((s || !n) && accept); - - char const* const end = s + n; - for (char const* cur = s; cur < end; ++cur) { - int const c = *cur; - for (char const* a = accept; *a; ++a) { - if (*a == c) { - return cur; - } - } - } - return NULL; -} -static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) { - if (value == NULL) - return ""; - // Not sure how to handle unicode... - if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL && - !containsControlCharacter0(value, length)) - return JSONCPP_STRING("\"") + value + "\""; - // We have to walk value and escape any special characters. - // Appending to JSONCPP_STRING is not efficient, but this should be rare. - // (Note: forward slashes are *not* rare, but I am not escaping them.) - JSONCPP_STRING::size_type maxsize = - length * 2 + 3; // allescaped+quotes+NULL - JSONCPP_STRING result; - result.reserve(maxsize); // to avoid lots of mallocs - result += "\""; - char const* end = value + length; - for (const char* c = value; c != end; ++c) { - switch (*c) { - case '\"': - result += "\\\""; - break; - case '\\': - result += "\\\\"; - break; - case '\b': - result += "\\b"; - break; - case '\f': - result += "\\f"; - break; - case '\n': - result += "\\n"; - break; - case '\r': - result += "\\r"; - break; - case '\t': - result += "\\t"; - break; - // case '/': - // Even though \/ is considered a legal escape in JSON, a bare - // slash is also legal, so I see no reason to escape it. - // (I hope I am not misunderstanding something.) - // blep notes: actually escaping \/ may be useful in javascript to avoid (*c); - result += oss.str(); - } else { - result += *c; - } - break; - } - } - result += "\""; - return result; -} - -// Class Writer -// ////////////////////////////////////////////////////////////////// -Writer::~Writer() {} - -// Class FastWriter -// ////////////////////////////////////////////////////////////////// - -FastWriter::FastWriter() - : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false), - omitEndingLineFeed_(false) {} - -void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; } - -void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; } - -void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; } - -JSONCPP_STRING FastWriter::write(const Value& root) { - document_ = ""; - writeValue(root); - if (!omitEndingLineFeed_) - document_ += "\n"; - return document_; -} - -void FastWriter::writeValue(const Value& value) { - switch (value.type()) { - case nullValue: - if (!dropNullPlaceholders_) - document_ += "null"; - break; - case intValue: - document_ += valueToString(value.asLargestInt()); - break; - case uintValue: - document_ += valueToString(value.asLargestUInt()); - break; - case realValue: - document_ += valueToString(value.asDouble()); - break; - case stringValue: - { - // Is NULL possible for value.string_? No. - char const* str; - char const* end; - bool ok = value.getString(&str, &end); - if (ok) document_ += valueToQuotedStringN(str, static_cast(end-str)); - break; - } - case booleanValue: - document_ += valueToString(value.asBool()); - break; - case arrayValue: { - document_ += '['; - ArrayIndex size = value.size(); - for (ArrayIndex index = 0; index < size; ++index) { - if (index > 0) - document_ += ','; - writeValue(value[index]); - } - document_ += ']'; - } break; - case objectValue: { - Value::Members members(value.getMemberNames()); - document_ += '{'; - for (Value::Members::iterator it = members.begin(); it != members.end(); - ++it) { - const JSONCPP_STRING& name = *it; - if (it != members.begin()) - document_ += ','; - document_ += valueToQuotedStringN(name.data(), static_cast(name.length())); - document_ += yamlCompatiblityEnabled_ ? ": " : ":"; - writeValue(value[name]); - } - document_ += '}'; - } break; - } -} - -// Class StyledWriter -// ////////////////////////////////////////////////////////////////// - -StyledWriter::StyledWriter() - : rightMargin_(74), indentSize_(3), addChildValues_() {} - -JSONCPP_STRING StyledWriter::write(const Value& root) { - document_ = ""; - addChildValues_ = false; - indentString_ = ""; - writeCommentBeforeValue(root); - writeValue(root); - writeCommentAfterValueOnSameLine(root); - document_ += "\n"; - return document_; -} - -void StyledWriter::writeValue(const Value& value) { - switch (value.type()) { - case nullValue: - pushValue("null"); - break; - case intValue: - pushValue(valueToString(value.asLargestInt())); - break; - case uintValue: - pushValue(valueToString(value.asLargestUInt())); - break; - case realValue: - pushValue(valueToString(value.asDouble())); - break; - case stringValue: - { - // Is NULL possible for value.string_? No. - char const* str; - char const* end; - bool ok = value.getString(&str, &end); - if (ok) pushValue(valueToQuotedStringN(str, static_cast(end-str))); - else pushValue(""); - break; - } - case booleanValue: - pushValue(valueToString(value.asBool())); - break; - case arrayValue: - writeArrayValue(value); - break; - case objectValue: { - Value::Members members(value.getMemberNames()); - if (members.empty()) - pushValue("{}"); - else { - writeWithIndent("{"); - indent(); - Value::Members::iterator it = members.begin(); - for (;;) { - const JSONCPP_STRING& name = *it; - const Value& childValue = value[name]; - writeCommentBeforeValue(childValue); - writeWithIndent(valueToQuotedString(name.c_str())); - document_ += " : "; - writeValue(childValue); - if (++it == members.end()) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - document_ += ','; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("}"); - } - } break; - } -} - -void StyledWriter::writeArrayValue(const Value& value) { - unsigned size = value.size(); - if (size == 0) - pushValue("[]"); - else { - bool isArrayMultiLine = isMultineArray(value); - if (isArrayMultiLine) { - writeWithIndent("["); - indent(); - bool hasChildValue = !childValues_.empty(); - unsigned index = 0; - for (;;) { - const Value& childValue = value[index]; - writeCommentBeforeValue(childValue); - if (hasChildValue) - writeWithIndent(childValues_[index]); - else { - writeIndent(); - writeValue(childValue); - } - if (++index == size) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - document_ += ','; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("]"); - } else // output on a single line - { - assert(childValues_.size() == size); - document_ += "[ "; - for (unsigned index = 0; index < size; ++index) { - if (index > 0) - document_ += ", "; - document_ += childValues_[index]; - } - document_ += " ]"; - } - } -} - -bool StyledWriter::isMultineArray(const Value& value) { - ArrayIndex const size = value.size(); - bool isMultiLine = size * 3 >= rightMargin_; - childValues_.clear(); - for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { - const Value& childValue = value[index]; - isMultiLine = ((childValue.isArray() || childValue.isObject()) && - childValue.size() > 0); - } - if (!isMultiLine) // check if line length > max line length - { - childValues_.reserve(size); - addChildValues_ = true; - ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' - for (ArrayIndex index = 0; index < size; ++index) { - if (hasCommentForValue(value[index])) { - isMultiLine = true; - } - writeValue(value[index]); - lineLength += static_cast(childValues_[index].length()); - } - addChildValues_ = false; - isMultiLine = isMultiLine || lineLength >= rightMargin_; - } - return isMultiLine; -} - -void StyledWriter::pushValue(const JSONCPP_STRING& value) { - if (addChildValues_) - childValues_.push_back(value); - else - document_ += value; -} - -void StyledWriter::writeIndent() { - if (!document_.empty()) { - char last = document_[document_.length() - 1]; - if (last == ' ') // already indented - return; - if (last != '\n') // Comments may add new-line - document_ += '\n'; - } - document_ += indentString_; -} - -void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) { - writeIndent(); - document_ += value; -} - -void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); } - -void StyledWriter::unindent() { - assert(indentString_.size() >= indentSize_); - indentString_.resize(indentString_.size() - indentSize_); -} - -void StyledWriter::writeCommentBeforeValue(const Value& root) { - if (!root.hasComment(commentBefore)) - return; - - document_ += "\n"; - writeIndent(); - const JSONCPP_STRING& comment = root.getComment(commentBefore); - JSONCPP_STRING::const_iterator iter = comment.begin(); - while (iter != comment.end()) { - document_ += *iter; - if (*iter == '\n' && - (iter != comment.end() && *(iter + 1) == '/')) - writeIndent(); - ++iter; - } - - // Comments are stripped of trailing newlines, so add one here - document_ += "\n"; -} - -void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) { - if (root.hasComment(commentAfterOnSameLine)) - document_ += " " + root.getComment(commentAfterOnSameLine); - - if (root.hasComment(commentAfter)) { - document_ += "\n"; - document_ += root.getComment(commentAfter); - document_ += "\n"; - } -} - -bool StyledWriter::hasCommentForValue(const Value& value) { - return value.hasComment(commentBefore) || - value.hasComment(commentAfterOnSameLine) || - value.hasComment(commentAfter); -} - -// Class StyledStreamWriter -// ////////////////////////////////////////////////////////////////// - -StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation) - : document_(NULL), rightMargin_(74), indentation_(indentation), - addChildValues_() {} - -void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) { - document_ = &out; - addChildValues_ = false; - indentString_ = ""; - indented_ = true; - writeCommentBeforeValue(root); - if (!indented_) writeIndent(); - indented_ = true; - writeValue(root); - writeCommentAfterValueOnSameLine(root); - *document_ << "\n"; - document_ = NULL; // Forget the stream, for safety. -} - -void StyledStreamWriter::writeValue(const Value& value) { - switch (value.type()) { - case nullValue: - pushValue("null"); - break; - case intValue: - pushValue(valueToString(value.asLargestInt())); - break; - case uintValue: - pushValue(valueToString(value.asLargestUInt())); - break; - case realValue: - pushValue(valueToString(value.asDouble())); - break; - case stringValue: - { - // Is NULL possible for value.string_? No. - char const* str; - char const* end; - bool ok = value.getString(&str, &end); - if (ok) pushValue(valueToQuotedStringN(str, static_cast(end-str))); - else pushValue(""); - break; - } - case booleanValue: - pushValue(valueToString(value.asBool())); - break; - case arrayValue: - writeArrayValue(value); - break; - case objectValue: { - Value::Members members(value.getMemberNames()); - if (members.empty()) - pushValue("{}"); - else { - writeWithIndent("{"); - indent(); - Value::Members::iterator it = members.begin(); - for (;;) { - const JSONCPP_STRING& name = *it; - const Value& childValue = value[name]; - writeCommentBeforeValue(childValue); - writeWithIndent(valueToQuotedString(name.c_str())); - *document_ << " : "; - writeValue(childValue); - if (++it == members.end()) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - *document_ << ","; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("}"); - } - } break; - } -} - -void StyledStreamWriter::writeArrayValue(const Value& value) { - unsigned size = value.size(); - if (size == 0) - pushValue("[]"); - else { - bool isArrayMultiLine = isMultineArray(value); - if (isArrayMultiLine) { - writeWithIndent("["); - indent(); - bool hasChildValue = !childValues_.empty(); - unsigned index = 0; - for (;;) { - const Value& childValue = value[index]; - writeCommentBeforeValue(childValue); - if (hasChildValue) - writeWithIndent(childValues_[index]); - else { - if (!indented_) writeIndent(); - indented_ = true; - writeValue(childValue); - indented_ = false; - } - if (++index == size) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - *document_ << ","; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("]"); - } else // output on a single line - { - assert(childValues_.size() == size); - *document_ << "[ "; - for (unsigned index = 0; index < size; ++index) { - if (index > 0) - *document_ << ", "; - *document_ << childValues_[index]; - } - *document_ << " ]"; - } - } -} - -bool StyledStreamWriter::isMultineArray(const Value& value) { - ArrayIndex const size = value.size(); - bool isMultiLine = size * 3 >= rightMargin_; - childValues_.clear(); - for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { - const Value& childValue = value[index]; - isMultiLine = ((childValue.isArray() || childValue.isObject()) && - childValue.size() > 0); - } - if (!isMultiLine) // check if line length > max line length - { - childValues_.reserve(size); - addChildValues_ = true; - ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' - for (ArrayIndex index = 0; index < size; ++index) { - if (hasCommentForValue(value[index])) { - isMultiLine = true; - } - writeValue(value[index]); - lineLength += static_cast(childValues_[index].length()); - } - addChildValues_ = false; - isMultiLine = isMultiLine || lineLength >= rightMargin_; - } - return isMultiLine; -} - -void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) { - if (addChildValues_) - childValues_.push_back(value); - else - *document_ << value; -} - -void StyledStreamWriter::writeIndent() { - // blep intended this to look at the so-far-written string - // to determine whether we are already indented, but - // with a stream we cannot do that. So we rely on some saved state. - // The caller checks indented_. - *document_ << '\n' << indentString_; -} - -void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) { - if (!indented_) writeIndent(); - *document_ << value; - indented_ = false; -} - -void StyledStreamWriter::indent() { indentString_ += indentation_; } - -void StyledStreamWriter::unindent() { - assert(indentString_.size() >= indentation_.size()); - indentString_.resize(indentString_.size() - indentation_.size()); -} - -void StyledStreamWriter::writeCommentBeforeValue(const Value& root) { - if (!root.hasComment(commentBefore)) - return; - - if (!indented_) writeIndent(); - const JSONCPP_STRING& comment = root.getComment(commentBefore); - JSONCPP_STRING::const_iterator iter = comment.begin(); - while (iter != comment.end()) { - *document_ << *iter; - if (*iter == '\n' && - (iter != comment.end() && *(iter + 1) == '/')) - // writeIndent(); // would include newline - *document_ << indentString_; - ++iter; - } - indented_ = false; -} - -void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) { - if (root.hasComment(commentAfterOnSameLine)) - *document_ << ' ' << root.getComment(commentAfterOnSameLine); - - if (root.hasComment(commentAfter)) { - writeIndent(); - *document_ << root.getComment(commentAfter); - } - indented_ = false; -} - -bool StyledStreamWriter::hasCommentForValue(const Value& value) { - return value.hasComment(commentBefore) || - value.hasComment(commentAfterOnSameLine) || - value.hasComment(commentAfter); -} - -////////////////////////// -// BuiltStyledStreamWriter - -/// Scoped enums are not available until C++11. -struct CommentStyle { - /// Decide whether to write comments. - enum Enum { - None, ///< Drop all comments. - Most, ///< Recover odd behavior of previous versions (not implemented yet). - All ///< Keep all comments. - }; -}; - -struct BuiltStyledStreamWriter : public StreamWriter -{ - BuiltStyledStreamWriter( - JSONCPP_STRING const& indentation, - CommentStyle::Enum cs, - JSONCPP_STRING const& colonSymbol, - JSONCPP_STRING const& nullSymbol, - JSONCPP_STRING const& endingLineFeedSymbol, - bool useSpecialFloats, - unsigned int precision); - int write(Value const& root, JSONCPP_OSTREAM* sout) JSONCPP_OVERRIDE; -private: - void writeValue(Value const& value); - void writeArrayValue(Value const& value); - bool isMultineArray(Value const& value); - void pushValue(JSONCPP_STRING const& value); - void writeIndent(); - void writeWithIndent(JSONCPP_STRING const& value); - void indent(); - void unindent(); - void writeCommentBeforeValue(Value const& root); - void writeCommentAfterValueOnSameLine(Value const& root); - static bool hasCommentForValue(const Value& value); - - typedef std::vector ChildValues; - - ChildValues childValues_; - JSONCPP_STRING indentString_; - unsigned int rightMargin_; - JSONCPP_STRING indentation_; - CommentStyle::Enum cs_; - JSONCPP_STRING colonSymbol_; - JSONCPP_STRING nullSymbol_; - JSONCPP_STRING endingLineFeedSymbol_; - bool addChildValues_ : 1; - bool indented_ : 1; - bool useSpecialFloats_ : 1; - unsigned int precision_; -}; -BuiltStyledStreamWriter::BuiltStyledStreamWriter( - JSONCPP_STRING const& indentation, - CommentStyle::Enum cs, - JSONCPP_STRING const& colonSymbol, - JSONCPP_STRING const& nullSymbol, - JSONCPP_STRING const& endingLineFeedSymbol, - bool useSpecialFloats, - unsigned int precision) - : rightMargin_(74) - , indentation_(indentation) - , cs_(cs) - , colonSymbol_(colonSymbol) - , nullSymbol_(nullSymbol) - , endingLineFeedSymbol_(endingLineFeedSymbol) - , addChildValues_(false) - , indented_(false) - , useSpecialFloats_(useSpecialFloats) - , precision_(precision) -{ -} -int BuiltStyledStreamWriter::write(Value const& root, JSONCPP_OSTREAM* sout) -{ - sout_ = sout; - addChildValues_ = false; - indented_ = true; - indentString_ = ""; - writeCommentBeforeValue(root); - if (!indented_) writeIndent(); - indented_ = true; - writeValue(root); - writeCommentAfterValueOnSameLine(root); - *sout_ << endingLineFeedSymbol_; - sout_ = NULL; - return 0; -} -void BuiltStyledStreamWriter::writeValue(Value const& value) { - switch (value.type()) { - case nullValue: - pushValue(nullSymbol_); - break; - case intValue: - pushValue(valueToString(value.asLargestInt())); - break; - case uintValue: - pushValue(valueToString(value.asLargestUInt())); - break; - case realValue: - pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_)); - break; - case stringValue: - { - // Is NULL is possible for value.string_? No. - char const* str; - char const* end; - bool ok = value.getString(&str, &end); - if (ok) pushValue(valueToQuotedStringN(str, static_cast(end-str))); - else pushValue(""); - break; - } - case booleanValue: - pushValue(valueToString(value.asBool())); - break; - case arrayValue: - writeArrayValue(value); - break; - case objectValue: { - Value::Members members(value.getMemberNames()); - if (members.empty()) - pushValue("{}"); - else { - writeWithIndent("{"); - indent(); - Value::Members::iterator it = members.begin(); - for (;;) { - JSONCPP_STRING const& name = *it; - Value const& childValue = value[name]; - writeCommentBeforeValue(childValue); - writeWithIndent(valueToQuotedStringN(name.data(), static_cast(name.length()))); - *sout_ << colonSymbol_; - writeValue(childValue); - if (++it == members.end()) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - *sout_ << ","; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("}"); - } - } break; - } -} - -void BuiltStyledStreamWriter::writeArrayValue(Value const& value) { - unsigned size = value.size(); - if (size == 0) - pushValue("[]"); - else { - bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value); - if (isMultiLine) { - writeWithIndent("["); - indent(); - bool hasChildValue = !childValues_.empty(); - unsigned index = 0; - for (;;) { - Value const& childValue = value[index]; - writeCommentBeforeValue(childValue); - if (hasChildValue) - writeWithIndent(childValues_[index]); - else { - if (!indented_) writeIndent(); - indented_ = true; - writeValue(childValue); - indented_ = false; - } - if (++index == size) { - writeCommentAfterValueOnSameLine(childValue); - break; - } - *sout_ << ","; - writeCommentAfterValueOnSameLine(childValue); - } - unindent(); - writeWithIndent("]"); - } else // output on a single line - { - assert(childValues_.size() == size); - *sout_ << "["; - if (!indentation_.empty()) *sout_ << " "; - for (unsigned index = 0; index < size; ++index) { - if (index > 0) - *sout_ << ((!indentation_.empty()) ? ", " : ","); - *sout_ << childValues_[index]; - } - if (!indentation_.empty()) *sout_ << " "; - *sout_ << "]"; - } - } -} - -bool BuiltStyledStreamWriter::isMultineArray(Value const& value) { - ArrayIndex const size = value.size(); - bool isMultiLine = size * 3 >= rightMargin_; - childValues_.clear(); - for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { - Value const& childValue = value[index]; - isMultiLine = ((childValue.isArray() || childValue.isObject()) && - childValue.size() > 0); - } - if (!isMultiLine) // check if line length > max line length - { - childValues_.reserve(size); - addChildValues_ = true; - ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' - for (ArrayIndex index = 0; index < size; ++index) { - if (hasCommentForValue(value[index])) { - isMultiLine = true; - } - writeValue(value[index]); - lineLength += static_cast(childValues_[index].length()); - } - addChildValues_ = false; - isMultiLine = isMultiLine || lineLength >= rightMargin_; - } - return isMultiLine; -} - -void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) { - if (addChildValues_) - childValues_.push_back(value); - else - *sout_ << value; -} - -void BuiltStyledStreamWriter::writeIndent() { - // blep intended this to look at the so-far-written string - // to determine whether we are already indented, but - // with a stream we cannot do that. So we rely on some saved state. - // The caller checks indented_. - - if (!indentation_.empty()) { - // In this case, drop newlines too. - *sout_ << '\n' << indentString_; - } -} - -void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) { - if (!indented_) writeIndent(); - *sout_ << value; - indented_ = false; -} - -void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; } - -void BuiltStyledStreamWriter::unindent() { - assert(indentString_.size() >= indentation_.size()); - indentString_.resize(indentString_.size() - indentation_.size()); -} - -void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) { - if (cs_ == CommentStyle::None) return; - if (!root.hasComment(commentBefore)) - return; - - if (!indented_) writeIndent(); - const JSONCPP_STRING& comment = root.getComment(commentBefore); - JSONCPP_STRING::const_iterator iter = comment.begin(); - while (iter != comment.end()) { - *sout_ << *iter; - if (*iter == '\n' && - (iter != comment.end() && *(iter + 1) == '/')) - // writeIndent(); // would write extra newline - *sout_ << indentString_; - ++iter; - } - indented_ = false; -} - -void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) { - if (cs_ == CommentStyle::None) return; - if (root.hasComment(commentAfterOnSameLine)) - *sout_ << " " + root.getComment(commentAfterOnSameLine); - - if (root.hasComment(commentAfter)) { - writeIndent(); - *sout_ << root.getComment(commentAfter); - } -} - -// static -bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) { - return value.hasComment(commentBefore) || - value.hasComment(commentAfterOnSameLine) || - value.hasComment(commentAfter); -} - -/////////////// -// StreamWriter - -StreamWriter::StreamWriter() - : sout_(NULL) -{ -} -StreamWriter::~StreamWriter() -{ -} -StreamWriter::Factory::~Factory() -{} -StreamWriterBuilder::StreamWriterBuilder() -{ - setDefaults(&settings_); -} -StreamWriterBuilder::~StreamWriterBuilder() -{} -StreamWriter* StreamWriterBuilder::newStreamWriter() const -{ - JSONCPP_STRING indentation = settings_["indentation"].asString(); - JSONCPP_STRING cs_str = settings_["commentStyle"].asString(); - bool eyc = settings_["enableYAMLCompatibility"].asBool(); - bool dnp = settings_["dropNullPlaceholders"].asBool(); - bool usf = settings_["useSpecialFloats"].asBool(); - unsigned int pre = settings_["precision"].asUInt(); - CommentStyle::Enum cs = CommentStyle::All; - if (cs_str == "All") { - cs = CommentStyle::All; - } else if (cs_str == "None") { - cs = CommentStyle::None; - } else { - throwRuntimeError("commentStyle must be 'All' or 'None'"); - } - JSONCPP_STRING colonSymbol = " : "; - if (eyc) { - colonSymbol = ": "; - } else if (indentation.empty()) { - colonSymbol = ":"; - } - JSONCPP_STRING nullSymbol = "null"; - if (dnp) { - nullSymbol = ""; - } - if (pre > 17) pre = 17; - JSONCPP_STRING endingLineFeedSymbol = ""; - return new BuiltStyledStreamWriter( - indentation, cs, - colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre); -} -static void getValidWriterKeys(std::set* valid_keys) -{ - valid_keys->clear(); - valid_keys->insert("indentation"); - valid_keys->insert("commentStyle"); - valid_keys->insert("enableYAMLCompatibility"); - valid_keys->insert("dropNullPlaceholders"); - valid_keys->insert("useSpecialFloats"); - valid_keys->insert("precision"); -} -bool StreamWriterBuilder::validate(Json::Value* invalid) const -{ - Json::Value my_invalid; - if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL - Json::Value& inv = *invalid; - std::set valid_keys; - getValidWriterKeys(&valid_keys); - Value::Members keys = settings_.getMemberNames(); - size_t n = keys.size(); - for (size_t i = 0; i < n; ++i) { - JSONCPP_STRING const& key = keys[i]; - if (valid_keys.find(key) == valid_keys.end()) { - inv[key] = settings_[key]; - } - } - return 0u == inv.size(); -} -Value& StreamWriterBuilder::operator[](JSONCPP_STRING key) -{ - return settings_[key]; -} -// static -void StreamWriterBuilder::setDefaults(Json::Value* settings) -{ - //! [StreamWriterBuilderDefaults] - (*settings)["commentStyle"] = "All"; - (*settings)["indentation"] = "\t"; - (*settings)["enableYAMLCompatibility"] = false; - (*settings)["dropNullPlaceholders"] = false; - (*settings)["useSpecialFloats"] = false; - (*settings)["precision"] = 17; - //! [StreamWriterBuilderDefaults] -} - -JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) { - JSONCPP_OSTRINGSTREAM sout; - StreamWriterPtr const writer(builder.newStreamWriter()); - writer->write(root, &sout); - return sout.str(); -} - -JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) { - StreamWriterBuilder builder; - StreamWriterPtr const writer(builder.newStreamWriter()); - writer->write(root, &sout); - return sout; -} - -} // namespace Json diff --git a/thirdparty/jsoncpp/src/lib_json/sconscript b/thirdparty/jsoncpp/src/lib_json/sconscript deleted file mode 100644 index 6e7c6c8a07..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/sconscript +++ /dev/null @@ -1,8 +0,0 @@ -Import( 'env buildLibrary' ) - -buildLibrary( env, Split( """ - json_reader.cpp - json_value.cpp - json_writer.cpp - """ ), - 'json' ) diff --git a/thirdparty/jsoncpp/src/lib_json/version.h.in b/thirdparty/jsoncpp/src/lib_json/version.h.in deleted file mode 100644 index 47aac69bdd..0000000000 --- a/thirdparty/jsoncpp/src/lib_json/version.h.in +++ /dev/null @@ -1,20 +0,0 @@ -// DO NOT EDIT. This file (and "version") is generated by CMake. -// Run CMake configure step to update it. -#ifndef JSON_VERSION_H_INCLUDED -# define JSON_VERSION_H_INCLUDED - -# define JSONCPP_VERSION_STRING "@JSONCPP_VERSION@" -# define JSONCPP_VERSION_MAJOR @JSONCPP_VERSION_MAJOR@ -# define JSONCPP_VERSION_MINOR @JSONCPP_VERSION_MINOR@ -# define JSONCPP_VERSION_PATCH @JSONCPP_VERSION_PATCH@ -# define JSONCPP_VERSION_QUALIFIER -# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8)) - -#ifdef JSONCPP_USING_SECURE_MEMORY -#undef JSONCPP_USING_SECURE_MEMORY -#endif -#define JSONCPP_USING_SECURE_MEMORY @JSONCPP_USE_SECURE_MEMORY@ -// If non-zero, the library zeroes any memory that it has allocated before -// it frees its memory. - -#endif // JSON_VERSION_H_INCLUDED diff --git a/thirdparty/jsoncpp/src/test_lib_json/CMakeLists.txt b/thirdparty/jsoncpp/src/test_lib_json/CMakeLists.txt deleted file mode 100644 index 7000264a71..0000000000 --- a/thirdparty/jsoncpp/src/test_lib_json/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -# vim: et ts=4 sts=4 sw=4 tw=0 - -ADD_EXECUTABLE( jsoncpp_test - jsontest.cpp - jsontest.h - main.cpp - ) - - -IF(BUILD_SHARED_LIBS) - ADD_DEFINITIONS( -DJSON_DLL ) - TARGET_LINK_LIBRARIES(jsoncpp_test jsoncpp_lib) -ELSE(BUILD_SHARED_LIBS) - TARGET_LINK_LIBRARIES(jsoncpp_test jsoncpp_lib_static) -ENDIF() - -# another way to solve issue #90 -#set_target_properties(jsoncpp_test PROPERTIES COMPILE_FLAGS -ffloat-store) - -# Run unit tests in post-build -# (default cmake workflow hides away the test result into a file, resulting in poor dev workflow?!?) -IF(JSONCPP_WITH_POST_BUILD_UNITTEST) - IF(BUILD_SHARED_LIBS) - # First, copy the shared lib, for Microsoft. - # Then, run the test executable. - ADD_CUSTOM_COMMAND( TARGET jsoncpp_test - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ - COMMAND $) - ELSE(BUILD_SHARED_LIBS) - # Just run the test executable. - ADD_CUSTOM_COMMAND( TARGET jsoncpp_test - POST_BUILD - COMMAND $) - ENDIF() -ENDIF() - -SET_TARGET_PROPERTIES(jsoncpp_test PROPERTIES OUTPUT_NAME jsoncpp_test) diff --git a/thirdparty/jsoncpp/src/test_lib_json/jsontest.cpp b/thirdparty/jsoncpp/src/test_lib_json/jsontest.cpp deleted file mode 100644 index 4c10a37cfb..0000000000 --- a/thirdparty/jsoncpp/src/test_lib_json/jsontest.cpp +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#define _CRT_SECURE_NO_WARNINGS 1 // Prevents deprecation warning with MSVC -#include "jsontest.h" -#include -#include - -#if defined(_MSC_VER) -// Used to install a report hook that prevent dialog on assertion and error. -#include -#endif // if defined(_MSC_VER) - -#if defined(_WIN32) -// Used to prevent dialog on memory fault. -// Limits headers included by Windows.h -#define WIN32_LEAN_AND_MEAN -#define NOSERVICE -#define NOMCX -#define NOIME -#define NOSOUND -#define NOCOMM -#define NORPC -#define NOGDI -#define NOUSER -#define NODRIVERS -#define NOLOGERROR -#define NOPROFILER -#define NOMEMMGR -#define NOLFILEIO -#define NOOPENFILE -#define NORESOURCE -#define NOATOM -#define NOLANGUAGE -#define NOLSTRING -#define NODBCS -#define NOKEYBOARDINFO -#define NOGDICAPMASKS -#define NOCOLOR -#define NOGDIOBJ -#define NODRAWTEXT -#define NOTEXTMETRIC -#define NOSCALABLEFONT -#define NOBITMAP -#define NORASTEROPS -#define NOMETAFILE -#define NOSYSMETRICS -#define NOSYSTEMPARAMSINFO -#define NOMSG -#define NOWINSTYLES -#define NOWINOFFSETS -#define NOSHOWWINDOW -#define NODEFERWINDOWPOS -#define NOVIRTUALKEYCODES -#define NOKEYSTATES -#define NOWH -#define NOMENUS -#define NOSCROLL -#define NOCLIPBOARD -#define NOICONS -#define NOMB -#define NOSYSCOMMANDS -#define NOMDI -#define NOCTLMGR -#define NOWINMESSAGES -#include -#endif // if defined(_WIN32) - -namespace JsonTest { - -// class TestResult -// ////////////////////////////////////////////////////////////////// - -TestResult::TestResult() - : predicateId_(1), lastUsedPredicateId_(0), messageTarget_(0) { - // The root predicate has id 0 - rootPredicateNode_.id_ = 0; - rootPredicateNode_.next_ = 0; - predicateStackTail_ = &rootPredicateNode_; -} - -void TestResult::setTestName(const JSONCPP_STRING& name) { name_ = name; } - -TestResult& -TestResult::addFailure(const char* file, unsigned int line, const char* expr) { - /// Walks the PredicateContext stack adding them to failures_ if not already - /// added. - unsigned int nestingLevel = 0; - PredicateContext* lastNode = rootPredicateNode_.next_; - for (; lastNode != 0; lastNode = lastNode->next_) { - if (lastNode->id_ > lastUsedPredicateId_) // new PredicateContext - { - lastUsedPredicateId_ = lastNode->id_; - addFailureInfo( - lastNode->file_, lastNode->line_, lastNode->expr_, nestingLevel); - // Link the PredicateContext to the failure for message target when - // popping the PredicateContext. - lastNode->failure_ = &(failures_.back()); - } - ++nestingLevel; - } - - // Adds the failed assertion - addFailureInfo(file, line, expr, nestingLevel); - messageTarget_ = &(failures_.back()); - return *this; -} - -void TestResult::addFailureInfo(const char* file, - unsigned int line, - const char* expr, - unsigned int nestingLevel) { - Failure failure; - failure.file_ = file; - failure.line_ = line; - if (expr) { - failure.expr_ = expr; - } - failure.nestingLevel_ = nestingLevel; - failures_.push_back(failure); -} - -TestResult& TestResult::popPredicateContext() { - PredicateContext* lastNode = &rootPredicateNode_; - while (lastNode->next_ != 0 && lastNode->next_->next_ != 0) { - lastNode = lastNode->next_; - } - // Set message target to popped failure - PredicateContext* tail = lastNode->next_; - if (tail != 0 && tail->failure_ != 0) { - messageTarget_ = tail->failure_; - } - // Remove tail from list - predicateStackTail_ = lastNode; - lastNode->next_ = 0; - return *this; -} - -bool TestResult::failed() const { return !failures_.empty(); } - -unsigned int TestResult::getAssertionNestingLevel() const { - unsigned int level = 0; - const PredicateContext* lastNode = &rootPredicateNode_; - while (lastNode->next_ != 0) { - lastNode = lastNode->next_; - ++level; - } - return level; -} - -void TestResult::printFailure(bool printTestName) const { - if (failures_.empty()) { - return; - } - - if (printTestName) { - printf("* Detail of %s test failure:\n", name_.c_str()); - } - - // Print in reverse to display the callstack in the right order - Failures::const_iterator itEnd = failures_.end(); - for (Failures::const_iterator it = failures_.begin(); it != itEnd; ++it) { - const Failure& failure = *it; - JSONCPP_STRING indent(failure.nestingLevel_ * 2, ' '); - if (failure.file_) { - printf("%s%s(%d): ", indent.c_str(), failure.file_, failure.line_); - } - if (!failure.expr_.empty()) { - printf("%s\n", failure.expr_.c_str()); - } else if (failure.file_) { - printf("\n"); - } - if (!failure.message_.empty()) { - JSONCPP_STRING reindented = indentText(failure.message_, indent + " "); - printf("%s\n", reindented.c_str()); - } - } -} - -JSONCPP_STRING TestResult::indentText(const JSONCPP_STRING& text, - const JSONCPP_STRING& indent) { - JSONCPP_STRING reindented; - JSONCPP_STRING::size_type lastIndex = 0; - while (lastIndex < text.size()) { - JSONCPP_STRING::size_type nextIndex = text.find('\n', lastIndex); - if (nextIndex == JSONCPP_STRING::npos) { - nextIndex = text.size() - 1; - } - reindented += indent; - reindented += text.substr(lastIndex, nextIndex - lastIndex + 1); - lastIndex = nextIndex + 1; - } - return reindented; -} - -TestResult& TestResult::addToLastFailure(const JSONCPP_STRING& message) { - if (messageTarget_ != 0) { - messageTarget_->message_ += message; - } - return *this; -} - -TestResult& TestResult::operator<<(Json::Int64 value) { - return addToLastFailure(Json::valueToString(value)); -} - -TestResult& TestResult::operator<<(Json::UInt64 value) { - return addToLastFailure(Json::valueToString(value)); -} - -TestResult& TestResult::operator<<(bool value) { - return addToLastFailure(value ? "true" : "false"); -} - -// class TestCase -// ////////////////////////////////////////////////////////////////// - -TestCase::TestCase() : result_(0) {} - -TestCase::~TestCase() {} - -void TestCase::run(TestResult& result) { - result_ = &result; - runTestCase(); -} - -// class Runner -// ////////////////////////////////////////////////////////////////// - -Runner::Runner() {} - -Runner& Runner::add(TestCaseFactory factory) { - tests_.push_back(factory); - return *this; -} - -unsigned int Runner::testCount() const { - return static_cast(tests_.size()); -} - -JSONCPP_STRING Runner::testNameAt(unsigned int index) const { - TestCase* test = tests_[index](); - JSONCPP_STRING name = test->testName(); - delete test; - return name; -} - -void Runner::runTestAt(unsigned int index, TestResult& result) const { - TestCase* test = tests_[index](); - result.setTestName(test->testName()); - printf("Testing %s: ", test->testName()); - fflush(stdout); -#if JSON_USE_EXCEPTION - try { -#endif // if JSON_USE_EXCEPTION - test->run(result); -#if JSON_USE_EXCEPTION - } - catch (const std::exception& e) { - result.addFailure(__FILE__, __LINE__, "Unexpected exception caught:") - << e.what(); - } -#endif // if JSON_USE_EXCEPTION - delete test; - const char* status = result.failed() ? "FAILED" : "OK"; - printf("%s\n", status); - fflush(stdout); -} - -bool Runner::runAllTest(bool printSummary) const { - unsigned int count = testCount(); - std::deque failures; - for (unsigned int index = 0; index < count; ++index) { - TestResult result; - runTestAt(index, result); - if (result.failed()) { - failures.push_back(result); - } - } - - if (failures.empty()) { - if (printSummary) { - printf("All %d tests passed\n", count); - } - return true; - } else { - for (unsigned int index = 0; index < failures.size(); ++index) { - TestResult& result = failures[index]; - result.printFailure(count > 1); - } - - if (printSummary) { - unsigned int failedCount = static_cast(failures.size()); - unsigned int passedCount = count - failedCount; - printf("%d/%d tests passed (%d failure(s))\n", - passedCount, - count, - failedCount); - } - return false; - } -} - -bool Runner::testIndex(const JSONCPP_STRING& testName, - unsigned int& indexOut) const { - unsigned int count = testCount(); - for (unsigned int index = 0; index < count; ++index) { - if (testNameAt(index) == testName) { - indexOut = index; - return true; - } - } - return false; -} - -void Runner::listTests() const { - unsigned int count = testCount(); - for (unsigned int index = 0; index < count; ++index) { - printf("%s\n", testNameAt(index).c_str()); - } -} - -int Runner::runCommandLine(int argc, const char* argv[]) const { - // typedef std::deque TestNames; - Runner subrunner; - for (int index = 1; index < argc; ++index) { - JSONCPP_STRING opt = argv[index]; - if (opt == "--list-tests") { - listTests(); - return 0; - } else if (opt == "--test-auto") { - preventDialogOnCrash(); - } else if (opt == "--test") { - ++index; - if (index < argc) { - unsigned int testNameIndex; - if (testIndex(argv[index], testNameIndex)) { - subrunner.add(tests_[testNameIndex]); - } else { - fprintf(stderr, "Test '%s' does not exist!\n", argv[index]); - return 2; - } - } else { - printUsage(argv[0]); - return 2; - } - } else { - printUsage(argv[0]); - return 2; - } - } - bool succeeded; - if (subrunner.testCount() > 0) { - succeeded = subrunner.runAllTest(subrunner.testCount() > 1); - } else { - succeeded = runAllTest(true); - } - return succeeded ? 0 : 1; -} - -#if defined(_MSC_VER) && defined(_DEBUG) -// Hook MSVCRT assertions to prevent dialog from appearing -static int -msvcrtSilentReportHook(int reportType, char* message, int* /*returnValue*/) { - // The default CRT handling of error and assertion is to display - // an error dialog to the user. - // Instead, when an error or an assertion occurs, we force the - // application to terminate using abort() after display - // the message on stderr. - if (reportType == _CRT_ERROR || reportType == _CRT_ASSERT) { - // calling abort() cause the ReportHook to be called - // The following is used to detect this case and let's the - // error handler fallback on its default behaviour ( - // display a warning message) - static volatile bool isAborting = false; - if (isAborting) { - return TRUE; - } - isAborting = true; - - fprintf(stderr, "CRT Error/Assert:\n%s\n", message); - fflush(stderr); - abort(); - } - // Let's other reportType (_CRT_WARNING) be handled as they would by default - return FALSE; -} -#endif // if defined(_MSC_VER) - -void Runner::preventDialogOnCrash() { -#if defined(_MSC_VER) && defined(_DEBUG) - // Install a hook to prevent MSVCRT error and assertion from - // popping a dialog - // This function a NO-OP in release configuration - // (which cause warning since msvcrtSilentReportHook is not referenced) - _CrtSetReportHook(&msvcrtSilentReportHook); -#endif // if defined(_MSC_VER) - -// @todo investiguate this handler (for buffer overflow) -// _set_security_error_handler - -#if defined(_WIN32) - // Prevents the system from popping a dialog for debugging if the - // application fails due to invalid memory access. - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | - SEM_NOOPENFILEERRORBOX); -#endif // if defined(_WIN32) -} - -void Runner::printUsage(const char* appName) { - printf("Usage: %s [options]\n" - "\n" - "If --test is not specified, then all the test cases be run.\n" - "\n" - "Valid options:\n" - "--list-tests: print the name of all test cases on the standard\n" - " output and exit.\n" - "--test TESTNAME: executes the test case with the specified name.\n" - " May be repeated.\n" - "--test-auto: prevent dialog prompting for debugging on crash.\n", - appName); -} - -// Assertion functions -// ////////////////////////////////////////////////////////////////// - -JSONCPP_STRING ToJsonString(const char* toConvert) { - return JSONCPP_STRING(toConvert); -} - -JSONCPP_STRING ToJsonString(JSONCPP_STRING in) { - return in; -} - -#if JSONCPP_USING_SECURE_MEMORY -JSONCPP_STRING ToJsonString(std::string in) { - return JSONCPP_STRING(in.data(), in.data() + in.length()); -} -#endif - -TestResult& checkStringEqual(TestResult& result, - const JSONCPP_STRING& expected, - const JSONCPP_STRING& actual, - const char* file, - unsigned int line, - const char* expr) { - if (expected != actual) { - result.addFailure(file, line, expr); - result << "Expected: '" << expected << "'\n"; - result << "Actual : '" << actual << "'"; - } - return result; -} - -} // namespace JsonTest diff --git a/thirdparty/jsoncpp/src/test_lib_json/jsontest.h b/thirdparty/jsoncpp/src/test_lib_json/jsontest.h deleted file mode 100644 index f0ba1fafbe..0000000000 --- a/thirdparty/jsoncpp/src/test_lib_json/jsontest.h +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#ifndef JSONTEST_H_INCLUDED -#define JSONTEST_H_INCLUDED - -#include -#include -#include -#include -#include -#include -#include - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// Mini Unit Testing framework -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -/** \brief Unit testing framework. - * \warning: all assertions are non-aborting, test case execution will continue - * even if an assertion namespace. - * This constraint is for portability: the framework needs to compile - * on Visual Studio 6 and must not require exception usage. - */ -namespace JsonTest { - -class Failure { -public: - const char* file_; - unsigned int line_; - JSONCPP_STRING expr_; - JSONCPP_STRING message_; - unsigned int nestingLevel_; -}; - -/// Context used to create the assertion callstack on failure. -/// Must be a POD to allow inline initialisation without stepping -/// into the debugger. -struct PredicateContext { - typedef unsigned int Id; - Id id_; - const char* file_; - unsigned int line_; - const char* expr_; - PredicateContext* next_; - /// Related Failure, set when the PredicateContext is converted - /// into a Failure. - Failure* failure_; -}; - -class TestResult { -public: - TestResult(); - - /// \internal Implementation detail for assertion macros - /// Not encapsulated to prevent step into when debugging failed assertions - /// Incremented by one on assertion predicate entry, decreased by one - /// by addPredicateContext(). - PredicateContext::Id predicateId_; - - /// \internal Implementation detail for predicate macros - PredicateContext* predicateStackTail_; - - void setTestName(const JSONCPP_STRING& name); - - /// Adds an assertion failure. - TestResult& - addFailure(const char* file, unsigned int line, const char* expr = 0); - - /// Removes the last PredicateContext added to the predicate stack - /// chained list. - /// Next messages will be targed at the PredicateContext that was removed. - TestResult& popPredicateContext(); - - bool failed() const; - - void printFailure(bool printTestName) const; - - // Generic operator that will work with anything ostream can deal with. - template TestResult& operator<<(const T& value) { - JSONCPP_OSTRINGSTREAM oss; - oss.precision(16); - oss.setf(std::ios_base::floatfield); - oss << value; - return addToLastFailure(oss.str()); - } - - // Specialized versions. - TestResult& operator<<(bool value); - // std:ostream does not support 64bits integers on all STL implementation - TestResult& operator<<(Json::Int64 value); - TestResult& operator<<(Json::UInt64 value); - -private: - TestResult& addToLastFailure(const JSONCPP_STRING& message); - unsigned int getAssertionNestingLevel() const; - /// Adds a failure or a predicate context - void addFailureInfo(const char* file, - unsigned int line, - const char* expr, - unsigned int nestingLevel); - static JSONCPP_STRING indentText(const JSONCPP_STRING& text, - const JSONCPP_STRING& indent); - - typedef std::deque Failures; - Failures failures_; - JSONCPP_STRING name_; - PredicateContext rootPredicateNode_; - PredicateContext::Id lastUsedPredicateId_; - /// Failure which is the target of the messages added using operator << - Failure* messageTarget_; -}; - -class TestCase { -public: - TestCase(); - - virtual ~TestCase(); - - void run(TestResult& result); - - virtual const char* testName() const = 0; - -protected: - TestResult* result_; - -private: - virtual void runTestCase() = 0; -}; - -/// Function pointer type for TestCase factory -typedef TestCase* (*TestCaseFactory)(); - -class Runner { -public: - Runner(); - - /// Adds a test to the suite - Runner& add(TestCaseFactory factory); - - /// Runs test as specified on the command-line - /// If no command-line arguments are provided, run all tests. - /// If --list-tests is provided, then print the list of all test cases - /// If --test is provided, then run test testname. - int runCommandLine(int argc, const char* argv[]) const; - - /// Runs all the test cases - bool runAllTest(bool printSummary) const; - - /// Returns the number of test case in the suite - unsigned int testCount() const; - - /// Returns the name of the test case at the specified index - JSONCPP_STRING testNameAt(unsigned int index) const; - - /// Runs the test case at the specified index using the specified TestResult - void runTestAt(unsigned int index, TestResult& result) const; - - static void printUsage(const char* appName); - -private: // prevents copy construction and assignment - Runner(const Runner& other); - Runner& operator=(const Runner& other); - -private: - void listTests() const; - bool testIndex(const JSONCPP_STRING& testName, unsigned int& index) const; - static void preventDialogOnCrash(); - -private: - typedef std::deque Factories; - Factories tests_; -}; - -template -TestResult& checkEqual(TestResult& result, - T expected, - U actual, - const char* file, - unsigned int line, - const char* expr) { - if (static_cast(expected) != actual) { - result.addFailure(file, line, expr); - result << "Expected: " << static_cast(expected) << "\n"; - result << "Actual : " << actual; - } - return result; -} - -JSONCPP_STRING ToJsonString(const char* toConvert); -JSONCPP_STRING ToJsonString(JSONCPP_STRING in); -#if JSONCPP_USING_SECURE_MEMORY -JSONCPP_STRING ToJsonString(std::string in); -#endif - -TestResult& checkStringEqual(TestResult& result, - const JSONCPP_STRING& expected, - const JSONCPP_STRING& actual, - const char* file, - unsigned int line, - const char* expr); - -} // namespace JsonTest - -/// \brief Asserts that the given expression is true. -/// JSONTEST_ASSERT( x == y ) << "x=" << x << ", y=" << y; -/// JSONTEST_ASSERT( x == y ); -#define JSONTEST_ASSERT(expr) \ - if (expr) { \ - } else \ - result_->addFailure(__FILE__, __LINE__, #expr) - -/// \brief Asserts that the given predicate is true. -/// The predicate may do other assertions and be a member function of the -/// fixture. -#define JSONTEST_ASSERT_PRED(expr) \ - { \ - JsonTest::PredicateContext _minitest_Context = { \ - result_->predicateId_, __FILE__, __LINE__, #expr, NULL, NULL \ - }; \ - result_->predicateStackTail_->next_ = &_minitest_Context; \ - result_->predicateId_ += 1; \ - result_->predicateStackTail_ = &_minitest_Context; \ - (expr); \ - result_->popPredicateContext(); \ - } - -/// \brief Asserts that two values are equals. -#define JSONTEST_ASSERT_EQUAL(expected, actual) \ - JsonTest::checkEqual(*result_, \ - expected, \ - actual, \ - __FILE__, \ - __LINE__, \ - #expected " == " #actual) - -/// \brief Asserts that two values are equals. -#define JSONTEST_ASSERT_STRING_EQUAL(expected, actual) \ - JsonTest::checkStringEqual(*result_, \ - JsonTest::ToJsonString(expected), \ - JsonTest::ToJsonString(actual), \ - __FILE__, \ - __LINE__, \ - #expected " == " #actual) - -/// \brief Asserts that a given expression throws an exception -#define JSONTEST_ASSERT_THROWS(expr) \ - { \ - bool _threw = false; \ - try { \ - expr; \ - } \ - catch (...) { \ - _threw = true; \ - } \ - if (!_threw) \ - result_->addFailure( \ - __FILE__, __LINE__, "expected exception thrown: " #expr); \ - } - -/// \brief Begin a fixture test case. -#define JSONTEST_FIXTURE(FixtureType, name) \ - class Test##FixtureType##name : public FixtureType { \ - public: \ - static JsonTest::TestCase* factory() { \ - return new Test##FixtureType##name(); \ - } \ - \ - public: /* overidden from TestCase */ \ - const char* testName() const JSONCPP_OVERRIDE { return #FixtureType "/" #name; } \ - void runTestCase() JSONCPP_OVERRIDE; \ - }; \ - \ - void Test##FixtureType##name::runTestCase() - -#define JSONTEST_FIXTURE_FACTORY(FixtureType, name) \ - &Test##FixtureType##name::factory - -#define JSONTEST_REGISTER_FIXTURE(runner, FixtureType, name) \ - (runner).add(JSONTEST_FIXTURE_FACTORY(FixtureType, name)) - -#endif // ifndef JSONTEST_H_INCLUDED diff --git a/thirdparty/jsoncpp/src/test_lib_json/main.cpp b/thirdparty/jsoncpp/src/test_lib_json/main.cpp deleted file mode 100644 index 47cd981aa7..0000000000 --- a/thirdparty/jsoncpp/src/test_lib_json/main.cpp +++ /dev/null @@ -1,2589 +0,0 @@ -// Copyright 2007-2010 Baptiste Lepilleur -// Distributed under MIT license, or public domain if desired and -// recognized in your jurisdiction. -// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE - -#include "jsontest.h" -#include -#include -#include -#include -#include -#include -#include - -// Make numeric limits more convenient to talk about. -// Assumes int type in 32 bits. -#define kint32max Json::Value::maxInt -#define kint32min Json::Value::minInt -#define kuint32max Json::Value::maxUInt -#define kint64max Json::Value::maxInt64 -#define kint64min Json::Value::minInt64 -#define kuint64max Json::Value::maxUInt64 - -//static const double kdint64max = double(kint64max); -//static const float kfint64max = float(kint64max); -static const float kfint32max = float(kint32max); -static const float kfuint32max = float(kuint32max); - -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// -// Json Library test cases -// ////////////////////////////////////////////////////////////////// -// ////////////////////////////////////////////////////////////////// - -#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) -static inline double uint64ToDouble(Json::UInt64 value) { - return static_cast(value); -} -#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) -static inline double uint64ToDouble(Json::UInt64 value) { - return static_cast(Json::Int64(value / 2)) * 2.0 + - static_cast(Json::Int64(value & 1)); -} -#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) - -struct ValueTest : JsonTest::TestCase { - Json::Value null_; - Json::Value emptyArray_; - Json::Value emptyObject_; - Json::Value integer_; - Json::Value unsignedInteger_; - Json::Value smallUnsignedInteger_; - Json::Value real_; - Json::Value float_; - Json::Value array1_; - Json::Value object1_; - Json::Value emptyString_; - Json::Value string1_; - Json::Value string_; - Json::Value true_; - Json::Value false_; - - ValueTest() - : emptyArray_(Json::arrayValue), emptyObject_(Json::objectValue), - integer_(123456789), unsignedInteger_(34567890u), - smallUnsignedInteger_(Json::Value::UInt(Json::Value::maxInt)), - real_(1234.56789), float_(0.00390625f), emptyString_(""), string1_("a"), - string_("sometext with space"), true_(true), false_(false) { - array1_.append(1234); - object1_["id"] = 1234; - } - - struct IsCheck { - /// Initialize all checks to \c false by default. - IsCheck(); - - bool isObject_; - bool isArray_; - bool isBool_; - bool isString_; - bool isNull_; - - bool isInt_; - bool isInt64_; - bool isUInt_; - bool isUInt64_; - bool isIntegral_; - bool isDouble_; - bool isNumeric_; - }; - - void checkConstMemberCount(const Json::Value& value, - unsigned int expectedCount); - - void checkMemberCount(Json::Value& value, unsigned int expectedCount); - - void checkIs(const Json::Value& value, const IsCheck& check); - - void checkIsLess(const Json::Value& x, const Json::Value& y); - - void checkIsEqual(const Json::Value& x, const Json::Value& y); - - /// Normalize the representation of floating-point number by stripped leading - /// 0 in exponent. - static JSONCPP_STRING normalizeFloatingPointStr(const JSONCPP_STRING& s); -}; - -JSONCPP_STRING ValueTest::normalizeFloatingPointStr(const JSONCPP_STRING& s) { - JSONCPP_STRING::size_type index = s.find_last_of("eE"); - if (index != JSONCPP_STRING::npos) { - JSONCPP_STRING::size_type hasSign = - (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0; - JSONCPP_STRING::size_type exponentStartIndex = index + 1 + hasSign; - JSONCPP_STRING normalized = s.substr(0, exponentStartIndex); - JSONCPP_STRING::size_type indexDigit = - s.find_first_not_of('0', exponentStartIndex); - JSONCPP_STRING exponent = "0"; - if (indexDigit != - JSONCPP_STRING::npos) // There is an exponent different from 0 - { - exponent = s.substr(indexDigit); - } - return normalized + exponent; - } - return s; -} - -JSONTEST_FIXTURE(ValueTest, checkNormalizeFloatingPointStr) { - JSONTEST_ASSERT_STRING_EQUAL("0.0", normalizeFloatingPointStr("0.0")); - JSONTEST_ASSERT_STRING_EQUAL("0e0", normalizeFloatingPointStr("0e0")); - JSONTEST_ASSERT_STRING_EQUAL("1234.0", normalizeFloatingPointStr("1234.0")); - JSONTEST_ASSERT_STRING_EQUAL("1234.0e0", - normalizeFloatingPointStr("1234.0e0")); - JSONTEST_ASSERT_STRING_EQUAL("1234.0e+0", - normalizeFloatingPointStr("1234.0e+0")); - JSONTEST_ASSERT_STRING_EQUAL("1234e-1", normalizeFloatingPointStr("1234e-1")); - JSONTEST_ASSERT_STRING_EQUAL("1234e10", normalizeFloatingPointStr("1234e10")); - JSONTEST_ASSERT_STRING_EQUAL("1234e10", - normalizeFloatingPointStr("1234e010")); - JSONTEST_ASSERT_STRING_EQUAL("1234e+10", - normalizeFloatingPointStr("1234e+010")); - JSONTEST_ASSERT_STRING_EQUAL("1234e-10", - normalizeFloatingPointStr("1234e-010")); - JSONTEST_ASSERT_STRING_EQUAL("1234e+100", - normalizeFloatingPointStr("1234e+100")); - JSONTEST_ASSERT_STRING_EQUAL("1234e-100", - normalizeFloatingPointStr("1234e-100")); - JSONTEST_ASSERT_STRING_EQUAL("1234e+1", - normalizeFloatingPointStr("1234e+001")); -} - -JSONTEST_FIXTURE(ValueTest, memberCount) { - JSONTEST_ASSERT_PRED(checkMemberCount(emptyArray_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(emptyObject_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(array1_, 1)); - JSONTEST_ASSERT_PRED(checkMemberCount(object1_, 1)); - JSONTEST_ASSERT_PRED(checkMemberCount(null_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(integer_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(unsignedInteger_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(smallUnsignedInteger_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(real_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(emptyString_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(string_, 0)); - JSONTEST_ASSERT_PRED(checkMemberCount(true_, 0)); -} - -JSONTEST_FIXTURE(ValueTest, objects) { - // Types - IsCheck checks; - checks.isObject_ = true; - JSONTEST_ASSERT_PRED(checkIs(emptyObject_, checks)); - JSONTEST_ASSERT_PRED(checkIs(object1_, checks)); - - JSONTEST_ASSERT_EQUAL(Json::objectValue, emptyObject_.type()); - - // Empty object okay - JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::nullValue)); - - // Non-empty object not okay - JSONTEST_ASSERT(!object1_.isConvertibleTo(Json::nullValue)); - - // Always okay - JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::objectValue)); - - // Never okay - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::stringValue)); - - // Access through const reference - const Json::Value& constObject = object1_; - - JSONTEST_ASSERT_EQUAL(Json::Value(1234), constObject["id"]); - JSONTEST_ASSERT_EQUAL(Json::Value(), constObject["unknown id"]); - - // Access through non-const reference - JSONTEST_ASSERT_EQUAL(Json::Value(1234), object1_["id"]); - JSONTEST_ASSERT_EQUAL(Json::Value(), object1_["unknown id"]); - - object1_["some other id"] = "foo"; - JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]); - JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]); - - // Remove. - Json::Value got; - bool did; - did = object1_.removeMember("some other id", &got); - JSONTEST_ASSERT_EQUAL(Json::Value("foo"), got); - JSONTEST_ASSERT_EQUAL(true, did); - got = Json::Value("bar"); - did = object1_.removeMember("some other id", &got); - JSONTEST_ASSERT_EQUAL(Json::Value("bar"), got); - JSONTEST_ASSERT_EQUAL(false, did); -} - -JSONTEST_FIXTURE(ValueTest, arrays) { - const unsigned int index0 = 0; - - // Types - IsCheck checks; - checks.isArray_ = true; - JSONTEST_ASSERT_PRED(checkIs(emptyArray_, checks)); - JSONTEST_ASSERT_PRED(checkIs(array1_, checks)); - - JSONTEST_ASSERT_EQUAL(Json::arrayValue, array1_.type()); - - // Empty array okay - JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::nullValue)); - - // Non-empty array not okay - JSONTEST_ASSERT(!array1_.isConvertibleTo(Json::nullValue)); - - // Always okay - JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::arrayValue)); - - // Never okay - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::objectValue)); - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::stringValue)); - - // Access through const reference - const Json::Value& constArray = array1_; - JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[index0]); - JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[0]); - - // Access through non-const reference - JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[index0]); - JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[0]); - - array1_[2] = Json::Value(17); - JSONTEST_ASSERT_EQUAL(Json::Value(), array1_[1]); - JSONTEST_ASSERT_EQUAL(Json::Value(17), array1_[2]); - Json::Value got; - JSONTEST_ASSERT_EQUAL(true, array1_.removeIndex(2, &got)); - JSONTEST_ASSERT_EQUAL(Json::Value(17), got); - JSONTEST_ASSERT_EQUAL(false, array1_.removeIndex(2, &got)); // gone now -} -JSONTEST_FIXTURE(ValueTest, arrayIssue252) -{ - int count = 5; - Json::Value root; - Json::Value item; - root["array"] = Json::Value::nullRef; - for (int i = 0; i < count; i++) - { - item["a"] = i; - item["b"] = i; - root["array"][i] = item; - } - //JSONTEST_ASSERT_EQUAL(5, root["array"].size()); -} - -JSONTEST_FIXTURE(ValueTest, null) { - JSONTEST_ASSERT_EQUAL(Json::nullValue, null_.type()); - - IsCheck checks; - checks.isNull_ = true; - JSONTEST_ASSERT_PRED(checkIs(null_, checks)); - - JSONTEST_ASSERT(null_.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(null_.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(Json::Int(0), null_.asInt()); - JSONTEST_ASSERT_EQUAL(Json::LargestInt(0), null_.asLargestInt()); - JSONTEST_ASSERT_EQUAL(Json::UInt(0), null_.asUInt()); - JSONTEST_ASSERT_EQUAL(Json::LargestUInt(0), null_.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, null_.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, null_.asFloat()); - JSONTEST_ASSERT_STRING_EQUAL("", null_.asString()); - - JSONTEST_ASSERT_EQUAL(Json::Value::null, null_); -} - -JSONTEST_FIXTURE(ValueTest, strings) { - JSONTEST_ASSERT_EQUAL(Json::stringValue, string1_.type()); - - IsCheck checks; - checks.isString_ = true; - JSONTEST_ASSERT_PRED(checkIs(emptyString_, checks)); - JSONTEST_ASSERT_PRED(checkIs(string_, checks)); - JSONTEST_ASSERT_PRED(checkIs(string1_, checks)); - - // Empty string okay - JSONTEST_ASSERT(emptyString_.isConvertibleTo(Json::nullValue)); - - // Non-empty string not okay - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::nullValue)); - - // Always okay - JSONTEST_ASSERT(string1_.isConvertibleTo(Json::stringValue)); - - // Never okay - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::objectValue)); - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::realValue)); - - JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asString()); - JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asCString()); -} - -JSONTEST_FIXTURE(ValueTest, bools) { - JSONTEST_ASSERT_EQUAL(Json::booleanValue, false_.type()); - - IsCheck checks; - checks.isBool_ = true; - JSONTEST_ASSERT_PRED(checkIs(false_, checks)); - JSONTEST_ASSERT_PRED(checkIs(true_, checks)); - - // False okay - JSONTEST_ASSERT(false_.isConvertibleTo(Json::nullValue)); - - // True not okay - JSONTEST_ASSERT(!true_.isConvertibleTo(Json::nullValue)); - - // Always okay - JSONTEST_ASSERT(true_.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(true_.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(true_.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(true_.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(true_.isConvertibleTo(Json::stringValue)); - - // Never okay - JSONTEST_ASSERT(!true_.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!true_.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(true, true_.asBool()); - JSONTEST_ASSERT_EQUAL(1, true_.asInt()); - JSONTEST_ASSERT_EQUAL(1, true_.asLargestInt()); - JSONTEST_ASSERT_EQUAL(1, true_.asUInt()); - JSONTEST_ASSERT_EQUAL(1, true_.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(1.0, true_.asDouble()); - JSONTEST_ASSERT_EQUAL(1.0, true_.asFloat()); - - JSONTEST_ASSERT_EQUAL(false, false_.asBool()); - JSONTEST_ASSERT_EQUAL(0, false_.asInt()); - JSONTEST_ASSERT_EQUAL(0, false_.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, false_.asUInt()); - JSONTEST_ASSERT_EQUAL(0, false_.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, false_.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, false_.asFloat()); -} - -JSONTEST_FIXTURE(ValueTest, integers) { - IsCheck checks; - Json::Value val; - - // Conversions that don't depend on the value. - JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::objectValue)); - - // Default int - val = Json::Value(Json::intValue); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); - - // Default uint - val = Json::Value(Json::uintValue); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); - - // Default real - val = Json::Value(Json::realValue); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString()); - - // Zero (signed constructor arg) - val = Json::Value(0); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); - - // Zero (unsigned constructor arg) - val = Json::Value(0u); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); - - // Zero (floating-point constructor arg) - val = Json::Value(0.0); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(0, val.asInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(0, val.asUInt()); - JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(false, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString()); - - // 2^20 (signed constructor arg) - val = Json::Value(1 << 20); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString()); - - // 2^20 (unsigned constructor arg) - val = Json::Value(Json::UInt(1 << 20)); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString()); - - // 2^20 (floating-point constructor arg) - val = Json::Value((1 << 20) / 1.0); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); - JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1048576.0", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // -2^20 - val = Json::Value(-(1 << 20)); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asInt()); - JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asDouble()); - JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-1048576", val.asString()); - - // int32 max - val = Json::Value(kint32max); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kint32max, val.asInt()); - JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(kint32max, val.asUInt()); - JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(kint32max, val.asDouble()); - JSONTEST_ASSERT_EQUAL(kfint32max, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("2147483647", val.asString()); - - // int32 min - val = Json::Value(kint32min); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt_ = true; - checks.isInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kint32min, val.asInt()); - JSONTEST_ASSERT_EQUAL(kint32min, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(kint32min, val.asDouble()); - JSONTEST_ASSERT_EQUAL(kint32min, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-2147483648", val.asString()); - - // uint32 max - val = Json::Value(kuint32max); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isUInt_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - -#ifndef JSON_NO_INT64 - JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestInt()); -#endif - JSONTEST_ASSERT_EQUAL(kuint32max, val.asUInt()); - JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(kuint32max, val.asDouble()); - JSONTEST_ASSERT_EQUAL(kfuint32max, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("4294967295", val.asString()); - -#ifdef JSON_NO_INT64 - // int64 max - val = Json::Value(double(kint64max)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("9.22337e+18", val.asString()); - - // int64 min - val = Json::Value(double(kint64min)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-9.22337e+18", val.asString()); - - // uint64 max - val = Json::Value(double(kuint64max)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(double(kuint64max), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(kuint64max), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1.84467e+19", val.asString()); -#else // ifdef JSON_NO_INT64 - // 2^40 (signed constructor arg) - val = Json::Value(Json::Int64(1) << 40); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString()); - - // 2^40 (unsigned constructor arg) - val = Json::Value(Json::UInt64(1) << 40); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString()); - - // 2^40 (floating-point constructor arg) - val = Json::Value((Json::Int64(1) << 40) / 1.0); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1099511627776.0", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // -2^40 - val = Json::Value(-(Json::Int64(1) << 40)); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asInt64()); - JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asDouble()); - JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-1099511627776", val.asString()); - - // int64 max - val = Json::Value(Json::Int64(kint64max)); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kint64max, val.asInt64()); - JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(kint64max, val.asUInt64()); - JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("9223372036854775807", val.asString()); - - // int64 max (floating point constructor). Note that kint64max is not exactly - // representable as a double, and will be rounded up to be higher. - val = Json::Value(double(kint64max)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asUInt64()); - JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(uint64ToDouble(Json::UInt64(1) << 63), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(Json::UInt64(1) << 63)), - val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("9.2233720368547758e+18", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // int64 min - val = Json::Value(Json::Int64(kint64min)); - - JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kint64min, val.asInt64()); - JSONTEST_ASSERT_EQUAL(kint64min, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-9223372036854775808", val.asString()); - - // int64 min (floating point constructor). Note that kint64min *is* exactly - // representable as a double. - val = Json::Value(double(kint64min)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kint64min, val.asInt64()); - JSONTEST_ASSERT_EQUAL(kint64min, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("-9.2233720368547758e+18", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // 10^19 - const Json::UInt64 ten_to_19 = static_cast(1e19); - val = Json::Value(Json::UInt64(ten_to_19)); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(ten_to_19, val.asUInt64()); - JSONTEST_ASSERT_EQUAL(ten_to_19, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(uint64ToDouble(ten_to_19), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(ten_to_19)), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("10000000000000000000", val.asString()); - - // 10^19 (double constructor). Note that 10^19 is not exactly representable - // as a double. - val = Json::Value(uint64ToDouble(ten_to_19)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(1e19, val.asDouble()); - JSONTEST_ASSERT_EQUAL(1e19, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1e+19", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // uint64 max - val = Json::Value(Json::UInt64(kuint64max)); - - JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); - - checks = IsCheck(); - checks.isUInt64_ = true; - checks.isIntegral_ = true; - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(kuint64max, val.asUInt64()); - JSONTEST_ASSERT_EQUAL(kuint64max, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(uint64ToDouble(kuint64max), val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(kuint64max)), val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("18446744073709551615", val.asString()); - - // uint64 max (floating point constructor). Note that kuint64max is not - // exactly representable as a double, and will be rounded up to be higher. - val = Json::Value(uint64ToDouble(kuint64max)); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - - JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asDouble()); - JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asFloat()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_STRING_EQUAL("1.8446744073709552e+19", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); -#endif -} - -JSONTEST_FIXTURE(ValueTest, nonIntegers) { - IsCheck checks; - Json::Value val; - - // Small positive number - val = Json::Value(1.5); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(1.5, val.asDouble()); - JSONTEST_ASSERT_EQUAL(1.5, val.asFloat()); - JSONTEST_ASSERT_EQUAL(1, val.asInt()); - JSONTEST_ASSERT_EQUAL(1, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(1, val.asUInt()); - JSONTEST_ASSERT_EQUAL(1, val.asLargestUInt()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_EQUAL("1.5", val.asString()); - - // Small negative number - val = Json::Value(-1.5); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(-1.5, val.asDouble()); - JSONTEST_ASSERT_EQUAL(-1.5, val.asFloat()); - JSONTEST_ASSERT_EQUAL(-1, val.asInt()); - JSONTEST_ASSERT_EQUAL(-1, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_EQUAL("-1.5", val.asString()); - - // A bit over int32 max - val = Json::Value(kint32max + 0.5); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(2147483647.5, val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(2147483647.5), val.asFloat()); - JSONTEST_ASSERT_EQUAL(2147483647U, val.asUInt()); -#ifdef JSON_HAS_INT64 - JSONTEST_ASSERT_EQUAL(2147483647L, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL(2147483647U, val.asLargestUInt()); -#endif - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_EQUAL("2147483647.5", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // A bit under int32 min - val = Json::Value(kint32min - 0.5); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(-2147483648.5, val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(-2147483648.5), val.asFloat()); -#ifdef JSON_HAS_INT64 - JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 31), val.asLargestInt()); -#endif - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_EQUAL("-2147483648.5", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // A bit over uint32 max - val = Json::Value(kuint32max + 0.5); - - JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); - - checks = IsCheck(); - checks.isDouble_ = true; - checks.isNumeric_ = true; - JSONTEST_ASSERT_PRED(checkIs(val, checks)); - - JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); - JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); - JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); - - JSONTEST_ASSERT_EQUAL(4294967295.5, val.asDouble()); - JSONTEST_ASSERT_EQUAL(float(4294967295.5), val.asFloat()); -#ifdef JSON_HAS_INT64 - JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 32) - 1, val.asLargestInt()); - JSONTEST_ASSERT_EQUAL((Json::UInt64(1) << 32) - Json::UInt64(1), - val.asLargestUInt()); -#endif - JSONTEST_ASSERT_EQUAL(true, val.asBool()); - JSONTEST_ASSERT_EQUAL("4294967295.5", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - val = Json::Value(1.2345678901234); - JSONTEST_ASSERT_STRING_EQUAL("1.2345678901234001", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // A 16-digit floating point number. - val = Json::Value(2199023255552000.0f); - JSONTEST_ASSERT_EQUAL(float(2199023255552000.0f), val.asFloat()); - JSONTEST_ASSERT_STRING_EQUAL("2199023255552000.0", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // A very large floating point number. - val = Json::Value(3.402823466385289e38); - JSONTEST_ASSERT_EQUAL(float(3.402823466385289e38), val.asFloat()); - JSONTEST_ASSERT_STRING_EQUAL("3.402823466385289e+38", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); - - // An even larger floating point number. - val = Json::Value(1.2345678e300); - JSONTEST_ASSERT_EQUAL(double(1.2345678e300), val.asDouble()); - JSONTEST_ASSERT_STRING_EQUAL("1.2345678e+300", - normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); -} - -void ValueTest::checkConstMemberCount(const Json::Value& value, - unsigned int expectedCount) { - unsigned int count = 0; - Json::Value::const_iterator itEnd = value.end(); - for (Json::Value::const_iterator it = value.begin(); it != itEnd; ++it) { - ++count; - } - JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::const_iterator"; -} - -void ValueTest::checkMemberCount(Json::Value& value, - unsigned int expectedCount) { - JSONTEST_ASSERT_EQUAL(expectedCount, value.size()); - - unsigned int count = 0; - Json::Value::iterator itEnd = value.end(); - for (Json::Value::iterator it = value.begin(); it != itEnd; ++it) { - ++count; - } - JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::iterator"; - - JSONTEST_ASSERT_PRED(checkConstMemberCount(value, expectedCount)); -} - -ValueTest::IsCheck::IsCheck() - : isObject_(false), isArray_(false), isBool_(false), isString_(false), - isNull_(false), isInt_(false), isInt64_(false), isUInt_(false), - isUInt64_(false), isIntegral_(false), isDouble_(false), - isNumeric_(false) {} - -void ValueTest::checkIs(const Json::Value& value, const IsCheck& check) { - JSONTEST_ASSERT_EQUAL(check.isObject_, value.isObject()); - JSONTEST_ASSERT_EQUAL(check.isArray_, value.isArray()); - JSONTEST_ASSERT_EQUAL(check.isBool_, value.isBool()); - JSONTEST_ASSERT_EQUAL(check.isDouble_, value.isDouble()); - JSONTEST_ASSERT_EQUAL(check.isInt_, value.isInt()); - JSONTEST_ASSERT_EQUAL(check.isUInt_, value.isUInt()); - JSONTEST_ASSERT_EQUAL(check.isIntegral_, value.isIntegral()); - JSONTEST_ASSERT_EQUAL(check.isNumeric_, value.isNumeric()); - JSONTEST_ASSERT_EQUAL(check.isString_, value.isString()); - JSONTEST_ASSERT_EQUAL(check.isNull_, value.isNull()); - -#ifdef JSON_HAS_INT64 - JSONTEST_ASSERT_EQUAL(check.isInt64_, value.isInt64()); - JSONTEST_ASSERT_EQUAL(check.isUInt64_, value.isUInt64()); -#else - JSONTEST_ASSERT_EQUAL(false, value.isInt64()); - JSONTEST_ASSERT_EQUAL(false, value.isUInt64()); -#endif -} - -JSONTEST_FIXTURE(ValueTest, compareNull) { - JSONTEST_ASSERT_PRED(checkIsEqual(Json::Value(), Json::Value())); -} - -JSONTEST_FIXTURE(ValueTest, compareInt) { - JSONTEST_ASSERT_PRED(checkIsLess(0, 10)); - JSONTEST_ASSERT_PRED(checkIsEqual(10, 10)); - JSONTEST_ASSERT_PRED(checkIsEqual(-10, -10)); - JSONTEST_ASSERT_PRED(checkIsLess(-10, 0)); -} - -JSONTEST_FIXTURE(ValueTest, compareUInt) { - JSONTEST_ASSERT_PRED(checkIsLess(0u, 10u)); - JSONTEST_ASSERT_PRED(checkIsLess(0u, Json::Value::maxUInt)); - JSONTEST_ASSERT_PRED(checkIsEqual(10u, 10u)); -} - -JSONTEST_FIXTURE(ValueTest, compareDouble) { - JSONTEST_ASSERT_PRED(checkIsLess(0.0, 10.0)); - JSONTEST_ASSERT_PRED(checkIsEqual(10.0, 10.0)); - JSONTEST_ASSERT_PRED(checkIsEqual(-10.0, -10.0)); - JSONTEST_ASSERT_PRED(checkIsLess(-10.0, 0.0)); -} - -JSONTEST_FIXTURE(ValueTest, compareString) { - JSONTEST_ASSERT_PRED(checkIsLess("", " ")); - JSONTEST_ASSERT_PRED(checkIsLess("", "a")); - JSONTEST_ASSERT_PRED(checkIsLess("abcd", "zyui")); - JSONTEST_ASSERT_PRED(checkIsLess("abc", "abcd")); - JSONTEST_ASSERT_PRED(checkIsEqual("abcd", "abcd")); - JSONTEST_ASSERT_PRED(checkIsEqual(" ", " ")); - JSONTEST_ASSERT_PRED(checkIsLess("ABCD", "abcd")); - JSONTEST_ASSERT_PRED(checkIsEqual("ABCD", "ABCD")); -} - -JSONTEST_FIXTURE(ValueTest, compareBoolean) { - JSONTEST_ASSERT_PRED(checkIsLess(false, true)); - JSONTEST_ASSERT_PRED(checkIsEqual(false, false)); - JSONTEST_ASSERT_PRED(checkIsEqual(true, true)); -} - -JSONTEST_FIXTURE(ValueTest, compareArray) { - // array compare size then content - Json::Value emptyArray(Json::arrayValue); - Json::Value l1aArray; - l1aArray.append(0); - Json::Value l1bArray; - l1bArray.append(10); - Json::Value l2aArray; - l2aArray.append(0); - l2aArray.append(0); - Json::Value l2bArray; - l2bArray.append(0); - l2bArray.append(10); - JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l1aArray)); - JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l2aArray)); - JSONTEST_ASSERT_PRED(checkIsLess(l1aArray, l2aArray)); - JSONTEST_ASSERT_PRED(checkIsLess(l2aArray, l2bArray)); - JSONTEST_ASSERT_PRED(checkIsEqual(emptyArray, Json::Value(emptyArray))); - JSONTEST_ASSERT_PRED(checkIsEqual(l1aArray, Json::Value(l1aArray))); - JSONTEST_ASSERT_PRED(checkIsEqual(l2bArray, Json::Value(l2bArray))); -} - -JSONTEST_FIXTURE(ValueTest, compareObject) { - // object compare size then content - Json::Value emptyObject(Json::objectValue); - Json::Value l1aObject; - l1aObject["key1"] = 0; - Json::Value l1bObject; - l1aObject["key1"] = 10; - Json::Value l2aObject; - l2aObject["key1"] = 0; - l2aObject["key2"] = 0; - JSONTEST_ASSERT_PRED(checkIsLess(emptyObject, l1aObject)); - JSONTEST_ASSERT_PRED(checkIsLess(emptyObject, l2aObject)); - JSONTEST_ASSERT_PRED(checkIsLess(l1aObject, l2aObject)); - JSONTEST_ASSERT_PRED(checkIsEqual(emptyObject, Json::Value(emptyObject))); - JSONTEST_ASSERT_PRED(checkIsEqual(l1aObject, Json::Value(l1aObject))); - JSONTEST_ASSERT_PRED(checkIsEqual(l2aObject, Json::Value(l2aObject))); -} - -JSONTEST_FIXTURE(ValueTest, compareType) { - // object of different type are ordered according to their type - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(), Json::Value(1))); - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1), Json::Value(1u))); - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1u), Json::Value(1.0))); - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1.0), Json::Value("a"))); - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value("a"), Json::Value(true))); - JSONTEST_ASSERT_PRED( - checkIsLess(Json::Value(true), Json::Value(Json::arrayValue))); - JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(Json::arrayValue), - Json::Value(Json::objectValue))); -} - -void ValueTest::checkIsLess(const Json::Value& x, const Json::Value& y) { - JSONTEST_ASSERT(x < y); - JSONTEST_ASSERT(y > x); - JSONTEST_ASSERT(x <= y); - JSONTEST_ASSERT(y >= x); - JSONTEST_ASSERT(!(x == y)); - JSONTEST_ASSERT(!(y == x)); - JSONTEST_ASSERT(!(x >= y)); - JSONTEST_ASSERT(!(y <= x)); - JSONTEST_ASSERT(!(x > y)); - JSONTEST_ASSERT(!(y < x)); - JSONTEST_ASSERT(x.compare(y) < 0); - JSONTEST_ASSERT(y.compare(x) >= 0); -} - -void ValueTest::checkIsEqual(const Json::Value& x, const Json::Value& y) { - JSONTEST_ASSERT(x == y); - JSONTEST_ASSERT(y == x); - JSONTEST_ASSERT(x <= y); - JSONTEST_ASSERT(y <= x); - JSONTEST_ASSERT(x >= y); - JSONTEST_ASSERT(y >= x); - JSONTEST_ASSERT(!(x < y)); - JSONTEST_ASSERT(!(y < x)); - JSONTEST_ASSERT(!(x > y)); - JSONTEST_ASSERT(!(y > x)); - JSONTEST_ASSERT(x.compare(y) == 0); - JSONTEST_ASSERT(y.compare(x) == 0); -} - -JSONTEST_FIXTURE(ValueTest, typeChecksThrowExceptions) { -#if JSON_USE_EXCEPTION - - Json::Value intVal(1); - Json::Value strVal("Test"); - Json::Value objVal(Json::objectValue); - Json::Value arrVal(Json::arrayValue); - - JSONTEST_ASSERT_THROWS(intVal["test"]); - JSONTEST_ASSERT_THROWS(strVal["test"]); - JSONTEST_ASSERT_THROWS(arrVal["test"]); - - JSONTEST_ASSERT_THROWS(intVal.removeMember("test")); - JSONTEST_ASSERT_THROWS(strVal.removeMember("test")); - JSONTEST_ASSERT_THROWS(arrVal.removeMember("test")); - - JSONTEST_ASSERT_THROWS(intVal.getMemberNames()); - JSONTEST_ASSERT_THROWS(strVal.getMemberNames()); - JSONTEST_ASSERT_THROWS(arrVal.getMemberNames()); - - JSONTEST_ASSERT_THROWS(intVal[0]); - JSONTEST_ASSERT_THROWS(objVal[0]); - JSONTEST_ASSERT_THROWS(strVal[0]); - - JSONTEST_ASSERT_THROWS(intVal.clear()); - - JSONTEST_ASSERT_THROWS(intVal.resize(1)); - JSONTEST_ASSERT_THROWS(strVal.resize(1)); - JSONTEST_ASSERT_THROWS(objVal.resize(1)); - - JSONTEST_ASSERT_THROWS(intVal.asCString()); - - JSONTEST_ASSERT_THROWS(objVal.asString()); - JSONTEST_ASSERT_THROWS(arrVal.asString()); - - JSONTEST_ASSERT_THROWS(strVal.asInt()); - JSONTEST_ASSERT_THROWS(objVal.asInt()); - JSONTEST_ASSERT_THROWS(arrVal.asInt()); - - JSONTEST_ASSERT_THROWS(strVal.asUInt()); - JSONTEST_ASSERT_THROWS(objVal.asUInt()); - JSONTEST_ASSERT_THROWS(arrVal.asUInt()); - - JSONTEST_ASSERT_THROWS(strVal.asInt64()); - JSONTEST_ASSERT_THROWS(objVal.asInt64()); - JSONTEST_ASSERT_THROWS(arrVal.asInt64()); - - JSONTEST_ASSERT_THROWS(strVal.asUInt64()); - JSONTEST_ASSERT_THROWS(objVal.asUInt64()); - JSONTEST_ASSERT_THROWS(arrVal.asUInt64()); - - JSONTEST_ASSERT_THROWS(strVal.asDouble()); - JSONTEST_ASSERT_THROWS(objVal.asDouble()); - JSONTEST_ASSERT_THROWS(arrVal.asDouble()); - - JSONTEST_ASSERT_THROWS(strVal.asFloat()); - JSONTEST_ASSERT_THROWS(objVal.asFloat()); - JSONTEST_ASSERT_THROWS(arrVal.asFloat()); - - JSONTEST_ASSERT_THROWS(strVal.asBool()); - JSONTEST_ASSERT_THROWS(objVal.asBool()); - JSONTEST_ASSERT_THROWS(arrVal.asBool()); - -#endif -} - -JSONTEST_FIXTURE(ValueTest, offsetAccessors) { - Json::Value x; - JSONTEST_ASSERT(x.getOffsetStart() == 0); - JSONTEST_ASSERT(x.getOffsetLimit() == 0); - x.setOffsetStart(10); - x.setOffsetLimit(20); - JSONTEST_ASSERT(x.getOffsetStart() == 10); - JSONTEST_ASSERT(x.getOffsetLimit() == 20); - Json::Value y(x); - JSONTEST_ASSERT(y.getOffsetStart() == 10); - JSONTEST_ASSERT(y.getOffsetLimit() == 20); - Json::Value z; - z.swap(y); - JSONTEST_ASSERT(z.getOffsetStart() == 10); - JSONTEST_ASSERT(z.getOffsetLimit() == 20); - JSONTEST_ASSERT(y.getOffsetStart() == 0); - JSONTEST_ASSERT(y.getOffsetLimit() == 0); -} - -JSONTEST_FIXTURE(ValueTest, StaticString) { - char mutant[] = "hello"; - Json::StaticString ss(mutant); - JSONCPP_STRING regular(mutant); - mutant[1] = 'a'; - JSONTEST_ASSERT_STRING_EQUAL("hallo", ss.c_str()); - JSONTEST_ASSERT_STRING_EQUAL("hello", regular.c_str()); - { - Json::Value root; - root["top"] = ss; - JSONTEST_ASSERT_STRING_EQUAL("hallo", root["top"].asString()); - mutant[1] = 'u'; - JSONTEST_ASSERT_STRING_EQUAL("hullo", root["top"].asString()); - } - { - Json::Value root; - root["top"] = regular; - JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString()); - mutant[1] = 'u'; - JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString()); - } -} - -JSONTEST_FIXTURE(ValueTest, CommentBefore) { - Json::Value val; // fill val - val.setComment(JSONCPP_STRING("// this comment should appear before"), Json::commentBefore); - Json::StreamWriterBuilder wbuilder; - wbuilder.settings_["commentStyle"] = "All"; - { - char const expected[] = "// this comment should appear before\nnull"; - JSONCPP_STRING result = Json::writeString(wbuilder, val); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - JSONCPP_STRING res2 = val.toStyledString(); - JSONCPP_STRING exp2 = "\n"; - exp2 += expected; - exp2 += "\n"; - JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); - } - Json::Value other = "hello"; - val.swapPayload(other); - { - char const expected[] = "// this comment should appear before\n\"hello\""; - JSONCPP_STRING result = Json::writeString(wbuilder, val); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - JSONCPP_STRING res2 = val.toStyledString(); - JSONCPP_STRING exp2 = "\n"; - exp2 += expected; - exp2 += "\n"; - JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); - JSONTEST_ASSERT_STRING_EQUAL("null\n", other.toStyledString()); - } - val = "hello"; - // val.setComment("// this comment should appear before", Json::CommentPlacement::commentBefore); - // Assignment over-writes comments. - { - char const expected[] = "\"hello\""; - JSONCPP_STRING result = Json::writeString(wbuilder, val); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - JSONCPP_STRING res2 = val.toStyledString(); - JSONCPP_STRING exp2 = ""; - exp2 += expected; - exp2 += "\n"; - JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); - } -} - -JSONTEST_FIXTURE(ValueTest, zeroes) { - char const cstr[] = "h\0i"; - JSONCPP_STRING binary(cstr, sizeof(cstr)); // include trailing 0 - JSONTEST_ASSERT_EQUAL(4U, binary.length()); - Json::StreamWriterBuilder b; - { - Json::Value root; - root = binary; - JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString()); - } - { - char const top[] = "top"; - Json::Value root; - root[top] = binary; - JSONTEST_ASSERT_STRING_EQUAL(binary, root[top].asString()); - Json::Value removed; - bool did; - did = root.removeMember(top, top + sizeof(top) - 1U, - &removed); - JSONTEST_ASSERT(did); - JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString()); - did = root.removeMember(top, top + sizeof(top) - 1U, - &removed); - JSONTEST_ASSERT(!did); - JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString()); // still - } -} - -JSONTEST_FIXTURE(ValueTest, zeroesInKeys) { - char const cstr[] = "h\0i"; - JSONCPP_STRING binary(cstr, sizeof(cstr)); // include trailing 0 - JSONTEST_ASSERT_EQUAL(4U, binary.length()); - { - Json::Value root; - root[binary] = "there"; - JSONTEST_ASSERT_STRING_EQUAL("there", root[binary].asString()); - JSONTEST_ASSERT(!root.isMember("h")); - JSONTEST_ASSERT(root.isMember(binary)); - JSONTEST_ASSERT_STRING_EQUAL("there", root.get(binary, Json::Value::nullRef).asString()); - Json::Value removed; - bool did; - did = root.removeMember(binary.data(), binary.data() + binary.length(), - &removed); - JSONTEST_ASSERT(did); - JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString()); - did = root.removeMember(binary.data(), binary.data() + binary.length(), - &removed); - JSONTEST_ASSERT(!did); - JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString()); // still - JSONTEST_ASSERT(!root.isMember(binary)); - JSONTEST_ASSERT_STRING_EQUAL("", root.get(binary, Json::Value::nullRef).asString()); - } -} - -JSONTEST_FIXTURE(ValueTest, specialFloats) { - Json::StreamWriterBuilder b; - b.settings_["useSpecialFloats"] = true; - - Json::Value v = std::numeric_limits::quiet_NaN(); - JSONCPP_STRING expected = "NaN"; - JSONCPP_STRING result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - v = std::numeric_limits::infinity(); - expected = "Infinity"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - v = -std::numeric_limits::infinity(); - expected = "-Infinity"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); -} - -JSONTEST_FIXTURE(ValueTest, precision) { - Json::StreamWriterBuilder b; - b.settings_["precision"] = 5; - - Json::Value v = 100.0/3; - JSONCPP_STRING expected = "33.333"; - JSONCPP_STRING result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - v = 0.25000000; - expected = "0.25"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - v = 0.2563456; - expected = "0.25635"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - b.settings_["precision"] = 1; - expected = "0.3"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - b.settings_["precision"] = 17; - v = 1234857476305.256345694873740545068; - expected = "1234857476305.2563"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); - - b.settings_["precision"] = 24; - v = 0.256345694873740545068; - expected = "0.25634569487374054"; - result = Json::writeString(b, v); - JSONTEST_ASSERT_STRING_EQUAL(expected, result); -} - -struct WriterTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(WriterTest, dropNullPlaceholders) { - Json::FastWriter writer; - Json::Value nullValue; - JSONTEST_ASSERT(writer.write(nullValue) == "null\n"); - - writer.dropNullPlaceholders(); - JSONTEST_ASSERT(writer.write(nullValue) == "\n"); -} - -struct StreamWriterTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(StreamWriterTest, dropNullPlaceholders) { - Json::StreamWriterBuilder b; - Json::Value nullValue; - b.settings_["dropNullPlaceholders"] = false; - JSONTEST_ASSERT(Json::writeString(b, nullValue) == "null"); - b.settings_["dropNullPlaceholders"] = true; - JSONTEST_ASSERT(Json::writeString(b, nullValue) == ""); -} - -JSONTEST_FIXTURE(StreamWriterTest, writeZeroes) { - JSONCPP_STRING binary("hi", 3); // include trailing 0 - JSONTEST_ASSERT_EQUAL(3, binary.length()); - JSONCPP_STRING expected("\"hi\\u0000\""); // unicoded zero - Json::StreamWriterBuilder b; - { - Json::Value root; - root = binary; - JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString()); - JSONCPP_STRING out = Json::writeString(b, root); - JSONTEST_ASSERT_EQUAL(expected.size(), out.size()); - JSONTEST_ASSERT_STRING_EQUAL(expected, out); - } - { - Json::Value root; - root["top"] = binary; - JSONTEST_ASSERT_STRING_EQUAL(binary, root["top"].asString()); - JSONCPP_STRING out = Json::writeString(b, root["top"]); - JSONTEST_ASSERT_STRING_EQUAL(expected, out); - } -} - -struct ReaderTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(ReaderTest, parseWithNoErrors) { - Json::Reader reader; - Json::Value root; - bool ok = reader.parse("{ \"property\" : \"value\" }", root); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(reader.getFormattedErrorMessages().size() == 0); - JSONTEST_ASSERT(reader.getStructuredErrors().size() == 0); -} - -JSONTEST_FIXTURE(ReaderTest, parseWithNoErrorsTestingOffsets) { - Json::Reader reader; - Json::Value root; - bool ok = reader.parse("{ \"property\" : [\"value\", \"value2\"], \"obj\" : " - "{ \"nested\" : 123, \"bool\" : true}, \"null\" : " - "null, \"false\" : false }", - root); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(reader.getFormattedErrorMessages().size() == 0); - JSONTEST_ASSERT(reader.getStructuredErrors().size() == 0); - JSONTEST_ASSERT(root["property"].getOffsetStart() == 15); - JSONTEST_ASSERT(root["property"].getOffsetLimit() == 34); - JSONTEST_ASSERT(root["property"][0].getOffsetStart() == 16); - JSONTEST_ASSERT(root["property"][0].getOffsetLimit() == 23); - JSONTEST_ASSERT(root["property"][1].getOffsetStart() == 25); - JSONTEST_ASSERT(root["property"][1].getOffsetLimit() == 33); - JSONTEST_ASSERT(root["obj"].getOffsetStart() == 44); - JSONTEST_ASSERT(root["obj"].getOffsetLimit() == 76); - JSONTEST_ASSERT(root["obj"]["nested"].getOffsetStart() == 57); - JSONTEST_ASSERT(root["obj"]["nested"].getOffsetLimit() == 60); - JSONTEST_ASSERT(root["obj"]["bool"].getOffsetStart() == 71); - JSONTEST_ASSERT(root["obj"]["bool"].getOffsetLimit() == 75); - JSONTEST_ASSERT(root["null"].getOffsetStart() == 87); - JSONTEST_ASSERT(root["null"].getOffsetLimit() == 91); - JSONTEST_ASSERT(root["false"].getOffsetStart() == 103); - JSONTEST_ASSERT(root["false"].getOffsetLimit() == 108); - JSONTEST_ASSERT(root.getOffsetStart() == 0); - JSONTEST_ASSERT(root.getOffsetLimit() == 110); -} - -JSONTEST_FIXTURE(ReaderTest, parseWithOneError) { - Json::Reader reader; - Json::Value root; - bool ok = reader.parse("{ \"property\" :: \"value\" }", root); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(reader.getFormattedErrorMessages() == - "* Line 1, Column 15\n Syntax error: value, object or array " - "expected.\n"); - std::vector errors = - reader.getStructuredErrors(); - JSONTEST_ASSERT(errors.size() == 1); - JSONTEST_ASSERT(errors.at(0).offset_start == 14); - JSONTEST_ASSERT(errors.at(0).offset_limit == 15); - JSONTEST_ASSERT(errors.at(0).message == - "Syntax error: value, object or array expected."); -} - -JSONTEST_FIXTURE(ReaderTest, parseChineseWithOneError) { - Json::Reader reader; - Json::Value root; - bool ok = reader.parse("{ \"pr佐藤erty\" :: \"value\" }", root); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(reader.getFormattedErrorMessages() == - "* Line 1, Column 19\n Syntax error: value, object or array " - "expected.\n"); - std::vector errors = - reader.getStructuredErrors(); - JSONTEST_ASSERT(errors.size() == 1); - JSONTEST_ASSERT(errors.at(0).offset_start == 18); - JSONTEST_ASSERT(errors.at(0).offset_limit == 19); - JSONTEST_ASSERT(errors.at(0).message == - "Syntax error: value, object or array expected."); -} - -JSONTEST_FIXTURE(ReaderTest, parseWithDetailError) { - Json::Reader reader; - Json::Value root; - bool ok = reader.parse("{ \"property\" : \"v\\alue\" }", root); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(reader.getFormattedErrorMessages() == - "* Line 1, Column 16\n Bad escape sequence in string\nSee " - "Line 1, Column 20 for detail.\n"); - std::vector errors = - reader.getStructuredErrors(); - JSONTEST_ASSERT(errors.size() == 1); - JSONTEST_ASSERT(errors.at(0).offset_start == 15); - JSONTEST_ASSERT(errors.at(0).offset_limit == 23); - JSONTEST_ASSERT(errors.at(0).message == "Bad escape sequence in string"); -} - -struct CharReaderTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderTest, parseWithNoErrors) { - Json::CharReaderBuilder b; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - Json::Value root; - char const doc[] = "{ \"property\" : \"value\" }"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs.size() == 0); - delete reader; -} - -JSONTEST_FIXTURE(CharReaderTest, parseWithNoErrorsTestingOffsets) { - Json::CharReaderBuilder b; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - Json::Value root; - char const doc[] = - "{ \"property\" : [\"value\", \"value2\"], \"obj\" : " - "{ \"nested\" : 123, \"bool\" : true}, \"null\" : " - "null, \"false\" : false }"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs.size() == 0); - delete reader; -} - -JSONTEST_FIXTURE(CharReaderTest, parseWithOneError) { - Json::CharReaderBuilder b; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - Json::Value root; - char const doc[] = - "{ \"property\" :: \"value\" }"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(errs == - "* Line 1, Column 15\n Syntax error: value, object or array " - "expected.\n"); - delete reader; -} - -JSONTEST_FIXTURE(CharReaderTest, parseChineseWithOneError) { - Json::CharReaderBuilder b; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - Json::Value root; - char const doc[] = - "{ \"pr佐藤erty\" :: \"value\" }"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(errs == - "* Line 1, Column 19\n Syntax error: value, object or array " - "expected.\n"); - delete reader; -} - -JSONTEST_FIXTURE(CharReaderTest, parseWithDetailError) { - Json::CharReaderBuilder b; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - Json::Value root; - char const doc[] = - "{ \"property\" : \"v\\alue\" }"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT(errs == - "* Line 1, Column 16\n Bad escape sequence in string\nSee " - "Line 1, Column 20 for detail.\n"); - delete reader; -} - -JSONTEST_FIXTURE(CharReaderTest, parseWithStackLimit) { - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - "{ \"property\" : \"value\" }"; - { - b.settings_["stackLimit"] = 2; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL("value", root["property"]); - delete reader; - } - { - b.settings_["stackLimit"] = 1; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - JSONTEST_ASSERT_THROWS(reader->parse( - doc, doc + std::strlen(doc), - &root, &errs)); - delete reader; - } -} - -struct CharReaderStrictModeTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderStrictModeTest, dupKeys) { - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - "{ \"property\" : \"value\", \"key\" : \"val1\", \"key\" : \"val2\" }"; - { - b.strictMode(&b.settings_); - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT_STRING_EQUAL( - "* Line 1, Column 41\n" - " Duplicate key: 'key'\n", - errs); - JSONTEST_ASSERT_EQUAL("val1", root["key"]); // so far - delete reader; - } -} -struct CharReaderFailIfExtraTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderFailIfExtraTest, issue164) { - // This is interpreted as a string value followed by a colon. - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - " \"property\" : \"value\" }"; - { - b.settings_["failIfExtra"] = false; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL("property", root); - delete reader; - } - { - b.settings_["failIfExtra"] = true; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT_STRING_EQUAL(errs, - "* Line 1, Column 13\n" - " Extra non-whitespace after JSON value.\n"); - JSONTEST_ASSERT_EQUAL("property", root); - delete reader; - } - { - b.settings_["failIfExtra"] = false; - b.strictMode(&b.settings_); - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT_STRING_EQUAL(errs, - "* Line 1, Column 13\n" - " Extra non-whitespace after JSON value.\n"); - JSONTEST_ASSERT_EQUAL("property", root); - delete reader; - } -} -JSONTEST_FIXTURE(CharReaderFailIfExtraTest, issue107) { - // This is interpretted as an int value followed by a colon. - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - "1:2:3"; - b.settings_["failIfExtra"] = true; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(!ok); - JSONTEST_ASSERT_STRING_EQUAL( - "* Line 1, Column 2\n" - " Extra non-whitespace after JSON value.\n", - errs); - JSONTEST_ASSERT_EQUAL(1, root.asInt()); - delete reader; -} -JSONTEST_FIXTURE(CharReaderFailIfExtraTest, commentAfterObject) { - Json::CharReaderBuilder b; - Json::Value root; - { - char const doc[] = - "{ \"property\" : \"value\" } //trailing\n//comment\n"; - b.settings_["failIfExtra"] = true; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL("value", root["property"]); - delete reader; - } -} -JSONTEST_FIXTURE(CharReaderFailIfExtraTest, commentAfterArray) { - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - "[ \"property\" , \"value\" ] //trailing\n//comment\n"; - b.settings_["failIfExtra"] = true; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL("value", root[1u]); - delete reader; -} -JSONTEST_FIXTURE(CharReaderFailIfExtraTest, commentAfterBool) { - Json::CharReaderBuilder b; - Json::Value root; - char const doc[] = - " true /*trailing\ncomment*/"; - b.settings_["failIfExtra"] = true; - Json::CharReader* reader(b.newCharReader()); - JSONCPP_STRING errs; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(true, root.asBool()); - delete reader; -} -struct CharReaderAllowDropNullTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderAllowDropNullTest, issue178) { - Json::CharReaderBuilder b; - b.settings_["allowDroppedNullPlaceholders"] = true; - Json::Value root; - JSONCPP_STRING errs; - Json::CharReader* reader(b.newCharReader()); - { - char const doc[] = "{\"a\":,\"b\":true}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::nullValue, root.get("a", true)); - } - { - char const doc[] = "{\"a\":}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(1u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::nullValue, root.get("a", true)); - } - { - char const doc[] = "[]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL(0u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::arrayValue, root); - } - { - char const doc[] = "[null]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL(1u, root.size()); - } - { - char const doc[] = "[,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - } - { - char const doc[] = "[,,,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(4u, root.size()); - } - { - char const doc[] = "[null,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - } - { - char const doc[] = "[,null]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - } - { - char const doc[] = "[,,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(3u, root.size()); - } - { - char const doc[] = "[null,,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(3u, root.size()); - } - { - char const doc[] = "[,null,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(3u, root.size()); - } - { - char const doc[] = "[,,null]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL(3u, root.size()); - } - { - char const doc[] = "[[],,,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(4u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::arrayValue, root[0u]); - } - { - char const doc[] = "[,[],,]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(4u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::arrayValue, root[1u]); - } - { - char const doc[] = "[,,,[]]"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT(errs == ""); - JSONTEST_ASSERT_EQUAL(4u, root.size()); - JSONTEST_ASSERT_EQUAL(Json::arrayValue, root[3u]); - } - delete reader; -} - -struct CharReaderAllowSingleQuotesTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderAllowSingleQuotesTest, issue182) { - Json::CharReaderBuilder b; - b.settings_["allowSingleQuotes"] = true; - Json::Value root; - JSONCPP_STRING errs; - Json::CharReader* reader(b.newCharReader()); - { - char const doc[] = "{'a':true,\"b\":true}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_EQUAL(true, root.get("a", false)); - JSONTEST_ASSERT_EQUAL(true, root.get("b", false)); - } - { - char const doc[] = "{'a': 'x', \"b\":'y'}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString()); - JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString()); - } - delete reader; -} - -struct CharReaderAllowZeroesTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderAllowZeroesTest, issue176) { - Json::CharReaderBuilder b; - b.settings_["allowSingleQuotes"] = true; - Json::Value root; - JSONCPP_STRING errs; - Json::CharReader* reader(b.newCharReader()); - { - char const doc[] = "{'a':true,\"b\":true}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_EQUAL(true, root.get("a", false)); - JSONTEST_ASSERT_EQUAL(true, root.get("b", false)); - } - { - char const doc[] = "{'a': 'x', \"b\":'y'}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString()); - JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString()); - } - delete reader; -} - -struct CharReaderAllowSpecialFloatsTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(CharReaderAllowSpecialFloatsTest, issue209) { - Json::CharReaderBuilder b; - b.settings_["allowSpecialFloats"] = true; - Json::Value root; - JSONCPP_STRING errs; - Json::CharReader* reader(b.newCharReader()); - { - char const doc[] = "{\"a\":NaN,\"b\":Infinity,\"c\":-Infinity}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(3u, root.size()); - double n = root["a"].asDouble(); - JSONTEST_ASSERT(n != n); - JSONTEST_ASSERT_EQUAL(std::numeric_limits::infinity(), root.get("b", 0.0)); - JSONTEST_ASSERT_EQUAL(-std::numeric_limits::infinity(), root.get("c", 0.0)); - } - - struct TestData { - int line; - bool ok; - JSONCPP_STRING in; - }; - const TestData test_data[] = { - {__LINE__, 1, "{\"a\":9}"}, - {__LINE__, 0, "{\"a\":0Infinity}"}, - {__LINE__, 0, "{\"a\":1Infinity}"}, - {__LINE__, 0, "{\"a\":9Infinity}"}, - {__LINE__, 0, "{\"a\":0nfinity}"}, - {__LINE__, 0, "{\"a\":1nfinity}"}, - {__LINE__, 0, "{\"a\":9nfinity}"}, - {__LINE__, 0, "{\"a\":nfinity}"}, - {__LINE__, 0, "{\"a\":.nfinity}"}, - {__LINE__, 0, "{\"a\":9nfinity}"}, - {__LINE__, 0, "{\"a\":-nfinity}"}, - {__LINE__, 1, "{\"a\":Infinity}"}, - {__LINE__, 0, "{\"a\":.Infinity}"}, - {__LINE__, 0, "{\"a\":_Infinity}"}, - {__LINE__, 0, "{\"a\":_nfinity}"}, - {__LINE__, 1, "{\"a\":-Infinity}"} - }; - for (size_t tdi = 0; tdi < sizeof(test_data) / sizeof(*test_data); ++tdi) { - const TestData& td = test_data[tdi]; - bool ok = reader->parse(&*td.in.begin(), - &*td.in.begin() + td.in.size(), - &root, &errs); - JSONTEST_ASSERT(td.ok == ok) - << "line:" << td.line << "\n" - << " expected: {" - << "ok:" << td.ok - << ", in:\'" << td.in << "\'" - << "}\n" - << " actual: {" - << "ok:" << ok - << "}\n"; - } - - { - char const doc[] = "{\"posInf\": Infinity, \"NegInf\": -Infinity}"; - bool ok = reader->parse( - doc, doc + std::strlen(doc), - &root, &errs); - JSONTEST_ASSERT(ok); - JSONTEST_ASSERT_STRING_EQUAL("", errs); - JSONTEST_ASSERT_EQUAL(2u, root.size()); - JSONTEST_ASSERT_EQUAL(std::numeric_limits::infinity(), root["posInf"].asDouble()); - JSONTEST_ASSERT_EQUAL(-std::numeric_limits::infinity(), root["NegInf"].asDouble()); - } - delete reader; -} - -struct BuilderTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(BuilderTest, settings) { - { - Json::Value errs; - Json::CharReaderBuilder rb; - JSONTEST_ASSERT_EQUAL(false, rb.settings_.isMember("foo")); - JSONTEST_ASSERT_EQUAL(true, rb.validate(&errs)); - rb["foo"] = "bar"; - JSONTEST_ASSERT_EQUAL(true, rb.settings_.isMember("foo")); - JSONTEST_ASSERT_EQUAL(false, rb.validate(&errs)); - } - { - Json::Value errs; - Json::StreamWriterBuilder wb; - JSONTEST_ASSERT_EQUAL(false, wb.settings_.isMember("foo")); - JSONTEST_ASSERT_EQUAL(true, wb.validate(&errs)); - wb["foo"] = "bar"; - JSONTEST_ASSERT_EQUAL(true, wb.settings_.isMember("foo")); - JSONTEST_ASSERT_EQUAL(false, wb.validate(&errs)); - } -} - -struct IteratorTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(IteratorTest, distance) { - Json::Value json; - json["k1"] = "a"; - json["k2"] = "b"; - int dist = 0; - JSONCPP_STRING str; - for (Json::ValueIterator it = json.begin(); it != json.end(); ++it) { - dist = it - json.begin(); - str = it->asString().c_str(); - } - JSONTEST_ASSERT_EQUAL(1, dist); - JSONTEST_ASSERT_STRING_EQUAL("b", str); -} - -JSONTEST_FIXTURE(IteratorTest, names) { - Json::Value json; - json["k1"] = "a"; - json["k2"] = "b"; - Json::ValueIterator it = json.begin(); - JSONTEST_ASSERT(it != json.end()); - JSONTEST_ASSERT_EQUAL(Json::Value("k1"), it.key()); - JSONTEST_ASSERT_STRING_EQUAL("k1", it.name()); - JSONTEST_ASSERT_EQUAL(-1, it.index()); - ++it; - JSONTEST_ASSERT(it != json.end()); - JSONTEST_ASSERT_EQUAL(Json::Value("k2"), it.key()); - JSONTEST_ASSERT_STRING_EQUAL("k2", it.name()); - JSONTEST_ASSERT_EQUAL(-1, it.index()); - ++it; - JSONTEST_ASSERT(it == json.end()); -} - -JSONTEST_FIXTURE(IteratorTest, indexes) { - Json::Value json; - json[0] = "a"; - json[1] = "b"; - Json::ValueIterator it = json.begin(); - JSONTEST_ASSERT(it != json.end()); - JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(0)), it.key()); - JSONTEST_ASSERT_STRING_EQUAL("", it.name()); - JSONTEST_ASSERT_EQUAL(0, it.index()); - ++it; - JSONTEST_ASSERT(it != json.end()); - JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(1)), it.key()); - JSONTEST_ASSERT_STRING_EQUAL("", it.name()); - JSONTEST_ASSERT_EQUAL(1, it.index()); - ++it; - JSONTEST_ASSERT(it == json.end()); -} - -JSONTEST_FIXTURE(IteratorTest, const) { - Json::Value const v; - JSONTEST_ASSERT_THROWS( - Json::Value::iterator it(v.begin()) // Compile, but throw. - ); - - Json::Value value; - - for(int i = 9; i < 12; ++i) - { - JSONCPP_OSTRINGSTREAM out; - out << std::setw(2) << i; - JSONCPP_STRING str = out.str(); - value[str] = str; - } - - JSONCPP_OSTRINGSTREAM out; - //in old code, this will get a compile error - Json::Value::const_iterator iter = value.begin(); - for(; iter != value.end(); ++iter) - { - out << *iter << ','; - } - JSONCPP_STRING expected = "\" 9\",\"10\",\"11\","; - JSONTEST_ASSERT_STRING_EQUAL(expected, out.str()); -} - -struct RValueTest : JsonTest::TestCase {}; - -JSONTEST_FIXTURE(RValueTest, moveConstruction) { -#if JSON_HAS_RVALUE_REFERENCES - Json::Value json; - json["key"] = "value"; - Json::Value moved = std::move(json); - JSONTEST_ASSERT(moved != json); // Possibly not nullValue; definitely not equal. - JSONTEST_ASSERT_EQUAL(Json::objectValue, moved.type()); - JSONTEST_ASSERT_EQUAL(Json::stringValue, moved["key"].type()); -#endif -} - -int main(int argc, const char* argv[]) { - JsonTest::Runner runner; - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, checkNormalizeFloatingPointStr); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, memberCount); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, objects); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, arrays); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, arrayIssue252); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, null); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, strings); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, bools); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, integers); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, nonIntegers); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareNull); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareInt); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareUInt); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareDouble); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareString); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareBoolean); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareArray); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareObject); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, compareType); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, offsetAccessors); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, typeChecksThrowExceptions); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, StaticString); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, CommentBefore); - //JSONTEST_REGISTER_FIXTURE(runner, ValueTest, nulls); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, zeroes); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, zeroesInKeys); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, specialFloats); - JSONTEST_REGISTER_FIXTURE(runner, ValueTest, precision); - - JSONTEST_REGISTER_FIXTURE(runner, WriterTest, dropNullPlaceholders); - JSONTEST_REGISTER_FIXTURE(runner, StreamWriterTest, dropNullPlaceholders); - JSONTEST_REGISTER_FIXTURE(runner, StreamWriterTest, writeZeroes); - - JSONTEST_REGISTER_FIXTURE(runner, ReaderTest, parseWithNoErrors); - JSONTEST_REGISTER_FIXTURE( - runner, ReaderTest, parseWithNoErrorsTestingOffsets); - JSONTEST_REGISTER_FIXTURE(runner, ReaderTest, parseWithOneError); - JSONTEST_REGISTER_FIXTURE(runner, ReaderTest, parseChineseWithOneError); - JSONTEST_REGISTER_FIXTURE(runner, ReaderTest, parseWithDetailError); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderTest, parseWithNoErrors); - JSONTEST_REGISTER_FIXTURE( - runner, CharReaderTest, parseWithNoErrorsTestingOffsets); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderTest, parseWithOneError); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderTest, parseChineseWithOneError); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderTest, parseWithDetailError); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderTest, parseWithStackLimit); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderStrictModeTest, dupKeys); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderFailIfExtraTest, issue164); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderFailIfExtraTest, issue107); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderFailIfExtraTest, commentAfterObject); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderFailIfExtraTest, commentAfterArray); - JSONTEST_REGISTER_FIXTURE(runner, CharReaderFailIfExtraTest, commentAfterBool); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderAllowDropNullTest, issue178); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderAllowSingleQuotesTest, issue182); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderAllowZeroesTest, issue176); - - JSONTEST_REGISTER_FIXTURE(runner, CharReaderAllowSpecialFloatsTest, issue209); - - JSONTEST_REGISTER_FIXTURE(runner, BuilderTest, settings); - - JSONTEST_REGISTER_FIXTURE(runner, IteratorTest, distance); - JSONTEST_REGISTER_FIXTURE(runner, IteratorTest, names); - JSONTEST_REGISTER_FIXTURE(runner, IteratorTest, indexes); - JSONTEST_REGISTER_FIXTURE(runner, IteratorTest, const); - - JSONTEST_REGISTER_FIXTURE(runner, RValueTest, moveConstruction); - - return runner.runCommandLine(argc, argv); -} diff --git a/thirdparty/jsoncpp/src/test_lib_json/sconscript b/thirdparty/jsoncpp/src/test_lib_json/sconscript deleted file mode 100644 index 915fd01c0a..0000000000 --- a/thirdparty/jsoncpp/src/test_lib_json/sconscript +++ /dev/null @@ -1,10 +0,0 @@ -Import( 'env_testing buildUnitTests' ) - -buildUnitTests( env_testing, Split( """ - main.cpp - jsontest.cpp - """ ), - 'test_lib_json' ) - -# For 'check' to work, 'libs' must be built first. -env_testing.Depends('test_lib_json', '#libs') diff --git a/thirdparty/jsoncpp/version b/thirdparty/jsoncpp/version deleted file mode 100644 index 27f9cd322b..0000000000 --- a/thirdparty/jsoncpp/version +++ /dev/null @@ -1 +0,0 @@ -1.8.0 diff --git a/thirdparty/jsoncpp/version.in b/thirdparty/jsoncpp/version.in deleted file mode 100644 index bfc03f7dd7..0000000000 --- a/thirdparty/jsoncpp/version.in +++ /dev/null @@ -1 +0,0 @@ -@JSONCPP_VERSION@ diff --git a/thirdparty/rapidjson-1.1.0/.gitattributes b/thirdparty/rapidjson-1.1.0/.gitattributes new file mode 100644 index 0000000000..6f598bb7f9 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/.gitattributes @@ -0,0 +1,22 @@ +# Set the default behavior, in case people don't have core.autocrlf set. +* text=auto + +# Explicitly declare text files you want to always be normalized and converted +# to native line endings on checkout. +*.cpp text +*.h text +*.txt text +*.md text +*.cmake text +*.svg text +*.dot text +*.yml text +*.in text +*.sh text +*.autopkg text +Dockerfile text + +# Denote all files that are truly binary and should not be modified. +*.png binary +*.jpg binary +*.json binary \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/.gitignore b/thirdparty/rapidjson-1.1.0/.gitignore new file mode 100644 index 0000000000..e7e8fba9bb --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/.gitignore @@ -0,0 +1,25 @@ +/bin/* +!/bin/data +!/bin/encodings +!/bin/jsonchecker +!/bin/types +/build +/doc/html +/doc/doxygen_*.db +*.a + +# Temporary files created during CMake build +CMakeCache.txt +CMakeFiles +cmake_install.cmake +CTestTestfile.cmake +Makefile +RapidJSON*.cmake +RapidJSON.pc +Testing +/googletest +install_manifest.txt +Doxyfile +Doxyfile.zh-cn +DartConfiguration.tcl +*.nupkg diff --git a/thirdparty/rapidjson-1.1.0/.gitmodules b/thirdparty/rapidjson-1.1.0/.gitmodules new file mode 100644 index 0000000000..5e41f7c975 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/.gitmodules @@ -0,0 +1,3 @@ +[submodule "thirdparty/gtest"] + path = thirdparty/gtest + url = https://github.com/google/googletest.git diff --git a/thirdparty/rapidjson-1.1.0/.travis.yml b/thirdparty/rapidjson-1.1.0/.travis.yml new file mode 100644 index 0000000000..f9319f2edb --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/.travis.yml @@ -0,0 +1,98 @@ +sudo: required +dist: precise + +language: cpp +cache: + - ccache + +env: + global: + - USE_CCACHE=1 + - CCACHE_SLOPPINESS=pch_defines,time_macros + - CCACHE_COMPRESS=1 + - CCACHE_MAXSIZE=100M + - ARCH_FLAGS_x86='-m32' # #266: don't use SSE on 32-bit + - ARCH_FLAGS_x86_64='-msse4.2' # use SSE4.2 on 64-bit + - GITHUB_REPO='miloyip/rapidjson' + - secure: "HrsaCb+N66EG1HR+LWH1u51SjaJyRwJEDzqJGYMB7LJ/bfqb9mWKF1fLvZGk46W5t7TVaXRDD5KHFx9DPWvKn4gRUVkwTHEy262ah5ORh8M6n/6VVVajeV/AYt2C0sswdkDBDO4Xq+xy5gdw3G8s1A4Inbm73pUh+6vx+7ltBbk=" + +before_install: + - sudo apt-add-repository -y ppa:ubuntu-toolchain-r/test + - sudo apt-get update -qq + - sudo apt-get install -y cmake valgrind g++-multilib libc6-dbg:i386 + +matrix: + include: + # gcc + - env: CONF=release ARCH=x86 CXX11=ON + compiler: gcc + - env: CONF=release ARCH=x86_64 CXX11=ON + compiler: gcc + - env: CONF=debug ARCH=x86 CXX11=OFF + compiler: gcc + - env: CONF=debug ARCH=x86_64 CXX11=OFF + compiler: gcc + # clang + - env: CONF=debug ARCH=x86 CXX11=ON CCACHE_CPP2=yes + compiler: clang + - env: CONF=debug ARCH=x86_64 CXX11=ON CCACHE_CPP2=yes + compiler: clang + - env: CONF=debug ARCH=x86 CXX11=OFF CCACHE_CPP2=yes + compiler: clang + - env: CONF=debug ARCH=x86_64 CXX11=OFF CCACHE_CPP2=yes + compiler: clang + - env: CONF=release ARCH=x86 CXX11=ON CCACHE_CPP2=yes + compiler: clang + - env: CONF=release ARCH=x86_64 CXX11=ON CCACHE_CPP2=yes + compiler: clang + # coverage report + - env: CONF=debug ARCH=x86 CXX11=ON GCOV_FLAGS='--coverage' + compiler: gcc + cache: + - ccache + - pip + after_success: + - pip install --user cpp-coveralls + - coveralls -r .. --gcov-options '\-lp' -e thirdparty -e example -e test -e build/CMakeFiles -e include/rapidjson/msinttypes -e include/rapidjson/internal/meta.h -e include/rapidjson/error/en.h + - env: CONF=debug ARCH=x86_64 GCOV_FLAGS='--coverage' + compiler: gcc + cache: + - ccache + - pip + after_success: + - pip install --user cpp-coveralls + - coveralls -r .. --gcov-options '\-lp' -e thirdparty -e example -e test -e build/CMakeFiles -e include/rapidjson/msinttypes -e include/rapidjson/internal/meta.h -e include/rapidjson/error/en.h + - script: # Documentation task + - cd build + - cmake .. -DRAPIDJSON_HAS_STDSTRING=ON -DCMAKE_VERBOSE_MAKEFILE=ON + - make travis_doc + cache: false + addons: + apt: + packages: + - doxygen + +before_script: + - ccache -s + # hack to avoid Valgrind bug (https://bugs.kde.org/show_bug.cgi?id=326469), + # exposed by merging PR#163 (using -march=native) + # TODO: Since this bug is already fixed. Remove this when valgrind can be upgraded. + - sed -i "s/-march=native//" CMakeLists.txt + - mkdir build + +script: + - if [ "$CXX" = "clang++" ]; then export CXXFLAGS="-stdlib=libc++ ${CXXFLAGS}"; fi + - > + eval "ARCH_FLAGS=\${ARCH_FLAGS_${ARCH}}" ; + (cd build && cmake + -DRAPIDJSON_HAS_STDSTRING=ON + -DRAPIDJSON_BUILD_CXX11=$CXX11 + -DCMAKE_VERBOSE_MAKEFILE=ON + -DCMAKE_BUILD_TYPE=$CONF + -DCMAKE_CXX_FLAGS="$ARCH_FLAGS $GCOV_FLAGS" + -DCMAKE_EXE_LINKER_FLAGS=$GCOV_FLAGS + ..) + - cd build + - make tests -j 2 + - make examples -j 2 + - ctest -j 2 -V `[ "$CONF" = "release" ] || echo "-E perftest"` diff --git a/thirdparty/rapidjson-1.1.0/CHANGELOG.md b/thirdparty/rapidjson-1.1.0/CHANGELOG.md new file mode 100644 index 0000000000..0205e7b89f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/CHANGELOG.md @@ -0,0 +1,158 @@ +# Change Log +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] + +## 1.1.0 - 2016-08-25 + +### Added +* Add GenericDocument ctor overload to specify JSON type (#369) +* Add FAQ (#372, #373, #374, #376) +* Add forward declaration header `fwd.h` +* Add @PlatformIO Library Registry manifest file (#400) +* Implement assignment operator for BigInteger (#404) +* Add comments support (#443) +* Adding coapp definition (#460) +* documenttest.cpp: EXPECT_THROW when checking empty allocator (470) +* GenericDocument: add implicit conversion to ParseResult (#480) +* Use with C++ linkage on Windows ARM (#485) +* Detect little endian for Microsoft ARM targets +* Check Nan/Inf when writing a double (#510) +* Add JSON Schema Implementation (#522) +* Add iostream wrapper (#530) +* Add Jsonx example for converting JSON into JSONx (a XML format) (#531) +* Add optional unresolvedTokenIndex parameter to Pointer::Get() (#532) +* Add encoding validation option for Writer/PrettyWriter (#534) +* Add Writer::SetMaxDecimalPlaces() (#536) +* Support {0, } and {0, m} in Regex (#539) +* Add Value::Get/SetFloat(), Value::IsLossLessFloat/Double() (#540) +* Add stream position check to reader unit tests (#541) +* Add Templated accessors and range-based for (#542) +* Add (Pretty)Writer::RawValue() (#543) +* Add Document::Parse(std::string), Document::Parse(const char*, size_t length) and related APIs. (#553) +* Add move constructor for GenericSchemaDocument (#554) +* Add VS2010 and VS2015 to AppVeyor CI (#555) +* Add parse-by-parts example (#556, #562) +* Support parse number as string (#564, #589) +* Add kFormatSingleLineArray for PrettyWriter (#577) +* Added optional support for trailing commas (#584) +* Added filterkey and filterkeydom examples (#615) +* Added npm docs (#639) +* Allow options for writing and parsing NaN/Infinity (#641) +* Add std::string overload to PrettyWriter::Key() when RAPIDJSON_HAS_STDSTRING is defined (#698) + +### Fixed +* Fix gcc/clang/vc warnings (#350, #394, #397, #444, #447, #473, #515, #582, #589, #595, #667) +* Fix documentation (#482, #511, #550, #557, #614, #635, #660) +* Fix emscripten alignment issue (#535) +* Fix missing allocator to uses of AddMember in document (#365) +* CMake will no longer complain that the minimum CMake version is not specified (#501) +* Make it usable with old VC8 (VS2005) (#383) +* Prohibit C++11 move from Document to Value (#391) +* Try to fix incorrect 64-bit alignment (#419) +* Check return of fwrite to avoid warn_unused_result build failures (#421) +* Fix UB in GenericDocument::ParseStream (#426) +* Keep Document value unchanged on parse error (#439) +* Add missing return statement (#450) +* Fix Document::Parse(const Ch*) for transcoding (#478) +* encodings.h: fix typo in preprocessor condition (#495) +* Custom Microsoft headers are necessary only for Visual Studio 2012 and lower (#559) +* Fix memory leak for invalid regex (26e69ffde95ba4773ab06db6457b78f308716f4b) +* Fix a bug in schema minimum/maximum keywords for 64-bit integer (e7149d665941068ccf8c565e77495521331cf390) +* Fix a crash bug in regex (#605) +* Fix schema "required" keyword cannot handle duplicated keys (#609) +* Fix cmake CMP0054 warning (#612) +* Added missing include guards in istreamwrapper.h and ostreamwrapper.h (#634) +* Fix undefined behaviour (#646) +* Fix buffer overrun using PutN (#673) +* Fix rapidjson::value::Get() may returns wrong data (#681) +* Add Flush() for all value types (#689) +* Handle malloc() fail in PoolAllocator (#691) +* Fix builds on x32 platform. #703 + +### Changed +* Clarify problematic JSON license (#392) +* Move Travis to container based infrastructure (#504, #558) +* Make whitespace array more compact (#513) +* Optimize Writer::WriteString() with SIMD (#544) +* x86-64 48-bit pointer optimization for GenericValue (#546) +* Define RAPIDJSON_HAS_CXX11_RVALUE_REFS directly in clang (#617) +* Make GenericSchemaDocument constructor explicit (#674) +* Optimize FindMember when use std::string (#690) + +## [1.0.2] - 2015-05-14 + +### Added +* Add Value::XXXMember(...) overloads for std::string (#335) + +### Fixed +* Include rapidjson.h for all internal/error headers. +* Parsing some numbers incorrectly in full-precision mode (`kFullPrecisionParseFlag`) (#342) +* Fix some numbers parsed incorrectly (#336) +* Fix alignment of 64bit platforms (#328) +* Fix MemoryPoolAllocator::Clear() to clear user-buffer (0691502573f1afd3341073dd24b12c3db20fbde4) + +### Changed +* CMakeLists for include as a thirdparty in projects (#334, #337) +* Change Document::ParseStream() to use stack allocator for Reader (ffbe38614732af8e0b3abdc8b50071f386a4a685) + +## [1.0.1] - 2015-04-25 + +### Added +* Changelog following [Keep a CHANGELOG](https://github.com/olivierlacan/keep-a-changelog) suggestions. + +### Fixed +* Parsing of some numbers (e.g. "1e-00011111111111") causing assertion (#314). +* Visual C++ 32-bit compilation error in `diyfp.h` (#317). + +## [1.0.0] - 2015-04-22 + +### Added +* 100% [Coverall](https://coveralls.io/r/miloyip/rapidjson?branch=master) coverage. +* Version macros (#311) + +### Fixed +* A bug in trimming long number sequence (4824f12efbf01af72b8cb6fc96fae7b097b73015). +* Double quote in unicode escape (#288). +* Negative zero roundtrip (double only) (#289). +* Standardize behavior of `memcpy()` and `malloc()` (0c5c1538dcfc7f160e5a4aa208ddf092c787be5a, #305, 0e8bbe5e3ef375e7f052f556878be0bd79e9062d). + +### Removed +* Remove an invalid `Document::ParseInsitu()` API (e7f1c6dd08b522cfcf9aed58a333bd9a0c0ccbeb). + +## 1.0-beta - 2015-04-8 + +### Added +* RFC 7159 (#101) +* Optional Iterative Parser (#76) +* Deep-copy values (#20) +* Error code and message (#27) +* ASCII Encoding (#70) +* `kParseStopWhenDoneFlag` (#83) +* `kParseFullPrecisionFlag` (881c91d696f06b7f302af6d04ec14dd08db66ceb) +* Add `Key()` to handler concept (#134) +* C++11 compatibility and support (#128) +* Optimized number-to-string and vice versa conversions (#137, #80) +* Short-String Optimization (#131) +* Local stream optimization by traits (#32) +* Travis & Appveyor Continuous Integration, with Valgrind verification (#24, #242) +* Redo all documentation (English, Simplified Chinese) + +### Changed +* Copyright ownership transfered to THL A29 Limited (a Tencent company). +* Migrating from Premake to CMAKE (#192) +* Resolve all warning reports + +### Removed +* Remove other JSON libraries for performance comparison (#180) + +## 0.11 - 2012-11-16 + +## 0.1 - 2011-11-18 + +[Unreleased]: https://github.com/miloyip/rapidjson/compare/v1.1.0...HEAD +[1.1.0]: https://github.com/miloyip/rapidjson/compare/v1.0.2...v1.1.0 +[1.0.2]: https://github.com/miloyip/rapidjson/compare/v1.0.1...v1.0.2 +[1.0.1]: https://github.com/miloyip/rapidjson/compare/v1.0.0...v1.0.1 +[1.0.0]: https://github.com/miloyip/rapidjson/compare/v1.0-beta...v1.0.0 diff --git a/thirdparty/rapidjson-1.1.0/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/CMakeLists.txt new file mode 100644 index 0000000000..ceda71b1b6 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/CMakeLists.txt @@ -0,0 +1,173 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.8) +if(POLICY CMP0025) + # detect Apple's Clang + cmake_policy(SET CMP0025 NEW) +endif() +if(POLICY CMP0054) + cmake_policy(SET CMP0054 NEW) +endif() + +SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules) + +PROJECT(RapidJSON CXX) + +set(LIB_MAJOR_VERSION "1") +set(LIB_MINOR_VERSION "1") +set(LIB_PATCH_VERSION "0") +set(LIB_VERSION_STRING "${LIB_MAJOR_VERSION}.${LIB_MINOR_VERSION}.${LIB_PATCH_VERSION}") + +# compile in release with debug info mode by default +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." FORCE) +endif() + +# Build all binaries in a separate directory +SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) + +option(RAPIDJSON_BUILD_DOC "Build rapidjson documentation." ON) +option(RAPIDJSON_BUILD_EXAMPLES "Build rapidjson examples." ON) +option(RAPIDJSON_BUILD_TESTS "Build rapidjson perftests and unittests." ON) +option(RAPIDJSON_BUILD_THIRDPARTY_GTEST + "Use gtest installation in `thirdparty/gtest` by default if available" OFF) + +option(RAPIDJSON_BUILD_CXX11 "Build rapidjson with C++11 (gcc/clang)" ON) + +option(RAPIDJSON_BUILD_ASAN "Build rapidjson with address sanitizer (gcc/clang)" OFF) +option(RAPIDJSON_BUILD_UBSAN "Build rapidjson with undefined behavior sanitizer (gcc/clang)" OFF) + +option(RAPIDJSON_HAS_STDSTRING "" OFF) +if(RAPIDJSON_HAS_STDSTRING) + add_definitions(-DRAPIDJSON_HAS_STDSTRING) +endif() + +find_program(CCACHE_FOUND ccache) +if(CCACHE_FOUND) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) + if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments -fcolor-diagnostics") + endif() +endif(CCACHE_FOUND) + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native -Wall -Wextra -Werror") + if (RAPIDJSON_BUILD_CXX11) + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7.0") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + endif() + endif() + if (RAPIDJSON_BUILD_ASAN) + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.8.0") + message(FATAL_ERROR "GCC < 4.8 doesn't support the address sanitizer") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") + endif() + endif() + if (RAPIDJSON_BUILD_UBSAN) + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.9.0") + message(FATAL_ERROR "GCC < 4.9 doesn't support the undefined behavior sanitizer") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined") + endif() + endif() +elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native -Wall -Wextra -Werror -Wno-missing-field-initializers") + if (RAPIDJSON_BUILD_CXX11) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + endif() + if (RAPIDJSON_BUILD_ASAN) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address") + endif() + if (RAPIDJSON_BUILD_UBSAN) + if (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined-trap -fsanitize-undefined-trap-on-error") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined") + endif() + endif() +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + add_definitions(-D_CRT_SECURE_NO_WARNINGS=1) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc") +endif() + +#add extra search paths for libraries and includes +SET(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "The directory the headers are installed in") +SET(LIB_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/lib" CACHE STRING "Directory where lib will install") +SET(DOC_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/share/doc/${PROJECT_NAME}" CACHE PATH "Path to the documentation") + +IF(UNIX OR CYGWIN) + SET(_CMAKE_INSTALL_DIR "${LIB_INSTALL_DIR}/cmake/${PROJECT_NAME}") +ELSEIF(WIN32) + SET(_CMAKE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/cmake") +ENDIF() +SET(CMAKE_INSTALL_DIR "${_CMAKE_INSTALL_DIR}" CACHE PATH "The directory cmake fiels are installed in") + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) + +if(RAPIDJSON_BUILD_DOC) + add_subdirectory(doc) +endif() + +add_custom_target(travis_doc) +add_custom_command(TARGET travis_doc + COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/travis-doxygen.sh) + +if(RAPIDJSON_BUILD_EXAMPLES) + add_subdirectory(example) +endif() + +if(RAPIDJSON_BUILD_TESTS) + if(MSVC11) + # required for VS2012 due to missing support for variadic templates + add_definitions(-D_VARIADIC_MAX=10) + endif(MSVC11) + add_subdirectory(test) + include(CTest) +endif() + +# pkg-config +IF (UNIX OR CYGWIN) + CONFIGURE_FILE (${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}.pc.in + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc + @ONLY) + INSTALL (FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc + DESTINATION "${LIB_INSTALL_DIR}/pkgconfig" + COMPONENT pkgconfig) +ENDIF() + +install(FILES readme.md + DESTINATION "${DOC_INSTALL_DIR}" + COMPONENT doc) + +install(DIRECTORY include/rapidjson + DESTINATION "${INCLUDE_INSTALL_DIR}" + COMPONENT dev) + +install(DIRECTORY example/ + DESTINATION "${DOC_INSTALL_DIR}/examples" + COMPONENT examples + # Following patterns are for excluding the intermediate/object files + # from an install of in-source CMake build. + PATTERN "CMakeFiles" EXCLUDE + PATTERN "Makefile" EXCLUDE + PATTERN "cmake_install.cmake" EXCLUDE) + +# Provide config and version files to be used by other applications +# =============================== + +export(PACKAGE ${PROJECT_NAME}) + +# cmake-modules +CONFIGURE_FILE(${PROJECT_NAME}Config.cmake.in + ${PROJECT_NAME}Config.cmake + @ONLY) +CONFIGURE_FILE(${PROJECT_NAME}ConfigVersion.cmake.in + ${PROJECT_NAME}ConfigVersion.cmake + @ONLY) +INSTALL(FILES + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + DESTINATION "${CMAKE_INSTALL_DIR}" + COMPONENT dev) diff --git a/thirdparty/rapidjson-1.1.0/CMakeModules/FindGTestSrc.cmake b/thirdparty/rapidjson-1.1.0/CMakeModules/FindGTestSrc.cmake new file mode 100644 index 0000000000..f3cb8c9908 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/CMakeModules/FindGTestSrc.cmake @@ -0,0 +1,30 @@ + +SET(GTEST_SEARCH_PATH + "${GTEST_SOURCE_DIR}" + "${CMAKE_CURRENT_LIST_DIR}/../thirdparty/gtest/googletest") + +IF(UNIX) + IF(RAPIDJSON_BUILD_THIRDPARTY_GTEST) + LIST(APPEND GTEST_SEARCH_PATH "/usr/src/gtest") + ELSE() + LIST(INSERT GTEST_SEARCH_PATH 1 "/usr/src/gtest") + ENDIF() +ENDIF() + +FIND_PATH(GTEST_SOURCE_DIR + NAMES CMakeLists.txt src/gtest_main.cc + PATHS ${GTEST_SEARCH_PATH}) + + +# Debian installs gtest include directory in /usr/include, thus need to look +# for include directory separately from source directory. +FIND_PATH(GTEST_INCLUDE_DIR + NAMES gtest/gtest.h + PATH_SUFFIXES include + HINTS ${GTEST_SOURCE_DIR} + PATHS ${GTEST_SEARCH_PATH}) + +INCLUDE(FindPackageHandleStandardArgs) +find_package_handle_standard_args(GTestSrc DEFAULT_MSG + GTEST_SOURCE_DIR + GTEST_INCLUDE_DIR) diff --git a/thirdparty/rapidjson-1.1.0/RapidJSON.pc.in b/thirdparty/rapidjson-1.1.0/RapidJSON.pc.in new file mode 100644 index 0000000000..7467f9779b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/RapidJSON.pc.in @@ -0,0 +1,7 @@ +includedir=@INCLUDE_INSTALL_DIR@ + +Name: @PROJECT_NAME@ +Description: A fast JSON parser/generator for C++ with both SAX/DOM style API +Version: @LIB_VERSION_STRING@ +URL: https://github.com/miloyip/rapidjson +Cflags: -I${includedir} diff --git a/thirdparty/rapidjson-1.1.0/RapidJSONConfig.cmake.in b/thirdparty/rapidjson-1.1.0/RapidJSONConfig.cmake.in new file mode 100644 index 0000000000..9fa12186ab --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/RapidJSONConfig.cmake.in @@ -0,0 +1,3 @@ +get_filename_component(RAPIDJSON_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +set(RAPIDJSON_INCLUDE_DIRS "@INCLUDE_INSTALL_DIR@") +message(STATUS "RapidJSON found. Headers: ${RAPIDJSON_INCLUDE_DIRS}") diff --git a/thirdparty/rapidjson-1.1.0/RapidJSONConfigVersion.cmake.in b/thirdparty/rapidjson-1.1.0/RapidJSONConfigVersion.cmake.in new file mode 100644 index 0000000000..25741fc097 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/RapidJSONConfigVersion.cmake.in @@ -0,0 +1,10 @@ +SET(PACKAGE_VERSION "@LIB_VERSION_STRING@") + +IF (PACKAGE_FIND_VERSION VERSION_EQUAL PACKAGE_VERSION) + SET(PACKAGE_VERSION_EXACT "true") +ENDIF (PACKAGE_FIND_VERSION VERSION_EQUAL PACKAGE_VERSION) +IF (NOT PACKAGE_FIND_VERSION VERSION_GREATER PACKAGE_VERSION) + SET(PACKAGE_VERSION_COMPATIBLE "true") +ELSE (NOT PACKAGE_FIND_VERSION VERSION_GREATER PACKAGE_VERSION) + SET(PACKAGE_VERSION_UNSUITABLE "true") +ENDIF (NOT PACKAGE_FIND_VERSION VERSION_GREATER PACKAGE_VERSION) diff --git a/thirdparty/rapidjson-1.1.0/appveyor.yml b/thirdparty/rapidjson-1.1.0/appveyor.yml new file mode 100644 index 0000000000..dfedf9c297 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/appveyor.yml @@ -0,0 +1,41 @@ +os: Visual Studio 2015 CTP +version: 1.1.0.{build} + +configuration: +- Debug +- Release + +environment: + matrix: + # - VS_VERSION: 9 2008 + # VS_PLATFORM: win32 + # - VS_VERSION: 9 2008 + # VS_PLATFORM: x64 + - VS_VERSION: 10 2010 + VS_PLATFORM: win32 + - VS_VERSION: 10 2010 + VS_PLATFORM: x64 + - VS_VERSION: 11 2012 + VS_PLATFORM: win32 + - VS_VERSION: 11 2012 + VS_PLATFORM: x64 + - VS_VERSION: 12 2013 + VS_PLATFORM: win32 + - VS_VERSION: 12 2013 + VS_PLATFORM: x64 + - VS_VERSION: 14 2015 + VS_PLATFORM: win32 + - VS_VERSION: 14 2015 + VS_PLATFORM: x64 + +before_build: +- git submodule update --init --recursive +- cmake -H. -BBuild/VS -G "Visual Studio %VS_VERSION%" -DCMAKE_GENERATOR_PLATFORM=%VS_PLATFORM% -DCMAKE_VERBOSE_MAKEFILE=ON -DBUILD_SHARED_LIBS=true -Wno-dev + +build: + project: Build\VS\RapidJSON.sln + parallel: true + verbosity: minimal + +test_script: +- cd Build\VS && if %CONFIGURATION%==Debug (ctest --verbose -E perftest --build-config %CONFIGURATION%) else (ctest --verbose --build-config %CONFIGURATION%) diff --git a/thirdparty/rapidjson-1.1.0/doc/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/doc/CMakeLists.txt new file mode 100644 index 0000000000..c1f165a37a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/CMakeLists.txt @@ -0,0 +1,25 @@ +find_package(Doxygen) + +IF(NOT DOXYGEN_FOUND) + MESSAGE(STATUS "No Doxygen found. Documentation won't be built") +ELSE() + file(GLOB SOURCES ${CMAKE_CURRENT_LIST_DIR}/../include/*) + file(GLOB MARKDOWN_DOC ${CMAKE_CURRENT_LIST_DIR}/../doc/*.md) + list(APPEND MARKDOWN_DOC ${CMAKE_CURRENT_LIST_DIR}/../readme.md) + + CONFIGURE_FILE(Doxyfile.in Doxyfile @ONLY) + CONFIGURE_FILE(Doxyfile.zh-cn.in Doxyfile.zh-cn @ONLY) + + add_custom_command(OUTPUT html + COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile + COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile.zh-cn + COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/html + DEPENDS ${MARKDOWN_DOC} ${SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile* + WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../ + ) + + add_custom_target(doc ALL DEPENDS html) + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html + DESTINATION ${DOC_INSTALL_DIR} + COMPONENT doc) +ENDIF() diff --git a/thirdparty/jsoncpp/doc/web_doxyfile.in b/thirdparty/rapidjson-1.1.0/doc/Doxyfile.in similarity index 92% rename from thirdparty/jsoncpp/doc/web_doxyfile.in rename to thirdparty/rapidjson-1.1.0/doc/Doxyfile.in index 07d6819a74..ca14233960 100644 --- a/thirdparty/jsoncpp/doc/web_doxyfile.in +++ b/thirdparty/rapidjson-1.1.0/doc/Doxyfile.in @@ -1,4 +1,4 @@ -# Doxyfile 1.8.5 +# Doxyfile 1.8.7 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. @@ -32,19 +32,19 @@ DOXYFILE_ENCODING = UTF-8 # title of most generated pages and in a few other places. # The default value is: My Project. -PROJECT_NAME = "JsonCpp" +PROJECT_NAME = RapidJSON # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = %JSONCPP_VERSION% +PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. -PROJECT_BRIEF = +PROJECT_BRIEF = "A fast JSON parser/generator for C++ with both SAX/DOM style API" # With the PROJECT_LOGO tag one can specify an logo or icon that is included in # the documentation. The maximum height of the logo should not exceed 55 pixels @@ -58,7 +58,7 @@ PROJECT_LOGO = # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. -OUTPUT_DIRECTORY = %DOC_TOPDIR% +OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and @@ -70,15 +70,25 @@ OUTPUT_DIRECTORY = %DOC_TOPDIR% CREATE_SUBDIRS = NO +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese- -# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en, -# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish, -# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, -# Turkish, Ukrainian and Vietnamese. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English @@ -152,7 +162,7 @@ FULL_PATH_NAMES = YES # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. -STRIP_FROM_PATH = %TOPDIR% +STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which @@ -161,7 +171,7 @@ STRIP_FROM_PATH = %TOPDIR% # specify the list of include paths that are normally passed to the compiler # using the -I flag. -STRIP_FROM_INC_PATH = %TOPDIR%/include +STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't @@ -177,7 +187,7 @@ SHORT_NAMES = NO # description.) # The default value is: NO. -JAVADOC_AUTOBRIEF = YES +JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If @@ -216,7 +226,7 @@ SEPARATE_MEMBER_PAGES = NO # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. -TAB_SIZE = 3 +TAB_SIZE = 4 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: @@ -228,10 +238,7 @@ TAB_SIZE = 3 # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. -ALIASES = "testCaseSetup=\link CppUT::TestCase::setUp() setUp()\endlink" \ - "testCaseRun=\link CppUT::TestCase::run() run()\endlink" \ - "testCaseTearDown=\link CppUT::TestCase::tearDown() tearDown()\endlink" \ - "json_ref=JSON (JavaScript Object Notation)" +ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" @@ -272,9 +279,12 @@ OPTIMIZE_OUTPUT_VHDL = NO # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. # # Note For files without extension you can use no_extension as a placeholder. # @@ -309,7 +319,7 @@ AUTOLINK_SUPPORT = YES # diagrams that involve STL classes more complete and accurate. # The default value is: NO. -BUILTIN_STL_SUPPORT = YES +BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. @@ -361,7 +371,7 @@ SUBGROUPING = YES # SEPARATE_MEMBER_PAGES. # The default value is: NO. -INLINE_GROUPED_CLASSES = NO +INLINE_GROUPED_CLASSES = YES # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in @@ -409,7 +419,7 @@ LOOKUP_CACHE_SIZE = 0 # normally produced when WARNINGS is set to YES. # The default value is: NO. -EXTRACT_ALL = YES +EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class will # be included in the documentation. @@ -427,7 +437,7 @@ EXTRACT_PACKAGE = NO # included in the documentation. # The default value is: NO. -EXTRACT_STATIC = YES +EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined # locally in source files will be included in the documentation. If set to NO @@ -435,7 +445,7 @@ EXTRACT_STATIC = YES # for Java sources. # The default value is: YES. -EXTRACT_LOCAL_CLASSES = NO +EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local methods, # which are defined in the implementation section but not in the interface are @@ -489,7 +499,7 @@ HIDE_IN_BODY_DOCS = NO # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. -INTERNAL_DOCS = YES +INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES upper-case letters are also @@ -513,6 +523,13 @@ HIDE_SCOPE_NAMES = NO SHOW_INCLUDE_FILES = YES +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. @@ -534,7 +551,8 @@ SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. +# name. If set to NO the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO @@ -566,7 +584,7 @@ SORT_GROUP_NAMES = NO # list. # The default value is: NO. -SORT_BY_SCOPE_NAME = YES +SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between @@ -590,13 +608,13 @@ GENERATE_TODOLIST = YES # documentation. # The default value is: YES. -GENERATE_TESTLIST = NO +GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. -GENERATE_BUGLIST = NO +GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) # the deprecated list. This list is created by putting \deprecated commands in @@ -609,7 +627,7 @@ GENERATE_DEPRECATEDLIST= YES # sections, marked by \if ... \endif and \cond # ... \endcond blocks. -ENABLED_SECTIONS = +ENABLED_SECTIONS = $(RAPIDJSON_SECTIONS) # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the @@ -641,7 +659,7 @@ SHOW_FILES = YES # Folder Tree View (if specified). # The default value is: YES. -SHOW_NAMESPACES = YES +SHOW_NAMESPACES = NO # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from @@ -734,7 +752,7 @@ WARN_FORMAT = "$file:$line: $text" # messages should be written. If left blank the output is written to standard # error (stderr). -WARN_LOGFILE = %WARNING_LOG_PATH% +WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files @@ -746,9 +764,21 @@ WARN_LOGFILE = %WARNING_LOG_PATH% # spaces. # Note: If this tag is empty the current directory is searched. -INPUT = ../include \ - ../src/lib_json \ - . +INPUT = readme.md \ + CHANGELOG.md \ + include/rapidjson/rapidjson.h \ + include/ \ + doc/features.md \ + doc/tutorial.md \ + doc/pointer.md \ + doc/stream.md \ + doc/encoding.md \ + doc/dom.md \ + doc/sax.md \ + doc/schema.md \ + doc/performance.md \ + doc/internals.md \ + doc/faq.md # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -768,10 +798,16 @@ INPUT_ENCODING = UTF-8 # *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, # *.qsf, *.as and *.js. -FILE_PATTERNS = *.h \ +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ *.cpp \ - *.inl \ - *.dox + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.inc \ + *.md # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. @@ -786,7 +822,7 @@ RECURSIVE = YES # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = +EXCLUDE = ./include/rapidjson/msinttypes/ # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -813,13 +849,13 @@ EXCLUDE_PATTERNS = # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* -EXCLUDE_SYMBOLS = +EXCLUDE_SYMBOLS = internal # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). -EXAMPLE_PATH = .. +EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and @@ -839,7 +875,7 @@ EXAMPLE_RECURSIVE = NO # that contain images that are to be included in the documentation (see the # \image command). -IMAGE_PATH = +IMAGE_PATH = ./doc # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program @@ -887,7 +923,7 @@ FILTER_SOURCE_PATTERNS = # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = readme.md #--------------------------------------------------------------------------- # Configuration options related to source browsing @@ -913,7 +949,7 @@ INLINE_SOURCES = NO # Fortran comments will always remain visible. # The default value is: YES. -STRIP_CODE_COMMENTS = YES +STRIP_CODE_COMMENTS = NO # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # function all documented functions referencing it will be listed. @@ -973,7 +1009,26 @@ USE_HTAGS = NO # See also: Section \class. # The default value is: YES. -VERBATIM_HEADERS = NO +VERBATIM_HEADERS = YES + +# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the +# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the +# cost of reduced performance. This can be particularly helpful with template +# rich C++ code for which doxygen's built-in parser lacks the necessary type +# information. +# Note: The availability of this option depends on whether or not doxygen was +# compiled with the --with-libclang option. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index @@ -1016,7 +1071,7 @@ GENERATE_HTML = YES # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_OUTPUT = %HTML_OUTPUT% +HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). @@ -1043,7 +1098,7 @@ HTML_FILE_EXTENSION = .html # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_HEADER = header.html +HTML_HEADER = ./doc/misc/header.html # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard @@ -1053,7 +1108,7 @@ HTML_HEADER = header.html # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_FOOTER = footer.html +HTML_FOOTER = ./doc/misc/footer.html # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of @@ -1076,7 +1131,7 @@ HTML_STYLESHEET = # see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_STYLESHEET = +HTML_EXTRA_STYLESHEET = ./doc/misc/doxygenextra.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note @@ -1132,7 +1187,7 @@ HTML_TIMESTAMP = YES # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_DYNAMIC_SECTIONS = YES +HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand @@ -1207,14 +1262,14 @@ DOCSET_PUBLISHER_NAME = Publisher # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -GENERATE_HTMLHELP = %HTML_HELP% +GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_FILE = jsoncpp-%JSONCPP_VERSION%.chm +CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler ( hhc.exe). If non-empty @@ -1222,14 +1277,14 @@ CHM_FILE = jsoncpp-%JSONCPP_VERSION%.chm # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -HHC_LOCATION = "c:\Program Files\HTML Help Workshop\hhc.exe" +HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated ( # YES) or that it should be included in the master .chm file ( NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -GENERATE_CHI = YES +GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) # and project file content. @@ -1238,18 +1293,19 @@ GENERATE_CHI = YES CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. +# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -BINARY_TOC = YES +BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -TOC_EXPAND = YES +TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that @@ -1273,7 +1329,7 @@ QCH_FILE = # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_NAMESPACE = +QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual @@ -1343,7 +1399,7 @@ ECLIPSE_DOC_ID = org.doxygen.Project # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -DISABLE_INDEX = NO +DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag @@ -1360,7 +1416,7 @@ DISABLE_INDEX = NO # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -GENERATE_TREEVIEW = NO +GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. @@ -1438,7 +1494,7 @@ MATHJAX_FORMAT = HTML-CSS # The default value is: http://cdn.mathjax.org/mathjax/latest. # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest +MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example @@ -1474,15 +1530,15 @@ MATHJAX_CODEFILE = # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. -SEARCHENGINE = NO +SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. There -# are two flavours of web server based searching depending on the -# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for -# searching and an index file used by the script. When EXTERNAL_SEARCH is -# enabled the indexing and searching needs to be provided by external tools. See -# the section "External Indexing and Searching" for details. +# are two flavors of web server based searching depending on the EXTERNAL_SEARCH +# setting. When disabled, doxygen will generate a PHP script for searching and +# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing +# and searching needs to be provided by external tools. See the section +# "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. @@ -1591,7 +1647,7 @@ COMPACT_LATEX = NO # The default value is: a4. # This tag requires that the tag GENERATE_LATEX is set to YES. -PAPER_TYPE = a4wide +PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names # that should be included in the LaTeX output. To get the times font for @@ -1642,7 +1698,7 @@ LATEX_EXTRA_FILES = # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. -PDF_HYPERLINKS = NO +PDF_HYPERLINKS = YES # If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate # the PDF file directly from the LaTeX files. Set this option to YES to get a @@ -1650,7 +1706,7 @@ PDF_HYPERLINKS = NO # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. -USE_PDFLATEX = NO +USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode # command to the generated LaTeX files. This will instruct LaTeX to keep running @@ -1770,6 +1826,13 @@ MAN_OUTPUT = man MAN_EXTENSION = .3 +# The MAN_SUBDIR tag determines the name of the directory created within +# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by +# MAN_EXTENSION with the initial . removed. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_SUBDIR = + # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real # man page(s). These additional files only source the real man page, but without @@ -1797,18 +1860,6 @@ GENERATE_XML = NO XML_OUTPUT = xml -# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a -# validating XML parser to check the syntax of the XML files. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify a XML DTD, which can be used by a -# validating XML parser to check the syntax of the XML files. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_DTD = - # If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program # listings (including syntax highlighting and cross-referencing information) to # the XML output. Note that enabling this will significantly increase the size @@ -1911,7 +1962,7 @@ MACRO_EXPANSION = YES # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_ONLY_PREDEF = NO +EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES the includes files in the # INCLUDE_PATH will be searched if a #include is found. @@ -1925,7 +1976,7 @@ SEARCH_INCLUDES = YES # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. -INCLUDE_PATH = ../include +INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the @@ -1933,7 +1984,7 @@ INCLUDE_PATH = ../include # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -INCLUDE_FILE_PATTERNS = *.h +INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. @@ -1943,10 +1994,13 @@ INCLUDE_FILE_PATTERNS = *.h # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -PREDEFINED = "_MSC_VER=1400" \ - _CPPRTTI \ - _WIN32 \ - JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +PREDEFINED = \ + RAPIDJSON_DOXYGEN_RUNNING \ + RAPIDJSON_NAMESPACE_BEGIN="namespace rapidjson {" \ + RAPIDJSON_NAMESPACE_END="}" \ + RAPIDJSON_REMOVEFPTR_(x)=x \ + RAPIDJSON_ENABLEIF_RETURN(cond,returntype)="RAPIDJSON_REMOVEFPTR_ returntype" \ + RAPIDJSON_DISABLEIF_RETURN(cond,returntype)="RAPIDJSON_REMOVEFPTR_ returntype" # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The @@ -1955,12 +2009,13 @@ PREDEFINED = "_MSC_VER=1400" \ # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_AS_DEFINED = +EXPAND_AS_DEFINED = \ + RAPIDJSON_NOEXCEPT # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will -# remove all refrences to function-like macros that are alone on a line, have an -# all uppercase name, and do not end with a semicolon. Such function macros are -# typically used for boiler-plate code, and will confuse the parser if not +# remove all references to function-like macros that are alone on a line, have +# an all uppercase name, and do not end with a semicolon. Such function macros +# are typically used for boiler-plate code, and will confuse the parser if not # removed. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. @@ -1980,7 +2035,7 @@ SKIP_FUNCTION_MACROS = YES # where loc1 and loc2 can be relative or absolute paths or URLs. See the # section "Linking to external documentation" for more information about the use # of tag files. -# Note: Each tag file must have an unique name (where the name does NOT include +# Note: Each tag file must have a unique name (where the name does NOT include # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. @@ -2029,7 +2084,7 @@ PERL_PATH = /usr/bin/perl # powerful graphs. # The default value is: YES. -CLASS_DIAGRAMS = NO +CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see: @@ -2040,11 +2095,18 @@ CLASS_DIAGRAMS = NO MSCGEN_PATH = +# You can include diagrams made with dia in doxygen documentation. Doxygen will +# then run dia to produce the diagram and insert it in the documentation. The +# DIA_PATH tag allows you to specify the directory where the dia binary resides. +# If left empty dia is assumed to be found in the default search path. + +DIA_PATH = + # If set to YES, the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. # The default value is: YES. -HIDE_UNDOC_RELATIONS = NO +HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz (see: @@ -2053,7 +2115,7 @@ HIDE_UNDOC_RELATIONS = NO # set to NO # The default value is: NO. -HAVE_DOT = %HAVE_DOT% +HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed # to run in parallel. When set to 0 doxygen will base this on the number of @@ -2073,7 +2135,7 @@ DOT_NUM_THREADS = 0 # The default value is: Helvetica. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_FONTNAME = FreeSans +DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size (in points) of the font of # dot graphs. @@ -2119,7 +2181,7 @@ GROUP_GRAPHS = YES # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -UML_LOOK = %UML_LOOK% +UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside the # class node. If there are many fields or methods and many nodes the graph may @@ -2140,7 +2202,7 @@ UML_LIMIT_NUM_FIELDS = 10 # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -TEMPLATE_RELATIONS = YES +TEMPLATE_RELATIONS = NO # If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to # YES then doxygen will generate a graph for each documented file showing the @@ -2180,7 +2242,7 @@ CALL_GRAPH = NO # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -CALLER_GRAPH = YES +CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical # hierarchy of all classes instead of a textual one. @@ -2225,7 +2287,7 @@ INTERACTIVE_SVG = NO # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_PATH = %DOT_PATH% +DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile @@ -2240,6 +2302,12 @@ DOTFILE_DIRS = MSCFILE_DIRS = +# The DIAFILE_DIRS tag can be used to specify one or more directories that +# contain dia files that are included in the documentation (see the \diafile +# command). + +DIAFILE_DIRS = + # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes # larger than this value, doxygen will truncate the graph, which is visualized @@ -2262,7 +2330,7 @@ DOT_GRAPH_MAX_NODES = 50 # Minimum value: 0, maximum value: 1000, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. -MAX_DOT_GRAPH_DEPTH = 1000 +MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not seem @@ -2283,7 +2351,7 @@ DOT_TRANSPARENT = NO # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_MULTI_TARGETS = YES +DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page # explaining the meaning of the various boxes and arrows in the dot generated diff --git a/thirdparty/jsoncpp/doc/doxyfile.in b/thirdparty/rapidjson-1.1.0/doc/Doxyfile.zh-cn.in similarity index 92% rename from thirdparty/jsoncpp/doc/doxyfile.in rename to thirdparty/rapidjson-1.1.0/doc/Doxyfile.zh-cn.in index 57c61c27e4..87dd8661b9 100644 --- a/thirdparty/jsoncpp/doc/doxyfile.in +++ b/thirdparty/rapidjson-1.1.0/doc/Doxyfile.zh-cn.in @@ -1,4 +1,4 @@ -# Doxyfile 1.8.5 +# Doxyfile 1.8.7 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. @@ -32,19 +32,19 @@ DOXYFILE_ENCODING = UTF-8 # title of most generated pages and in a few other places. # The default value is: My Project. -PROJECT_NAME = "JsonCpp" +PROJECT_NAME = RapidJSON # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = %JSONCPP_VERSION% +PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. -PROJECT_BRIEF = +PROJECT_BRIEF = "一个C++快速JSON解析器及生成器,包含SAX/DOM风格API" # With the PROJECT_LOGO tag one can specify an logo or icon that is included in # the documentation. The maximum height of the logo should not exceed 55 pixels @@ -58,7 +58,7 @@ PROJECT_LOGO = # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. -OUTPUT_DIRECTORY = %DOC_TOPDIR% +OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and @@ -70,18 +70,28 @@ OUTPUT_DIRECTORY = %DOC_TOPDIR% CREATE_SUBDIRS = NO +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese- -# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en, -# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish, -# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, -# Turkish, Ukrainian and Vietnamese. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. # The default value is: English. -OUTPUT_LANGUAGE = English +OUTPUT_LANGUAGE = Chinese # If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member # descriptions after the members that are listed in the file and class @@ -152,7 +162,7 @@ FULL_PATH_NAMES = YES # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. -STRIP_FROM_PATH = %TOPDIR% +STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which @@ -161,7 +171,7 @@ STRIP_FROM_PATH = %TOPDIR% # specify the list of include paths that are normally passed to the compiler # using the -I flag. -STRIP_FROM_INC_PATH = %TOPDIR%/include +STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't @@ -177,7 +187,7 @@ SHORT_NAMES = NO # description.) # The default value is: NO. -JAVADOC_AUTOBRIEF = YES +JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If @@ -216,7 +226,7 @@ SEPARATE_MEMBER_PAGES = NO # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. -TAB_SIZE = 3 +TAB_SIZE = 4 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: @@ -228,10 +238,7 @@ TAB_SIZE = 3 # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. -ALIASES = "testCaseSetup=\link CppUT::TestCase::setUp() setUp()\endlink" \ - "testCaseRun=\link CppUT::TestCase::run() run()\endlink" \ - "testCaseTearDown=\link CppUT::TestCase::tearDown() tearDown()\endlink" \ - "json_ref=JSON (JavaScript Object Notation)" +ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" @@ -272,9 +279,12 @@ OPTIMIZE_OUTPUT_VHDL = NO # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. # # Note For files without extension you can use no_extension as a placeholder. # @@ -309,7 +319,7 @@ AUTOLINK_SUPPORT = YES # diagrams that involve STL classes more complete and accurate. # The default value is: NO. -BUILTIN_STL_SUPPORT = YES +BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. @@ -361,7 +371,7 @@ SUBGROUPING = YES # SEPARATE_MEMBER_PAGES. # The default value is: NO. -INLINE_GROUPED_CLASSES = NO +INLINE_GROUPED_CLASSES = YES # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in @@ -409,7 +419,7 @@ LOOKUP_CACHE_SIZE = 0 # normally produced when WARNINGS is set to YES. # The default value is: NO. -EXTRACT_ALL = YES +EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class will # be included in the documentation. @@ -427,7 +437,7 @@ EXTRACT_PACKAGE = NO # included in the documentation. # The default value is: NO. -EXTRACT_STATIC = YES +EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined # locally in source files will be included in the documentation. If set to NO @@ -435,7 +445,7 @@ EXTRACT_STATIC = YES # for Java sources. # The default value is: YES. -EXTRACT_LOCAL_CLASSES = NO +EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local methods, # which are defined in the implementation section but not in the interface are @@ -489,7 +499,7 @@ HIDE_IN_BODY_DOCS = NO # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. -INTERNAL_DOCS = YES +INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES upper-case letters are also @@ -513,6 +523,13 @@ HIDE_SCOPE_NAMES = NO SHOW_INCLUDE_FILES = YES +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. @@ -534,7 +551,8 @@ SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. +# name. If set to NO the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO @@ -566,7 +584,7 @@ SORT_GROUP_NAMES = NO # list. # The default value is: NO. -SORT_BY_SCOPE_NAME = YES +SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between @@ -590,13 +608,13 @@ GENERATE_TODOLIST = YES # documentation. # The default value is: YES. -GENERATE_TESTLIST = NO +GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. -GENERATE_BUGLIST = NO +GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) # the deprecated list. This list is created by putting \deprecated commands in @@ -609,7 +627,7 @@ GENERATE_DEPRECATEDLIST= YES # sections, marked by \if ... \endif and \cond # ... \endcond blocks. -ENABLED_SECTIONS = +ENABLED_SECTIONS = $(RAPIDJSON_SECTIONS) # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the @@ -641,7 +659,7 @@ SHOW_FILES = YES # Folder Tree View (if specified). # The default value is: YES. -SHOW_NAMESPACES = YES +SHOW_NAMESPACES = NO # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from @@ -734,7 +752,7 @@ WARN_FORMAT = "$file:$line: $text" # messages should be written. If left blank the output is written to standard # error (stderr). -WARN_LOGFILE = %WARNING_LOG_PATH% +WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files @@ -746,9 +764,21 @@ WARN_LOGFILE = %WARNING_LOG_PATH% # spaces. # Note: If this tag is empty the current directory is searched. -INPUT = ../include \ - ../src/lib_json \ - . +INPUT = readme.zh-cn.md \ + CHANGELOG.md \ + include/rapidjson/rapidjson.h \ + include/ \ + doc/features.zh-cn.md \ + doc/tutorial.zh-cn.md \ + doc/pointer.zh-cn.md \ + doc/stream.zh-cn.md \ + doc/encoding.zh-cn.md \ + doc/dom.zh-cn.md \ + doc/sax.zh-cn.md \ + doc/schema.zh-cn.md \ + doc/performance.zh-cn.md \ + doc/internals.md \ + doc/faq.zh-cn.md # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses @@ -768,10 +798,16 @@ INPUT_ENCODING = UTF-8 # *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, # *.qsf, *.as and *.js. -FILE_PATTERNS = *.h \ +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ *.cpp \ - *.inl \ - *.dox + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.inc \ + *.md # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. @@ -786,7 +822,7 @@ RECURSIVE = YES # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = +EXCLUDE = ./include/rapidjson/msinttypes/ # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -813,13 +849,13 @@ EXCLUDE_PATTERNS = # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* -EXCLUDE_SYMBOLS = +EXCLUDE_SYMBOLS = internal # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). -EXAMPLE_PATH = .. +EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and @@ -839,7 +875,7 @@ EXAMPLE_RECURSIVE = NO # that contain images that are to be included in the documentation (see the # \image command). -IMAGE_PATH = +IMAGE_PATH = ./doc # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program @@ -887,7 +923,7 @@ FILTER_SOURCE_PATTERNS = # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = readme.zh-cn.md #--------------------------------------------------------------------------- # Configuration options related to source browsing @@ -900,7 +936,7 @@ USE_MDFILE_AS_MAINPAGE = # also VERBATIM_HEADERS is set to NO. # The default value is: NO. -SOURCE_BROWSER = YES +SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. @@ -913,19 +949,19 @@ INLINE_SOURCES = NO # Fortran comments will always remain visible. # The default value is: YES. -STRIP_CODE_COMMENTS = YES +STRIP_CODE_COMMENTS = NO # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # function all documented functions referencing it will be listed. # The default value is: NO. -REFERENCED_BY_RELATION = YES +REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. -REFERENCES_RELATION = YES +REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES, then the hyperlinks from functions in REFERENCES_RELATION and @@ -975,6 +1011,25 @@ USE_HTAGS = NO VERBATIM_HEADERS = YES +# If the CLANG_ASSISTED_PARSING tag is set to YES, then doxygen will use the +# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the +# cost of reduced performance. This can be particularly helpful with template +# rich C++ code for which doxygen's built-in parser lacks the necessary type +# information. +# Note: The availability of this option depends on whether or not doxygen was +# compiled with the --with-libclang option. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = + #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- @@ -1016,7 +1071,7 @@ GENERATE_HTML = YES # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_OUTPUT = %HTML_OUTPUT% +HTML_OUTPUT = html/zh-cn # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). @@ -1043,7 +1098,7 @@ HTML_FILE_EXTENSION = .html # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_HEADER = header.html +HTML_HEADER = ./doc/misc/header.html # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard @@ -1053,7 +1108,7 @@ HTML_HEADER = header.html # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_FOOTER = footer.html +HTML_FOOTER = ./doc/misc/footer.html # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of @@ -1076,7 +1131,7 @@ HTML_STYLESHEET = # see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_EXTRA_STYLESHEET = +HTML_EXTRA_STYLESHEET = ./doc/misc/doxygenextra.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note @@ -1132,7 +1187,7 @@ HTML_TIMESTAMP = YES # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -HTML_DYNAMIC_SECTIONS = YES +HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand @@ -1207,14 +1262,14 @@ DOCSET_PUBLISHER_NAME = Publisher # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -GENERATE_HTMLHELP = %HTML_HELP% +GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -CHM_FILE = jsoncpp-%JSONCPP_VERSION%.chm +CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler ( hhc.exe). If non-empty @@ -1222,14 +1277,14 @@ CHM_FILE = jsoncpp-%JSONCPP_VERSION%.chm # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -HHC_LOCATION = "c:\Program Files\HTML Help Workshop\hhc.exe" +HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated ( # YES) or that it should be included in the master .chm file ( NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -GENERATE_CHI = YES +GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) # and project file content. @@ -1238,18 +1293,19 @@ GENERATE_CHI = YES CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. +# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -BINARY_TOC = YES +BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. -TOC_EXPAND = YES +TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that @@ -1273,7 +1329,7 @@ QCH_FILE = # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. -QHP_NAMESPACE = +QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual @@ -1343,7 +1399,7 @@ ECLIPSE_DOC_ID = org.doxygen.Project # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -DISABLE_INDEX = NO +DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag @@ -1360,7 +1416,7 @@ DISABLE_INDEX = NO # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. -GENERATE_TREEVIEW = NO +GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. @@ -1438,7 +1494,7 @@ MATHJAX_FORMAT = HTML-CSS # The default value is: http://cdn.mathjax.org/mathjax/latest. # This tag requires that the tag USE_MATHJAX is set to YES. -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest +MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example @@ -1474,15 +1530,15 @@ MATHJAX_CODEFILE = # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. -SEARCHENGINE = NO +SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. There -# are two flavours of web server based searching depending on the -# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for -# searching and an index file used by the script. When EXTERNAL_SEARCH is -# enabled the indexing and searching needs to be provided by external tools. See -# the section "External Indexing and Searching" for details. +# are two flavors of web server based searching depending on the EXTERNAL_SEARCH +# setting. When disabled, doxygen will generate a PHP script for searching and +# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing +# and searching needs to be provided by external tools. See the section +# "External Indexing and Searching" for details. # The default value is: NO. # This tag requires that the tag SEARCHENGINE is set to YES. @@ -1591,7 +1647,7 @@ COMPACT_LATEX = NO # The default value is: a4. # This tag requires that the tag GENERATE_LATEX is set to YES. -PAPER_TYPE = a4wide +PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names # that should be included in the LaTeX output. To get the times font for @@ -1642,7 +1698,7 @@ LATEX_EXTRA_FILES = # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. -PDF_HYPERLINKS = NO +PDF_HYPERLINKS = YES # If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate # the PDF file directly from the LaTeX files. Set this option to YES to get a @@ -1650,7 +1706,7 @@ PDF_HYPERLINKS = NO # The default value is: YES. # This tag requires that the tag GENERATE_LATEX is set to YES. -USE_PDFLATEX = NO +USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode # command to the generated LaTeX files. This will instruct LaTeX to keep running @@ -1770,6 +1826,13 @@ MAN_OUTPUT = man MAN_EXTENSION = .3 +# The MAN_SUBDIR tag determines the name of the directory created within +# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by +# MAN_EXTENSION with the initial . removed. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_SUBDIR = + # If the MAN_LINKS tag is set to YES and doxygen generates man output, then it # will generate one additional man file for each entity documented in the real # man page(s). These additional files only source the real man page, but without @@ -1797,18 +1860,6 @@ GENERATE_XML = NO XML_OUTPUT = xml -# The XML_SCHEMA tag can be used to specify a XML schema, which can be used by a -# validating XML parser to check the syntax of the XML files. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify a XML DTD, which can be used by a -# validating XML parser to check the syntax of the XML files. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_DTD = - # If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program # listings (including syntax highlighting and cross-referencing information) to # the XML output. Note that enabling this will significantly increase the size @@ -1911,7 +1962,7 @@ MACRO_EXPANSION = YES # The default value is: NO. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_ONLY_PREDEF = NO +EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES the includes files in the # INCLUDE_PATH will be searched if a #include is found. @@ -1925,7 +1976,7 @@ SEARCH_INCLUDES = YES # preprocessor. # This tag requires that the tag SEARCH_INCLUDES is set to YES. -INCLUDE_PATH = ../include +INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the @@ -1933,7 +1984,7 @@ INCLUDE_PATH = ../include # used. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -INCLUDE_FILE_PATTERNS = *.h +INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that are # defined before the preprocessor is started (similar to the -D option of e.g. @@ -1943,10 +1994,13 @@ INCLUDE_FILE_PATTERNS = *.h # recursively expanded use the := operator instead of the = operator. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -PREDEFINED = "_MSC_VER=1400" \ - _CPPRTTI \ - _WIN32 \ - JSONCPP_DOC_EXCLUDE_IMPLEMENTATION +PREDEFINED = \ + RAPIDJSON_DOXYGEN_RUNNING \ + RAPIDJSON_NAMESPACE_BEGIN="namespace rapidjson {" \ + RAPIDJSON_NAMESPACE_END="}" \ + RAPIDJSON_REMOVEFPTR_(x)=x \ + RAPIDJSON_ENABLEIF_RETURN(cond,returntype)="RAPIDJSON_REMOVEFPTR_ returntype" \ + RAPIDJSON_DISABLEIF_RETURN(cond,returntype)="RAPIDJSON_REMOVEFPTR_ returntype" # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The @@ -1955,12 +2009,13 @@ PREDEFINED = "_MSC_VER=1400" \ # definition found in the source code. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. -EXPAND_AS_DEFINED = +EXPAND_AS_DEFINED = \ + RAPIDJSON_NOEXCEPT # If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will -# remove all refrences to function-like macros that are alone on a line, have an -# all uppercase name, and do not end with a semicolon. Such function macros are -# typically used for boiler-plate code, and will confuse the parser if not +# remove all references to function-like macros that are alone on a line, have +# an all uppercase name, and do not end with a semicolon. Such function macros +# are typically used for boiler-plate code, and will confuse the parser if not # removed. # The default value is: YES. # This tag requires that the tag ENABLE_PREPROCESSING is set to YES. @@ -1980,7 +2035,7 @@ SKIP_FUNCTION_MACROS = YES # where loc1 and loc2 can be relative or absolute paths or URLs. See the # section "Linking to external documentation" for more information about the use # of tag files. -# Note: Each tag file must have an unique name (where the name does NOT include +# Note: Each tag file must have a unique name (where the name does NOT include # the path). If a tag file is not located in the directory in which doxygen is # run, you must also specify the path to the tagfile here. @@ -2029,7 +2084,7 @@ PERL_PATH = /usr/bin/perl # powerful graphs. # The default value is: YES. -CLASS_DIAGRAMS = NO +CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see: @@ -2040,11 +2095,18 @@ CLASS_DIAGRAMS = NO MSCGEN_PATH = +# You can include diagrams made with dia in doxygen documentation. Doxygen will +# then run dia to produce the diagram and insert it in the documentation. The +# DIA_PATH tag allows you to specify the directory where the dia binary resides. +# If left empty dia is assumed to be found in the default search path. + +DIA_PATH = + # If set to YES, the inheritance and collaboration graphs will hide inheritance # and usage relations if the target is undocumented or is not a class. # The default value is: YES. -HIDE_UNDOC_RELATIONS = NO +HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz (see: @@ -2053,7 +2115,7 @@ HIDE_UNDOC_RELATIONS = NO # set to NO # The default value is: NO. -HAVE_DOT = %HAVE_DOT% +HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed # to run in parallel. When set to 0 doxygen will base this on the number of @@ -2073,7 +2135,7 @@ DOT_NUM_THREADS = 0 # The default value is: Helvetica. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_FONTNAME = FreeSans +DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size (in points) of the font of # dot graphs. @@ -2119,7 +2181,7 @@ GROUP_GRAPHS = YES # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -UML_LOOK = %UML_LOOK% +UML_LOOK = NO # If the UML_LOOK tag is enabled, the fields and methods are shown inside the # class node. If there are many fields or methods and many nodes the graph may @@ -2140,7 +2202,7 @@ UML_LIMIT_NUM_FIELDS = 10 # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -TEMPLATE_RELATIONS = YES +TEMPLATE_RELATIONS = NO # If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to # YES then doxygen will generate a graph for each documented file showing the @@ -2180,7 +2242,7 @@ CALL_GRAPH = NO # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -CALLER_GRAPH = YES +CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical # hierarchy of all classes instead of a textual one. @@ -2225,7 +2287,7 @@ INTERACTIVE_SVG = NO # found. If left blank, it is assumed the dot tool can be found in the path. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_PATH = %DOT_PATH% +DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the \dotfile @@ -2240,6 +2302,12 @@ DOTFILE_DIRS = MSCFILE_DIRS = +# The DIAFILE_DIRS tag can be used to specify one or more directories that +# contain dia files that are included in the documentation (see the \diafile +# command). + +DIAFILE_DIRS = + # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes # that will be shown in the graph. If the number of nodes in a graph becomes # larger than this value, doxygen will truncate the graph, which is visualized @@ -2262,7 +2330,7 @@ DOT_GRAPH_MAX_NODES = 50 # Minimum value: 0, maximum value: 1000, default value: 0. # This tag requires that the tag HAVE_DOT is set to YES. -MAX_DOT_GRAPH_DEPTH = 1000 +MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not seem @@ -2283,7 +2351,7 @@ DOT_TRANSPARENT = NO # The default value is: NO. # This tag requires that the tag HAVE_DOT is set to YES. -DOT_MULTI_TARGETS = YES +DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page # explaining the meaning of the various boxes and arrows in the dot generated diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/architecture.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/architecture.dot new file mode 100644 index 0000000000..c816c87183 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/architecture.dot @@ -0,0 +1,50 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + nodesep=0.5 + penwidth=0.5 + colorscheme=spectral7 + + node [shape=box, fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5, style=filled, fillcolor=white] + edge [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "SAX" + style=filled + fillcolor=6 + + Reader -> Writer [style=invis] + } + + subgraph cluster2 { + margin="10,10" + labeljust="left" + label = "DOM" + style=filled + fillcolor=7 + + Value + Document + } + + Handler [label="<>\nHandler"] + + { + edge [arrowtail=onormal, dir=back] + Value -> Document + Handler -> Document + Handler -> Writer + } + + { + edge [arrowhead=vee, style=dashed, constraint=false] + Reader -> Handler [label="calls"] + Value -> Handler [label="calls"] + Document -> Reader [label="uses"] + } +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/architecture.png b/thirdparty/rapidjson-1.1.0/doc/diagram/architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..556c7e729148cc37be23f083292e21954c12dd73 GIT binary patch literal 16569 zcmcIsWl&XZw1xvHA<`lu-I9WIceivmNOz~wCEYEeboZgVL-NqwA#rH#M*V)>e|P52 z>``>~UVH8JzVC`>J&RBUIdN3vH^?wBFsPCeB1$kYuqVLJQ;5%iKYujl&H#VGIx2|^ z!IX}?-GzY>fRPjt{OAUInDIOvYwEHW&3hM&OCuG-keyAeUcpN{>+aIE3G!8-RN?d z>Uc4wmL>u(BJk&GBZ7a1`o@?7pUukL`}XoeJW@p(10DA7<@tCIEve@S@k9K3T}At0 z*FPSme4+!95 zoJ9D-!~gq+X!vh!_ii&E&HkwEA3;Toka-&I2lG$s7=eEEcVP2z(tTeI-y)ql7rO49 zSq}8RcN#sJ9_PCp@!v=RYut&g^l$4{#;j9nRv7NZU2iUxXx4Tud9BhE>9s!CsBuyv z@ELT#(=PK2YM$HFLU6|XPf3_gFCj2j(5p9QN|#O8acL1ju#f`%up z?ygSX%Wf0Ifu4I!&8sX>DccGaYP*KUQYhuWD-1>q5ePtvXNcR3cikOe#qu)EuyIA| z%B!I896XwsvH$z|q+dk(4B z|GWa{vMY_vs*+I;&*bd;a24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~ zwOZ{9aTqn`ZB<5RZ%Q*yBj@a`4I3YlvE8!xybZY;UPcl5J7ygawRU`r1!R^XHecVx zJ+*c8ra0GWJ%zNwRf2oIwKc$2s1mQ+=Kh%z7l?odaFQ}t`-m6!ZuMR(KFyYeReux` z=mDDTqgUbrFn^cv4w$w6{~mPzJSI5{{9*vJr{4wee;j%T(rKdO)V;r>`d?4s!&uG7 rhzkIC5D!i0-m|s|g|\\0|:|\"|H|e|l|l|o|\\n|W|o|r|l|d|!|\\0|\"|,|\"|s|t|a|r|s|\\0|t|a|r|s|:|1|0|\}", xlabel="After Parsing"] + newjson [shape=plaintext, label=< + + + + + + + + + + +
{"msg\\0:"Hello\\nWorld!\\0","stars\\0tars:10}
+>, xlabel="After Parsing"] + } + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Document by In situ Parsing" + style=filled + fillcolor=gray95 + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + root [label="{object|}", fillcolor=3] + + { + msg [label="{string|}", fillcolor=5] + helloworld [label="{string|}", fillcolor=5] + stars [label="{string|}", fillcolor=5] + ten [label="{number|10}", fillcolor=6] + } + } + + oldjson -> root [label=" ParseInsitu()" lhead="cluster1"] + edge [arrowhead=vee] + root -> { msg; stars } + + edge [arrowhead="none"] + msg -> helloworld + stars -> ten + + { + edge [arrowhead=vee, arrowtail=dot, arrowsize=0.5, dir=both, tailclip=false] + msg:a:c -> newjson:a + helloworld:a:c -> newjson:b + stars:a:c -> newjson:c + } + + //oldjson -> newjson [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/insituparsing.png b/thirdparty/rapidjson-1.1.0/doc/diagram/insituparsing.png new file mode 100644 index 0000000000000000000000000000000000000000..4400c88466a8fb5ec0774b72acd52bf41c670c6e GIT binary patch literal 37281 zcma%jbyQW|`ZXX*cT0DJfP~WBARyf>-ICJX-Jz64qjYy8-6@?1P&&SKeDA%!0L2CnRD@=vdLh<327@ zlMrKsg)I`7gWWv}Dbh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u@BEk!sj3d+c3=z@py?ebkD3kpy$LufjMRIYk{cO_aGPHW6NCK!E&?zM9af?IHRa&qTRcK zjre(5AgvhLVEE|=Wfq^;4wV?W-pmc!a7m&Zi}?H|qI(7w=sausUxU$G6B(Mo%CutX}tvG_qfeo0Zh0T$4IFhI=$r#H2W+Ni~rcm9V2?dtSBQN=~TI z@vR-mlhDx@OK0~iSN2% z6&eFe7wLlzD=+_*7gJkbRU^TiQWQyON)`qScE2Maduo5fJe^u`=h=f%V^e(cn(6Z6 zExE!5UA5TnA2I9AupeQj5+L-M`&0Os6u3lv_!hYAwD5uiULQ-AFOf@|AfU!-4D%Dj zS8Ads!nZ(Z6^04tSWaPxp;NXA#qFC`TrkxHKKk=auI1+btL%GPb zrlgzpr&gx8IA+Y{ku*9Xnme!L(&S(7PNeG#Pf5*Rb|dulZsqyvf3N>qqSYTJw_oe+ z%2W9vzrTG_yB{{uzH;u9->d$5$N6vFzv@ru&zq+o`u(?k2wZfYReSYc)Aoy>+J)+W zZ@je4dFB6A*O#~P*4;hmzWVvOue|1ZF82;BQb<42wa7RHxVjHCTn+W6VjshAjkX`G z2kxdL^-2#&0z05q&TaiD9oR>p4(uawhVuE4zAK~)n+_Cx!6RvR4q<4ILkDQFLq|Nr zomyB&7o>O&Xr&nz7if1W)-e`*2M#ksd&Lcc1#JiZGc$d>!Z3S%Y&QcCc)I$ztaD0e F0sxnWX08AL literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.dot new file mode 100644 index 0000000000..82ebfe1f09 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.dot @@ -0,0 +1,62 @@ +digraph { + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + penwidth=0.0 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + + node [shape = doublecircle]; Start; Finish; + node [shape = box; style = "rounded, filled"; fillcolor=white ]; + + Start -> ArrayInitial [label=" ["]; + Start -> ObjectInitial [label=" {"]; + + subgraph clusterArray { + margin="10,10" + style=filled + fillcolor=gray95 + label = "Array" + + ArrayInitial; Element; ElementDelimiter; ArrayFinish; + } + + subgraph clusterObject { + margin="10,10" + style=filled + fillcolor=gray95 + label = "Object" + + ObjectInitial; MemberKey; KeyValueDelimiter; MemberValue; MemberDelimiter; ObjectFinish; + } + + ArrayInitial -> ArrayInitial [label="["]; + ArrayInitial -> ArrayFinish [label=" ]"]; + ArrayInitial -> ObjectInitial [label="{", constraint=false]; + ArrayInitial -> Element [label="string\nfalse\ntrue\nnull\nnumber"]; + + Element -> ArrayFinish [label="]"]; + Element -> ElementDelimiter [label=","]; + + ElementDelimiter -> ArrayInitial [label=" ["]; + ElementDelimiter -> ObjectInitial [label="{"]; + ElementDelimiter -> Element [label="string\nfalse\ntrue\nnull\nnumber"]; + + ObjectInitial -> ObjectFinish [label=" }"]; + ObjectInitial -> MemberKey [label=" string "]; + + MemberKey -> KeyValueDelimiter [label=":"]; + + KeyValueDelimiter -> ArrayInitial [label="["]; + KeyValueDelimiter -> ObjectInitial [label=" {"]; + KeyValueDelimiter -> MemberValue [label=" string\n false\n true\n null\n number"]; + + MemberValue -> ObjectFinish [label="}"]; + MemberValue -> MemberDelimiter [label=","]; + + MemberDelimiter -> MemberKey [label=" string "]; + + ArrayFinish -> Finish; + ObjectFinish -> Finish; +} diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.png b/thirdparty/rapidjson-1.1.0/doc/diagram/iterative-parser-states-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..f315494db1d7b3a91ffef5eb395c0fc67e462d4c GIT binary patch literal 92378 zcmZU5by!qg+b@ix3_T#-UD8MiA}QU1bcb|FH_|QAt&~W2hm^D;NP~a^(j_GzXKmm2 zeBX7Q^Vc&E&g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Dk%8d}ZWq#|%TmtKCyy+r zblwzHx%L>BDPM%yqmrawtqY1hsvgE%rtN2f-{iMb-AIq36}pN_eQ_EH8sKRCxhln! zt8K;XP&}X=M^kgru&VowS`0YkKb^|7TfMsB?O~fV0*A5_s~QjHg&(+xh$$-hK}*iQ zeA`_0xof`#Q5%4fFXr1;CK}5A1l5#)LgRo@rCJgGz2@4+P~LFvMo}&V2hBM6$tPy$ zO)wBBlJUkO`byAB8EFZwDUTq1Go(>X6!9GUVHGU=zs3G$BuHf5KpoO|?y#S}65x6~ z(>gthtuV(DcC+p8U^g7>Y+H=3`}440eR&t1yoLD&$M{F{7Oj_HZ8fB*BJVjv`w#%AmN g_y54FdZG_W?!8m#U7i*cB!YkRw2U?D)tzJi4?{YQ3jhEB literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/makefile b/thirdparty/rapidjson-1.1.0/doc/diagram/makefile new file mode 100644 index 0000000000..3483977655 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/makefile @@ -0,0 +1,8 @@ +%.pdf: %.dot + dot $< -Tpdf -o $@ + +%.png: %.dot + dot $< -Tpng -o $@ + +DOTFILES = $(basename $(wildcard *.dot)) +all: $(addsuffix .png, $(DOTFILES)) $(addsuffix .pdf, $(DOTFILES)) diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move1.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/move1.dot new file mode 100644 index 0000000000..a7c1464ad0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/move1.dot @@ -0,0 +1,47 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, arrowhead=normal] + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Before" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + { + rank = same + b1 [label="{b:number|456}", fillcolor=6] + a1 [label="{a:number|123}", fillcolor=6] + } + + a1 -> b1 [style="dashed", label="Move", dir=back] + } + + subgraph cluster2 { + margin="10,10" + labeljust="left" + label = "After" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + { + rank = same + b2 [label="{b:null|}", fillcolor=1] + a2 [label="{a:number|456}", fillcolor=6] + } + a2 -> b2 [style=invis, dir=back] + } + b1 -> b2 [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move1.png b/thirdparty/rapidjson-1.1.0/doc/diagram/move1.png new file mode 100644 index 0000000000000000000000000000000000000000..ab322d084bd6d819fdb93a014d19e5fbf6e2b2b0 GIT binary patch literal 16081 zcmbtbRa9KTvJDd4-ED9uxVyU(+}%BRaCZsrPH=Y#?oM!b32p)2$^E}?y|vyC%s@?d zRh{mhuDy3fC@DxH!r{Sv`t%7=T1rgi(8mbmVPRz<3}H1TRAD7lHKllcKS*(* z_)YHwO8JaAZ)E8JlsUS;E>xXn=7ze^ zdSP(Fg*b%qrV*mYXK}zJ0#F0cO?qLN!J`9MV3@6Ng0P0oAaTHmtp2e6`|A*CF9>n( z&+baJP^x5rG-zB99N`nlkN{i`Z)j(*4);5K+@~aoRDVdEPZGUckU!X>2ck?^!M_rL zQO3}Jz%YM`4siN6Y#8>iIb=N_@UgG&sD__#!1hoK=a`Y0VkcotzX2bs{|oB<^q=X9 zj0p4zGEqlvU|LO~z86Zy86VH&m+5u5o7e9&0s$COKoSZ1Mf*J87~SlTQl|Z&nQL`9 zLV`lX3$E7d$j}8-7yDIDOoT;Fg6?)R!Np%M+n=#aC!lXYaMq)JiWZe1g()1 zq=KLj9p7H=5i%c-XF;yVGhpxU?-_Tvl)EthV$y)D;+f0K@b>iFuB_>vV+#z=({8d} zsWl2(r!Il~H9QQWp`pR#UhnZYfbxGnNON@d>hr+hBqxUqfyY*GGZ>{~W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z$LO|rn<$MQ&#K=Wn z`f2IYh{m{-oYb#W+_l+qKMMpura{iCpG)kl_s*F559aR=ba0K9fo_T-YHwIHtQX82 zc3L8QFM0y80)jqKNFqHZvc{T4!o4XBs#qYXm|wFYRE{U%ZmGt00cr2G`cS#jSCFv;ctvFEqF}jMIxw?3_Rv$b)NbFis?0JW) zL3sT%pCi64B^XlMfM0MytH8Fa3c0hKA zyYcV-V#iw#@lmhA;=nmPI4M21`UQTn!OG!k(x)CJw#s<|6TiPu07RThJ7s=bj4BC$ z$x4;>g!HdwV3g+@ajQ<#N|OM(6AbO)ouX5x%!NiAGTz2Fa~kCF$Ec+`uZy;s)?F44 zlA0grTWl7Yr<8Yk`eS6f)j{|{zkzTCzWL|oQH+C=s!oU1tX#oIkuvxlol-xiX0zC* zTn2mERDX3DgNdS>OG?^T-pt1TB;$d{E#v630Fyzvq)ZmJTLF*ChH>HU_UUeDYb}=; zlw==o2PfXLT_BcVV?a%f8%JdE!X(GXtx*Z>% z??ON?oD#W}hDm@M#ZiR{t(ECU3X>JUr zm_aT8xU}e-z&0K;xO)f?f}R_;W-6)@F%a4PYk*BJ%nBwDu=}E(?pFyRUmy?v-+{k> aKn%h5W>`e-p#nYXpQObV#HvLM1OEpM8uU{D literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move2.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/move2.dot new file mode 100644 index 0000000000..7037ea6cbb --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/move2.dot @@ -0,0 +1,62 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, arrowhead=normal] + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Before Copying (Hypothetic)" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + c1 [label="{contact:array|}", fillcolor=4] + c11 [label="{|}"] + c12 [label="{|}"] + c13 [shape="none", label="...", style="solid"] + o1 [label="{o:object|}", fillcolor=3] + ghost [label="{o:object|}", style=invis] + + c1 -> o1 [style="dashed", label="AddMember", constraint=false] + + edge [arrowhead=vee] + c1 -> { c11; c12; c13 } + o1 -> ghost [style=invis] + } + + subgraph cluster2 { + margin="10,10" + labeljust="left" + label = "After Copying (Hypothetic)" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + c2 [label="{contact:array|}", fillcolor=4] + c3 [label="{array|}", fillcolor=4] + c21 [label="{|}"] + c22 [label="{|}"] + c23 [shape=none, label="...", style="solid"] + o2 [label="{o:object|}", fillcolor=3] + cs [label="{string|\"contact\"}", fillcolor=5] + c31 [label="{|}"] + c32 [label="{|}"] + c33 [shape="none", label="...", style="solid"] + + edge [arrowhead=vee] + c2 -> { c21; c22; c23 } + o2 -> cs + cs -> c3 [arrowhead=none] + c3 -> { c31; c32; c33 } + } + ghost -> o2 [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move2.png b/thirdparty/rapidjson-1.1.0/doc/diagram/move2.png new file mode 100644 index 0000000000000000000000000000000000000000..8d4fc5bcc2223e127f672666b8eddbce4020e01c GIT binary patch literal 41517 zcmdqJWmH|k)-8wy4sOBSU4sO753a!_1PH<1-Gh5@3$6izJAnWpxCIaH8XUUFz26(% z?~NX#fA_EC9QLl-Rke22nsd#0B2<)QP>~3cprD{oJ|IfV-OYSZ1Rm-Cd$)aVa4-!Yrt^D3kOlJTS%dx!Te=Gs^R@5&>xa_;GK~&zkJfrO2m=nI zM)>y_66;jT%=G_W<%6ly>dLaz>h{Z4&GahkZW*?M@82AehJl9|aADvL|99n;l)u~$ zpSu`ti|486`h#JtcGkqY3D5C7r>h-cu+4TWwOjut*qs;#Eu!P=i{z{0mB|{D-cNOf zN?D&7wJKya%QQIn?RE#U1l%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4b*Ic`npK3A!qCj32g8>Y09?i}vLt@w$S~Xf*+SMAf5;TDjq-sM!hk&s zXsqc&S=-W?<;`A=t>e$g{~FYU73B0fM6S%Iw=W`hq$e;;P!YR zPd%{ACr|Gy8P?@GXnq?&#YY0N$h%|tyZTGBewW;omDwqQ3iZ4hjd&3|-Xl|6D{y=TdTiwaN(=pYVh~QtM=R~D-l)@MZkYR4)m@#@ zYwOUsws&+g@P^FvD}l_tkC-(L*u9*n??VZF6vHd0Mjo4S_op278Ix@^iC$(LqT;HHIe zfA(P;{_?ENUVbgy*}L+N(y(A{Sp55sx7|>cEpsWq3!S-}w{Ke$qkd`)Rxdivl-$4f z_k{KK%R(^$E%{;p=I^*lXDrX>zfU-BZXVdLFoo3G5qlmmxRV3jmmElS9DwcM`m&zB zS(8FO6cuIeeo&lM0~PBe)u=iLy-!pjoDvMu1`u~Y*q&;d+J|JXLIs&QS$57w&WR;#v?0*0tg%HgE literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move3.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/move3.dot new file mode 100644 index 0000000000..c197b99df5 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/move3.dot @@ -0,0 +1,60 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + forcelabels=true + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, arrowhead=normal] + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Before Moving" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + c1 [label="{contact:array|}", fillcolor=4] + c11 [label="{|}"] + c12 [label="{|}"] + c13 [shape=none, label="...", style="solid"] + o1 [label="{o:object|}", fillcolor=3] + ghost [label="{o:object|}", style=invis] + + c1 -> o1 [style="dashed", constraint=false, label="AddMember"] + + edge [arrowhead=vee] + c1 -> { c11; c12; c13 } + o1 -> ghost [style=invis] + } + + subgraph cluster2 { + margin="10,10" + labeljust="left" + label = "After Moving" + style=filled + fillcolor=gray95 + + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + c2 [label="{contact:null|}", fillcolor=1] + c3 [label="{array|}", fillcolor=4] + c21 [label="{|}"] + c22 [label="{|}"] + c23 [shape="none", label="...", style="solid"] + o2 [label="{o:object|}", fillcolor=3] + cs [label="{string|\"contact\"}", fillcolor=5] + c2 -> o2 [style="dashed", constraint=false, label="AddMember", style=invis] + + edge [arrowhead=vee] + c3 -> { c21; c22; c23 } + o2 -> cs + cs -> c3 [arrowhead=none] + } + ghost -> o2 [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/move3.png b/thirdparty/rapidjson-1.1.0/doc/diagram/move3.png new file mode 100644 index 0000000000000000000000000000000000000000..558470f1fab8390faa35fca1ef85c0e7f048d3c4 GIT binary patch literal 36371 zcmd?Rbx>Ww*DV+bkN^RKy99!}26uONcY?b^2=4Cg?(V_iBEj9=-7W8s{NBu0U%jcC z|K6(^swh&q=k)3BvwO?hYu#X3X%RRWESPui-oc593d+BG2Uhy-9XS3+DByp_a;{>5 zKVbIqBK+?v#&8baz2ki+CdjAg0(PAKK^H{`ec%r-%vatYQR82(S2_Gv-7C>}KSNx+ zM^yYQ6q5B5g`Du`&mY(DlX-U(?aoN-Vg%3!=cB1j1KM_pZboOP;o4Ttpw#3wswXSs z)sZ~ctKCuYDg$uIAJBAQBw1SEB58sPEvAhgnhYerAd=o8>w@#D2mI$>lDtO{s%mEK z{!JeLuK&eF=>_%oB1zsSh$fT#7nV&V1~A}GoQ!vrl!4w57;huIeF)sw8Q$dg_r5^V zUm(y1J{Z*BamTsAl$95)iDXgN^hqEPUa0>2%t*oqSmS@|wnT1nxgdOf*vnKz zoh$<#zP>zRu-Xu?JM2f5@Z0GF(*T}br3IcV5-IJt;fg^w^HJ^Zx_&?>r2^};M>c-= zw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Pk^cv-I zB^nj=1*N1vsL9EFL3)x1pgYga%zT~r?#&JE?!Zc3e8jMD=P%?x^yYdq8%j`Vwg{wKN4^|e#W_AjQ!hOAp5AR6G01_>d1wqXXWFVXp5=;b zxK6g9zvRLKM!!wjh<;Hwj#-`6YJ~*i47fI2_;unRC-?75-vBNFH>$-EY-(Dl8JGKx z4gf{in>4(Dv}_Aiy)~!3SnUd1k2?R^>4WSZeQxdf)Pj4xQL^TCo$uiN;=E%)UU z>Z6UWtG<$BaD1P}8A?yM)|`kQ;2m7Y{PqsM(}3)#A0HqL(}X_>5d?$z3jO%J2Ua?o zHY+W`KZn8qHK0a~3Kcx?Em0is|7PO*8UK6u5xPIA?gSq8{}(S5j+{Z%t+R}OPlgTw zi}VQr9BAlOg5>4=&TzEm*WC$-Ro7Y0rPgX>kRyauLIC{|lFroHGCb literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.dot new file mode 100644 index 0000000000..b15941ba0f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.dot @@ -0,0 +1,56 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, arrowhead=normal] + + { + node [shape=record, fontsize="8", margin="0.04", height=0.2, color=gray] + normaljson [label="\{|\"|m|s|g|\"|:|\"|H|e|l|l|o|\\|n|W|o|r|l|d|!|\"|,|\"|\\|u|0|0|7|3|t|a|r|s\"|:|1|0|\}"] + + { + rank = same + msgstring [label="m|s|g|\\0"] + helloworldstring [label="H|e|l|l|o|\\n|W|o|r|l|d|!|\\0"] + starsstring [label="s|t|a|r|s\\0"] + } + } + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Document by Normal Parsing" + style=filled + fillcolor=gray95 + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + root [label="{object|}", fillcolor=3] + + { + msg [label="{string|}", fillcolor=5] + helloworld [label="{string|}", fillcolor=5] + stars [label="{string|}", fillcolor=5] + ten [label="{number|10}", fillcolor=6] + } + } + + normaljson -> root [label=" Parse()" lhead="cluster1"] + edge [arrowhead=vee] + root -> { msg; stars } + + edge [arrowhead="none"] + msg -> helloworld + stars -> ten + + edge [arrowhead=vee, arrowtail=dot, arrowsize=0.5, dir=both, tailclip=false] + msg:a:c -> msgstring:w + helloworld:a:c -> helloworldstring:w + stars:a:c -> starsstring:w + + msgstring -> helloworldstring -> starsstring [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.png b/thirdparty/rapidjson-1.1.0/doc/diagram/normalparsing.png new file mode 100644 index 0000000000000000000000000000000000000000..702512ca3678f62f4a35100953d2dad02fc84fab GIT binary patch literal 32887 zcmce;WmuMN*DWfDQX<_A(k-Q5k+h;*lPNq2`d(%m3k(zQ;WcRla7*0F!= zWB=JdJn+Wry3d+1=9uF&R6$N00S*W5)vH$sk`f}HUcG|227mNm-h$u!z+hYgKOh`F zi3`0dAH~~y^-AECq==xhE5uuu$Zm=#4S@!k&>}%>)2~;Y7e>C(r+n80D0?0)q z_{bunqDaV4RYd;2XnQJ(%3*&|+)s#Oo=&(McDL;l7p1K$yk93Srt^&*9A~b7CdEn!{^z3r3=D**KwvWujL^$p!DEmSzA)FXN))J~ULJq> zCGzq4yMO)(yaK}riG3KqyEBs7;IJFTOHqaTpJ%{}EfPc)Go=HuWYS@rm5UDi_FFK& z^QBGxIBXB1FSU6s#_0CB-TgJ|_Qu~{pDI$K?_W3PyR2c*Y5AIzgw?&*7|X8u@R7g# zZg!~Sq_B`utJ!(Pmh*3=<)7sSyKV)J+*@vsD_Rs3ly|*Fy8)}^JltXz2Kf9HO1Pui zXAQA@xNDx}R+DuuCsHjl>)NopVXJdL%JcS|6F~-XVqzle8IRK*>wJ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4cYC?a6My+j%LJ=t*F32iq@xo8&ymy z-CF#kM~`g%0~y8V@F@K6mH$GxL4{hhzt)O1^T7hx!^`FS6rszmrnB+iDgV!xaY6); zMvrMjb>08I0!rk)g=Z&R)2mmn@V*LvQ3PnPNkmkO68Mt;^8)vvwr42jq#||C?=&jl PMX$b!NDG$;>iYgK0)w4D literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.dot new file mode 100644 index 0000000000..959cdbb417 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.dot @@ -0,0 +1,54 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10, arrowhead=normal] + + { + node [shape=record, fontsize="8", margin="0.04", height=0.2, color=gray] + srcjson [label="\{|\"|p|r|o|j|e|c|t|\"|:|\"|r|a|p|i|d|j|s|o|n|\"|,|\"|s|t|a|r|s|\"|:|1|0|\}"] + dstjson [label="\{|\"|p|r|o|j|e|c|t|\"|:|\"|r|a|p|i|d|j|s|o|n|\"|,|\"|s|t|a|r|s|\"|:|1|1|\}"] + } + + { + node [shape="box", style="filled", fillcolor="gray95"] + Document2 [label="(Modified) Document"] + Writer + } + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Document" + style=filled + fillcolor=gray95 + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + root [label="{object|}", fillcolor=3] + + { + project [label="{string|\"project\"}", fillcolor=5] + rapidjson [label="{string|\"rapidjson\"}", fillcolor=5] + stars [label="{string|\"stars\"}", fillcolor=5] + ten [label="{number|10}", fillcolor=6] + } + + edge [arrowhead=vee] + root -> { project; stars } + + edge [arrowhead="none"] + project -> rapidjson + stars -> ten + } + + srcjson -> root [label=" Parse()", lhead="cluster1"] + + ten -> Document2 [label=" Increase \"stars\"", ltail="cluster1" ] + Document2 -> Writer [label=" Traverse DOM by Accept()"] + Writer -> dstjson [label=" Output to StringBuffer"] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.png b/thirdparty/rapidjson-1.1.0/doc/diagram/simpledom.png new file mode 100644 index 0000000000000000000000000000000000000000..38d9c5dc126f9f28e799b877cb4737cdfebd787e GIT binary patch literal 43670 zcmce;RaBf^v@9A39^5UsySpX0ySux4B@ytXWlab|RD%B#{vC5#GIfha@c}rth=n`o(RMZk2Yp_qk8h-(d6r?pp5bFII!7Bmtj!WlaL#uZm_3yRG@htB3rIl9p zD+{i%543^rF^nMP0^wO8sNy%Evf1?BYy3C(4we260~P8Q&DGcc{si76LJkaVi%GSR zsQ%|AyW|J_|NV468srifytUkHt91DH=6H#nhnF{^x5=zT;O_cBwXLnKSit_WGt+k} zPgv5#ge*HJM}Cx3PUK;qS+|9w9+zq$iCXc`;bG=+b|SOQA?cW`loTqT`ADL;komQ0 zwJ+z55`EUS#xjh}p_P_5r#bGfst!&^ERESj<~&R1i0P>0iFhxP>Zb~(P?x!;EMp

d-WmRivHS`b^sdFqpGs`!Rk@*~d`T6-k9)`sUj$ zUzu;R~pz;~3=NhQij%v@a98yg$n#v)>4CFJA~5wIE3tB#v`%4ddHdU+rANk#l4=a`@dw>hESl>{esYP4}z3JA4o~hehpxMIwZr{`oBYmjf+)7}Wzwmwn;`g1S6ayxX{|Sac&X7+ zvPQ2xIb1=;_375$%iH_M#029(cH(=^UQZL*9W$FEIYky3pT^|WT$hy6vaB+2Q)rB= zVzSKD%xqRB-|&u-VDheNQ5-{_(8LHeJNc>{G;ehxwNmqA`MmzZK=LFebD8?`V1pbl zvEMg%nWN8(P9&&mp0WUW= z9;d%6s4A&ukqNjEx6cc?mf78!v*gI6slaJ@DK_e$G|8 z1zf7SfWQ8}4?AfV`kjN@__@?&-S1(MadX+cefK6m0x^ry>2boAk%~U;`_Os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4!aW5nPMxr{;7wTDltV zxAk9~O;d+|9~xB6Jfs=25LbFTZFVH@KI3WGSf8Wp?ODAcXMH|s&*^Zq`-zIV|BV0l z4U6qGg|brn#-1_9(<5vf#k9;37y&N<1)ckkzA>&>KhH&i#dL7;6v2{bpm$@o#EkA6fKX=TS-}lW%H$?$y zk?-Iu_6enuro)>L0|aY)+KsCMJ#v#seGhx!UAR(?w_sZFey}ep^;sHI|5VoG>$$>^ zvv<2vLl(n{gq`e&A={@n;9JO1f9w;QiN6qNmHIAt?Y7{x>al45279;a4PGxZo2h zB(cNTx#rkwWqMei#+^L>GW?F0s^jB~UZ>H1wUSm!(co9fGwozJNK)09kwgB{87*Xv zE(cB^LOA@~u-?@|?*h{FT;(60IN#=0=DJ?$b97@;wk*q$%{g8|2XE|TRdDB4QZIdP zS-Nn7%T}tg4i zjCrp%HNN1>vuXtCL#xKZw}UbUow_nwiNsQ-%w&?|nkr@6b!4=&rry8v=%d~_m8QSW z`5ZMn;Ed)~o{Mx}k~d7c;zF;lY#-i3ICiRPVQMmD?kn5hJml>WYJ0eo)z@Xvf07qn zU!|?m5c&lbcM{EBAsY)c#8D zD8YvUmvJi02Fsqz(xn4U>Hc5aWZIoJL6;SNsXDSvsQ&dHC>0P^muAgZS`zJ&Upser zpEwMaSKttgN)I(8+rKy-j*!%p8nE!W{O_0p_EB&cy2sC2`~UM;J_^ bNY2eb)1a^t{00J^Q}CyurmI?}Y!&=Jjhtmx literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.dot new file mode 100644 index 0000000000..138ddc381d --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.dot @@ -0,0 +1,58 @@ +digraph { + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.2 + penwidth=0.5 + + node [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + edge [fontname="Inconsolata, Consolas", fontsize=10] + + subgraph cluster1 { + margin="10,10" + labeljust="left" + label = "Document" + style=filled + fillcolor=gray95 + node [shape=Mrecord, style=filled, colorscheme=spectral7] + + root [label="{object|}", fillcolor=3] + + { + hello [label="{string|\"hello\"}", fillcolor=5] + t [label="{string|\"t\"}", fillcolor=5] + f [label="{string|\"f\"}", fillcolor=5] + n [label="{string|\"n\"}", fillcolor=5] + i [label="{string|\"i\"}", fillcolor=5] + pi [label="{string|\"pi\"}", fillcolor=5] + a [label="{string|\"a\"}", fillcolor=5] + + world [label="{string|\"world\"}", fillcolor=5] + true [label="{true|}", fillcolor=7] + false [label="{false|}", fillcolor=2] + null [label="{null|}", fillcolor=1] + i1 [label="{number|123}", fillcolor=6] + pi1 [label="{number|3.1416}", fillcolor=6] + array [label="{array|size=4}", fillcolor=4] + + a1 [label="{number|1}", fillcolor=6] + a2 [label="{number|2}", fillcolor=6] + a3 [label="{number|3}", fillcolor=6] + a4 [label="{number|4}", fillcolor=6] + } + + edge [arrowhead=vee] + root -> { hello; t; f; n; i; pi; a } + array -> { a1; a2; a3; a4 } + + edge [arrowhead=none] + hello -> world + t -> true + f -> false + n -> null + i -> i1 + pi -> pi1 + a -> array + } +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.png b/thirdparty/rapidjson-1.1.0/doc/diagram/tutorial.png new file mode 100644 index 0000000000000000000000000000000000000000..8a12924acdd72a9c1b99c0a48a201b936f3557f4 GIT binary patch literal 44634 zcmbTebyOTp_b!SCw?L5K5H!KvA-HP-!3n|Loxuaag1fuBI|N8@cbCE4VSwA@`_AvY z?^)}vb?*Ix1>I9!UA6VuPwgQ@NkI|~`7JUO6cn1Yl$Z(>6ig2k6toiJE8vc1yaOxn z3)(?N@*`CF2+bKMR9x}pipOiR@aHG$W4nYUYL_PO8*t3<@yPMWkhh7=^-&6! z4eRna%sWJAax%C8A52V`kHUzEzMYiJe6**>Uyd~p|Mkf`Y)k`7_Wk{|YEas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tX-)?Hl? zn#|^&+w-lp-c3+aFs-T#nxu+Mktgh*@6&wm4sYQ_Ru z$_UC#+5XR~pdR|S+?(vaa)X`EzpdO-GSDVPIPsCdZvXqLlO(3G=Y*Ch{?#7(5ug|K zAl)7R9v%!pMEX{$bL1bx`@dp7KLVZ08MtimkE(%%X$%n2=h0i!@!#kE+}67Tx-n7O gh5uhyfkk+UWj;EVf|_o7eg*s~$*DgomNg6dKPBaN@Bjb+ literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.dot b/thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.dot new file mode 100644 index 0000000000..1492a8a7af --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.dot @@ -0,0 +1,73 @@ +digraph { + rankdir=LR + compound=true + fontname="Inconsolata, Consolas" + fontsize=10 + margin="0,0" + ranksep=0.3 + nodesep=0.15 + penwidth=0.5 + colorscheme=spectral7 + + node [shape=box, fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5, style=filled, fillcolor=white] + edge [fontname="Inconsolata, Consolas", fontsize=10, penwidth=0.5] + + subgraph cluster0 { + style=filled + fillcolor=4 + + Encoding [label="<>\nEncoding"] + + edge [arrowtail=onormal, dir=back] + Encoding -> { UTF8; UTF16; UTF32; ASCII; AutoUTF } + UTF16 -> { UTF16LE; UTF16BE } + UTF32 -> { UTF32LE; UTF32BE } + } + + subgraph cluster1 { + style=filled + fillcolor=5 + + Stream [label="<>\nStream"] + InputByteStream [label="<>\nInputByteStream"] + OutputByteStream [label="<>\nOutputByteStream"] + + edge [arrowtail=onormal, dir=back] + Stream -> { + StringStream; InsituStringStream; StringBuffer; + EncodedInputStream; EncodedOutputStream; + AutoUTFInputStream; AutoUTFOutputStream + InputByteStream; OutputByteStream + } + + InputByteStream -> { MemoryStream; FlieReadStream } + OutputByteStream -> { MemoryBuffer; FileWriteStream } + } + + subgraph cluster2 { + style=filled + fillcolor=3 + + Allocator [label="<>\nAllocator"] + + edge [arrowtail=onormal, dir=back] + Allocator -> { CrtAllocator; MemoryPoolAllocator } + } + + { + edge [arrowtail=odiamond, arrowhead=vee, dir=both] + EncodedInputStream -> InputByteStream + EncodedOutputStream -> OutputByteStream + AutoUTFInputStream -> InputByteStream + AutoUTFOutputStream -> OutputByteStream + MemoryPoolAllocator -> Allocator [label="base", tailport=s] + } + + { + edge [arrowhead=vee, style=dashed] + AutoUTFInputStream -> AutoUTF + AutoUTFOutputStream -> AutoUTF + } + + //UTF32LE -> Stream [style=invis] +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.png b/thirdparty/rapidjson-1.1.0/doc/diagram/utilityclass.png new file mode 100644 index 0000000000000000000000000000000000000000..ce029a4d0670e0a358e3bdb8c030083f67b1ffcd GIT binary patch literal 99993 zcmZU51yojB7cC%4Nh?T5hje#$gLFxEcXxwygOniMASEpwN|!VOBHa!0_UFA<|M%V< zjH_!s;dFVm6q7dXtu z?&=NJng%4$7({=50;d_ zqDLbeR?`2^Pl}{3-2eO&)|ygKCV&6S6)Zv=)W1JXe9&(t8y^tS{u=RrnAiNfxABj@<^UdP?7r>Ryw^dNk|1-7^Yq;=Ba+MN`K^On(i9oy{ zD;lT6_h4SH3tC())5J>2_b$6LO2w~<)$wurMIm3yl@yH_{gd$^h9<956YE`F^%8f_ zTggr}nA9qPBpV(A=|(%x`I}e6iGqwU>XmQeU2U|71A@YWHjkhDo}*4bSQ0W4MY*7N zA!o;W$*m*-#pJ6#JB6(=coMj*=4kcEAK6mLpwO>Je<0Iyv7@|&%-WumzZJ>8RH94# zpLzAqKm(7Hi2cJjIf%jJP%ymfCi}bSUKn5wDdlFw{%5L%!BorX zvW7|h9lIa{E28kOJo0}QE*LCaMyokW;@>gw$f<{|z*IOqgf!wkLU9vVX^_DZ!;)6UI7!qJV6b0`?Wj(uSB*+TSsK1#sy_{$TUp zfb5ime=XWP82N)y>Q7j8W`hO($PAuzL~!+Jt()0uhL%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W)PZnq2Z`IyWVpLxdT^(%ncKj=;{Jb z*msl7lzkjwIO4BDpPQ4Z{6W)APRtN6Ne) zFJ5bfWQe;j6V>9s3tSRJ6+2HG0Ui4M-1?)q;~WL-bgdz3Y;r{q2dQ)r&|za7=6)Fy zDMfyIvEL|umGslCnqFx&k>{ncjtaK2!oDyBhk{K-r_-_Jooh$*tvBPFS3Lb8uU@=ul$^x9x`^`+s;!Bj+~@j!G?q23 zVH2}6laX^8X&hd}47vUqo-d>zqpsr?u&ewaWjC&{Ai?Y4AF>V-nHh)gf{u<;ssgA6 zWC*NyD_OX7YhCCrqI7dRu`?g`$foVCR(z0zTD$ByC$?lMMXKTS&chizhJyPiyJ%SI{ z-6*Jne(_E(mRRpu=Q?v^K{ULe=J0!93Li4HbZ)}P3#xtfqf{JGg4HR0cM4xQL1gN3 z@OYInS{+q*UfbwurV&f>aBeJ`TfNu?n*tz(c2T|P4Kf=u(q5`!@_PBV7?XVaF&sB_ zeaxRP!IRsyZ3q;_l8rGihWlNT$oOmembd^*dMw+F|LFtDBU=Xti>{}y!Yx{fX z;RxOyH2reOS~|NQ`jAAL(f$arXDS8)!rSwTHN)h_slRk$qw JR@TJ(e*o()o2UQ) literal 0 HcmV?d00001 diff --git a/thirdparty/rapidjson-1.1.0/doc/dom.md b/thirdparty/rapidjson-1.1.0/doc/dom.md new file mode 100644 index 0000000000..6c541fe93c --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/dom.md @@ -0,0 +1,280 @@ +# DOM + +Document Object Model(DOM) is an in-memory representation of JSON for query and manipulation. The basic usage of DOM is described in [Tutorial](doc/tutorial.md). This section will describe some details and more advanced usages. + +[TOC] + +# Template {#Template} + +In the tutorial, `Value` and `Document` was used. Similarly to `std::string`, these are actually `typedef` of template classes: + +~~~~~~~~~~cpp +namespace rapidjson { + +template > +class GenericValue { + // ... +}; + +template > +class GenericDocument : public GenericValue { + // ... +}; + +typedef GenericValue > Value; +typedef GenericDocument > Document; + +} // namespace rapidjson +~~~~~~~~~~ + +User can customize these template parameters. + +## Encoding {#Encoding} + +The `Encoding` parameter specifies the encoding of JSON String value in memory. Possible options are `UTF8`, `UTF16`, `UTF32`. Note that, these 3 types are also template class. `UTF8<>` is `UTF8`, which means using char to store the characters. You may refer to [Encoding](doc/encoding.md) for details. + +Suppose a Windows application would query localization strings stored in JSON files. Unicode-enabled functions in Windows use UTF-16 (wide character) encoding. No matter what encoding was used in JSON files, we can store the strings in UTF-16 in memory. + +~~~~~~~~~~cpp +using namespace rapidjson; + +typedef GenericDocument > WDocument; +typedef GenericValue > WValue; + +FILE* fp = fopen("localization.json", "rb"); // non-Windows use "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +AutoUTFInputStream eis(bis); // wraps bis into eis + +WDocument d; +d.ParseStream<0, AutoUTF >(eis); + +const WValue locale(L"ja"); // Japanese + +MessageBoxW(hWnd, d[locale].GetString(), L"Test", MB_OK); +~~~~~~~~~~ + +## Allocator {#Allocator} + +The `Allocator` defines which allocator class is used when allocating/deallocating memory for `Document`/`Value`. `Document` owns, or references to an `Allocator` instance. On the other hand, `Value` does not do so, in order to reduce memory consumption. + +The default allocator used in `GenericDocument` is `MemoryPoolAllocator`. This allocator actually allocate memory sequentially, and cannot deallocate one by one. This is very suitable when parsing a JSON into a DOM tree. + +Another allocator is `CrtAllocator`, of which CRT is short for C RunTime library. This allocator simply calls the standard `malloc()`/`realloc()`/`free()`. When there is a lot of add and remove operations, this allocator may be preferred. But this allocator is far less efficient than `MemoryPoolAllocator`. + +# Parsing {#Parsing} + +`Document` provides several functions for parsing. In below, (1) is the fundamental function, while the others are helpers which call (1). + +~~~~~~~~~~cpp +using namespace rapidjson; + +// (1) Fundamental +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (2) Using the same Encoding for stream +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (3) Using default parse flags +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (4) In situ parsing +template +GenericDocument& GenericDocument::ParseInsitu(Ch* str); + +// (5) In situ parsing, using default parse flags +GenericDocument& GenericDocument::ParseInsitu(Ch* str); + +// (6) Normal parsing of a string +template +GenericDocument& GenericDocument::Parse(const Ch* str); + +// (7) Normal parsing of a string, using same Encoding of Document +template +GenericDocument& GenericDocument::Parse(const Ch* str); + +// (8) Normal parsing of a string, using default parse flags +GenericDocument& GenericDocument::Parse(const Ch* str); +~~~~~~~~~~ + +The examples of [tutorial](doc/tutorial.md) uses (8) for normal parsing of string. The examples of [stream](doc/stream.md) uses the first three. *In situ* parsing will be described soon. + +The `parseFlags` are combination of the following bit-flags: + +Parse flags | Meaning +------------------------------|----------------------------------- +`kParseNoFlags` | No flag is set. +`kParseDefaultFlags` | Default parse flags. It is equal to macro `RAPIDJSON_PARSE_DEFAULT_FLAGS`, which is defined as `kParseNoFlags`. +`kParseInsituFlag` | In-situ(destructive) parsing. +`kParseValidateEncodingFlag` | Validate encoding of JSON strings. +`kParseIterativeFlag` | Iterative(constant complexity in terms of function call stack size) parsing. +`kParseStopWhenDoneFlag` | After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate `kParseErrorDocumentRootNotSingular` error. Using this flag for parsing multiple JSONs in the same stream. +`kParseFullPrecisionFlag` | Parse number in full precision (slower). If this flag is not set, the normal precision (faster) is used. Normal precision has maximum 3 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) error. +`kParseCommentsFlag` | Allow one-line `// ...` and multi-line `/* ... */` comments (relaxed JSON syntax). +`kParseNumbersAsStringsFlag` | Parse numerical type values as strings. +`kParseTrailingCommasFlag` | Allow trailing commas at the end of objects and arrays (relaxed JSON syntax). +`kParseNanAndInfFlag` | Allow parsing `NaN`, `Inf`, `Infinity`, `-Inf` and `-Infinity` as `double` values (relaxed JSON syntax). + +By using a non-type template parameter, instead of a function parameter, C++ compiler can generate code which is optimized for specified combinations, improving speed, and reducing code size (if only using a single specialization). The downside is the flags needed to be determined in compile-time. + +The `SourceEncoding` parameter defines what encoding is in the stream. This can be differed to the `Encoding` of the `Document`. See [Transcoding and Validation](#TranscodingAndValidation) section for details. + +And the `InputStream` is type of input stream. + +## Parse Error {#ParseError} + +When the parse processing succeeded, the `Document` contains the parse results. When there is an error, the original DOM is *unchanged*. And the error state of parsing can be obtained by `bool HasParseError()`, `ParseErrorCode GetParseError()` and `size_t GetParseOffset()`. + +Parse Error Code | Description +--------------------------------------------|--------------------------------------------------- +`kParseErrorNone` | No error. +`kParseErrorDocumentEmpty` | The document is empty. +`kParseErrorDocumentRootNotSingular` | The document root must not follow by other values. +`kParseErrorValueInvalid` | Invalid value. +`kParseErrorObjectMissName` | Missing a name for object member. +`kParseErrorObjectMissColon` | Missing a colon after a name of object member. +`kParseErrorObjectMissCommaOrCurlyBracket` | Missing a comma or `}` after an object member. +`kParseErrorArrayMissCommaOrSquareBracket` | Missing a comma or `]` after an array element. +`kParseErrorStringUnicodeEscapeInvalidHex` | Incorrect hex digit after `\\u` escape in string. +`kParseErrorStringUnicodeSurrogateInvalid` | The surrogate pair in string is invalid. +`kParseErrorStringEscapeInvalid` | Invalid escape character in string. +`kParseErrorStringMissQuotationMark` | Missing a closing quotation mark in string. +`kParseErrorStringInvalidEncoding` | Invalid encoding in string. +`kParseErrorNumberTooBig` | Number too big to be stored in `double`. +`kParseErrorNumberMissFraction` | Miss fraction part in number. +`kParseErrorNumberMissExponent` | Miss exponent in number. + +The offset of error is defined as the character number from beginning of stream. Currently RapidJSON does not keep track of line number. + +To get an error message, RapidJSON provided a English messages in `rapidjson/error/en.h`. User can customize it for other locales, or use a custom localization system. + +Here shows an example of parse error handling. + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" + +// ... +Document d; +if (d.Parse(json).HasParseError()) { + fprintf(stderr, "\nError(offset %u): %s\n", + (unsigned)d.GetErrorOffset(), + GetParseError_En(d.GetParseError())); + // ... +} +~~~~~~~~~~ + +## In Situ Parsing {#InSituParsing} + +From [Wikipedia](http://en.wikipedia.org/wiki/In_situ): + +> *In situ* ... is a Latin phrase that translates literally to "on site" or "in position". It means "locally", "on site", "on the premises" or "in place" to describe an event where it takes place, and is used in many different contexts. +> ... +> (In computer science) An algorithm is said to be an in situ algorithm, or in-place algorithm, if the extra amount of memory required to execute the algorithm is O(1), that is, does not exceed a constant no matter how large the input. For example, heapsort is an in situ sorting algorithm. + +In normal parsing process, a large overhead is to decode JSON strings and copy them to other buffers. *In situ* parsing decodes those JSON string at the place where it is stored. It is possible in JSON because the length of decoded string is always shorter than or equal to the one in JSON. In this context, decoding a JSON string means to process the escapes, such as `"\n"`, `"\u1234"`, etc., and add a null terminator (`'\0'`)at the end of string. + +The following diagrams compare normal and *in situ* parsing. The JSON string values contain pointers to the decoded string. + +![normal parsing](diagram/normalparsing.png) + +In normal parsing, the decoded string are copied to freshly allocated buffers. `"\\n"` (2 characters) is decoded as `"\n"` (1 character). `"\\u0073"` (6 characters) is decoded as `"s"` (1 character). + +![instiu parsing](diagram/insituparsing.png) + +*In situ* parsing just modified the original JSON. Updated characters are highlighted in the diagram. If the JSON string does not contain escape character, such as `"msg"`, the parsing process merely replace the closing double quotation mark with a null character. + +Since *in situ* parsing modify the input, the parsing API needs `char*` instead of `const char*`. + +~~~~~~~~~~cpp +// Read whole file into a buffer +FILE* fp = fopen("test.json", "r"); +fseek(fp, 0, SEEK_END); +size_t filesize = (size_t)ftell(fp); +fseek(fp, 0, SEEK_SET); +char* buffer = (char*)malloc(filesize + 1); +size_t readLength = fread(buffer, 1, filesize, fp); +buffer[readLength] = '\0'; +fclose(fp); + +// In situ parsing the buffer into d, buffer will also be modified +Document d; +d.ParseInsitu(buffer); + +// Query/manipulate the DOM here... + +free(buffer); +// Note: At this point, d may have dangling pointers pointed to the deallocated buffer. +~~~~~~~~~~ + +The JSON strings are marked as const-string. But they may not be really "constant". The life cycle of it depends on the JSON buffer. + +In situ parsing minimizes allocation overheads and memory copying. Generally this improves cache coherence, which is an important factor of performance in modern computer. + +There are some limitations of *in situ* parsing: + +1. The whole JSON is in memory. +2. The source encoding in stream and target encoding in document must be the same. +3. The buffer need to be retained until the document is no longer used. +4. If the DOM need to be used for long period after parsing, and there are few JSON strings in the DOM, retaining the buffer may be a memory waste. + +*In situ* parsing is mostly suitable for short-term JSON that only need to be processed once, and then be released from memory. In practice, these situation is very common, for example, deserializing JSON to C++ objects, processing web requests represented in JSON, etc. + +## Transcoding and Validation {#TranscodingAndValidation} + +RapidJSON supports conversion between Unicode formats (officially termed UCS Transformation Format) internally. During DOM parsing, the source encoding of the stream can be different from the encoding of the DOM. For example, the source stream contains a UTF-8 JSON, while the DOM is using UTF-16 encoding. There is an example code in [EncodedInputStream](doc/stream.md). + +When writing a JSON from DOM to output stream, transcoding can also be used. An example is in [EncodedOutputStream](doc/stream.md). + +During transcoding, the source string is decoded to into Unicode code points, and then the code points are encoded in the target format. During decoding, it will validate the byte sequence in the source string. If it is not a valid sequence, the parser will be stopped with `kParseErrorStringInvalidEncoding` error. + +When the source encoding of stream is the same as encoding of DOM, by default, the parser will *not* validate the sequence. User may use `kParseValidateEncodingFlag` to force validation. + +# Techniques {#Techniques} + +Some techniques about using DOM API is discussed here. + +## DOM as SAX Event Publisher + +In RapidJSON, stringifying a DOM with `Writer` may be look a little bit weired. + +~~~~~~~~~~cpp +// ... +Writer writer(buffer); +d.Accept(writer); +~~~~~~~~~~ + +Actually, `Value::Accept()` is responsible for publishing SAX events about the value to the handler. With this design, `Value` and `Writer` are decoupled. `Value` can generate SAX events, and `Writer` can handle those events. + +User may create custom handlers for transforming the DOM into other formats. For example, a handler which converts the DOM into XML. + +For more about SAX events and handler, please refer to [SAX](doc/sax.md). + +## User Buffer {#UserBuffer} + +Some applications may try to avoid memory allocations whenever possible. + +`MemoryPoolAllocator` can support this by letting user to provide a buffer. The buffer can be on the program stack, or a "scratch buffer" which is statically allocated (a static/global array) for storing temporary data. + +`MemoryPoolAllocator` will use the user buffer to satisfy allocations. When the user buffer is used up, it will allocate a chunk of memory from the base allocator (by default the `CrtAllocator`). + +Here is an example of using stack memory. The first allocator is for storing values, while the second allocator is for storing temporary data during parsing. + +~~~~~~~~~~cpp +typedef GenericDocument, MemoryPoolAllocator<>, MemoryPoolAllocator<>> DocumentType; +char valueBuffer[4096]; +char parseBuffer[1024]; +MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer)); +MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer)); +DocumentType d(&valueAllocator, sizeof(parseBuffer), &parseAllocator); +d.Parse(json); +~~~~~~~~~~ + +If the total size of allocation is less than 4096+1024 bytes during parsing, this code does not invoke any heap allocation (via `new` or `malloc()`) at all. + +User can query the current memory consumption in bytes via `MemoryPoolAllocator::Size()`. And then user can determine a suitable size of user buffer. diff --git a/thirdparty/rapidjson-1.1.0/doc/dom.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/dom.zh-cn.md new file mode 100644 index 0000000000..d93f6036b6 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/dom.zh-cn.md @@ -0,0 +1,284 @@ +# DOM + +文档对象模型(Document Object Model, DOM)是一种罝于内存中的 JSON 表示方式,以供查询及操作。我们己于 [教程](doc/tutorial.zh-cn.md) 中介绍了 DOM 的基本用法,本节将讲述一些细节及高级用法。 + +[TOC] + +# 模板 {#Template} + +教程中使用了 `Value` 和 `Document` 类型。与 `std::string` 相似,这些类型其实是两个模板类的 `typedef`: + +~~~~~~~~~~cpp +namespace rapidjson { + +template > +class GenericValue { + // ... +}; + +template > +class GenericDocument : public GenericValue { + // ... +}; + +typedef GenericValue > Value; +typedef GenericDocument > Document; + +} // namespace rapidjson +~~~~~~~~~~ + +使用者可以自定义这些模板参数。 + +## 编码 {#Encoding} + +`Encoding` 参数指明在内存中的 JSON String 使用哪种编码。可行的选项有 `UTF8`、`UTF16`、`UTF32`。要注意这 3 个类型其实也是模板类。`UTF8<>` 等同 `UTF8`,这代表它使用 `char` 来存储字符串。更多细节可以参考 [编码](doc/encoding.zh-cn.md)。 + +这里是一个例子。假设一个 Windows 应用软件希望查询存储于 JSON 中的本地化字符串。Windows 中含 Unicode 的函数使用 UTF-16(宽字符)编码。无论 JSON 文件使用哪种编码,我们都可以把字符串以 UTF-16 形式存储在内存。 + +~~~~~~~~~~cpp +using namespace rapidjson; + +typedef GenericDocument > WDocument; +typedef GenericValue > WValue; + +FILE* fp = fopen("localization.json", "rb"); // 非 Windows 平台使用 "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +AutoUTFInputStream eis(bis); // 包装 bis 成 eis + +WDocument d; +d.ParseStream<0, AutoUTF >(eis); + +const WValue locale(L"ja"); // Japanese + +MessageBoxW(hWnd, d[locale].GetString(), L"Test", MB_OK); +~~~~~~~~~~ + +## 分配器 {#Allocator} + +`Allocator` 定义当 `Document`/`Value` 分配或释放内存时使用那个分配类。`Document` 拥有或引用到一个 `Allocator` 实例。而为了节省内存,`Value` 没有这么做。 + +`GenericDocument` 的缺省分配器是 `MemoryPoolAllocator`。此分配器实际上会顺序地分配内存,并且不能逐一释放。当要解析一个 JSON 并生成 DOM,这种分配器是非常合适的。 + +RapidJSON 还提供另一个分配器 `CrtAllocator`,当中 CRT 是 C 运行库(C RunTime library)的缩写。此分配器简单地读用标准的 `malloc()`/`realloc()`/`free()`。当我们需要许多增减操作,这种分配器会更为适合。然而这种分配器远远比 `MemoryPoolAllocator` 低效。 + +# 解析 {#Parsing} + +`Document` 提供几个解析函数。以下的 (1) 是根本的函数,其他都是调用 (1) 的协助函数。 + +~~~~~~~~~~cpp +using namespace rapidjson; + +// (1) 根本 +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (2) 使用流的编码 +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (3) 使用缺省标志 +template +GenericDocument& GenericDocument::ParseStream(InputStream& is); + +// (4) 原位解析 +template +GenericDocument& GenericDocument::ParseInsitu(Ch* str); + +// (5) 原位解析,使用缺省标志 +GenericDocument& GenericDocument::ParseInsitu(Ch* str); + +// (6) 正常解析一个字符串 +template +GenericDocument& GenericDocument::Parse(const Ch* str); + +// (7) 正常解析一个字符串,使用 Document 的编码 +template +GenericDocument& GenericDocument::Parse(const Ch* str); + +// (8) 正常解析一个字符串,使用缺省标志 +GenericDocument& GenericDocument::Parse(const Ch* str); +~~~~~~~~~~ + +[教程](doc/tutorial.zh-cn.md) 中的例使用 (8) 去正常解析字符串。而 [流](doc/stream.zh-cn.md) 的例子使用前 3 个函数。我们将稍后介绍原位(*In situ*) 解析。 + +`parseFlags` 是以下位标置的组合: + +解析位标志 | 意义 +------------------------------|----------------------------------- +`kParseNoFlags` | 没有任何标志。 +`kParseDefaultFlags` | 缺省的解析选项。它等于 `RAPIDJSON_PARSE_DEFAULT_FLAGS` 宏,此宏定义为 `kParseNoFlags`。 +`kParseInsituFlag` | 原位(破坏性)解析。 +`kParseValidateEncodingFlag` | 校验 JSON 字符串的编码。 +`kParseIterativeFlag` | 迭代式(调用堆栈大小为常数复杂度)解析。 +`kParseStopWhenDoneFlag` | 当从流解析了一个完整的 JSON 根节点之后,停止继续处理余下的流。当使用了此标志,解析器便不会产生 `kParseErrorDocumentRootNotSingular` 错误。可使用本标志去解析同一个流里的多个 JSON。 +`kParseFullPrecisionFlag` | 使用完整的精确度去解析数字(较慢)。如不设置此标节,则会使用正常的精确度(较快)。正常精确度会有最多 3 个 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) 的误差。 +`kParseCommentsFlag` | 容许单行 `// ...` 及多行 `/* ... */` 注释(放宽的 JSON 语法)。 +`kParseNumbersAsStringsFlag` | 把数字类型解析成字符串。 +`kParseTrailingCommasFlag` | 容许在对象和数组结束前含有逗号(放宽的 JSON 语法)。 +`kParseNanAndInfFlag` | 容许 `NaN`、`Inf`、`Infinity`、`-Inf` 及 `-Infinity` 作为 `double` 值(放宽的 JSON 语法)。 + +由于使用了非类型模板参数,而不是函数参数,C++ 编译器能为个别组合生成代码,以改善性能及减少代码尺寸(当只用单种特化)。缺点是需要在编译期决定标志。 + +`SourceEncoding` 参数定义流使用了什么编码。这与 `Document` 的 `Encoding` 不相同。细节可参考 [转码和校验](#TranscodingAndValidation) 一节。 + +此外 `InputStream` 是输入流的类型。 + +## 解析错误 {#ParseError} + +当解析过程顺利完成,`Document` 便会含有解析结果。当过程出现错误,原来的 DOM 会 * 维持不便 *。可使用 `bool HasParseError()`、`ParseErrorCode GetParseError()` 及 `size_t GetParseOffset()` 获取解析的错误状态。 + +解析错误代号 | 描述 +--------------------------------------------|--------------------------------------------------- +`kParseErrorNone` | 无错误。 +`kParseErrorDocumentEmpty` | 文档是空的。 +`kParseErrorDocumentRootNotSingular` | 文档的根后面不能有其它值。 +`kParseErrorValueInvalid` | 不合法的值。 +`kParseErrorObjectMissName` | Object 成员缺少名字。 +`kParseErrorObjectMissColon` | Object 成员名字后缺少冒号。 +`kParseErrorObjectMissCommaOrCurlyBracket` | Object 成员后缺少逗号或 `}`。 +`kParseErrorArrayMissCommaOrSquareBracket` | Array 元素后缺少逗号或 `]` 。 +`kParseErrorStringUnicodeEscapeInvalidHex` | String 中的 `\\u` 转义符后含非十六进位数字。 +`kParseErrorStringUnicodeSurrogateInvalid` | String 中的代理对(surrogate pair)不合法。 +`kParseErrorStringEscapeInvalid` | String 含非法转义字符。 +`kParseErrorStringMissQuotationMark` | String 缺少关闭引号。 +`kParseErrorStringInvalidEncoding` | String 含非法编码。 +`kParseErrorNumberTooBig` | Number 的值太大,不能存储于 `double`。 +`kParseErrorNumberMissFraction` | Number 缺少了小数部分。 +`kParseErrorNumberMissExponent` | Number 缺少了指数。 + +错误的偏移量定义为从流开始至错误处的字符数量。目前 RapidJSON 不记录错误行号。 + +要取得错误讯息,RapidJSON 在 `rapidjson/error/en.h` 中提供了英文错误讯息。使用者可以修改它用于其他语言环境,或使用一个自定义的本地化系统。 + +以下是一个处理错误的例子。 + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" + +// ... +Document d; +if (d.Parse(json).HasParseError()) { + fprintf(stderr, "\nError(offset %u): %s\n", + (unsigned)d.GetErrorOffset(), + GetParseError_En(d.GetParseErrorCode())); + // ... +} +~~~~~~~~~~ + +## 原位解析 {#InSituParsing} + +根据 [维基百科](http://en.wikipedia.org/wiki/In_situ): + +> *In situ* ... is a Latin phrase that translates literally to "on site" or "in position". It means "locally", "on site", "on the premises" or "in place" to describe an event where it takes place, and is used in many different contexts. +> ... +> (In computer science) An algorithm is said to be an in situ algorithm, or in-place algorithm, if the extra amount of memory required to execute the algorithm is O(1), that is, does not exceed a constant no matter how large the input. For example, heapsort is an in situ sorting algorithm. + +> 翻译:*In situ*……是一个拉丁文片语,字面上的意思是指「现场」、「在位置」。在许多不同语境中,它描述一个事件发生的位置,意指「本地」、「现场」、「在处所」、「就位」。 +> …… +> (在计算机科学中)一个算法若称为原位算法,或在位算法,是指执行该算法所需的额外内存空间是 O(1) 的,换句话说,无论输入大小都只需要常数空间。例如,堆排序是一个原位排序算法。 + +在正常的解析过程中,对 JSON string 解码并复制至其他缓冲区是一个很大的开销。原位解析(*in situ* parsing)把这些 JSON string 直接解码于它原来存储的地方。由于解码后的 string 长度总是短于或等于原来储存于 JSON 的 string,所以这是可行的。在这个语境下,对 JSON string 进行解码是指处理转义符,如 `"\n"`、`"\u1234"` 等,以及在 string 末端加入空终止符号 (`'\0'`)。 + +以下的图比较正常及原位解析。JSON string 值包含指向解码后的字符串。 + +![正常解析](diagram/normalparsing.png) + +在正常解析中,解码后的字符串被复制至全新分配的缓冲区中。`"\\n"`(2 个字符)被解码成 `"\n"`(1 个字符)。`"\\u0073"`(6 个字符)被解码成 `"s"`(1 个字符)。 + +![原位解析](diagram/insituparsing.png) + +原位解析直接修改了原来的 JSON。图中高亮了被更新的字符。若 JSON string 不含转义符,例如 `"msg"`,那么解析过程仅仅是以空字符代替结束双引号。 + +由于原位解析修改了输入,其解析 API 需要 `char*` 而非 `const char*`。 + +~~~~~~~~~~cpp +// 把整个文件读入 buffer +FILE* fp = fopen("test.json", "r"); +fseek(fp, 0, SEEK_END); +size_t filesize = (size_t)ftell(fp); +fseek(fp, 0, SEEK_SET); +char* buffer = (char*)malloc(filesize + 1); +size_t readLength = fread(buffer, 1, filesize, fp); +buffer[readLength] = '\0'; +fclose(fp); + +// 原位解析 buffer 至 d,buffer 内容会被修改。 +Document d; +d.ParseInsitu(buffer); + +// 在此查询、修改 DOM…… + +free(buffer); +// 注意:在这个位置,d 可能含有指向已被释放的 buffer 的悬空指针 +~~~~~~~~~~ + +JSON string 会被打上 const-string 的标志。但它们可能并非真正的「常数」。它的生命周期取决于存储 JSON 的缓冲区。 + +原位解析把分配开销及内存复制减至最小。通常这样做能改善缓存一致性,而这对现代计算机来说是一个重要的性能因素。 + +原位解析有以下限制: + +1. 整个 JSON 须存储在内存之中。 +2. 流的来源缓码与文档的目标编码必须相同。 +3. 需要保留缓冲区,直至文档不再被使用。 +4. 若 DOM 需要在解析后被长期使用,而 DOM 内只有很少 JSON string,保留缓冲区可能造成内存浪费。 + +原位解析最适合用于短期的、用完即弃的 JSON。实际应用中,这些场合是非常普遍的,例如反序列化 JSON 至 C++ 对象、处理以 JSON 表示的 web 请求等。 + +## 转码与校验 {#TranscodingAndValidation} + +RapidJSON 内部支持不同 Unicode 格式(正式的术语是 UCS 变换格式)间的转换。在 DOM 解析时,流的来源编码与 DOM 的编码可以不同。例如,来源流可能含有 UTF-8 的 JSON,而 DOM 则使用 UTF-16 编码。在 [EncodedInputStream](doc/stream.zh-cn.md) 一节里有一个例子。 + +当从 DOM 输出一个 JSON 至输出流之时,也可以使用转码功能。在 [EncodedOutputStream](doc/stream.zh-cn.md) 一节里有一个例子。 + +在转码过程中,会把来源 string 解码成 Unicode 码点,然后把码点编码成目标格式。在解码时,它会校验来源 string 的字节序列是否合法。若遇上非合法序列,解析器会停止并返回 `kParseErrorStringInvalidEncoding` 错误。 + +当来源编码与 DOM 的编码相同,解析器缺省地 * 不会 * 校验序列。使用者可开启 `kParseValidateEncodingFlag` 去强制校验。 + +# 技巧 {#Techniques} + +这里讨论一些 DOM API 的使用技巧。 + +## 把 DOM 作为 SAX 事件发表者 + +在 RapidJSON 中,利用 `Writer` 把 DOM 生成 JSON 的做法,看来有点奇怪。 + +~~~~~~~~~~cpp +// ... +Writer writer(buffer); +d.Accept(writer); +~~~~~~~~~~ + +实际上,`Value::Accept()` 是负责发布该值相关的 SAX 事件至处理器的。通过这个设计,`Value` 及 `Writer` 解除了偶合。`Value` 可生成 SAX 事件,而 `Writer` 则可以处理这些事件。 + +使用者可以创建自定义的处理器,去把 DOM 转换成其它格式。例如,一个把 DOM 转换成 XML 的处理器。 + +要知道更多关于 SAX 事件与处理器,可参阅 [SAX](doc/sax.zh-cn.md)。 + +## 使用者缓冲区 {#UserBuffer} + +许多应用软件可能需要尽量减少内存分配。 + +`MemoryPoolAllocator` 可以帮助这方面,它容许使用者提供一个缓冲区。该缓冲区可能置于程序堆栈,或是一个静态分配的「草稿缓冲区(scratch buffer)」(一个静态/全局的数组),用于储存临时数据。 + +`MemoryPoolAllocator` 会先用使用者缓冲区去解决分配请求。当使用者缓冲区用完,就会从基础分配器(缺省为 `CrtAllocator`)分配一块内存。 + +以下是使用堆栈内存的例子,第一个分配器用于存储值,第二个用于解析时的临时缓冲。 + +~~~~~~~~~~cpp +typedef GenericDocument, MemoryPoolAllocator<>, MemoryPoolAllocator<>> DocumentType; +char valueBuffer[4096]; +char parseBuffer[1024]; +MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer)); +MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer)); +DocumentType d(&valueAllocator, sizeof(parseBuffer), &parseAllocator); +d.Parse(json); +~~~~~~~~~~ + +若解析时分配总量少于 4096+1024 字节时,这段代码不会造成任何堆内存分配(经 `new` 或 `malloc()`)。 + +使用者可以通过 `MemoryPoolAllocator::Size()` 查询当前已分的内存大小。那么使用者可以拟定使用者缓冲区的合适大小。 diff --git a/thirdparty/rapidjson-1.1.0/doc/encoding.md b/thirdparty/rapidjson-1.1.0/doc/encoding.md new file mode 100644 index 0000000000..8f8ff7f45a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/encoding.md @@ -0,0 +1,146 @@ +# Encoding + +According to [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf), + +> (in Introduction) JSON text is a sequence of Unicode code points. + +The earlier [RFC4627](http://www.ietf.org/rfc/rfc4627.txt) stated that, + +> (in §3) JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. + +> (in §6) JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used. + +RapidJSON supports various encodings. It can also validate the encodings of JSON, and transconding JSON among encodings. All these features are implemented internally, without the need for external libraries (e.g. [ICU](http://site.icu-project.org/)). + +[TOC] + +# Unicode {#Unicode} +From [Unicode's official website](http://www.unicode.org/standard/WhatIsUnicode.html): +> Unicode provides a unique number for every character, +> no matter what the platform, +> no matter what the program, +> no matter what the language. + +Those unique numbers are called code points, which is in the range `0x0` to `0x10FFFF`. + +## Unicode Transformation Format {#UTF} + +There are various encodings for storing Unicode code points. These are called Unicode Transformation Format (UTF). RapidJSON supports the most commonly used UTFs, including + +* UTF-8: 8-bit variable-width encoding. It maps a code point to 1–4 bytes. +* UTF-16: 16-bit variable-width encoding. It maps a code point to 1–2 16-bit code units (i.e., 2–4 bytes). +* UTF-32: 32-bit fixed-width encoding. It directly maps a code point to a single 32-bit code unit (i.e. 4 bytes). + +For UTF-16 and UTF-32, the byte order (endianness) does matter. Within computer memory, they are often stored in the computer's endianness. However, when it is stored in file or transferred over network, we need to state the byte order of the byte sequence, either little-endian (LE) or big-endian (BE). + +RapidJSON provide these encodings via the structs in `rapidjson/encodings.h`: + +~~~~~~~~~~cpp +namespace rapidjson { + +template +struct UTF8; + +template +struct UTF16; + +template +struct UTF16LE; + +template +struct UTF16BE; + +template +struct UTF32; + +template +struct UTF32LE; + +template +struct UTF32BE; + +} // namespace rapidjson +~~~~~~~~~~ + +For processing text in memory, we normally use `UTF8`, `UTF16` or `UTF32`. For processing text via I/O, we may use `UTF8`, `UTF16LE`, `UTF16BE`, `UTF32LE` or `UTF32BE`. + +When using the DOM-style API, the `Encoding` template parameter in `GenericValue` and `GenericDocument` indicates the encoding to be used to represent JSON string in memory. So normally we will use `UTF8`, `UTF16` or `UTF32` for this template parameter. The choice depends on operating systems and other libraries that the application is using. For example, Windows API represents Unicode characters in UTF-16, while most Linux distributions and applications prefer UTF-8. + +Example of UTF-16 DOM declaration: + +~~~~~~~~~~cpp +typedef GenericDocument > WDocument; +typedef GenericValue > WValue; +~~~~~~~~~~ + +For a detail example, please check the example in [DOM's Encoding](doc/stream.md) section. + +## Character Type {#CharacterType} + +As shown in the declaration, each encoding has a `CharType` template parameter. Actually, it may be a little bit confusing, but each `CharType` stores a code unit, not a character (code point). As mentioned in previous section, a code point may be encoded to 1–4 code units for UTF-8. + +For `UTF16(LE|BE)`, `UTF32(LE|BE)`, the `CharType` must be integer type of at least 2 and 4 bytes respectively. + +Note that C++11 introduces `char16_t` and `char32_t`, which can be used for `UTF16` and `UTF32` respectively. + +## AutoUTF {#AutoUTF} + +Previous encodings are statically bound in compile-time. In other words, user must know exactly which encodings will be used in the memory or streams. However, sometimes we may need to read/write files of different encodings. The encoding needed to be decided in runtime. + +`AutoUTF` is an encoding designed for this purpose. It chooses which encoding to be used according to the input or output stream. Currently, it should be used with `EncodedInputStream` and `EncodedOutputStream`. + +## ASCII {#ASCII} + +Although the JSON standards did not mention about [ASCII](http://en.wikipedia.org/wiki/ASCII), sometimes we would like to write 7-bit ASCII JSON for applications that cannot handle UTF-8. Since any JSON can represent unicode characters in escaped sequence `\uXXXX`, JSON can always be encoded in ASCII. + +Here is an example for writing a UTF-8 DOM into ASCII: + +~~~~~~~~~~cpp +using namespace rapidjson; +Document d; // UTF8<> +// ... +StringBuffer buffer; +Writer > writer(buffer); +d.Accept(writer); +std::cout << buffer.GetString(); +~~~~~~~~~~ + +ASCII can be used in input stream. If the input stream contains bytes with values above 127, it will cause `kParseErrorStringInvalidEncoding` error. + +ASCII *cannot* be used in memory (encoding of `Document` or target encoding of `Reader`), as it cannot represent Unicode code points. + +# Validation & Transcoding {#ValidationTranscoding} + +When RapidJSON parses a JSON, it can validate the input JSON, whether it is a valid sequence of a specified encoding. This option can be turned on by adding `kParseValidateEncodingFlag` in `parseFlags` template parameter. + +If the input encoding and output encoding is different, `Reader` and `Writer` will automatically transcode (convert) the text. In this case, `kParseValidateEncodingFlag` is not necessary, as it must decode the input sequence. And if the sequence was unable to be decoded, it must be invalid. + +## Transcoder {#Transcoder} + +Although the encoding functions in RapidJSON are designed for JSON parsing/generation, user may abuse them for transcoding of non-JSON strings. + +Here is an example for transcoding a string from UTF-8 to UTF-16: + +~~~~~~~~~~cpp +#include "rapidjson/encodings.h" + +using namespace rapidjson; + +const char* s = "..."; // UTF-8 string +StringStream source(s); +GenericStringBuffer > target; + +bool hasError = false; +while (source.Peek() != '\0') + if (!Transcoder, UTF16<> >::Transcode(source, target)) { + hasError = true; + break; + } + +if (!hasError) { + const wchar_t* t = target.GetString(); + // ... +} +~~~~~~~~~~ + +You may also use `AutoUTF` and the associated streams for setting source/target encoding in runtime. diff --git a/thirdparty/rapidjson-1.1.0/doc/encoding.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/encoding.zh-cn.md new file mode 100644 index 0000000000..6816923559 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/encoding.zh-cn.md @@ -0,0 +1,152 @@ +# 编码 + +根据 [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf): + +> (in Introduction) JSON text is a sequence of Unicode code points. +> +> 翻译:JSON 文本是 Unicode 码点的序列。 + +较早的 [RFC4627](http://www.ietf.org/rfc/rfc4627.txt) 申明: + +> (in §3) JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. +> +> 翻译:JSON 文本应该以 Unicode 编码。缺省的编码为 UTF-8。 + +> (in §6) JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used. +> +> 翻译:JSON 可使用 UTF-8、UTF-16 或 UTF-18 表示。当 JSON 以 UTF-8 写入,该 JSON 是 8 位兼容的。当 JSON 以 UTF-16 或 UTF-32 写入,就必须使用二进制的内容传送编码。 + +RapidJSON 支持多种编码。它也能检查 JSON 的编码,以及在不同编码中进行转码。所有这些功能都是在内部实现,无需使用外部的程序库(如 [ICU](http://site.icu-project.org/))。 + +[TOC] + +# Unicode {#Unicode} +根据 [Unicode 的官方网站](http://www.unicode.org/standard/translations/t-chinese.html): +>Unicode 给每个字符提供了一个唯一的数字, +不论是什么平台、 +不论是什么程序、 +不论是什么语言。 + +这些唯一数字称为码点(code point),其范围介乎 `0x0` 至 `0x10FFFF` 之间。 + +## Unicode 转换格式 {#UTF} + +存储 Unicode 码点有多种编码方式。这些称为 Unicode 转换格式(Unicode Transformation Format, UTF)。RapidJSON 支持最常用的 UTF,包括: + +* UTF-8:8 位可变长度编码。它把一个码点映射至 1 至 4 个字节。 +* UTF-16:16 位可变长度编码。它把一个码点映射至 1 至 2 个 16 位编码单元(即 2 至 4 个字节)。 +* UTF-32:32 位固定长度编码。它直接把码点映射至单个 32 位编码单元(即 4 字节)。 + +对于 UTF-16 及 UTF-32 来说,字节序(endianness)是有影响的。在内存中,它们通常都是以该计算机的字节序来存储。然而,当要储存在文件中或在网上传输,我们需要指明字节序列的字节序,是小端(little endian, LE)还是大端(big-endian, BE)。 + +RapidJSON 通过 `rapidjson/encodings.h` 中的 struct 去提供各种编码: + +~~~~~~~~~~cpp +namespace rapidjson { + +template +struct UTF8; + +template +struct UTF16; + +template +struct UTF16LE; + +template +struct UTF16BE; + +template +struct UTF32; + +template +struct UTF32LE; + +template +struct UTF32BE; + +} // namespace rapidjson +~~~~~~~~~~ + +对于在内存中的文本,我们正常会使用 `UTF8`、`UTF16` 或 `UTF32`。对于处理经过 I/O 的文本,我们可使用 `UTF8`、`UTF16LE`、`UTF16BE`、`UTF32LE` 或 `UTF32BE`。 + +当使用 DOM 风格的 API,`GenericValue` 及 `GenericDocument` 里的 `Encoding` 模板参数是用于指明内存中存储的 JSON 字符串使用哪种编码。因此通常我们会在此参数中使用 `UTF8`、`UTF16` 或 `UTF32`。如何选择,视乎应用软件所使用的操作系统及其他程序库。例如,Windows API 使用 UTF-16 表示 Unicode 字符,而多数的 Linux 发行版本及应用软件则更喜欢 UTF-8。 + +使用 UTF-16 的 DOM 声明例子: + +~~~~~~~~~~cpp +typedef GenericDocument > WDocument; +typedef GenericValue > WValue; +~~~~~~~~~~ + +可以在 [DOM's Encoding](doc/stream.zh-cn.md) 一节看到更详细的使用例子。 + +## 字符类型 {#CharacterType} + +从之前的声明中可以看到,每个编码都有一个 `CharType` 模板参数。这可能比较容易混淆,实际上,每个 `CharType` 存储一个编码单元,而不是一个字符(码点)。如之前所谈及,在 UTF-8 中一个码点可能会编码成 1 至 4 个编码单元。 + +对于 `UTF16(LE|BE)` 及 `UTF32(LE|BE)` 来说,`CharType` 必须分别是一个至少 2 及 4 字节的整数类型。 + +注意 C++11 新添了 `char16_t` 及 `char32_t` 类型,也可分别用于 `UTF16` 及 `UTF32`。 + +## AutoUTF {#AutoUTF} + +上述所介绍的编码都是在编译期静态挷定的。换句话说,使用者必须知道内存或流之中使用了哪种编码。然而,有时候我们可能需要读写不同编码的文件,而且这些编码需要在运行时才能决定。 + +`AutoUTF` 是为此而设计的编码。它根据输入或输出流来选择使用哪种编码。目前它应该与 `EncodedInputStream` 及 `EncodedOutputStream` 结合使用。 + +## ASCII {#ASCII} + +虽然 JSON 标准并未提及 [ASCII](http://en.wikipedia.org/wiki/ASCII),有时候我们希望写入 7 位的 ASCII JSON,以供未能处理 UTF-8 的应用程序使用。由于任 JSON 都可以把 Unicode 字符表示为 `\uXXXX` 转义序列,JSON 总是可用 ASCII 来编码。 + +以下的例子把 UTF-8 的 DOM 写成 ASCII 的 JSON: + +~~~~~~~~~~cpp +using namespace rapidjson; +Document d; // UTF8<> +// ... +StringBuffer buffer; +Writer > writer(buffer); +d.Accept(writer); +std::cout << buffer.GetString(); +~~~~~~~~~~ + +ASCII 可用于输入流。当输入流包含大于 127 的字节,就会导致 `kParseErrorStringInvalidEncoding` 错误。 + +ASCII * 不能 * 用于内存(`Document` 的编码,或 `Reader` 的目标编码),因为它不能表示 Unicode 码点。 + +# 校验及转码 {#ValidationTranscoding} + +当 RapidJSON 解析一个 JSON 时,它能校验输入 JSON,判断它是否所标明编码的合法序列。要开启此选项,请把 `kParseValidateEncodingFlag` 加入 `parseFlags` 模板参数。 + +若输入编码和输出编码并不相同,`Reader` 及 `Writer` 会算把文本转码。在这种情况下,并不需要 `kParseValidateEncodingFlag`,因为它必须解码输入序列。若序列不能被解码,它必然是不合法的。 + +## 转码器 {#Transcoder} + +虽然 RapidJSON 的编码功能是为 JSON 解析/生成而设计,使用者也可以“滥用”它们来为非 JSON 字符串转码。 + +以下的例子把 UTF-8 字符串转码成 UTF-16: + +~~~~~~~~~~cpp +#include "rapidjson/encodings.h" + +using namespace rapidjson; + +const char* s = "..."; // UTF-8 string +StringStream source(s); +GenericStringBuffer > target; + +bool hasError = false; +while (source.Peek() != '\0') + if (!Transcoder, UTF16<> >::Transcode(source, target)) { + hasError = true; + break; + } + +if (!hasError) { + const wchar_t* t = target.GetString(); + // ... +} +~~~~~~~~~~ + +你也可以用 `AutoUTF` 及对应的流来在运行时设置内源/目的之编码。 diff --git a/thirdparty/rapidjson-1.1.0/doc/faq.md b/thirdparty/rapidjson-1.1.0/doc/faq.md new file mode 100644 index 0000000000..1b0541c27a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/faq.md @@ -0,0 +1,289 @@ +# FAQ + +[TOC] + +## General + +1. What is RapidJSON? + + RapidJSON is a C++ library for parsing and generating JSON. You may check all [features](doc/features.md) of it. + +2. Why is RapidJSON named so? + + It is inspired by [RapidXML](http://rapidxml.sourceforge.net/), which is a fast XML DOM parser. + +3. Is RapidJSON similar to RapidXML? + + RapidJSON borrowed some designs of RapidXML, including *in situ* parsing, header-only library. But the two APIs are completely different. Also RapidJSON provide many features that are not in RapidXML. + +4. Is RapidJSON free? + + Yes, it is free under MIT license. It can be used in commercial applications. Please check the details in [license.txt](https://github.com/miloyip/rapidjson/blob/master/license.txt). + +5. Is RapidJSON small? What are its dependencies? + + Yes. A simple executable which parses a JSON and prints its statistics is less than 30KB on Windows. + + RapidJSON depends on C++ standard library only. + +6. How to install RapidJSON? + + Check [Installation section](https://miloyip.github.io/rapidjson/). + +7. Can RapidJSON run on my platform? + + RapidJSON has been tested in many combinations of operating systems, compilers and CPU architecture by the community. But we cannot ensure that it can be run on your particular platform. Building and running the unit test suite will give you the answer. + +8. Does RapidJSON support C++03? C++11? + + RapidJSON was firstly implemented for C++03. Later it added optional support of some C++11 features (e.g., move constructor, `noexcept`). RapidJSON shall be compatible with C++03 or C++11 compliant compilers. + +9. Does RapidJSON really work in real applications? + + Yes. It is deployed in both client and server real applications. A community member reported that RapidJSON in their system parses 50 million JSONs daily. + +10. How RapidJSON is tested? + + RapidJSON contains a unit test suite for automatic testing. [Travis](https://travis-ci.org/miloyip/rapidjson/)(for Linux) and [AppVeyor](https://ci.appveyor.com/project/miloyip/rapidjson/)(for Windows) will compile and run the unit test suite for all modifications. The test process also uses Valgrind (in Linux) to detect memory leaks. + +11. Is RapidJSON well documented? + + RapidJSON provides user guide and API documentationn. + +12. Are there alternatives? + + Yes, there are a lot alternatives. For example, [nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) has a listing of open-source C/C++ JSON libraries. [json.org](http://www.json.org/) also has a list. + +## JSON + +1. What is JSON? + + JSON (JavaScript Object Notation) is a lightweight data-interchange format. It uses human readable text format. More details of JSON can be referred to [RFC7159](http://www.ietf.org/rfc/rfc7159.txt) and [ECMA-404](http://www.ecma-international.org/publications/standards/Ecma-404.htm). + +2. What are applications of JSON? + + JSON are commonly used in web applications for transferring structured data. It is also used as a file format for data persistence. + +2. Does RapidJSON conform to the JSON standard? + + Yes. RapidJSON is fully compliance with [RFC7159](http://www.ietf.org/rfc/rfc7159.txt) and [ECMA-404](http://www.ecma-international.org/publications/standards/Ecma-404.htm). It can handle corner cases, such as supporting null character and surrogate pairs in JSON strings. + +3. Does RapidJSON support relaxed syntax? + + Currently no. RapidJSON only support the strict standardized format. Support on related syntax is under discussion in this [issue](https://github.com/miloyip/rapidjson/issues/36). + +## DOM and SAX + +1. What is DOM style API? + + Document Object Model (DOM) is an in-memory representation of JSON for query and manipulation. + +2. What is SAX style API? + + SAX is an event-driven API for parsing and generation. + +3. Should I choose DOM or SAX? + + DOM is easy for query and manipulation. SAX is very fast and memory-saving but often more difficult to be applied. + +4. What is *in situ* parsing? + + *in situ* parsing decodes the JSON strings directly into the input JSON. This is an optimization which can reduce memory consumption and improve performance, but the input JSON will be modified. Check [in-situ parsing](doc/dom.md) for details. + +5. When does parsing generate an error? + + The parser generates an error when the input JSON contains invalid syntax, or a value can not be represented (a number is too big), or the handler of parsers terminate the parsing. Check [parse error](doc/dom.md) for details. + +6. What error information is provided? + + The error is stored in `ParseResult`, which includes the error code and offset (number of characters from the beginning of JSON). The error code can be translated into human-readable error message. + +7. Why not just using `double` to represent JSON number? + + Some applications use 64-bit unsigned/signed integers. And these integers cannot be converted into `double` without loss of precision. So the parsers detects whether a JSON number is convertible to different types of integers and/or `double`. + +8. How to clear-and-minimize a document or value? + + Call one of the `SetXXX()` methods - they call destructor which deallocates DOM data: + + ~~~~~~~~~~cpp + Document d; + ... + d.SetObject(); // clear and minimize + ~~~~~~~~~~ + + Alternatively, use equivalent of the [C++ swap with temporary idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize): + ~~~~~~~~~~cpp + Value(kObjectType).Swap(d); + ~~~~~~~~~~ + or equivalent, but sightly longer to type: + ~~~~~~~~~~cpp + d.Swap(Value(kObjectType).Move()); + ~~~~~~~~~~ + +9. How to insert a document node into another document? + + Let's take the following two DOM trees represented as JSON documents: + ~~~~~~~~~~cpp + Document person; + person.Parse("{\"person\":{\"name\":{\"first\":\"Adam\",\"last\":\"Thomas\"}}}"); + + Document address; + address.Parse("{\"address\":{\"city\":\"Moscow\",\"street\":\"Quiet\"}}"); + ~~~~~~~~~~ + Let's assume we want to merge them in such way that the whole `address` document becomes a node of the `person`: + ~~~~~~~~~~js + { "person": { + "name": { "first": "Adam", "last": "Thomas" }, + "address": { "city": "Moscow", "street": "Quiet" } + } + } + ~~~~~~~~~~ + + The most important requirement to take care of document and value life-cycle as well as consistent memory managent using the right allocator during the value transfer. + + Simple yet most efficient way to achieve that is to modify the `address` definition above to initialize it with allocator of the `person` document, then we just add the root member of the value: + ~~~~~~~~~~cpp + Documnet address(person.GetAllocator()); + ... + person["person"].AddMember("address", address["address"], person.GetAllocator()); + ~~~~~~~~~~ +Alternatively, if we don't want to explicitly refer to the root value of `address` by name, we can refer to it via iterator: + ~~~~~~~~~~cpp + auto addressRoot = address.MemberBegin(); + person["person"].AddMember(addressRoot->name, addressRoot->value, person.GetAllocator()); + ~~~~~~~~~~ + + Second way is to deep-clone the value from the address document: + ~~~~~~~~~~cpp + Value addressValue = Value(address["address"], person.GetAllocator()); + person["person"].AddMember("address", addressValue, person.GetAllocator()); + ~~~~~~~~~~ + +## Document/Value (DOM) + +1. What is move semantics? Why? + + Instead of copy semantics, move semantics is used in `Value`. That means, when assigning a source value to a target value, the ownership of source value is moved to the target value. + + Since moving is faster than copying, this design decision forces user to aware of the copying overhead. + +2. How to copy a value? + + There are two APIs: constructor with allocator, and `CopyFrom()`. See [Deep Copy Value](doc/tutorial.md) for an example. + +3. Why do I need to provide the length of string? + + Since C string is null-terminated, the length of string needs to be computed via `strlen()`, with linear runtime complexity. This incurs an unncessary overhead of many operations, if the user already knows the length of string. + + Also, RapidJSON can handle `\u0000` (null character) within a string. If a string contains null characters, `strlen()` cannot return the true length of it. In such case user must provide the length of string explicitly. + +4. Why do I need to provide allocator parameter in many DOM manipulation API? + + Since the APIs are member functions of `Value`, we do not want to save an allocator pointer in every `Value`. + +5. Does it convert between numerical types? + + When using `GetInt()`, `GetUint()`, ... conversion may occur. For integer-to-integer conversion, it only convert when it is safe (otherwise it will assert). However, when converting a 64-bit signed/unsigned integer to double, it will convert but be aware that it may lose precision. A number with fraction, or an integer larger than 64-bit, can only be obtained by `GetDouble()`. + +## Reader/Writer (SAX) + +1. Why don't we just `printf` a JSON? Why do we need a `Writer`? + + Most importantly, `Writer` will ensure the output JSON is well-formed. Calling SAX events incorrectly (e.g. `StartObject()` pairing with `EndArray()`) will assert. Besides, `Writer` will escapes strings (e.g., `\n`). Finally, the numeric output of `printf()` may not be a valid JSON number, especially in some locale with digit delimiters. And the number-to-string conversion in `Writer` is implemented with very fast algorithms, which outperforms than `printf()` or `iostream`. + +2. Can I pause the parsing process and resume it later? + + This is not directly supported in the current version due to performance consideration. However, if the execution environment supports multi-threading, user can parse a JSON in a separate thread, and pause it by blocking in the input stream. + +## Unicode + +1. Does it support UTF-8, UTF-16 and other format? + + Yes. It fully support UTF-8, UTF-16 (LE/BE), UTF-32 (LE/BE) and ASCII. + +2. Can it validate the encoding? + + Yes, just pass `kParseValidateEncodingFlag` to `Parse()`. If there is invalid encoding in the stream, it wil generate `kParseErrorStringInvalidEncoding` error. + +3. What is surrogate pair? Does RapidJSON support it? + + JSON uses UTF-16 encoding when escaping unicode character, e.g. `\u5927` representing Chinese character "big". To handle characters other than those in basic multilingual plane (BMP), UTF-16 encodes those characters with two 16-bit values, which is called UTF-16 surrogate pair. For example, the Emoji character U+1F602 can be encoded as `\uD83D\uDE02` in JSON. + + RapidJSON fully support parsing/generating UTF-16 surrogates. + +4. Can it handle `\u0000` (null character) in JSON string? + + Yes. RapidJSON fully support null character in JSON string. However, user need to be aware of it and using `GetStringLength()` and related APIs to obtain the true length of string. + +5. Can I output `\uxxxx` for all non-ASCII character? + + Yes, use `ASCII<>` as output encoding template parameter in `Writer` can enforce escaping those characters. + +## Stream + +1. I have a big JSON file. Should I load the whole file to memory? + + User can use `FileReadStream` to read the file chunk-by-chunk. But for *in situ* parsing, the whole file must be loaded. + +2. Can I parse JSON while it is streamed from network? + + Yes. User can implement a custom stream for this. Please refer to the implementation of `FileReadStream`. + +3. I don't know what encoding will the JSON be. How to handle them? + + You may use `AutoUTFInputStream` which detects the encoding of input stream automatically. However, it will incur some performance overhead. + +4. What is BOM? How RapidJSON handle it? + + [Byte order mark (BOM)](http://en.wikipedia.org/wiki/Byte_order_mark) sometimes reside at the beginning of file/stream to indiciate the UTF encoding type of it. + + RapidJSON's `EncodedInputStream` can detect/consume BOM. `EncodedOutputStream` can optionally write a BOM. See [Encoded Streams](doc/stream.md) for example. + +5. Why little/big endian is related? + + little/big endian of stream is an issue for UTF-16 and UTF-32 streams, but not UTF-8 stream. + +## Performance + +1. Is RapidJSON really fast? + + Yes. It may be the fastest open source JSON library. There is a [benchmark](https://github.com/miloyip/nativejson-benchmark) for evaluating performance of C/C++ JSON libaries. + +2. Why is it fast? + + Many design decisions of RapidJSON is aimed at time/space performance. These may reduce user-friendliness of APIs. Besides, it also employs low-level optimizations (intrinsics, SIMD) and special algorithms (custom double-to-string, string-to-double conversions). + +3. What is SIMD? How it is applied in RapidJSON? + + [SIMD](http://en.wikipedia.org/wiki/SIMD) instructions can perform parallel computation in modern CPUs. RapidJSON support Intel's SSE2/SSE4.2 to accelerate whitespace skipping. This improves performance of parsing indent formatted JSON. Define `RAPIDJSON_SSE2` or `RAPIDJSON_SSE42` macro to enable this feature. However, running the executable on a machine without such instruction set support will make it crash. + +4. Does it consume a lot of memory? + + The design of RapidJSON aims at reducing memory footprint. + + In the SAX API, `Reader` consumes memory portional to maximum depth of JSON tree, plus maximum length of JSON string. + + In the DOM API, each `Value` consumes exactly 16/24 bytes for 32/64-bit architecture respectively. RapidJSON also uses a special memory allocator to minimize overhead of allocations. + +5. What is the purpose of being high performance? + + Some applications need to process very large JSON files. Some server-side applications need to process huge amount of JSONs. Being high performance can improve both latency and throuput. In a broad sense, it will also save energy. + +## Gossip + +1. Who are the developers of RapidJSON? + + Milo Yip ([miloyip](https://github.com/miloyip)) is the original author of RapidJSON. Many contributors from the world have improved RapidJSON. Philipp A. Hartmann ([pah](https://github.com/pah)) has implemented a lot of improvements, setting up automatic testing and also involves in a lot of discussions for the community. Don Ding ([thebusytypist](https://github.com/thebusytypist)) implemented the iterative parser. Andrii Senkovych ([jollyroger](https://github.com/jollyroger)) completed the CMake migration. Kosta ([Kosta-Github](https://github.com/Kosta-Github)) provided a very neat short-string optimization. Thank you for all other contributors and community members as well. + +2. Why do you develop RapidJSON? + + It was just a hobby project initially in 2011. Milo Yip is a game programmer and he just knew about JSON at that time and would like to apply JSON in future projects. As JSON seems very simple he would like to write a header-only and fast library. + +3. Why there is a long empty period of development? + + It is basically due to personal issues, such as getting new family members. Also, Milo Yip has spent a lot of spare time on translating "Game Engine Architecture" by Jason Gregory into Chinese. + +4. Why did the repository move from Google Code to GitHub? + + This is the trend. And GitHub is much more powerful and convenient. diff --git a/thirdparty/rapidjson-1.1.0/doc/faq.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/faq.zh-cn.md new file mode 100644 index 0000000000..ed100e1121 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/faq.zh-cn.md @@ -0,0 +1,290 @@ +# 常见问题 + +[TOC] + +## 一般问题 + +1. RapidJSON 是什么? + + RapidJSON 是一个 C++ 库,用于解析及生成 JSON。读者可参考它的所有 [特点](doc/features.zh-cn.md)。 + +2. 为什么称作 RapidJSON? + + 它的灵感来自于 [RapidXML](http://rapidxml.sourceforge.net/),RapidXML 是一个高速的 XML DOM 解析器。 + +3. RapidJSON 与 RapidXML 相似么? + + RapidJSON 借镜了 RapidXML 的一些设计, 包括原位(*in situ*)解析、只有头文件的库。但两者的 API 是完全不同的。此外 RapidJSON 也提供许多 RapidXML 没有的特点。 + +4. RapidJSON 是免费的么? + + 是的,它在 MIT 特許條款下免费。它可用于商业软件。详情请参看 [license.txt](https://github.com/miloyip/rapidjson/blob/master/license.txt)。 + +5. RapidJSON 很小么?它有何依赖? + + 是的。在 Windows 上,一个解析 JSON 并打印出统计的可执行文件少于 30KB。 + + RapidJSON 仅依赖于 C++ 标准库。 + +6. 怎样安装 RapidJSON? + + 见 [安装一节](../readme.zh-cn.md#安装)。 + +7. RapidJSON 能否运行于我的平台? + + 社区已在多个操作系统/编译器/CPU 架构的组合上测试 RapidJSON。但我们无法确保它能运行于你特定的平台上。只需要生成及执行单元测试便能获取答案。 + +8. RapidJSON 支持 C++03 么?C++11 呢? + + RapidJSON 开始时在 C++03 上实现。后来加入了可选的 C++11 特性支持(如转移构造函数、`noexcept`)。RapidJSON 应该兼容所有遵从 C++03 或 C++11 的编译器。 + +9. RapidJSON 是否真的用于实际应用? + + 是的。它被配置于前台及后台的真实应用中。一个社区成员说 RapidJSON 在他们的系统中每日解析 5 千万个 JSON。 + +10. RapidJSON 是如何被测试的? + + RapidJSON 包含一组单元测试去执行自动测试。[Travis](https://travis-ci.org/miloyip/rapidjson/)(供 Linux 平台)及 [AppVeyor](https://ci.appveyor.com/project/miloyip/rapidjson/)(供 Windows 平台)会对所有修改进行编译及执行单元测试。在 Linux 下还会使用 Valgrind 去检测内存泄漏。 + +11. RapidJSON 是否有完整的文档? + + RapidJSON 提供了使用手册及 API 说明文档。 + +12. 有没有其他替代品? + + 有许多替代品。例如 [nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) 列出了一些开源的 C/C++ JSON 库。[json.org](http://www.json.org/) 也有一个列表。 + +## JSON + +1. 什么是 JSON? + + JSON (JavaScript Object Notation) 是一个轻量的数据交换格式。它使用人类可读的文本格式。更多关于 JSON 的细节可考 [RFC7159](http://www.ietf.org/rfc/rfc7159.txt) 及 [ECMA-404](http://www.ecma-international.org/publications/standards/Ecma-404.htm)。 + +2. JSON 有什么应用场合? + + JSON 常用于网页应用程序,以传送结构化数据。它也可作为文件格式用于数据持久化。 + +2. RapidJSON 是否符合 JSON 标准? + + 是。RapidJSON 完全符合 [RFC7159](http://www.ietf.org/rfc/rfc7159.txt) 及 [ECMA-404](http://www.ecma-international.org/publications/standards/Ecma-404.htm)。它能处理一些特殊情况,例如支持 JSON 字符串中含有空字符及代理对(surrogate pair)。 + +3. RapidJSON 是否支持宽松的语法? + + 现时不支持。RapidJSON 只支持严格的标准格式。宽松语法现时在这 [issue](https://github.com/miloyip/rapidjson/issues/36) 中进行讨论。 + +## DOM 与 SAX + +1. 什么是 DOM 风格 API? + + Document Object Model(DOM)是一个储存于内存的 JSON 表示方式,用于查询及修改 JSON。 + +2. 什么是 SAX 风格 API? + + SAX 是一个事件驱动的 API,用于解析及生成 JSON。 + +3. 我应用 DOM 还是 SAX? + + DOM 易于查询及修改。SAX 则是非常快及省内存的,但通常较难使用。 + +4. 什么是原位(*in situ*)解析? + + 原位解析会把 JSON 字符串直接解码至输入的 JSON 中。这是一个优化,可减少内存消耗及提升性能,但输入的 JSON 会被更改。进一步细节请参考 [原位解析](doc/dom.zh-cn.md) 。 + +5. 什么时候会产生解析错误? + + 当输入的 JSON 包含非法语法,或不能表示一个值(如 Number 太大),或解析器的处理器中断解析过程,解析器都会产生一个错误。详情请参考 [解析错误](doc/dom.zh-cn.md)。 + +6. 有什么错误信息? + + 错误信息存储在 `ParseResult`,它包含错误代号及偏移值(从 JSON 开始至错误处的字符数目)。可以把错误代号翻译为人类可读的错误讯息。 + +7. 为何不只使用 `double` 去表示 JSON number? + + 一些应用需要使用 64 位无号/有号整数。这些整数不能无损地转换成 `double`。因此解析器会检测一个 JSON number 是否能转换至各种整数类型及 `double`。 + +8. 如何清空并最小化 `document` 或 `value` 的容量? + + 调用 `SetXXX()` 方法 - 这些方法会调用析构函数,并重建空的 Object 或 Array: + + ~~~~~~~~~~cpp + Document d; + ... + d.SetObject(); // clear and minimize + ~~~~~~~~~~ + + 另外,也可以参考在 [C++ swap with temporary idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize) 中的一种等价的方法: + ~~~~~~~~~~cpp + Value(kObjectType).Swap(d); + ~~~~~~~~~~ + 或者,使用这个稍微长一点的代码也能完成同样的事情: + ~~~~~~~~~~cpp + d.Swap(Value(kObjectType).Move()); + ~~~~~~~~~~ + +9. 如何将一个 `document` 节点插入到另一个 `document` 中? + + 比如有以下两个 document(DOM): + ~~~~~~~~~~cpp + Document person; + person.Parse("{\"person\":{\"name\":{\"first\":\"Adam\",\"last\":\"Thomas\"}}}"); + + Document address; + address.Parse("{\"address\":{\"city\":\"Moscow\",\"street\":\"Quiet\"}}"); + ~~~~~~~~~~ + 假设我们希望将整个 `address` 插入到 `person` 中,作为其的一个子节点: + ~~~~~~~~~~js + { "person": { + "name": { "first": "Adam", "last": "Thomas" }, + "address": { "city": "Moscow", "street": "Quiet" } + } + } + ~~~~~~~~~~ + + 在插入节点的过程中需要注意 `document` 和 `value` 的生命周期并且正确地使用 allocator 进行内存分配和管理。 + + 一个简单有效的方法就是修改上述 `address` 变量的定义,让其使用 `person` 的 allocator 初始化,然后将其添加到根节点。 + + ~~~~~~~~~~cpp + Documnet address(person.GetAllocator()); + ... + person["person"].AddMember("address", address["address"], person.GetAllocator()); + ~~~~~~~~~~ + 当然,如果你不想通过显式地写出 `address` 的 key 来得到其值,可以使用迭代器来实现: + ~~~~~~~~~~cpp + auto addressRoot = address.MemberBegin(); + person["person"].AddMember(addressRoot->name, addressRoot->value, person.GetAllocator()); + ~~~~~~~~~~ + + 此外,还可以通过深拷贝 address document 来实现: + ~~~~~~~~~~cpp + Value addressValue = Value(address["address"], person.GetAllocator()); + person["person"].AddMember("address", addressValue, person.GetAllocator()); + ~~~~~~~~~~ + +## Document/Value (DOM) + +1. 什么是转移语意?为什么? + + `Value` 不用复制语意,而使用了转移语意。这是指,当把来源值赋值于目标值时,来源值的所有权会转移至目标值。 + + 由于转移快于复制,此设计决定强迫使用者注意到复制的消耗。 + +2. 怎样去复制一个值? + + 有两个 API 可用:含 allocator 的构造函数,以及 `CopyFrom()`。可参考 [深复制 Value](doc/tutorial.zh-cn.md) 里的用例。 + +3. 为什么我需要提供字符串的长度? + + 由于 C 字符串是空字符结尾的,需要使用 `strlen()` 去计算其长度,这是线性复杂度的操作。若使用者已知字符串的长度,对很多操作来说会造成不必要的消耗。 + + 此外,RapidJSON 可处理含有 `\u0000`(空字符)的字符串。若一个字符串含有空字符,`strlen()` 便不能返回真正的字符串长度。在这种情况下使用者必须明确地提供字符串长度。 + +4. 为什么在许多 DOM 操作 API 中要提供分配器作为参数? + + 由于这些 API 是 `Value` 的成员函数,我们不希望为每个 `Value` 储存一个分配器指针。 + +5. 它会转换各种数值类型么? + + 当使用 `GetInt()`、`GetUint()` 等 API 时,可能会发生转换。对于整数至整数转换,仅当保证转换安全才会转换(否则会断言失败)。然而,当把一个 64 位有号/无号整数转换至 double 时,它会转换,但有可能会损失精度。含有小数的数字、或大于 64 位的整数,都只能使用 `GetDouble()` 获取其值。 + +## Reader/Writer (SAX) + +1. 为什么不仅仅用 `printf` 输出一个 JSON?为什么需要 `Writer`? + + 最重要的是,`Writer` 能确保输出的 JSON 是格式正确的。错误地调用 SAX 事件(如 `StartObject()` 错配 `EndArray()`)会造成断言失败。此外,`Writer` 会把字符串进行转义(如 `\n`)。最后,`printf()` 的数值输出可能并不是一个合法的 JSON number,特别是某些 locale 会有数字分隔符。而且 `Writer` 的数值字符串转换是使用非常快的算法来实现的,胜过 `printf()` 及 `iostream`。 + +2. 我能否暂停解析过程,并在稍后继续? + + 基于性能考虑,目前版本并不直接支持此功能。然而,若执行环境支持多线程,使用者可以在另一线程解析 JSON,并通过阻塞输入流去暂停。 + +## Unicode + +1. 它是否支持 UTF-8、UTF-16 及其他格式? + + 是。它完全支持 UTF-8、UTF-16(大端/小端)、UTF-32(大端/小端)及 ASCII。 + +2. 它能否检测编码的合法性? + + 能。只需把 `kParseValidateEncodingFlag` 参考传给 `Parse()`。若发现在输入流中有非法的编码,它就会产生 `kParseErrorStringInvalidEncoding` 错误。 + +3. 什么是代理对(surrogate pair)?RapidJSON 是否支持? + + JSON 使用 UTF-16 编码去转义 Unicode 字符,例如 `\u5927` 表示中文字“大”。要处理基本多文种平面(basic multilingual plane,BMP)以外的字符时,UTF-16 会把那些字符编码成两个 16 位值,这称为 UTF-16 代理对。例如,绘文字字符 U+1F602 在 JSON 中可被编码成 `\uD83D\uDE02`。 + + RapidJSON 完全支持解析及生成 UTF-16 代理对。 + +4. 它能否处理 JSON 字符串中的 `\u0000`(空字符)? + + 能。RapidJSON 完全支持 JSON 字符串中的空字符。然而,使用者需要注意到这件事,并使用 `GetStringLength()` 及相关 API 去取得字符串真正长度。 + +5. 能否对所有非 ASCII 字符输出成 `\uxxxx` 形式? + + 可以。只要在 `Writer` 中使用 `ASCII<>` 作为输出编码参数,就可以强逼转义那些字符。 + +## 流 + +1. 我有一个很大的 JSON 文件。我应否把它整个载入内存中? + + 使用者可使用 `FileReadStream` 去逐块读入文件。但若使用于原位解析,必须载入整个文件。 + +2. 我能否解析一个从网络上串流进来的 JSON? + + 可以。使用者可根据 `FileReadStream` 的实现,去实现一个自定义的流。 + +3. 我不知道一些 JSON 将会使用哪种编码。怎样处理它们? + + 你可以使用 `AutoUTFInputStream`,它能自动检测输入流的编码。然而,它会带来一些性能开销。 + +4. 什么是 BOM?RapidJSON 怎样处理它? + + [字节顺序标记(byte order mark, BOM)](http://en.wikipedia.org/wiki/Byte_order_mark) 有时会出现于文件/流的开始,以表示其 UTF 编码类型。 + + RapidJSON 的 `EncodedInputStream` 可检测/跳过 BOM。`EncodedOutputStream` 可选择是否写入 BOM。可参考 [编码流](doc/stream.zh-cn.md) 中的例子。 + +5. 为什么会涉及大端/小端? + + 流的大端/小端是 UTF-16 及 UTF-32 流要处理的问题,而 UTF-8 不需要处理。 + +## 性能 + +1. RapidJSON 是否真的快? + + 是。它可能是最快的开源 JSON 库。有一个 [评测](https://github.com/miloyip/nativejson-benchmark) 评估 C/C++ JSON 库的性能。 + +2. 为什么它会快? + + RapidJSON 的许多设计是针对时间/空间性能来设计的,这些决定可能会影响 API 的易用性。此外,它也使用了许多底层优化(内部函数/intrinsic、SIMD)及特别的算法(自定义的 double 至字符串转换、字符串至 double 的转换)。 + +3. 什是是 SIMD?它如何用于 RapidJSON? + + [SIMD](http://en.wikipedia.org/wiki/SIMD) 指令可以在现代 CPU 中执行并行运算。RapidJSON 支持了 Intel 的 SSE2/SSE4.2 去加速跳过空白字符。在解析含缩进的 JSON 时,这能提升性能。只要定义名为 `RAPIDJSON_SSE2` 或 `RAPIDJSON_SSE42` 的宏,就能启动这个功能。然而,若在不支持这些指令集的机器上执行这些可执行文件,会导致崩溃。 + +4. 它会消耗许多内存么? + + RapidJSON 的设计目标是减低内存占用。 + + 在 SAX API 中,`Reader` 消耗的内存与 JSON 树深度加上最长 JSON 字符成正比。 + + 在 DOM API 中,每个 `Value` 在 32/64 位架构下分别消耗 16/24 字节。RapidJSON 也使用一个特殊的内存分配器去减少分配的额外开销。 + +5. 高性能的意义何在? + + 有些应用程序需要处理非常大的 JSON 文件。而有些后台应用程序需要处理大量的 JSON。达到高性能同时改善延时及吞吐量。更广义来说,这也可以节省能源。 + +## 八挂 + +1. 谁是 RapidJSON 的开发者? + + 叶劲峰(Milo Yip,[miloyip](https://github.com/miloyip))是 RapidJSON 的原作者。全世界许多贡献者一直在改善 RapidJSON。Philipp A. Hartmann([pah](https://github.com/pah))实现了许多改进,也设置了自动化测试,而且还参与许多社区讨论。丁欧南(Don Ding,[thebusytypist](https://github.com/thebusytypist))实现了迭代式解析器。Andrii Senkovych([jollyroger](https://github.com/jollyroger))完成了向 CMake 的迁移。Kosta([Kosta-Github](https://github.com/Kosta-Github))提供了一个非常灵巧的短字符串优化。也需要感谢其他献者及社区成员。 + +2. 为何你要开发 RapidJSON? + + 在 2011 年开始这项目是,它仅一个兴趣项目。Milo Yip 是一个游戏程序员,他在那时候认识到 JSON 并希望在未来的项目中使用。由于 JSON 好像很简单,他希望写一个仅有头文件并且快速的程序库。 + +3. 为什么开发中段有一段长期空档? + + 主要是个人因素,例如加入新家庭成员。另外,Milo Yip 也花了许多业馀时间去翻译 Jason Gregory 的《Game Engine Architecture》至中文版《游戏引擎架构》。 + +4. 为什么这个项目从 Google Code 搬到 GitHub? + + 这是大势所趋,而且 GitHub 更为强大及方便。 diff --git a/thirdparty/rapidjson-1.1.0/doc/features.md b/thirdparty/rapidjson-1.1.0/doc/features.md new file mode 100644 index 0000000000..732fb21f40 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/features.md @@ -0,0 +1,104 @@ +# Features + +## General + +* Cross-platform + * Compilers: Visual Studio, gcc, clang, etc. + * Architectures: x86, x64, ARM, etc. + * Operating systems: Windows, Mac OS X, Linux, iOS, Android, etc. +* Easy installation + * Header files only library. Just copy the headers to your project. +* Self-contained, minimal dependences + * No STL, BOOST, etc. + * Only included ``, ``, ``, ``, ``, ``. +* Without C++ exception, RTTI +* High performance + * Use template and inline functions to reduce function call overheads. + * Internal optimized Grisu2 and floating point parsing implementations. + * Optional SSE2/SSE4.2 support. + +## Standard compliance + +* RapidJSON should be fully RFC4627/ECMA-404 compliance. +* Support JSON Pointer (RFC6901). +* Support JSON Schema Draft v4. +* Support Unicode surrogate. +* Support null character (`"\u0000"`) + * For example, `["Hello\u0000World"]` can be parsed and handled gracefully. There is API for getting/setting lengths of string. +* Support optional relaxed syntax. + * Single line (`// ...`) and multiple line (`/* ... */`) comments (`kParseCommentsFlag`). + * Trailing commas at the end of objects and arrays (`kParseTrailingCommasFlag`). + * `NaN`, `Inf`, `Infinity`, `-Inf` and `-Infinity` as `double` values (`kParseNanAndInfFlag`) +* [NPM compliant](http://github.com/miloyip/rapidjson/blob/master/doc/npm.md). + +## Unicode + +* Support UTF-8, UTF-16, UTF-32 encodings, including little endian and big endian. + * These encodings are used in input/output streams and in-memory representation. +* Support automatic detection of encodings in input stream. +* Support transcoding between encodings internally. + * For example, you can read a UTF-8 file and let RapidJSON transcode the JSON strings into UTF-16 in the DOM. +* Support encoding validation internally. + * For example, you can read a UTF-8 file, and let RapidJSON check whether all JSON strings are valid UTF-8 byte sequence. +* Support custom character types. + * By default the character types are `char` for UTF8, `wchar_t` for UTF16, `uint32_t` for UTF32. +* Support custom encodings. + +## API styles + +* SAX (Simple API for XML) style API + * Similar to [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML), RapidJSON provides a event sequential access parser API (`rapidjson::GenericReader`). It also provides a generator API (`rapidjson::Writer`) which consumes the same set of events. +* DOM (Document Object Model) style API + * Similar to [DOM](http://en.wikipedia.org/wiki/Document_Object_Model) for HTML/XML, RapidJSON can parse JSON into a DOM representation (`rapidjson::GenericDocument`), for easy manipulation, and finally stringify back to JSON if needed. + * The DOM style API (`rapidjson::GenericDocument`) is actually implemented with SAX style API (`rapidjson::GenericReader`). SAX is faster but sometimes DOM is easier. Users can pick their choices according to scenarios. + +## Parsing + +* Recursive (default) and iterative parser + * Recursive parser is faster but prone to stack overflow in extreme cases. + * Iterative parser use custom stack to keep parsing state. +* Support *in situ* parsing. + * Parse JSON string values in-place at the source JSON, and then the DOM points to addresses of those strings. + * Faster than convention parsing: no allocation for strings, no copy (if string does not contain escapes), cache-friendly. +* Support 32-bit/64-bit signed/unsigned integer and `double` for JSON number type. +* Support parsing multiple JSONs in input stream (`kParseStopWhenDoneFlag`). +* Error Handling + * Support comprehensive error code if parsing failed. + * Support error message localization. + +## DOM (Document) + +* RapidJSON checks range of numerical values for conversions. +* Optimization for string literal + * Only store pointer instead of copying +* Optimization for "short" strings + * Store short string in `Value` internally without additional allocation. + * For UTF-8 string: maximum 11 characters in 32-bit, 21 characters in 64-bit (13 characters in x86-64). +* Optionally support `std::string` (define `RAPIDJSON_HAS_STDSTRING=1`) + +## Generation + +* Support `rapidjson::PrettyWriter` for adding newlines and indentations. + +## Stream + +* Support `rapidjson::GenericStringBuffer` for storing the output JSON as string. +* Support `rapidjson::FileReadStream` and `rapidjson::FileWriteStream` for input/output `FILE` object. +* Support custom streams. + +## Memory + +* Minimize memory overheads for DOM. + * Each JSON value occupies exactly 16/20 bytes for most 32/64-bit machines (excluding text string). +* Support fast default allocator. + * A stack-based allocator (allocate sequentially, prohibit to free individual allocations, suitable for parsing). + * User can provide a pre-allocated buffer. (Possible to parse a number of JSONs without any CRT allocation) +* Support standard CRT(C-runtime) allocator. +* Support custom allocators. + +## Miscellaneous + +* Some C++11 support (optional) + * Rvalue reference + * `noexcept` specifier + * Range-based for loop diff --git a/thirdparty/rapidjson-1.1.0/doc/features.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/features.zh-cn.md new file mode 100644 index 0000000000..fd3fd4d665 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/features.zh-cn.md @@ -0,0 +1,103 @@ +# 特点 + +## 总体 + +* 跨平台 + * 编译器:Visual Studio、gcc、clang 等 + * 架构:x86、x64、ARM 等 + * 操作系统:Windows、Mac OS X、Linux、iOS、Android 等 +* 容易安装 + * 只有头文件的库。只需把头文件复制至你的项目中。 +* 独立、最小依赖 + * 不需依赖 STL、BOOST 等。 + * 只包含 ``, ``, ``, ``, ``, ``。 +* 没使用 C++ 异常、RTTI +* 高性能 + * 使用模版及内联函数去降低函数调用开销。 + * 内部经优化的 Grisu2 及浮点数解析实现。 + * 可选的 SSE2/SSE4.2 支持。 + +## 符合标准 + +* RapidJSON 应完全符合 RFC4627/ECMA-404 标准。 +* 支持 JSON Pointer (RFC6901). +* 支持 JSON Schema Draft v4. +* 支持 Unicod 代理对(surrogate pair)。 +* 支持空字符(`"\u0000"`)。 + * 例如,可以优雅地解析及处理 `["Hello\u0000World"]`。含读写字符串长度的 API。 +* 支持可选的放宽语法 + * 单行(`// ...`)及多行(`/* ... */`) 注释 (`kParseCommentsFlag`)。 + * 在对象和数组结束前含逗号 (`kParseTrailingCommasFlag`)。 + * `NaN`、`Inf`、`Infinity`、`-Inf` 及 `-Infinity` 作为 `double` 值 (`kParseNanAndInfFlag`) +* [NPM 兼容](https://github.com/miloyip/rapidjson/blob/master/doc/npm.md). + +## Unicode + +* 支持 UTF-8、UTF-16、UTF-32 编码,包括小端序和大端序。 + * 这些编码用于输入输出流,以及内存中的表示。 +* 支持从输入流自动检测编码。 +* 内部支持编码的转换。 + * 例如,你可以读取一个 UTF-8 文件,让 RapidJSON 把 JSON 字符串转换至 UTF-16 的 DOM。 +* 内部支持编码校验。 + * 例如,你可以读取一个 UTF-8 文件,让 RapidJSON 检查是否所有 JSON 字符串是合法的 UTF-8 字节序列。 +* 支持自定义的字符类型。 + * 预设的字符类型是:UTF-8 为 `char`,UTF-16 为 `wchar_t`,UTF32 为 `uint32_t`。 +* 支持自定义的编码。 + +## API 风格 + +* SAX(Simple API for XML)风格 API + * 类似于 [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML), RapidJSON 提供一个事件循序访问的解析器 API(`rapidjson::GenericReader`)。RapidJSON 也提供一个生成器 API(`rapidjson::Writer`),可以处理相同的事件集合。 +* DOM(Document Object Model)风格 API + * 类似于 HTML/XML 的 [DOM](http://en.wikipedia.org/wiki/Document_Object_Model),RapidJSON 可把 JSON 解析至一个 DOM 表示方式(`rapidjson::GenericDocument`),以方便操作。如有需要,可把 DOM 转换(stringify)回 JSON。 + * DOM 风格 API(`rapidjson::GenericDocument`)实际上是由 SAX 风格 API(`rapidjson::GenericReader`)实现的。SAX 更快,但有时 DOM 更易用。用户可根据情况作出选择。 + +## 解析 + +* 递归式(预设)及迭代式解析器 + * 递归式解析器较快,但在极端情况下可出现堆栈溢出。 + * 迭代式解析器使用自定义的堆栈去维持解析状态。 +* 支持原位(*in situ*)解析。 + * 把 JSON 字符串的值解析至原 JSON 之中,然后让 DOM 指向那些字符串。 + * 比常规分析更快:不需字符串的内存分配、不需复制(如字符串不含转义符)、缓存友好。 +* 对于 JSON 数字类型,支持 32-bit/64-bit 的有号/无号整数,以及 `double`。 +* 错误处理 + * 支持详尽的解析错误代号。 + * 支持本地化错误信息。 + +## DOM (Document) + +* RapidJSON 在类型转换时会检查数值的范围。 +* 字符串字面量的优化 + * 只储存指针,不作复制 +* 优化“短”字符串 + * 在 `Value` 内储存短字符串,无需额外分配。 + * 对 UTF-8 字符串来说,32 位架构下可存储最多 11 字符,64 位下 21 字符(x86-64 下 13 字符)。 +* 可选地支持 `std::string`(定义 `RAPIDJSON_HAS_STDSTRING=1`) + +## 生成 + +* 支持 `rapidjson::PrettyWriter` 去加入换行及缩进。 + +## 输入输出流 + +* 支持 `rapidjson::GenericStringBuffer`,把输出的 JSON 储存于字符串内。 +* 支持 `rapidjson::FileReadStream` 及 `rapidjson::FileWriteStream`,使用 `FILE` 对象作输入输出。 +* 支持自定义输入输出流。 + +## 内存 + +* 最小化 DOM 的内存开销。 + * 对大部分 32/64 位机器而言,每个 JSON 值只占 16 或 20 字节(不包含字符串)。 +* 支持快速的预设分配器。 + * 它是一个堆栈形式的分配器(顺序分配,不容许单独释放,适合解析过程之用)。 + * 使用者也可提供一个预分配的缓冲区。(有可能达至无需 CRT 分配就能解析多个 JSON) +* 支持标准 CRT(C-runtime)分配器。 +* 支持自定义分配器。 + +## 其他 + +* 一些 C++11 的支持(可选) + * 右值引用(rvalue reference) + * `noexcept` 修饰符 + * 范围 for 循环 diff --git a/thirdparty/rapidjson-1.1.0/doc/internals.md b/thirdparty/rapidjson-1.1.0/doc/internals.md new file mode 100644 index 0000000000..49802a0fd7 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/internals.md @@ -0,0 +1,365 @@ +# Internals + +This section records some design and implementation details. + +[TOC] + +# Architecture {#Architecture} + +## SAX and DOM + +The basic relationships of SAX and DOM is shown in the following UML diagram. + +![Architecture UML class diagram](diagram/architecture.png) + +The core of the relationship is the `Handler` concept. From the SAX side, `Reader` parses a JSON from a stream and publish events to a `Handler`. `Writer` implements the `Handler` concept to handle the same set of events. From the DOM side, `Document` implements the `Handler` concept to build a DOM according to the events. `Value` supports a `Value::Accept(Handler&)` function, which traverses the DOM to publish events. + +With this design, SAX is not dependent on DOM. Even `Reader` and `Writer` have no dependencies between them. This provides flexibility to chain event publisher and handlers. Besides, `Value` does not depends on SAX as well. So, in addition to stringify a DOM to JSON, user may also stringify it to a XML writer, or do anything else. + +## Utility Classes + +Both SAX and DOM APIs depends on 3 additional concepts: `Allocator`, `Encoding` and `Stream`. Their inheritance hierarchy is shown as below. + +![Utility classes UML class diagram](diagram/utilityclass.png) + +# Value {#Value} + +`Value` (actually a typedef of `GenericValue>`) is the core of DOM API. This section describes the design of it. + +## Data Layout {#DataLayout} + +`Value` is a [variant type](http://en.wikipedia.org/wiki/Variant_type). In RapidJSON's context, an instance of `Value` can contain 1 of 6 JSON value types. This is possible by using `union`. Each `Value` contains two members: `union Data data_` and a`unsigned flags_`. The `flags_` indiciates the JSON type, and also additional information. + +The following tables show the data layout of each type. The 32-bit/64-bit columns indicates the size of the field in bytes. + +| Null | |32-bit|64-bit| +|-------------------|----------------------------------|:----:|:----:| +| (unused) | |4 |8 | +| (unused) | |4 |4 | +| (unused) | |4 |4 | +| `unsigned flags_` | `kNullType kNullFlag` |4 |4 | + +| Bool | |32-bit|64-bit| +|-------------------|----------------------------------------------------|:----:|:----:| +| (unused) | |4 |8 | +| (unused) | |4 |4 | +| (unused) | |4 |4 | +| `unsigned flags_` | `kBoolType` (either `kTrueFlag` or `kFalseFlag`) |4 |4 | + +| String | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `Ch* str` | Pointer to the string (may own) |4 |8 | +| `SizeType length` | Length of string |4 |4 | +| (unused) | |4 |4 | +| `unsigned flags_` | `kStringType kStringFlag ...` |4 |4 | + +| Object | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `Member* members` | Pointer to array of members (owned) |4 |8 | +| `SizeType size` | Number of members |4 |4 | +| `SizeType capacity` | Capacity of members |4 |4 | +| `unsigned flags_` | `kObjectType kObjectFlag` |4 |4 | + +| Array | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `Value* values` | Pointer to array of values (owned) |4 |8 | +| `SizeType size` | Number of values |4 |4 | +| `SizeType capacity` | Capacity of values |4 |4 | +| `unsigned flags_` | `kArrayType kArrayFlag` |4 |4 | + +| Number (Int) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `int i` | 32-bit signed integer |4 |4 | +| (zero padding) | 0 |4 |4 | +| (unused) | |4 |8 | +| `unsigned flags_` | `kNumberType kNumberFlag kIntFlag kInt64Flag ...` |4 |4 | + +| Number (UInt) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `unsigned u` | 32-bit unsigned integer |4 |4 | +| (zero padding) | 0 |4 |4 | +| (unused) | |4 |8 | +| `unsigned flags_` | `kNumberType kNumberFlag kUIntFlag kUInt64Flag ...` |4 |4 | + +| Number (Int64) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `int64_t i64` | 64-bit signed integer |8 |8 | +| (unused) | |4 |8 | +| `unsigned flags_` | `kNumberType kNumberFlag kInt64Flag ...` |4 |4 | + +| Number (Uint64) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `uint64_t i64` | 64-bit unsigned integer |8 |8 | +| (unused) | |4 |8 | +| `unsigned flags_` | `kNumberType kNumberFlag kInt64Flag ...` |4 |4 | + +| Number (Double) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `uint64_t i64` | Double precision floating-point |8 |8 | +| (unused) | |4 |8 | +| `unsigned flags_` | `kNumberType kNumberFlag kDoubleFlag` |4 |4 | + +Here are some notes: +* To reduce memory consumption for 64-bit architecture, `SizeType` is typedef as `unsigned` instead of `size_t`. +* Zero padding for 32-bit number may be placed after or before the actual type, according to the endianess. This makes possible for interpreting a 32-bit integer as a 64-bit integer, without any conversion. +* An `Int` is always an `Int64`, but the converse is not always true. + +## Flags {#Flags} + +The 32-bit `flags_` contains both JSON type and other additional information. As shown in the above tables, each JSON type contains redundant `kXXXType` and `kXXXFlag`. This design is for optimizing the operation of testing bit-flags (`IsNumber()`) and obtaining a sequential number for each type (`GetType()`). + +String has two optional flags. `kCopyFlag` means that the string owns a copy of the string. `kInlineStrFlag` means using [Short-String Optimization](#ShortString). + +Number is a bit more complicated. For normal integer values, it can contains `kIntFlag`, `kUintFlag`, `kInt64Flag` and/or `kUint64Flag`, according to the range of the integer. For numbers with fraction, and integers larger than 64-bit range, they will be stored as `double` with `kDoubleFlag`. + +## Short-String Optimization {#ShortString} + + [Kosta](https://github.com/Kosta-Github) provided a very neat short-string optimization. The optimization idea is given as follow. Excluding the `flags_`, a `Value` has 12 or 16 bytes (32-bit or 64-bit) for storing actual data. Instead of storing a pointer to a string, it is possible to store short strings in these space internally. For encoding with 1-byte character type (e.g. `char`), it can store maximum 11 or 15 characters string inside the `Value` type. + +| ShortString (Ch=char) | |32-bit|64-bit| +|---------------------|-------------------------------------|:----:|:----:| +| `Ch str[MaxChars]` | String buffer |11 |15 | +| `Ch invLength` | MaxChars - Length |1 |1 | +| `unsigned flags_` | `kStringType kStringFlag ...` |4 |4 | + +A special technique is applied. Instead of storing the length of string directly, it stores (MaxChars - length). This make it possible to store 11 characters with trailing `\0`. + +This optimization can reduce memory usage for copy-string. It can also improve cache-coherence thus improve runtime performance. + +# Allocator {#InternalAllocator} + +`Allocator` is a concept in RapidJSON: +~~~cpp +concept Allocator { + static const bool kNeedFree; //!< Whether this allocator needs to call Free(). + + // Allocate a memory block. + // \param size of the memory block in bytes. + // \returns pointer to the memory block. + void* Malloc(size_t size); + + // Resize a memory block. + // \param originalPtr The pointer to current memory block. Null pointer is permitted. + // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.) + // \param newSize the new size in bytes. + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize); + + // Free a memory block. + // \param pointer to the memory block. Null pointer is permitted. + static void Free(void *ptr); +}; +~~~ + +Note that `Malloc()` and `Realloc()` are member functions but `Free()` is static member function. + +## MemoryPoolAllocator {#MemoryPoolAllocator} + +`MemoryPoolAllocator` is the default allocator for DOM. It allocate but do not free memory. This is suitable for building a DOM tree. + +Internally, it allocates chunks of memory from the base allocator (by default `CrtAllocator`) and stores the chunks as a singly linked list. When user requests an allocation, it allocates memory from the following order: + +1. User supplied buffer if it is available. (See [User Buffer section in DOM](doc/dom.md)) +2. If user supplied buffer is full, use the current memory chunk. +3. If the current block is full, allocate a new block of memory. + +# Parsing Optimization {#ParsingOptimization} + +## Skip Whitespaces with SIMD {#SkipwhitespaceWithSIMD} + +When parsing JSON from a stream, the parser need to skip 4 whitespace characters: + +1. Space (`U+0020`) +2. Character Tabulation (`U+000B`) +3. Line Feed (`U+000A`) +4. Carriage Return (`U+000D`) + +A simple implementation will be simply: +~~~cpp +void SkipWhitespace(InputStream& s) { + while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t') + s.Take(); +} +~~~ + +However, this requires 4 comparisons and a few branching for each character. This was found to be a hot spot. + +To accelerate this process, SIMD was applied to compare 16 characters with 4 white spaces for each iteration. Currently RapidJSON only supports SSE2 and SSE4.2 instructions for this. And it is only activated for UTF-8 memory streams, including string stream or *in situ* parsing. + +To enable this optimization, need to define `RAPIDJSON_SSE2` or `RAPIDJSON_SSE42` before including `rapidjson.h`. Some compilers can detect the setting, as in `perftest.h`: + +~~~cpp +// __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler. +// We use -march=native with gmake to enable -msse2 and -msse4.2, if supported. +#if defined(__SSE4_2__) +# define RAPIDJSON_SSE42 +#elif defined(__SSE2__) +# define RAPIDJSON_SSE2 +#endif +~~~ + +Note that, these are compile-time settings. Running the executable on a machine without such instruction set support will make it crash. + +### Page boundary issue + +In an early version of RapidJSON, [an issue](https://code.google.com/archive/p/rapidjson/issues/104) reported that the `SkipWhitespace_SIMD()` causes crash very rarely (around 1 in 500,000). After investigation, it is suspected that `_mm_loadu_si128()` accessed bytes after `'\0'`, and across a protected page boundary. + +In [Intel® 64 and IA-32 Architectures Optimization Reference Manual +](http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html), section 10.2.1: + +> To support algorithms requiring unaligned 128-bit SIMD memory accesses, memory buffer allocation by a caller function should consider adding some pad space so that a callee function can safely use the address pointer safely with unaligned 128-bit SIMD memory operations. +> The minimal padding size should be the width of the SIMD register that might be used in conjunction with unaligned SIMD memory access. + +This is not feasible as RapidJSON should not enforce such requirement. + +To fix this issue, currently the routine process bytes up to the next aligned address. After tha, use aligned read to perform SIMD processing. Also see [#85](https://github.com/miloyip/rapidjson/issues/85). + +## Local Stream Copy {#LocalStreamCopy} + +During optimization, it is found that some compilers cannot localize some member data access of streams into local variables or registers. Experimental results show that for some stream types, making a copy of the stream and used it in inner-loop can improve performance. For example, the actual (non-SIMD) implementation of `SkipWhitespace()` is implemented as: + +~~~cpp +template +void SkipWhitespace(InputStream& is) { + internal::StreamLocalCopy copy(is); + InputStream& s(copy.s); + + while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t') + s.Take(); +} +~~~ + +Depending on the traits of stream, `StreamLocalCopy` will make (or not make) a copy of the stream object, use it locally and copy the states of stream back to the original stream. + +## Parsing to Double {#ParsingDouble} + +Parsing string into `double` is difficult. The standard library function `strtod()` can do the job but it is slow. By default, the parsers use normal precision setting. This has has maximum 3 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) error and implemented in `internal::StrtodNormalPrecision()`. + +When using `kParseFullPrecisionFlag`, the parsers calls `internal::StrtodFullPrecision()` instead, and this function actually implemented 3 versions of conversion methods. +1. [Fast-Path](http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/). +2. Custom DIY-FP implementation as in [double-conversion](https://github.com/floitsch/double-conversion). +3. Big Integer Method as in (Clinger, William D. How to read floating point numbers accurately. Vol. 25. No. 6. ACM, 1990). + +If the first conversion methods fail, it will try the second, and so on. + +# Generation Optimization {#GenerationOptimization} + +## Integer-to-String conversion {#itoa} + +The naive algorithm for integer-to-string conversion involves division per each decimal digit. We have implemented various implementations and evaluated them in [itoa-benchmark](https://github.com/miloyip/itoa-benchmark). + +Although SSE2 version is the fastest but the difference is minor by comparing to the first running-up `branchlut`. And `branchlut` is pure C++ implementation so we adopt `branchlut` in RapidJSON. + +## Double-to-String conversion {#dtoa} + +Originally RapidJSON uses `snprintf(..., ..., "%g")` to achieve double-to-string conversion. This is not accurate as the default precision is 6. Later we also find that this is slow and there is an alternative. + +Google's V8 [double-conversion](https://github.com/floitsch/double-conversion +) implemented a newer, fast algorithm called Grisu3 (Loitsch, Florian. "Printing floating-point numbers quickly and accurately with integers." ACM Sigplan Notices 45.6 (2010): 233-243.). + +However, since it is not header-only so that we implemented a header-only version of Grisu2. This algorithm guarantees that the result is always accurate. And in most of cases it produces the shortest (optimal) string representation. + +The header-only conversion function has been evaluated in [dtoa-benchmark](https://github.com/miloyip/dtoa-benchmark). + +# Parser {#Parser} + +## Iterative Parser {#IterativeParser} + +The iterative parser is a recursive descent LL(1) parser +implemented in a non-recursive manner. + +### Grammar {#IterativeParserGrammar} + +The grammar used for this parser is based on strict JSON syntax: +~~~~~~~~~~ +S -> array | object +array -> [ values ] +object -> { members } +values -> non-empty-values | ε +non-empty-values -> value addition-values +addition-values -> ε | , non-empty-values +members -> non-empty-members | ε +non-empty-members -> member addition-members +addition-members -> ε | , non-empty-members +member -> STRING : value +value -> STRING | NUMBER | NULL | BOOLEAN | object | array +~~~~~~~~~~ + +Note that left factoring is applied to non-terminals `values` and `members` +to make the grammar be LL(1). + +### Parsing Table {#IterativeParserParsingTable} + +Based on the grammar, we can construct the FIRST and FOLLOW set. + +The FIRST set of non-terminals is listed below: + +| NON-TERMINAL | FIRST | +|:-----------------:|:--------------------------------:| +| array | [ | +| object | { | +| values | ε STRING NUMBER NULL BOOLEAN { [ | +| addition-values | ε COMMA | +| members | ε STRING | +| addition-members | ε COMMA | +| member | STRING | +| value | STRING NUMBER NULL BOOLEAN { [ | +| S | [ { | +| non-empty-members | STRING | +| non-empty-values | STRING NUMBER NULL BOOLEAN { [ | + +The FOLLOW set is listed below: + +| NON-TERMINAL | FOLLOW | +|:-----------------:|:-------:| +| S | $ | +| array | , $ } ] | +| object | , $ } ] | +| values | ] | +| non-empty-values | ] | +| addition-values | ] | +| members | } | +| non-empty-members | } | +| addition-members | } | +| member | , } | +| value | , } ] | + +Finally the parsing table can be constructed from FIRST and FOLLOW set: + +| NON-TERMINAL | [ | { | , | : | ] | } | STRING | NUMBER | NULL | BOOLEAN | +|:-----------------:|:---------------------:|:---------------------:|:-------------------:|:-:|:-:|:-:|:-----------------------:|:---------------------:|:---------------------:|:---------------------:| +| S | array | object | | | | | | | | | +| array | [ values ] | | | | | | | | | | +| object | | { members } | | | | | | | | | +| values | non-empty-values | non-empty-values | | | ε | | non-empty-values | non-empty-values | non-empty-values | non-empty-values | +| non-empty-values | value addition-values | value addition-values | | | | | value addition-values | value addition-values | value addition-values | value addition-values | +| addition-values | | | , non-empty-values | | ε | | | | | | +| members | | | | | | ε | non-empty-members | | | | +| non-empty-members | | | | | | | member addition-members | | | | +| addition-members | | | , non-empty-members | | | ε | | | | | +| member | | | | | | | STRING : value | | | | +| value | array | object | | | | | STRING | NUMBER | NULL | BOOLEAN | + +There is a great [tool](http://hackingoff.com/compilers/predict-first-follow-set) for above grammar analysis. + +### Implementation {#IterativeParserImplementation} + +Based on the parsing table, a direct(or conventional) implementation +that pushes the production body in reverse order +while generating a production could work. + +In RapidJSON, several modifications(or adaptations to current design) are made to a direct implementation. + +First, the parsing table is encoded in a state machine in RapidJSON. +States are constructed by the head and body of production. +State transitions are constructed by production rules. +Besides, extra states are added for productions involved with `array` and `object`. +In this way the generation of array values or object members would be a single state transition, +rather than several pop/push operations in the direct implementation. +This also makes the estimation of stack size more easier. + +The state diagram is shown as follows: + +![State Diagram](diagram/iterative-parser-states-diagram.png) + +Second, the iterative parser also keeps track of array's value count and object's member count +in its internal stack, which may be different from a conventional implementation. diff --git a/thirdparty/rapidjson-1.1.0/doc/logo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aPRMt*w&S>nD?sB=UH+eDQH63H}dq$s$~{%SQBj+gYC(y%AJa3 zRf_R%iK1t`ZiuvLY!A%9lRq8{eHF44s``$ITtmkIilo?XRh=Xvn_)()Q52Im%*7&i z&eV?Sp`M{*jBm_`+dW3S3p1wdOnLnA``A+ScffU;kYdUQRsE%iJc?!08J3gx78W_D z0oq@Q$Rup9?+add2HOIR&++L_@z^u?9kQIfIlxgOG7cM{b|D6L2!>-8=a;eEcu5Le7b3DA7W2G5W|{AYDbx%stoYulzoVl3 z6|wXBE&2Ez^~dZSGqds(wxxQk*}meDzcQxmpT$;6>tI{l7qaqKRjrc9veU7|Df;4q zi0nwmpaKO})uk}gN*irdMdsR`ew{uX!77v>IJm(U*yIN^P`} zf-a%x+1F7QcRHmu+E`-IB@~@v#M%PP1FVfUx&*q4qPxrXC$#nHl-g)xiA7gc^!EO| zjV^_*qUfzi9o0q~OD&dpMHi9vfz_PL?HRp|E`?=Y(J9X6^DuYGHrnVi_< RrWpVL002ovPDHLkV1jI2B + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + RapidJSON + + diff --git a/thirdparty/rapidjson-1.1.0/doc/misc/DoxygenLayout.xml b/thirdparty/rapidjson-1.1.0/doc/misc/DoxygenLayout.xml new file mode 100644 index 0000000000..b7c958665b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/misc/DoxygenLayout.xml @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/thirdparty/rapidjson-1.1.0/doc/misc/doxygenextra.css b/thirdparty/rapidjson-1.1.0/doc/misc/doxygenextra.css new file mode 100644 index 0000000000..bd6737585b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/misc/doxygenextra.css @@ -0,0 +1,274 @@ +body code { + margin: 0; + border: 1px solid #ddd; + background-color: #f8f8f8; + border-radius: 3px; + padding: 0; +} + +a { + color: #4183c4; +} + +a.el { + font-weight: normal; +} + +body, table, div, p, dl { + color: #333333; + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + font-size: 15px; + font-style: normal; + font-variant: normal; + font-weight: normal; + line-height: 25.5px; +} + +body { + background-color: #eee; +} + +div.header { + background-image: none; + background-color: white; + margin: 0px; + border: 0px; +} + +div.headertitle { + width: 858px; + margin: 30px; + padding: 0px; +} + +div.toc { + background-color: #f8f8f8; + border-color: #ddd; + margin-right: 10px; + margin-left: 20px; +} +div.toc h3 { + color: #333333; + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + font-size: 18px; + font-style: normal; + font-variant: normal; + font-weight: normal; +} +div.toc li { + color: #333333; + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + font-size: 12px; + font-style: normal; + font-variant: normal; + font-weight: normal; +} + +.title { + font-size: 2.5em; + line-height: 63.75px; + border-bottom: 1px solid #ddd; + margin-bottom: 15px; + margin-left: 0px; + margin-right: 0px; + margin-top: 0px; +} + +.summary { + float: none !important; + width: auto !important; + padding-top: 10px; + padding-right: 10px !important; +} + +.summary + .headertitle .title { + font-size: 1.5em; + line-height: 2.0em; +} + +body h1 { + font-size: 2em; + line-height: 1.7; + border-bottom: 1px solid #eee; + margin: 1em 0 15px; + padding: 0; + overflow: hidden; +} + +body h2 { + font-size: 1.5em; + line-height: 1.7; + margin: 1em 0 15px; + padding: 0; +} + +pre.fragment { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 13px; + font-style: normal; + font-variant: normal; + font-weight: normal; + line-height: 19px; +} + +table.doxtable th { + background-color: #f8f8f8; + color: #333333; + font-size: 15px; +} + +table.doxtable td, table.doxtable th { + border: 1px solid #ddd; +} + +#doc-content { + background-color: #fff; + width: 918px; + height: auto !important; + margin-left: 270px !important; +} + +div.contents { + width: 858px; + margin: 30px; +} + +div.line { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 13px; + font-style: normal; + font-variant: normal; + font-weight: normal; + line-height: 19px; +} + +tt, code, pre { + font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; + font-size: 12px; +} + +div.fragment { + background-color: #f8f8f8; + border: 1px solid #ddd; + font-size: 13px; + line-height: 19px; + overflow: auto; + padding: 6px 10px; + border-radius: 3px; +} + +#topbanner { + position: fixed; + margin: 15px; + z-index: 101; +} + +#projectname +{ + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + font-size: 38px; + font-weight: bold; + line-height: 63.75px; + margin: 0px; + padding: 2px 0px; +} + +#projectbrief +{ + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + font-size: 16px; + line-height: 22.4px; + margin: 0px 0px 13px 0px; + padding: 2px; +} + +/* side bar and search */ + +#side-nav +{ + padding: 10px 0px 20px 20px; + border-top: 60px solid #2980b9; + background-color: #343131; + width: 250px !important; + height: 100% !important; + position: fixed; +} + +#nav-tree +{ + background-color: transparent; + background-image: none; + height: 100% !important; +} + +#nav-tree .label +{ + font-family: Helvetica, arial, freesans, clean, sans-serif, 'Segoe UI Emoji', 'Segoe UI Symbol'; + line-height: 25.5px; + font-size: 15px; +} + +#nav-tree +{ + color: #b3b3b3; +} + +#nav-tree .selected { + background-image: none; +} + +#nav-tree a +{ + color: #b3b3b3; +} + +#github +{ + position: fixed; + left: auto; + right: auto; + width: 250px; +} + +#MSearchBox +{ + margin: 20px; + left: 40px; + right: auto; + position: fixed; + width: 180px; +} + +#MSearchField +{ + width: 121px; +} + +#MSearchResultsWindow +{ + left: 45px !important; +} + +#nav-sync +{ + display: none; +} + +.ui-resizable .ui-resizable-handle +{ + width: 0px; +} + +#nav-path +{ + display: none; +} + +/* external link icon */ +div.contents a[href ^= "http"]:after { + content: " " url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAVklEQVR4Xn3PgQkAMQhDUXfqTu7kTtkpd5RA8AInfArtQ2iRXFWT2QedAfttj2FsPIOE1eCOlEuoWWjgzYaB/IkeGOrxXhqB+uA9Bfcm0lAZuh+YIeAD+cAqSz4kCMUAAAAASUVORK5CYII=); +} + +.githublogo { + content: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NDkxMSwgMjAxMy8xMC8yOS0xMTo0NzoxNiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RERCMUIwOUY4NkNFMTFFM0FBNTJFRTMzN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fIfgGZjhU6xPaJgBV8BdsMw5cbZoHsenwYFxkZzl83xTSKTiviCAfCsJLysH3POfC8m8NegyGAGfLP/VmGmfSChgXroR0RSWjEFv2J/nG84cuKFMf4sTCZqXuJd4KaXFVjEG3+tw4eXbNK/YC9oXXs3O8NY8y99L4BXY5cvLY/Bb2VZ58EOJVcB18DHJq9lRsKr8inyKGVjlmh29mtHs3AHfuhCwy1vXT/Nu2GKQt+UHsGdctyX6eQyNvc+5sfX9Dl7Pe2J/BRgAl2CpwmrsHR0AAAAASUVORK5CYII=); +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/doc/misc/footer.html b/thirdparty/rapidjson-1.1.0/doc/misc/footer.html new file mode 100644 index 0000000000..77f1131188 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/misc/footer.html @@ -0,0 +1,11 @@ + + + +

+ + + diff --git a/thirdparty/rapidjson-1.1.0/doc/misc/header.html b/thirdparty/rapidjson-1.1.0/doc/misc/header.html new file mode 100644 index 0000000000..2dbe721465 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/misc/header.html @@ -0,0 +1,24 @@ + + + + + + + +$projectname: $title +$title + + + +$treeview +$search +$mathjax + +$extrastylesheet + + +
+
+$searchbox + + diff --git a/thirdparty/rapidjson-1.1.0/doc/npm.md b/thirdparty/rapidjson-1.1.0/doc/npm.md new file mode 100644 index 0000000000..5efa768213 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/npm.md @@ -0,0 +1,31 @@ +## NPM + +# package.json {#package} + +~~~~~~~~~~js +{ + ... + "dependencies": { + ... + "rapidjson": "git@github.com:miloyip/rapidjson.git" + }, + ... + "gypfile": true +} +~~~~~~~~~~ + +# binding.gyp {#binding} + +~~~~~~~~~~js +{ + ... + 'targets': [ + { + ... + 'include_dirs': [ + 'SetInt(stars->GetInt() + 1); + +// { "project" : "RapidJSON", "stars" : 11 } + +// Set() and Create() automatically generate parents if not exist. +Pointer("/a/b/0").Create(d); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] } } + +// GetWithDefault() returns reference. And it deep clones the default value. +Value& hello = Pointer("/hello").GetWithDefault(d, "world"); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "world" } + +// Swap() is similar to Set() +Value x("C++"); +Pointer("/hello").Swap(d, x); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "C++" } +// x becomes "world" + +// Erase a member or element, return true if the value exists +bool success = Pointer("/a").Erase(d); +assert(success); + +// { "project" : "RapidJSON", "stars" : 10 } +~~~ + +# Helper Functions {#HelperFunctions} + +Since object-oriented calling convention may be non-intuitive, RapidJSON also provides helper functions, which just wrap the member functions with free-functions. + +The following example does exactly the same as the above one. + +~~~cpp +Document d; + +SetValueByPointer(d, "/project", "RapidJSON"); +SetValueByPointer(d, "/stars", 10); + +if (Value* stars = GetValueByPointer(d, "/stars")) + stars->SetInt(stars->GetInt() + 1); + +CreateValueByPointer(d, "/a/b/0"); + +Value& hello = GetValueByPointerWithDefault(d, "/hello", "world"); + +Value x("C++"); +SwapValueByPointer(d, "/hello", x); + +bool success = EraseValueByPointer(d, "/a"); +assert(success); +~~~ + +The conventions are shown here for comparison: + +1. `Pointer(source).(root, ...)` +2. `ValueByPointer(root, Pointer(source), ...)` +3. `ValueByPointer(root, source, ...)` + +# Resolving Pointer {#ResolvingPointer} + +`Pointer::Get()` or `GetValueByPointer()` function does not modify the DOM. If the tokens cannot match a value in the DOM, it returns `nullptr`. User can use this to check whether a value exists. + +Note that, numerical tokens can represent an array index or member name. The resolving process will match the values according to the types of value. + +~~~javascript +{ + "0" : 123, + "1" : [456] +} +~~~ + +1. `"/0"` → `123` +2. `"/1/0"` → `456` + +The token `"0"` is treated as member name in the first pointer. It is treated as an array index in the second pointer. + +The other functions, including `Create()`, `GetWithDefault()`, `Set()` and `Swap()`, will change the DOM. These functions will always succeed. They will create the parent values if they do not exist. If the parent values do not match the tokens, they will also be forced to change their type. Changing the type also mean fully removal of that DOM subtree. + +Parsing the above JSON into `d`, + +~~~cpp +SetValueByPointer(d, "1/a", 789); // { "0" : 123, "1" : { "a" : 789 } } +~~~ + +## Resolving Minus Sign Token + +Besides, [RFC6901] defines a special token `-` (single minus sign), which represents the pass-the-end element of an array. `Get()` only treats this token as a member name '"-"'. Yet the other functions can resolve this for array, equivalent to calling `Value::PushBack()` to the array. + +~~~cpp +Document d; +d.Parse("{\"foo\":[123]}"); +SetValueByPointer(d, "/foo/-", 456); // { "foo" : [123, 456] } +SetValueByPointer(d, "/-", 789); // { "foo" : [123, 456], "-" : 789 } +~~~ + +## Resolving Document and Value + +When using `p.Get(root)` or `GetValueByPointer(root, p)`, `root` is a (const) `Value&`. That means, it can be a subtree of the DOM. + +The other functions have two groups of signature. One group uses `Document& document` as parameter, another one uses `Value& root`. The first group uses `document.GetAllocator()` for creating values. And the second group needs user to supply an allocator, like the functions in DOM. + +All examples above do not require an allocator parameter, because the first parameter is a `Document&`. But if you want to resolve a pointer to a subtree, you need to supply the allocator as in the following example: + +~~~cpp +class Person { +public: + Person() { + document_ = new Document(); + // CreateValueByPointer() here no need allocator + SetLocation(CreateValueByPointer(*document_, "/residence"), ...); + SetLocation(CreateValueByPointer(*document_, "/office"), ...); + }; + +private: + void SetLocation(Value& location, const char* country, const char* addresses[2]) { + Value::Allocator& a = document_->GetAllocator(); + // SetValueByPointer() here need allocator + SetValueByPointer(location, "/country", country, a); + SetValueByPointer(location, "/address/0", address[0], a); + SetValueByPointer(location, "/address/1", address[1], a); + } + + // ... + + Document* document_; +}; +~~~ + +`Erase()` or `EraseValueByPointer()` does not need allocator. And they return `true` if the value is erased successfully. + +# Error Handling {#ErrorHandling} + +A `Pointer` parses a source string in its constructor. If there is parsing error, `Pointer::IsValid()` returns `false`. And you can use `Pointer::GetParseErrorCode()` and `GetParseErrorOffset()` to retrieve the error information. + +Note that, all resolving functions assumes valid pointer. Resolving with an invalid pointer causes assertion failure. + +# URI Fragment Representation {#URIFragment} + +In addition to the string representation of JSON pointer that we are using till now, [RFC6901] also defines the URI fragment representation of JSON pointer. URI fragment is specified in [RFC3986] "Uniform Resource Identifier (URI): Generic Syntax". + +The main differences are that a the URI fragment always has a `#` (pound sign) in the beginning, and some characters are encoded by percent-encoding in UTF-8 sequence. For example, the following table shows different C/C++ string literals of different representations. + +String Representation | URI Fragment Representation | Pointer Tokens (UTF-8) +----------------------|-----------------------------|------------------------ +`"/foo/0"` | `"#/foo/0"` | `{"foo", 0}` +`"/a~1b"` | `"#/a~1b"` | `{"a/b"}` +`"/m~0n"` | `"#/m~0n"` | `{"m~n"}` +`"/ "` | `"#/%20"` | `{" "}` +`"/\0"` | `"#/%00"` | `{"\0"}` +`"/€"` | `"#/%E2%82%AC"` | `{"€"}` + +RapidJSON fully support URI fragment representation. It automatically detects the pound sign during parsing. + +# Stringify + +You may also stringify a `Pointer` to a string or other output streams. This can be done by: + +~~~ +Pointer p(...); +StringBuffer sb; +p.Stringify(sb); +std::cout << sb.GetString() << std::endl; +~~~ + +It can also stringify to URI fragment reprsentation by `StringifyUriFragment()`. + +# User-Supplied Tokens {#UserSuppliedTokens} + +If a pointer will be resolved multiple times, it should be constructed once, and then apply it to different DOMs or in different times. This reduce time and memory allocation for constructing `Pointer` multiple times. + +We can go one step further, to completely eliminate the parsing process and dynamic memory allocation, we can establish the token array directly: + +~~~cpp +#define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } +#define INDEX(i) { #i, sizeof(#i) - 1, i } + +static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) }; +static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); +// Equivalent to static const Pointer p("/foo/123"); +~~~ + +This may be useful for memory constrained systems. + +[RFC3986]: https://tools.ietf.org/html/rfc3986 +[RFC6901]: https://tools.ietf.org/html/rfc6901 diff --git a/thirdparty/rapidjson-1.1.0/doc/pointer.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/pointer.zh-cn.md new file mode 100644 index 0000000000..f58f55f3d4 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/pointer.zh-cn.md @@ -0,0 +1,234 @@ +# Pointer + +(本功能于 v1.1.0 发布) + +JSON Pointer 是一个标准化([RFC6901])的方式去选取一个 JSON Document(DOM)中的值。这类似于 XML 的 XPath。然而,JSON Pointer 简单得多,而且每个 JSON Pointer 仅指向单个值。 + +使用 RapidJSON 的 JSON Pointer 实现能简化一些 DOM 的操作。 + +[TOC] + +# JSON Pointer {#JsonPointer} + +一个 JSON Pointer 由一串(零至多个)token 所组成,每个 token 都有 `/` 前缀。每个 token 可以是一个字符串或数字。例如,给定一个 JSON: +~~~javascript +{ + "foo" : ["bar", "baz"], + "pi" : 3.1416 +} +~~~ + +以下的 JSON Pointer 解析为: + +1. `"/foo"` → `[ "bar", "baz" ]` +2. `"/foo/0"` → `"bar"` +3. `"/foo/1"` → `"baz"` +4. `"/pi"` → `3.1416` + +要注意,一个空 JSON Pointer `""` (零个 token)解析为整个 JSON。 + +# 基本使用方法 {#BasicUsage} + +以下的代码范例不解自明。 + +~~~cpp +#include "rapidjson/pointer.h" + +// ... +Document d; + +// 使用 Set() 创建 DOM +Pointer("/project").Set(d, "RapidJSON"); +Pointer("/stars").Set(d, 10); + +// { "project" : "RapidJSON", "stars" : 10 } + +// 使用 Get() 访问 DOM。若该值不存在则返回 nullptr。 +if (Value* stars = Pointer("/stars").Get(d)) + stars->SetInt(stars->GetInt() + 1); + +// { "project" : "RapidJSON", "stars" : 11 } + +// Set() 和 Create() 自动生成父值(如果它们不存在)。 +Pointer("/a/b/0").Create(d); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] } } + +// GetWithDefault() 返回引用。若该值不存在则会深拷贝缺省值。 +Value& hello = Pointer("/hello").GetWithDefault(d, "world"); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "world" } + +// Swap() 和 Set() 相似 +Value x("C++"); +Pointer("/hello").Swap(d, x); + +// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "C++" } +// x 变成 "world" + +// 删去一个成员或元素,若值存在返回 true +bool success = Pointer("/a").Erase(d); +assert(success); + +// { "project" : "RapidJSON", "stars" : 10 } +~~~ + +# 辅助函数 {#HelperFunctions} + +由于面向对象的调用习惯可能不符直觉,RapidJSON 也提供了一些辅助函数,它们把成员函数包装成自由函数。 + +以下的例子与上面例子所做的事情完全相同。 + +~~~cpp +Document d; + +SetValueByPointer(d, "/project", "RapidJSON"); +SetValueByPointer(d, "/stars", 10); + +if (Value* stars = GetValueByPointer(d, "/stars")) + stars->SetInt(stars->GetInt() + 1); + +CreateValueByPointer(d, "/a/b/0"); + +Value& hello = GetValueByPointerWithDefault(d, "/hello", "world"); + +Value x("C++"); +SwapValueByPointer(d, "/hello", x); + +bool success = EraseValueByPointer(d, "/a"); +assert(success); +~~~ + +以下对比 3 种调用方式: + +1. `Pointer(source).(root, ...)` +2. `ValueByPointer(root, Pointer(source), ...)` +3. `ValueByPointer(root, source, ...)` + +# 解析 Pointer {#ResolvingPointer} + +`Pointer::Get()` 或 `GetValueByPointer()` 函数并不修改 DOM。若那些 token 不能匹配 DOM 里的值,这些函数便返回 `nullptr`。使用者可利用这个方法来检查一个值是否存在。 + +注意,数值 token 可表示数组索引或成员名字。解析过程中会按值的类型来匹配。 + +~~~javascript +{ + "0" : 123, + "1" : [456] +} +~~~ + +1. `"/0"` → `123` +2. `"/1/0"` → `456` + +Token `"0"` 在第一个 pointer 中被当作成员名字。它在第二个 pointer 中被当作成数组索引。 + +其他函数会改变 DOM,包括 `Create()`、`GetWithDefault()`、`Set()`、`Swap()`。这些函数总是成功的。若一些父值不存在,就会创建它们。若父值类型不匹配 token,也会强行改变其类型。改变类型也意味着完全移除其 DOM 子树的内容。 + +例如,把上面的 JSON 解译至 `d` 之后, + +~~~cpp +SetValueByPointer(d, "1/a", 789); // { "0" : 123, "1" : { "a" : 789 } } +~~~ + +## 解析负号 token + +另外,[RFC6901] 定义了一个特殊 token `-` (单个负号),用于表示数组最后元素的下一个元素。 `Get()` 只会把此 token 当作成员名字 '"-"'。而其他函数则会以此解析数组,等同于对数组调用 `Value::PushBack()` 。 + +~~~cpp +Document d; +d.Parse("{\"foo\":[123]}"); +SetValueByPointer(d, "/foo/-", 456); // { "foo" : [123, 456] } +SetValueByPointer(d, "/-", 789); // { "foo" : [123, 456], "-" : 789 } +~~~ + +## 解析 Document 及 Value + +当使用 `p.Get(root)` 或 `GetValueByPointer(root, p)`,`root` 是一个(常数) `Value&`。这意味着,它也可以是 DOM 里的一个子树。 + +其他函数有两组签名。一组使用 `Document& document` 作为参数,另一组使用 `Value& root`。第一组使用 `document.GetAllocator()` 去创建值,而第二组则需要使用者提供一个 allocator,如同 DOM 里的函数。 + +以上例子都不需要 allocator 参数,因为它的第一个参数是 `Document&`。但如果你需要对一个子树进行解析,就需要如下面的例子般提供 allocator: + +~~~cpp +class Person { +public: + Person() { + document_ = new Document(); + // CreateValueByPointer() here no need allocator + SetLocation(CreateValueByPointer(*document_, "/residence"), ...); + SetLocation(CreateValueByPointer(*document_, "/office"), ...); + }; + +private: + void SetLocation(Value& location, const char* country, const char* addresses[2]) { + Value::Allocator& a = document_->GetAllocator(); + // SetValueByPointer() here need allocator + SetValueByPointer(location, "/country", country, a); + SetValueByPointer(location, "/address/0", address[0], a); + SetValueByPointer(location, "/address/1", address[1], a); + } + + // ... + + Document* document_; +}; +~~~ + +`Erase()` 或 `EraseValueByPointer()` 不需要 allocator。而且它们成功删除值之后会返回 `true`。 + +# 错误处理 {#ErrorHandling} + +`Pointer` 在其建构函数里会解译源字符串。若有解析错误,`Pointer::IsValid()` 返回 `false`。你可使用 `Pointer::GetParseErrorCode()` 和 `GetParseErrorOffset()` 去获取错信息。 + +要注意的是,所有解析函数都假设 pointer 是合法的。对一个非法 pointer 解析会做成断言失败。 + +# URI 片段表示方式 {#URIFragment} + +除了我们一直在使用的字符串方式表示 JSON pointer,[RFC6901] 也定义了一个 JSON Pointer 的 URI 片段(fragment)表示方式。URI 片段是定义于 [RFC3986] "Uniform Resource Identifier (URI): Generic Syntax"。 + +URI 片段的主要分别是必然以 `#` (pound sign)开头,而一些字符也会以百分比编码成 UTF-8 序列。例如,以下的表展示了不同表示法下的 C/C++ 字符串常数。 + +字符串表示方式 | URI 片段表示方式 | Pointer Tokens (UTF-8) +----------------------|-----------------------------|------------------------ +`"/foo/0"` | `"#/foo/0"` | `{"foo", 0}` +`"/a~1b"` | `"#/a~1b"` | `{"a/b"}` +`"/m~0n"` | `"#/m~0n"` | `{"m~n"}` +`"/ "` | `"#/%20"` | `{" "}` +`"/\0"` | `"#/%00"` | `{"\0"}` +`"/€"` | `"#/%E2%82%AC"` | `{"€"}` + +RapidJSON 完全支持 URI 片段表示方式。它在解译时会自动检测 `#` 号。 + +# 字符串化 + +你也可以把一个 `Pointer` 字符串化,储存于字符串或其他输出流。例如: + +~~~ +Pointer p(...); +StringBuffer sb; +p.Stringify(sb); +std::cout << sb.GetString() << std::endl; +~~~ + +使用 `StringifyUriFragment()` 可以把 pointer 字符串化为 URI 片段表示法。 + +# 使用者提供的 tokens {#UserSuppliedTokens} + +若一个 pointer 会用于多次解析,它应该只被创建一次,然后再施于不同的 DOM ,或在不同时间做解析。这样可以避免多次创键 `Pointer`,节省时间和内存分配。 + +我们甚至可以再更进一步,完全消去解析过程及动态内存分配。我们可以直接生成 token 数组: + +~~~cpp +#define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } +#define INDEX(i) { #i, sizeof(#i) - 1, i } + +static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) }; +static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); +// Equivalent to static const Pointer p("/foo/123"); +~~~ + +这种做法可能适合内存受限的系统。 + +[RFC3986]: https://tools.ietf.org/html/rfc3986 +[RFC6901]: https://tools.ietf.org/html/rfc6901 diff --git a/thirdparty/rapidjson-1.1.0/doc/sax.md b/thirdparty/rapidjson-1.1.0/doc/sax.md new file mode 100644 index 0000000000..1d4fc2ae59 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/sax.md @@ -0,0 +1,486 @@ +# SAX + +The term "SAX" originated from [Simple API for XML](http://en.wikipedia.org/wiki/Simple_API_for_XML). We borrowed this term for JSON parsing and generation. + +In RapidJSON, `Reader` (typedef of `GenericReader<...>`) is the SAX-style parser for JSON, and `Writer` (typedef of `GenericWriter<...>`) is the SAX-style generator for JSON. + +[TOC] + +# Reader {#Reader} + +`Reader` parses a JSON from a stream. While it reads characters from the stream, it analyze the characters according to the syntax of JSON, and publish events to a handler. + +For example, here is a JSON. + +~~~~~~~~~~js +{ + "hello": "world", + "t": true , + "f": false, + "n": null, + "i": 123, + "pi": 3.1416, + "a": [1, 2, 3, 4] +} +~~~~~~~~~~ + +While a `Reader` parses this JSON, it publishes the following events to the handler sequentially: + +~~~~~~~~~~ +StartObject() +Key("hello", 5, true) +String("world", 5, true) +Key("t", 1, true) +Bool(true) +Key("f", 1, true) +Bool(false) +Key("n", 1, true) +Null() +Key("i") +UInt(123) +Key("pi") +Double(3.1416) +Key("a") +StartArray() +Uint(1) +Uint(2) +Uint(3) +Uint(4) +EndArray(4) +EndObject(7) +~~~~~~~~~~ + +These events can be easily matched with the JSON, except some event parameters need further explanation. Let's see the `simplereader` example which produces exactly the same output as above: + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include + +using namespace rapidjson; +using namespace std; + +struct MyHandler : public BaseReaderHandler, MyHandler> { + bool Null() { cout << "Null()" << endl; return true; } + bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; } + bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; } + bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; } + bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; } + bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; } + bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; } + bool String(const char* str, SizeType length, bool copy) { + cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool StartObject() { cout << "StartObject()" << endl; return true; } + bool Key(const char* str, SizeType length, bool copy) { + cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; } + bool StartArray() { cout << "StartArray()" << endl; return true; } + bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; } +}; + +void main() { + const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + + MyHandler handler; + Reader reader; + StringStream ss(json); + reader.Parse(ss, handler); +} +~~~~~~~~~~ + +Note that, RapidJSON uses template to statically bind the `Reader` type and the handler type, instead of using class with virtual functions. This paradigm can improve the performance by inlining functions. + +## Handler {#Handler} + +As the previous example showed, user needs to implement a handler, which consumes the events (function calls) from `Reader`. The handler must contain the following member functions. + +~~~~~~~~~~cpp +class Handler { + bool Null(); + bool Bool(bool b); + bool Int(int i); + bool Uint(unsigned i); + bool Int64(int64_t i); + bool Uint64(uint64_t i); + bool Double(double d); + bool RawNumber(const Ch* str, SizeType length, bool copy); + bool String(const Ch* str, SizeType length, bool copy); + bool StartObject(); + bool Key(const Ch* str, SizeType length, bool copy); + bool EndObject(SizeType memberCount); + bool StartArray(); + bool EndArray(SizeType elementCount); +}; +~~~~~~~~~~ + +`Null()` is called when the `Reader` encounters a JSON null value. + +`Bool(bool)` is called when the `Reader` encounters a JSON true or false value. + +When the `Reader` encounters a JSON number, it chooses a suitable C++ type mapping. And then it calls *one* function out of `Int(int)`, `Uint(unsigned)`, `Int64(int64_t)`, `Uint64(uint64_t)` and `Double(double)`. If `kParseNumbersAsStrings` is enabled, `Reader` will always calls `RawNumber()` instead. + +`String(const char* str, SizeType length, bool copy)` is called when the `Reader` encounters a string. The first parameter is pointer to the string. The second parameter is the length of the string (excluding the null terminator). Note that RapidJSON supports null character `'\0'` inside a string. If such situation happens, `strlen(str) < length`. The last `copy` indicates whether the handler needs to make a copy of the string. For normal parsing, `copy = true`. Only when *insitu* parsing is used, `copy = false`. And beware that, the character type depends on the target encoding, which will be explained later. + +When the `Reader` encounters the beginning of an object, it calls `StartObject()`. An object in JSON is a set of name-value pairs. If the object contains members it first calls `Key()` for the name of member, and then calls functions depending on the type of the value. These calls of name-value pairs repeats until calling `EndObject(SizeType memberCount)`. Note that the `memberCount` parameter is just an aid for the handler, user may not need this parameter. + +Array is similar to object but simpler. At the beginning of an array, the `Reader` calls `BeginArary()`. If there is elements, it calls functions according to the types of element. Similarly, in the last call `EndArray(SizeType elementCount)`, the parameter `elementCount` is just an aid for the handler. + +Every handler functions returns a `bool`. Normally it should returns `true`. If the handler encounters an error, it can return `false` to notify event publisher to stop further processing. + +For example, when we parse a JSON with `Reader` and the handler detected that the JSON does not conform to the required schema, then the handler can return `false` and let the `Reader` stop further parsing. And the `Reader` will be in error state with error code `kParseErrorTermination`. + +## GenericReader {#GenericReader} + +As mentioned before, `Reader` is a typedef of a template class `GenericReader`: + +~~~~~~~~~~cpp +namespace rapidjson { + +template > +class GenericReader { + // ... +}; + +typedef GenericReader, UTF8<> > Reader; + +} // namespace rapidjson +~~~~~~~~~~ + +The `Reader` uses UTF-8 as both source and target encoding. The source encoding means the encoding in the JSON stream. The target encoding means the encoding of the `str` parameter in `String()` calls. For example, to parse a UTF-8 stream and outputs UTF-16 string events, you can define a reader by: + +~~~~~~~~~~cpp +GenericReader, UTF16<> > reader; +~~~~~~~~~~ + +Note that, the default character type of `UTF16` is `wchar_t`. So this `reader`needs to call `String(const wchar_t*, SizeType, bool)` of the handler. + +The third template parameter `Allocator` is the allocator type for internal data structure (actually a stack). + +## Parsing {#SaxParsing} + +The one and only one function of `Reader` is to parse JSON. + +~~~~~~~~~~cpp +template +bool Parse(InputStream& is, Handler& handler); + +// with parseFlags = kDefaultParseFlags +template +bool Parse(InputStream& is, Handler& handler); +~~~~~~~~~~ + +If an error occurs during parsing, it will return `false`. User can also calls `bool HasParseEror()`, `ParseErrorCode GetParseErrorCode()` and `size_t GetErrorOffset()` to obtain the error states. Actually `Document` uses these `Reader` functions to obtain parse errors. Please refer to [DOM](doc/dom.md) for details about parse error. + +# Writer {#Writer} + +`Reader` converts (parses) JSON into events. `Writer` does exactly the opposite. It converts events into JSON. + +`Writer` is very easy to use. If your application only need to converts some data into JSON, it may be a good choice to use `Writer` directly, instead of building a `Document` and then stringifying it with a `Writer`. + +In `simplewriter` example, we do exactly the reverse of `simplereader`. + +~~~~~~~~~~cpp +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; +using namespace std; + +void main() { + StringBuffer s; + Writer writer(s); + + writer.StartObject(); + writer.Key("hello"); + writer.String("world"); + writer.Key("t"); + writer.Bool(true); + writer.Key("f"); + writer.Bool(false); + writer.Key("n"); + writer.Null(); + writer.Key("i"); + writer.Uint(123); + writer.Key("pi"); + writer.Double(3.1416); + writer.Key("a"); + writer.StartArray(); + for (unsigned i = 0; i < 4; i++) + writer.Uint(i); + writer.EndArray(); + writer.EndObject(); + + cout << s.GetString() << endl; +} +~~~~~~~~~~ + +~~~~~~~~~~ +{"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]} +~~~~~~~~~~ + +There are two `String()` and `Key()` overloads. One is the same as defined in handler concept with 3 parameters. It can handle string with null characters. Another one is the simpler version used in the above example. + +Note that, the example code does not pass any parameters in `EndArray()` and `EndObject()`. An `SizeType` can be passed but it will be simply ignored by `Writer`. + +You may doubt that, why not just using `sprintf()` or `std::stringstream` to build a JSON? + +There are various reasons: +1. `Writer` must output a well-formed JSON. If there is incorrect event sequence (e.g. `Int()` just after `StartObject()`), it generates assertion fail in debug mode. +2. `Writer::String()` can handle string escaping (e.g. converting code point `U+000A` to `\n`) and Unicode transcoding. +3. `Writer` handles number output consistently. +4. `Writer` implements the event handler concept. It can be used to handle events from `Reader`, `Document` or other event publisher. +5. `Writer` can be optimized for different platforms. + +Anyway, using `Writer` API is even simpler than generating a JSON by ad hoc methods. + +## Template {#WriterTemplate} + +`Writer` has a minor design difference to `Reader`. `Writer` is a template class, not a typedef. There is no `GenericWriter`. The following is the declaration. + +~~~~~~~~~~cpp +namespace rapidjson { + +template, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<>, unsigned writeFlags = kWriteDefaultFlags> +class Writer { +public: + Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) +// ... +}; + +} // namespace rapidjson +~~~~~~~~~~ + +The `OutputStream` template parameter is the type of output stream. It cannot be deduced and must be specified by user. + +The `SourceEncoding` template parameter specifies the encoding to be used in `String(const Ch*, ...)`. + +The `TargetEncoding` template parameter specifies the encoding in the output stream. + +The `Allocator` is the type of allocator, which is used for allocating internal data structure (a stack). + +The `writeFlags` are combination of the following bit-flags: + +Parse flags | Meaning +------------------------------|----------------------------------- +`kWriteNoFlags` | No flag is set. +`kWriteDefaultFlags` | Default write flags. It is equal to macro `RAPIDJSON_WRITE_DEFAULT_FLAGS`, which is defined as `kWriteNoFlags`. +`kWriteValidateEncodingFlag` | Validate encoding of JSON strings. +`kWriteNanAndInfFlag` | Allow writing of `Infinity`, `-Infinity` and `NaN`. + +Besides, the constructor of `Writer` has a `levelDepth` parameter. This parameter affects the initial memory allocated for storing information per hierarchy level. + +## PrettyWriter {#PrettyWriter} + +While the output of `Writer` is the most condensed JSON without white-spaces, suitable for network transfer or storage, it is not easily readable by human. + +Therefore, RapidJSON provides a `PrettyWriter`, which adds indentation and line feeds in the output. + +The usage of `PrettyWriter` is exactly the same as `Writer`, expect that `PrettyWriter` provides a `SetIndent(Ch indentChar, unsigned indentCharCount)` function. The default is 4 spaces. + +## Completeness and Reset {#CompletenessReset} + +A `Writer` can only output a single JSON, which can be any JSON type at the root. Once the singular event for root (e.g. `String()`), or the last matching `EndObject()` or `EndArray()` event, is handled, the output JSON is well-formed and complete. User can detect this state by calling `Writer::IsComplete()`. + +When a JSON is complete, the `Writer` cannot accept any new events. Otherwise the output will be invalid (i.e. having more than one root). To reuse the `Writer` object, user can call `Writer::Reset(OutputStream& os)` to reset all internal states of the `Writer` with a new output stream. + +# Techniques {#SaxTechniques} + +## Parsing JSON to Custom Data Structure {#CustomDataStructure} + +`Document`'s parsing capability is completely based on `Reader`. Actually `Document` is a handler which receives events from a reader to build a DOM during parsing. + +User may uses `Reader` to build other data structures directly. This eliminates building of DOM, thus reducing memory and improving performance. + +In the following `messagereader` example, `ParseMessages()` parses a JSON which should be an object with key-string pairs. + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include "rapidjson/error/en.h" +#include +#include +#include + +using namespace std; +using namespace rapidjson; + +typedef map MessageMap; + +struct MessageHandler + : public BaseReaderHandler, MessageHandler> { + MessageHandler() : state_(kExpectObjectStart) { + } + + bool StartObject() { + switch (state_) { + case kExpectObjectStart: + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool String(const char* str, SizeType length, bool) { + switch (state_) { + case kExpectNameOrObjectEnd: + name_ = string(str, length); + state_ = kExpectValue; + return true; + case kExpectValue: + messages_.insert(MessageMap::value_type(name_, string(str, length))); + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; } + + bool Default() { return false; } // All other events are invalid. + + MessageMap messages_; + enum State { + kExpectObjectStart, + kExpectNameOrObjectEnd, + kExpectValue, + }state_; + std::string name_; +}; + +void ParseMessages(const char* json, MessageMap& messages) { + Reader reader; + MessageHandler handler; + StringStream ss(json); + if (reader.Parse(ss, handler)) + messages.swap(handler.messages_); // Only change it if success. + else { + ParseErrorCode e = reader.GetParseErrorCode(); + size_t o = reader.GetErrorOffset(); + cout << "Error: " << GetParseError_En(e) << endl;; + cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl; + } +} + +int main() { + MessageMap messages; + + const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }"; + cout << json1 << endl; + ParseMessages(json1, messages); + + for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr) + cout << itr->first << ": " << itr->second << endl; + + cout << endl << "Parse a JSON with invalid schema." << endl; + const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }"; + cout << json2 << endl; + ParseMessages(json2, messages); + + return 0; +} +~~~~~~~~~~ + +~~~~~~~~~~ +{ "greeting" : "Hello!", "farewell" : "bye-bye!" } +farewell: bye-bye! +greeting: Hello! + +Parse a JSON with invalid schema. +{ "greeting" : "Hello!", "farewell" : "bye-bye!", "foo" : {} } +Error: Terminate parsing due to Handler error. + at offset 59 near '} }...' +~~~~~~~~~~ + +The first JSON (`json1`) was successfully parsed into `MessageMap`. Since `MessageMap` is a `std::map`, the printing order are sorted by the key. This order is different from the JSON's order. + +In the second JSON (`json2`), `foo`'s value is an empty object. As it is an object, `MessageHandler::StartObject()` will be called. However, at that moment `state_ = kExpectValue`, so that function returns `false` and cause the parsing process be terminated. The error code is `kParseErrorTermination`. + +## Filtering of JSON {#Filtering} + +As mentioned earlier, `Writer` can handle the events published by `Reader`. `condense` example simply set a `Writer` as handler of a `Reader`, so it can remove all white-spaces in JSON. `pretty` example uses the same relationship, but replacing `Writer` by `PrettyWriter`. So `pretty` can be used to reformat a JSON with indentation and line feed. + +Actually, we can add intermediate layer(s) to filter the contents of JSON via these SAX-style API. For example, `capitalize` example capitalize all strings in a JSON. + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include +#include + +using namespace rapidjson; + +template +struct CapitalizeFilter { + CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() { + } + + bool Null() { return out_.Null(); } + bool Bool(bool b) { return out_.Bool(b); } + bool Int(int i) { return out_.Int(i); } + bool Uint(unsigned u) { return out_.Uint(u); } + bool Int64(int64_t i) { return out_.Int64(i); } + bool Uint64(uint64_t u) { return out_.Uint64(u); } + bool Double(double d) { return out_.Double(d); } + bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); } + bool String(const char* str, SizeType length, bool) { + buffer_.clear(); + for (SizeType i = 0; i < length; i++) + buffer_.push_back(std::toupper(str[i])); + return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string + } + bool StartObject() { return out_.StartObject(); } + bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); } + bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); } + bool StartArray() { return out_.StartArray(); } + bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); } + + OutputHandler& out_; + std::vector buffer_; +}; + +int main(int, char*[]) { + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + CapitalizeFilter > filter(writer); + if (!reader.Parse(is, filter)) { + fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} +~~~~~~~~~~ + +Note that, it is incorrect to simply capitalize the JSON as a string. For example: +~~~~~~~~~~ +["Hello\nWorld"] +~~~~~~~~~~ + +Simply capitalizing the whole JSON would contain incorrect escape character: +~~~~~~~~~~ +["HELLO\NWORLD"] +~~~~~~~~~~ + +The correct result by `capitalize`: +~~~~~~~~~~ +["HELLO\nWORLD"] +~~~~~~~~~~ + +More complicated filters can be developed. However, since SAX-style API can only provide information about a single event at a time, user may need to book-keeping the contextual information (e.g. the path from root value, storage of other related values). Some processing may be easier to be implemented in DOM than SAX. diff --git a/thirdparty/rapidjson-1.1.0/doc/sax.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/sax.zh-cn.md new file mode 100644 index 0000000000..b20286de92 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/sax.zh-cn.md @@ -0,0 +1,487 @@ +# SAX + +"SAX" 此术语源于 [Simple API for XML](http://en.wikipedia.org/wiki/Simple_API_for_XML)。我们借了此术语去套用在 JSON 的解析及生成。 + +在 RapidJSON 中,`Reader`(`GenericReader<...>` 的 typedef)是 JSON 的 SAX 风格解析器,而 `Writer`(`GenericWriter<...>` 的 typedef)则是 JSON 的 SAX 风格生成器。 + +[TOC] + +# Reader {#Reader} + +`Reader` 从输入流解析一个 JSON。当它从流中读取字符时,它会基于 JSON 的语法去分析字符,并向处理器发送事件。 + +例如,以下是一个 JSON。 + +~~~~~~~~~~js +{ + "hello": "world", + "t": true , + "f": false, + "n": null, + "i": 123, + "pi": 3.1416, + "a": [1, 2, 3, 4] +} +~~~~~~~~~~ + +当一个 `Reader` 解析此 JSON 时,它会顺序地向处理器发送以下的事件: + +~~~~~~~~~~ +StartObject() +Key("hello", 5, true) +String("world", 5, true) +Key("t", 1, true) +Bool(true) +Key("f", 1, true) +Bool(false) +Key("n", 1, true) +Null() +Key("i") +UInt(123) +Key("pi") +Double(3.1416) +Key("a") +StartArray() +Uint(1) +Uint(2) +Uint(3) +Uint(4) +EndArray(4) +EndObject(7) +~~~~~~~~~~ + +除了一些事件参数需要再作解释,这些事件可以轻松地与 JSON 对上。我们可以看看 `simplereader` 例子怎样产生和以上完全相同的结果: + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include + +using namespace rapidjson; +using namespace std; + +struct MyHandler : public BaseReaderHandler, MyHandler> { + bool Null() { cout << "Null()" << endl; return true; } + bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; } + bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; } + bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; } + bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; } + bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; } + bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; } + bool String(const char* str, SizeType length, bool copy) { + cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool StartObject() { cout << "StartObject()" << endl; return true; } + bool Key(const char* str, SizeType length, bool copy) { + cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; } + bool StartArray() { cout << "StartArray()" << endl; return true; } + bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; } +}; + +void main() { + const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + + MyHandler handler; + Reader reader; + StringStream ss(json); + reader.Parse(ss, handler); +} +~~~~~~~~~~ + +注意 RapidJSON 使用模板去静态挷定 `Reader` 类型及处理器的类形,而不是使用含虚函数的类。这个范式可以通过把函数内联而改善性能。 + +## 处理器 {#Handler} + +如前例所示,使用者需要实现一个处理器(handler),用于处理来自 `Reader` 的事件(函数调用)。处理器必须包含以下的成员函数。 + +~~~~~~~~~~cpp +class Handler { + bool Null(); + bool Bool(bool b); + bool Int(int i); + bool Uint(unsigned i); + bool Int64(int64_t i); + bool Uint64(uint64_t i); + bool Double(double d); + bool RawNumber(const Ch* str, SizeType length, bool copy); + bool String(const Ch* str, SizeType length, bool copy); + bool StartObject(); + bool Key(const Ch* str, SizeType length, bool copy); + bool EndObject(SizeType memberCount); + bool StartArray(); + bool EndArray(SizeType elementCount); +}; +~~~~~~~~~~ + +当 `Reader` 遇到 JSON null 值时会调用 `Null()`。 + +当 `Reader` 遇到 JSON true 或 false 值时会调用 `Bool(bool)`。 + +当 `Reader` 遇到 JSON number,它会选择一个合适的 C++ 类型映射,然后调用 `Int(int)`、`Uint(unsigned)`、`Int64(int64_t)`、`Uint64(uint64_t)` 及 `Double(double)` 的 * 其中之一个 *。 若开启了 `kParseNumbersAsStrings` 选项,`Reader` 便会改为调用 `RawNumber()`。 + +当 `Reader` 遇到 JSON string,它会调用 `String(const char* str, SizeType length, bool copy)`。第一个参数是字符串的指针。第二个参数是字符串的长度(不包含空终止符号)。注意 RapidJSON 支持字串中含有空字符 `'\0'`。若出现这种情况,便会有 `strlen(str) < length`。最后的 `copy` 参数表示处理器是否需要复制该字符串。在正常解析时,`copy = true`。仅当使用原位解析时,`copy = false`。此外,还要注意字符的类型与目标编码相关,我们稍后会再谈这一点。 + +当 `Reader` 遇到 JSON object 的开始之时,它会调用 `StartObject()`。JSON 的 object 是一个键值对(成员)的集合。若 object 包含成员,它会先为成员的名字调用 `Key()`,然后再按值的类型调用函数。它不断调用这些键值对,直至最终调用 `EndObject(SizeType memberCount)`。注意 `memberCount` 参数对处理器来说只是协助性质,使用者可能不需要此参数。 + +JSON array 与 object 相似,但更简单。在 array 开始时,`Reader` 会调用 `BeginArary()`。若 array 含有元素,它会按元素的类型来读用函数。相似地,最后它会调用 `EndArray(SizeType elementCount)`,其中 `elementCount` 参数对处理器来说只是协助性质。 + +每个处理器函数都返回一个 `bool`。正常它们应返回 `true`。若处理器遇到错误,它可以返回 `false` 去通知事件发送方停止继续处理。 + +例如,当我们用 `Reader` 解析一个 JSON 时,处理器检测到该 JSON 并不符合所需的 schema,那么处理器可以返回 `false`,令 `Reader` 停止之后的解析工作。而 `Reader` 会进入一个错误状态,并以 `kParseErrorTermination` 错误码标识。 + +## GenericReader {#GenericReader} + +前面提及,`Reader` 是 `GenericReader` 模板类的 typedef: + +~~~~~~~~~~cpp +namespace rapidjson { + +template > +class GenericReader { + // ... +}; + +typedef GenericReader, UTF8<> > Reader; + +} // namespace rapidjson +~~~~~~~~~~ + +`Reader` 使用 UTF-8 作为来源及目标编码。来源编码是指 JSON 流的编码。目标编码是指 `String()` 的 `str` 参数所用的编码。例如,要解析一个 UTF-8 流并输出至 UTF-16 string 事件,你需要这么定义一个 reader: + +~~~~~~~~~~cpp +GenericReader, UTF16<> > reader; +~~~~~~~~~~ + +注意到 `UTF16` 的缺省类型是 `wchar_t`。因此这个 `reader` 需要调用处理器的 `String(const wchar_t*, SizeType, bool)`。 + +第三个模板参数 `Allocator` 是内部数据结构(实际上是一个堆栈)的分配器类型。 + +## 解析 {#SaxParsing} + +`Reader` 的唯一功能就是解析 JSON。 + +~~~~~~~~~~cpp +template +bool Parse(InputStream& is, Handler& handler); + +// 使用 parseFlags = kDefaultParseFlags +template +bool Parse(InputStream& is, Handler& handler); +~~~~~~~~~~ + +若在解析中出现错误,它会返回 `false`。使用者可调用 `bool HasParseEror()`, `ParseErrorCode GetParseErrorCode()` 及 `size_t GetErrorOffset()` 获取错误状态。实际上 `Document` 使用这些 `Reader` 函数去获取解析错误。请参考 [DOM](doc/dom.zh-cn.md) 去了解有关解析错误的细节。 + +# Writer {#Writer} + +`Reader` 把 JSON 转换(解析)成为事件。`Writer` 做完全相反的事情。它把事件转换成 JSON。 + +`Writer` 是非常容易使用的。若你的应用程序只需把一些数据转换成 JSON,可能直接使用 `Writer`,会比建立一个 `Document` 然后用 `Writer` 把它转换成 JSON 更加方便。 + +在 `simplewriter` 例子里,我们做 `simplereader` 完全相反的事情。 + +~~~~~~~~~~cpp +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; +using namespace std; + +void main() { + StringBuffer s; + Writer writer(s); + + writer.StartObject(); + writer.Key("hello"); + writer.String("world"); + writer.Key("t"); + writer.Bool(true); + writer.Key("f"); + writer.Bool(false); + writer.Key("n"); + writer.Null(); + writer.Key("i"); + writer.Uint(123); + writer.Key("pi"); + writer.Double(3.1416); + writer.Key("a"); + writer.StartArray(); + for (unsigned i = 0; i < 4; i++) + writer.Uint(i); + writer.EndArray(); + writer.EndObject(); + + cout << s.GetString() << endl; +} +~~~~~~~~~~ + +~~~~~~~~~~ +{"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]} +~~~~~~~~~~ + +`String()` 及 `Key()` 各有两个重载。一个是如处理器 concept 般,有 3 个参数。它能处理含空字符的字符串。另一个是如上中使用的较简单版本。 + +注意到,例子代码中的 `EndArray()` 及 `EndObject()` 并没有参数。可以传递一个 `SizeType` 的参数,但它会被 `Writer` 忽略。 + +你可能会怀疑,为什么不使用 `sprintf()` 或 `std::stringstream` 去建立一个 JSON? + +这有几个原因: +1. `Writer` 必然会输出一个结构良好(well-formed)的 JSON。若然有错误的事件次序(如 `Int()` 紧随 `StartObject()` 出现),它会在调试模式中产生断言失败。 +2. `Writer::String()` 可处理字符串转义(如把码点 `U+000A` 转换成 `\n`)及进行 Unicode 转码。 +3. `Writer` 一致地处理 number 的输出。 +4. `Writer` 实现了事件处理器 concept。可用于处理来自 `Reader`、`Document` 或其他事件发生器。 +5. `Writer` 可对不同平台进行优化。 + +无论如何,使用 `Writer` API 去生成 JSON 甚至乎比这些临时方法更简单。 + +## 模板 {#WriterTemplate} + +`Writer` 与 `Reader` 有少许设计区别。`Writer` 是一个模板类,而不是一个 typedef。 并没有 `GenericWriter`。以下是 `Writer` 的声明。 + +~~~~~~~~~~cpp +namespace rapidjson { + +template, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<> > +class Writer { +public: + Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) +// ... +}; + +} // namespace rapidjson +~~~~~~~~~~ + +`OutputStream` 模板参数是输出流的类型。它的类型不可以被自动推断,必须由使用者提供。 + +`SourceEncoding` 模板参数指定了 `String(const Ch*, ...)` 的编码。 + +`TargetEncoding` 模板参数指定输出流的编码。 + +`Allocator` 是分配器的类型,用于分配内部数据结构(一个堆栈)。 + +`writeFlags` 是以下位标志的组合: + +写入位标志 | 意义 +------------------------------|----------------------------------- +`kWriteNoFlags` | 没有任何标志。 +`kWriteDefaultFlags` | 缺省的解析选项。它等于 `RAPIDJSON_WRITE_DEFAULT_FLAGS` 宏,此宏定义为 `kWriteNoFlags`。 +`kWriteValidateEncodingFlag` | 校验 JSON 字符串的编码。 +`kWriteNanAndInfFlag` | 容许写入 `Infinity`, `-Infinity` 及 `NaN`。 + +此外,`Writer` 的构造函数有一 `levelDepth` 参数。存储每层阶信息的初始内存分配量受此参数影响。 + +## PrettyWriter {#PrettyWriter} + +`Writer` 所输出的是没有空格字符的最紧凑 JSON,适合网络传输或储存,但不适合人类阅读。 + +因此,RapidJSON 提供了一个 `PrettyWriter`,它在输出中加入缩进及换行。 + +`PrettyWriter` 的用法与 `Writer` 几乎一样,不同之处是 `PrettyWriter` 提供了一个 `SetIndent(Ch indentChar, unsigned indentCharCount)` 函数。缺省的缩进是 4 个空格。 + +## 完整性及重置 {#CompletenessReset} + +一个 `Writer` 只可输出单个 JSON,其根节点可以是任何 JSON 类型。当处理完单个根节点事件(如 `String()`),或匹配的最后 `EndObject()` 或 `EndArray()` 事件,输出的 JSON 是结构完整(well-formed)及完整的。使用者可调用 `Writer::IsComplete()` 去检测完整性。 + +当 JSON 完整时,`Writer` 不能再接受新的事件。不然其输出便会是不合法的(例如有超过一个根节点)。为了重新利用 `Writer` 对象,使用者可调用 `Writer::Reset(OutputStream& os)` 去重置其所有内部状态及设置新的输出流。 + +# 技巧 {#SaxTechniques} + +## 解析 JSON 至自定义结构 {#CustomDataStructure} + +`Document` 的解析功能完全依靠 `Reader`。实际上 `Document` 是一个处理器,在解析 JSON 时接收事件去建立一个 DOM。 + +使用者可以直接使用 `Reader` 去建立其他数据结构。这消除了建立 DOM 的步骤,从而减少了内存开销并改善性能。 + +在以下的 `messagereader` 例子中,`ParseMessages()` 解析一个 JSON,该 JSON 应该是一个含键值对的 object。 + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include "rapidjson/error/en.h" +#include +#include +#include + +using namespace std; +using namespace rapidjson; + +typedef map MessageMap; + +struct MessageHandler + : public BaseReaderHandler, MessageHandler> { + MessageHandler() : state_(kExpectObjectStart) { + } + + bool StartObject() { + switch (state_) { + case kExpectObjectStart: + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool String(const char* str, SizeType length, bool) { + switch (state_) { + case kExpectNameOrObjectEnd: + name_ = string(str, length); + state_ = kExpectValue; + return true; + case kExpectValue: + messages_.insert(MessageMap::value_type(name_, string(str, length))); + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; } + + bool Default() { return false; } // All other events are invalid. + + MessageMap messages_; + enum State { + kExpectObjectStart, + kExpectNameOrObjectEnd, + kExpectValue, + }state_; + std::string name_; +}; + +void ParseMessages(const char* json, MessageMap& messages) { + Reader reader; + MessageHandler handler; + StringStream ss(json); + if (reader.Parse(ss, handler)) + messages.swap(handler.messages_); // Only change it if success. + else { + ParseErrorCode e = reader.GetParseErrorCode(); + size_t o = reader.GetErrorOffset(); + cout << "Error: " << GetParseError_En(e) << endl;; + cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl; + } +} + +int main() { + MessageMap messages; + + const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }"; + cout << json1 << endl; + ParseMessages(json1, messages); + + for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr) + cout << itr->first << ": " << itr->second << endl; + + cout << endl << "Parse a JSON with invalid schema." << endl; + const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }"; + cout << json2 << endl; + ParseMessages(json2, messages); + + return 0; +} +~~~~~~~~~~ + +~~~~~~~~~~ +{ "greeting" : "Hello!", "farewell" : "bye-bye!" } +farewell: bye-bye! +greeting: Hello! + +Parse a JSON with invalid schema. +{ "greeting" : "Hello!", "farewell" : "bye-bye!", "foo" : {} } +Error: Terminate parsing due to Handler error. + at offset 59 near '} }...' +~~~~~~~~~~ + +第一个 JSON(`json1`)被成功地解析至 `MessageMap`。由于 `MessageMap` 是一个 `std::map`,打印次序按键值排序。此次序与 JSON 中的次序不同。 + +在第二个 JSON(`json2`)中,`foo` 的值是一个空 object。由于它是一个 object,`MessageHandler::StartObject()` 会被调用。然而,在 `state_ = kExpectValue` 的情况下,该函数会返回 `false`,并导致解析过程终止。错误代码是 `kParseErrorTermination`。 + +## 过滤 JSON {#Filtering} + +如前面提及过,`Writer` 可处理 `Reader` 发出的事件。`example/condense/condense.cpp` 例子简单地设置 `Writer` 作为一个 `Reader` 的处理器,因此它能移除 JSON 中的所有空白字符。`example/pretty/pretty.cpp` 例子使用同样的关系,只是以 `PrettyWriter` 取代 `Writer`。因此 `pretty` 能够重新格式化 JSON,加入缩进及换行。 + +实际上,我们可以使用 SAX 风格 API 去加入(多个)中间层去过滤 JSON 的内容。例如 `capitalize` 例子可以把所有 JSON string 改为大写。 + +~~~~~~~~~~cpp +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include +#include + +using namespace rapidjson; + +template +struct CapitalizeFilter { + CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() { + } + + bool Null() { return out_.Null(); } + bool Bool(bool b) { return out_.Bool(b); } + bool Int(int i) { return out_.Int(i); } + bool Uint(unsigned u) { return out_.Uint(u); } + bool Int64(int64_t i) { return out_.Int64(i); } + bool Uint64(uint64_t u) { return out_.Uint64(u); } + bool Double(double d) { return out_.Double(d); } + bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); } + bool String(const char* str, SizeType length, bool) { + buffer_.clear(); + for (SizeType i = 0; i < length; i++) + buffer_.push_back(std::toupper(str[i])); + return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string + } + bool StartObject() { return out_.StartObject(); } + bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); } + bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); } + bool StartArray() { return out_.StartArray(); } + bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); } + + OutputHandler& out_; + std::vector buffer_; +}; + +int main(int, char*[]) { + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + CapitalizeFilter > filter(writer); + if (!reader.Parse(is, filter)) { + fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} +~~~~~~~~~~ + +注意到,不可简单地把 JSON 当作字符串去改为大写。例如: +~~~~~~~~~~ +["Hello\nWorld"] +~~~~~~~~~~ + +简单地把整个 JSON 转为大写的话会产生错误的转义符: +~~~~~~~~~~ +["HELLO\NWORLD"] +~~~~~~~~~~ + +而 `capitalize` 就会产生正确的结果: +~~~~~~~~~~ +["HELLO\nWORLD"] +~~~~~~~~~~ + +我们还可以开发更复杂的过滤器。然而,由于 SAX 风格 API 在某一时间点只能提供单一事件的信息,使用者需要自行记录一些上下文信息(例如从根节点起的路径、储存其他相关值)。对于处理某些情况,用 DOM 会比 SAX 更容易实现。 + diff --git a/thirdparty/rapidjson-1.1.0/doc/schema.md b/thirdparty/rapidjson-1.1.0/doc/schema.md new file mode 100644 index 0000000000..a83cebcae7 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/schema.md @@ -0,0 +1,237 @@ +# Schema + +(This feature was released in v1.1.0) + +JSON Schema is a draft standard for describing the format of JSON data. The schema itself is also JSON data. By validating a JSON structure with JSON Schema, your code can safely access the DOM without manually checking types, or whether a key exists, etc. It can also ensure that the serialized JSON conform to a specified schema. + +RapidJSON implemented a JSON Schema validator for [JSON Schema Draft v4](http://json-schema.org/documentation.html). If you are not familiar with JSON Schema, you may refer to [Understanding JSON Schema](http://spacetelescope.github.io/understanding-json-schema/). + +[TOC] + +## Basic Usage + +First of all, you need to parse a JSON Schema into `Document`, and then compile the `Document` into a `SchemaDocument`. + +Secondly, construct a `SchemaValidator` with the `SchemaDocument`. It is similar to a `Writer` in the sense of handling SAX events. So, you can use `document.Accept(validator)` to validate a document, and then check the validity. + +~~~cpp +#include "rapidjson/schema.h" + +// ... + +Document sd; +if (!sd.Parse(schemaJson).HasParseError()) { + // the schema is not a valid JSON. + // ... +} +SchemaDocument schema(sd); // Compile a Document to SchemaDocument +// sd is no longer needed here. + +Document d; +if (!d.Parse(inputJson).HasParseError()) { + // the input is not a valid JSON. + // ... +} + +SchemaValidator validator(schema); +if (!d.Accept(validator)) { + // Input JSON is invalid according to the schema + // Output diagnostic information + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); +} +~~~ + +Some notes: + +* One `SchemaDocment` can be referenced by multiple `SchemaValidator`s. It will not be modified by `SchemaValidator`s. +* A `SchemaValidator` may be reused to validate multiple documents. To run it for other documents, call `validator.Reset()` first. + +## Validation during parsing/serialization + +Unlike most JSON Schema validator implementations, RapidJSON provides a SAX-based schema validator. Therefore, you can parse a JSON from a stream while validating it on the fly. If the validator encounters a JSON value that invalidates the supplied schema, the parsing will be terminated immediately. This design is especially useful for parsing large JSON files. + +### DOM parsing + +For using DOM in parsing, `Document` needs some preparation and finalizing tasks, in addition to receiving SAX events, thus it needs some work to route the reader, validator and the document. `SchemaValidatingReader` is a helper class that doing such work. + +~~~cpp +#include "rapidjson/filereadstream.h" + +// ... +SchemaDocument schema(sd); // Compile a Document to SchemaDocument + +// Use reader to parse the JSON +FILE* fp = fopen("big.json", "r"); +FileReadStream is(fp, buffer, sizeof(buffer)); + +// Parse JSON from reader, validate the SAX events, and store in d. +Document d; +SchemaValidatingReader > reader(is, schema); +d.Populate(reader); + +if (!reader.GetParseResult()) { + // Not a valid JSON + // When reader.GetParseResult().Code() == kParseErrorTermination, + // it may be terminated by: + // (1) the validator found that the JSON is invalid according to schema; or + // (2) the input stream has I/O error. + + // Check the validation result + if (!reader.IsValid()) { + // Input JSON is invalid according to the schema + // Output diagnostic information + StringBuffer sb; + reader.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", reader.GetInvalidSchemaKeyword()); + sb.Clear(); + reader.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); + } +} +~~~ + +### SAX parsing + +For using SAX in parsing, it is much simpler. If it only need to validate the JSON without further processing, it is simply: + +~~~ +SchemaValidator validator(schema); +Reader reader; +if (!reader.Parse(stream, validator)) { + if (!validator.IsValid()) { + // ... + } +} +~~~ + +This is exactly the method used in the [schemavalidator](example/schemavalidator/schemavalidator.cpp) example. The distinct advantage is low memory usage, no matter how big the JSON was (the memory usage depends on the complexity of the schema). + +If you need to handle the SAX events further, then you need to use the template class `GenericSchemaValidator` to set the output handler of the validator: + +~~~ +MyHandler handler; +GenericSchemaValidator validator(schema, handler); +Reader reader; +if (!reader.Parse(ss, validator)) { + if (!validator.IsValid()) { + // ... + } +} +~~~ + +### Serialization + +It is also possible to do validation during serializing. This can ensure the result JSON is valid according to the JSON schema. + +~~~ +StringBuffer sb; +Writer writer(sb); +GenericSchemaValidator > validator(s, writer); +if (!d.Accept(validator)) { + // Some problem during Accept(), it may be validation or encoding issues. + if (!validator.IsValid()) { + // ... + } +} +~~~ + +Of course, if your application only needs SAX-style serialization, it can simply send SAX events to `SchemaValidator` instead of `Writer`. + +## Remote Schema + +JSON Schema supports [`$ref` keyword](http://spacetelescope.github.io/understanding-json-schema/structuring.html), which is a [JSON pointer](doc/pointer.md) referencing to a local or remote schema. Local pointer is prefixed with `#`, while remote pointer is an relative or absolute URI. For example: + +~~~js +{ "$ref": "definitions.json#/address" } +~~~ + +As `SchemaDocument` does not know how to resolve such URI, it needs a user-provided `IRemoteSchemaDocumentProvider` instance to do so. + +~~~ +class MyRemoteSchemaDocumentProvider : public IRemoteSchemaDocumentProvider { +public: + virtual const SchemaDocument* GetRemoteDocument(const char* uri, SizeTyp length) { + // Resolve the uri and returns a pointer to that schema. + } +}; + +// ... + +MyRemoteSchemaDocumentProvider provider; +SchemaDocument schema(sd, &provider); +~~~ + +## Conformance + +RapidJSON passed 262 out of 263 tests in [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (Json Schema draft 4). + +The failed test is "changed scope ref invalid" of "change resolution scope" in `refRemote.json`. It is due to that `id` schema keyword and URI combining function are not implemented. + +Besides, the `format` schema keyword for string values is ignored, since it is not required by the specification. + +### Regular Expression + +The schema keyword `pattern` and `patternProperties` uses regular expression to match the required pattern. + +RapidJSON implemented a simple NFA regular expression engine, which is used by default. It supports the following syntax. + +|Syntax|Description| +|------|-----------| +|`ab` | Concatenation | +|`a|b` | Alternation | +|`a?` | Zero or one | +|`a*` | Zero or more | +|`a+` | One or more | +|`a{3}` | Exactly 3 times | +|`a{3,}` | At least 3 times | +|`a{3,5}`| 3 to 5 times | +|`(ab)` | Grouping | +|`^a` | At the beginning | +|`a$` | At the end | +|`.` | Any character | +|`[abc]` | Character classes | +|`[a-c]` | Character class range | +|`[a-z0-9_]` | Character class combination | +|`[^abc]` | Negated character classes | +|`[^a-c]` | Negated character class range | +|`[\b]` | Backspace (U+0008) | +|`\|`, `\\`, ... | Escape characters | +|`\f` | Form feed (U+000C) | +|`\n` | Line feed (U+000A) | +|`\r` | Carriage return (U+000D) | +|`\t` | Tab (U+0009) | +|`\v` | Vertical tab (U+000B) | + +For C++11 compiler, it is also possible to use the `std::regex` by defining `RAPIDJSON_SCHEMA_USE_INTERNALREGEX=0` and `RAPIDJSON_SCHEMA_USE_STDREGEX=1`. If your schemas do not need `pattern` and `patternProperties`, you can set both macros to zero to disable this feature, which will reduce some code size. + +## Performance + +Most C++ JSON libraries do not yet support JSON Schema. So we tried to evaluate the performance of RapidJSON's JSON Schema validator according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), which tests 11 JavaScript libraries running on Node.js. + +That benchmark runs validations on [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite), in which some test suites and tests are excluded. We made the same benchmarking procedure in [`schematest.cpp`](test/perftest/schematest.cpp). + +On a Mac Book Pro (2.8 GHz Intel Core i7), the following results are collected. + +|Validator|Relative speed|Number of test runs per second| +|---------|:------------:|:----------------------------:| +|RapidJSON|155%|30682| +|[`ajv`](https://github.com/epoberezkin/ajv)|100%|19770 (± 1.31%)| +|[`is-my-json-valid`](https://github.com/mafintosh/is-my-json-valid)|70%|13835 (± 2.84%)| +|[`jsen`](https://github.com/bugventure/jsen)|57.7%|11411 (± 1.27%)| +|[`schemasaurus`](https://github.com/AlexeyGrishin/schemasaurus)|26%|5145 (± 1.62%)| +|[`themis`](https://github.com/playlyfe/themis)|19.9%|3935 (± 2.69%)| +|[`z-schema`](https://github.com/zaggino/z-schema)|7%|1388 (± 0.84%)| +|[`jsck`](https://github.com/pandastrike/jsck#readme)|3.1%|606 (± 2.84%)| +|[`jsonschema`](https://github.com/tdegrunt/jsonschema#readme)|0.9%|185 (± 1.01%)| +|[`skeemas`](https://github.com/Prestaul/skeemas#readme)|0.8%|154 (± 0.79%)| +|tv4|0.5%|93 (± 0.94%)| +|[`jayschema`](https://github.com/natesilva/jayschema)|0.1%|21 (± 1.14%)| + +That is, RapidJSON is about 1.5x faster than the fastest JavaScript library (ajv). And 1400x faster than the slowest one. diff --git a/thirdparty/rapidjson-1.1.0/doc/schema.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/schema.zh-cn.md new file mode 100644 index 0000000000..a01c1b10e1 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/schema.zh-cn.md @@ -0,0 +1,237 @@ +# Schema + +(本功能于 v1.1.0 发布) + +JSON Schema 是描述 JSON 格式的一个标准草案。一个 schema 本身也是一个 JSON。使用 JSON Schema 去校验 JSON,可以让你的代码安全地访问 DOM,而无须检查类型或键值是否存在等。这也能确保输出的 JSON 是符合指定的 schema。 + +RapidJSON 实现了一个 [JSON Schema Draft v4](http://json-schema.org/documentation.html) 的校验器。若你不熟悉 JSON Schema,可以参考 [Understanding JSON Schema](http://spacetelescope.github.io/understanding-json-schema/)。 + +[TOC] + +## 基本用法 + +首先,你要把 JSON Schema 解析成 `Document`,再把它编译成一个 `SchemaDocument`。 + +然后,利用该 `SchemaDocument` 创建一个 `SchemaValidator`。它与 `Writer` 相似,都是能够处理 SAX 事件的。因此,你可以用 `document.Accept(validator)` 去校验一个 JSON,然后再获取校验结果。 + +~~~cpp +#include "rapidjson/schema.h" + +// ... + +Document sd; +if (!sd.Parse(schemaJson).HasParseError()) { + // 此 schema 不是合法的 JSON + // ... +} +SchemaDocument schema(sd); // 把一个 Document 编译至 SchemaDocument +// 之后不再需要 sd + +Document d; +if (!d.Parse(inputJson).HasParseError()) { + // 输入不是一个合法的 JSON + // ... +} + +SchemaValidator validator(schema); +if (!d.Accept(validator)) { + // 输入的 JSON 不合乎 schema + // 打印诊断信息 + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); +} +~~~ + +一些注意点: + +* 一个 `SchemaDocment` 能被多个 `SchemaValidator` 引用。它不会被 `SchemaValidator` 修改。 +* 可以重复使用一个 `SchemaValidator` 来校验多个文件。在校验其他文件前,须先调用 `validator.Reset()`。 + +## 在解析/生成时进行校验 + +与大部分 JSON Schema 校验器有所不同,RapidJSON 提供了一个基于 SAX 的 schema 校验器实现。因此,你可以在输入流解析 JSON 的同时进行校验。若校验器遇到一个与 schema 不符的值,就会立即终止解析。这设计对于解析大型 JSON 文件时特别有用。 + +### DOM 解析 + +在使用 DOM 进行解析时,`Document` 除了接收 SAX 事件外,还需做一些准备及结束工作,因此,为了连接 `Reader`、`SchemaValidator` 和 `Document` 要做多一点事情。`SchemaValidatingReader` 是一个辅助类去做那些工作。 + +~~~cpp +#include "rapidjson/filereadstream.h" + +// ... +SchemaDocument schema(sd); // 把一个 Document 编译至 SchemaDocument + +// 使用 reader 解析 JSON +FILE* fp = fopen("big.json", "r"); +FileReadStream is(fp, buffer, sizeof(buffer)); + +// 用 reader 解析 JSON,校验它的 SAX 事件,并存储至 d +Document d; +SchemaValidatingReader > reader(is, schema); +d.Populate(reader); + +if (!reader.GetParseResult()) { + // 不是一个合法的 JSON + // 当 reader.GetParseResult().Code() == kParseErrorTermination, + // 它可能是被以下原因中止: + // (1) 校验器发现 JSON 不合乎 schema;或 + // (2) 输入流有 I/O 错误。 + + // 检查校验结果 + if (!reader.IsValid()) { + // 输入的 JSON 不合乎 schema + // 打印诊断信息 + StringBuffer sb; + reader.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", reader.GetInvalidSchemaKeyword()); + sb.Clear(); + reader.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); + } +} +~~~ + +### SAX 解析 + +使用 SAX 解析时,情况就简单得多。若只需要校验 JSON 而无需进一步处理,那么仅需要: + +~~~ +SchemaValidator validator(schema); +Reader reader; +if (!reader.Parse(stream, validator)) { + if (!validator.IsValid()) { + // ... + } +} +~~~ + +这种方式和 [schemavalidator](example/schemavalidator/schemavalidator.cpp) 例子完全相同。这带来的独特优势是,无论 JSON 多巨大,永远维持低内存用量(内存用量只与 Schema 的复杂度相关)。 + +若你需要进一步处理 SAX 事件,便可使用模板类 `GenericSchemaValidator` 去设置校验器的输出 `Handler`: + +~~~ +MyHandler handler; +GenericSchemaValidator validator(schema, handler); +Reader reader; +if (!reader.Parse(ss, validator)) { + if (!validator.IsValid()) { + // ... + } +} +~~~ + +### 生成 + +我们也可以在生成(serialization)的时候进行校验。这能确保输出的 JSON 符合一个 JSON Schema。 + +~~~ +StringBuffer sb; +Writer writer(sb); +GenericSchemaValidator > validator(s, writer); +if (!d.Accept(validator)) { + // Some problem during Accept(), it may be validation or encoding issues. + if (!validator.IsValid()) { + // ... + } +} +~~~ + +当然,如果你的应用仅需要 SAX 风格的生成,那么只需要把 SAX 事件由原来发送到 `Writer`,改为发送到 `SchemaValidator`。 + +## 远程 Schema + +JSON Schema 支持 [`$ref` 关键字](http://spacetelescope.github.io/understanding-json-schema/structuring.html),它是一个 [JSON pointer](doc/pointer.zh-cn.md) 引用至一个本地(local)或远程(remote) schema。本地指针的首字符是 `#`,而远程指针是一个相对或绝对 URI。例如: + +~~~js +{ "$ref": "definitions.json#/address" } +~~~ + +由于 `SchemaDocument` 并不知道如何处理那些 URI,它需要使用者提供一个 `IRemoteSchemaDocumentProvider` 的实例去处理。 + +~~~ +class MyRemoteSchemaDocumentProvider : public IRemoteSchemaDocumentProvider { +public: + virtual const SchemaDocument* GetRemoteDocument(const char* uri, SizeTyp length) { + // Resolve the uri and returns a pointer to that schema. + } +}; + +// ... + +MyRemoteSchemaDocumentProvider provider; +SchemaDocument schema(sd, &provider); +~~~ + +## 标准的符合程度 + +RapidJSON 通过了 [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (Json Schema draft 4) 中 263 个测试的 262 个。 + +没通过的测试是 `refRemote.json` 中的 "change resolution scope" - "changed scope ref invalid"。这是由于未实现 `id` schema 关键字及 URI 合并功能。 + +除此以外,关于字符串类型的 `format` schema 关键字也会被忽略,因为标准中并没需求必须实现。 + +### 正则表达式 + +`pattern` 及 `patternProperties` 这两个 schema 关键字使用了正则表达式去匹配所需的模式。 + +RapidJSON 实现了一个简单的 NFA 正则表达式引擎,并预设使用。它支持以下语法。 + +|语法|描述| +|------|-----------| +|`ab` | 串联 | +|`a|b` | 交替 | +|`a?` | 零或一次 | +|`a*` | 零或多次 | +|`a+` | 一或多次 | +|`a{3}` | 刚好 3 次 | +|`a{3,}` | 至少 3 次 | +|`a{3,5}`| 3 至 5 次 | +|`(ab)` | 分组 | +|`^a` | 在开始处 | +|`a$` | 在结束处 | +|`.` | 任何字符 | +|`[abc]` | 字符组 | +|`[a-c]` | 字符组范围 | +|`[a-z0-9_]` | 字符组组合 | +|`[^abc]` | 字符组取反 | +|`[^a-c]` | 字符组范围取反 | +|`[\b]` | 退格符 (U+0008) | +|`\|`, `\\`, ... | 转义字符 | +|`\f` | 馈页 (U+000C) | +|`\n` | 馈行 (U+000A) | +|`\r` | 回车 (U+000D) | +|`\t` | 制表 (U+0009) | +|`\v` | 垂直制表 (U+000B) | + +对于使用 C++11 编译器的使用者,也可使用 `std::regex`,只需定义 `RAPIDJSON_SCHEMA_USE_INTERNALREGEX=0` 及 `RAPIDJSON_SCHEMA_USE_STDREGEX=1`。若你的 schema 无需使用 `pattern` 或 `patternProperties`,可以把两个宏都设为零,以禁用此功能,这样做可节省一些代码体积。 + +## 性能 + +大部分 C++ JSON 库都未支持 JSON Schema。因此我们尝试按照 [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) 去评估 RapidJSON 的 JSON Schema 校验器。该评测测试了 11 个运行在 node.js 上的 JavaScript 库。 + +该评测校验 [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) 中的测试,当中排除了一些测试套件及个别测试。我们在 [`schematest.cpp`](test/perftest/schematest.cpp) 实现了相同的评测。 + +在 MacBook Pro (2.8 GHz Intel Core i7) 上收集到以下结果。 + +|校验器|相对速度|每秒执行的测试数目| +|---------|:------------:|:----------------------------:| +|RapidJSON|155%|30682| +|[`ajv`](https://github.com/epoberezkin/ajv)|100%|19770 (± 1.31%)| +|[`is-my-json-valid`](https://github.com/mafintosh/is-my-json-valid)|70%|13835 (± 2.84%)| +|[`jsen`](https://github.com/bugventure/jsen)|57.7%|11411 (± 1.27%)| +|[`schemasaurus`](https://github.com/AlexeyGrishin/schemasaurus)|26%|5145 (± 1.62%)| +|[`themis`](https://github.com/playlyfe/themis)|19.9%|3935 (± 2.69%)| +|[`z-schema`](https://github.com/zaggino/z-schema)|7%|1388 (± 0.84%)| +|[`jsck`](https://github.com/pandastrike/jsck#readme)|3.1%|606 (± 2.84%)| +|[`jsonschema`](https://github.com/tdegrunt/jsonschema#readme)|0.9%|185 (± 1.01%)| +|[`skeemas`](https://github.com/Prestaul/skeemas#readme)|0.8%|154 (± 0.79%)| +|tv4|0.5%|93 (± 0.94%)| +|[`jayschema`](https://github.com/natesilva/jayschema)|0.1%|21 (± 1.14%)| + +换言之,RapidJSON 比最快的 JavaScript 库(ajv)快约 1.5x。比最慢的快 1400x。 diff --git a/thirdparty/rapidjson-1.1.0/doc/stream.md b/thirdparty/rapidjson-1.1.0/doc/stream.md new file mode 100644 index 0000000000..b79ce537ac --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/stream.md @@ -0,0 +1,426 @@ +# Stream + +In RapidJSON, `rapidjson::Stream` is a concept for reading/writing JSON. Here we first show how to use streams provided. And then see how to create a custom stream. + +[TOC] + +# Memory Streams {#MemoryStreams} + +Memory streams store JSON in memory. + +## StringStream (Input) {#StringStream} + +`StringStream` is the most basic input stream. It represents a complete, read-only JSON stored in memory. It is defined in `rapidjson/rapidjson.h`. + +~~~~~~~~~~cpp +#include "rapidjson/document.h" // will include "rapidjson/rapidjson.h" + +using namespace rapidjson; + +// ... +const char json[] = "[1, 2, 3, 4]"; +StringStream s(json); + +Document d; +d.ParseStream(s); +~~~~~~~~~~ + +Since this is very common usage, `Document::Parse(const char*)` is provided to do exactly the same as above: + +~~~~~~~~~~cpp +// ... +const char json[] = "[1, 2, 3, 4]"; +Document d; +d.Parse(json); +~~~~~~~~~~ + +Note that, `StringStream` is a typedef of `GenericStringStream >`, user may use another encodings to represent the character set of the stream. + +## StringBuffer (Output) {#StringBuffer} + +`StringBuffer` is a simple output stream. It allocates a memory buffer for writing the whole JSON. Use `GetString()` to obtain the buffer. + +~~~~~~~~~~cpp +#include "rapidjson/stringbuffer.h" + +StringBuffer buffer; +Writer writer(buffer); +d.Accept(writer); + +const char* output = buffer.GetString(); +~~~~~~~~~~ + +When the buffer is full, it will increases the capacity automatically. The default capacity is 256 characters (256 bytes for UTF8, 512 bytes for UTF16, etc.). User can provide an allocator and a initial capacity. + +~~~~~~~~~~cpp +StringBuffer buffer1(0, 1024); // Use its allocator, initial size = 1024 +StringBuffer buffer2(allocator, 1024); +~~~~~~~~~~ + +By default, `StringBuffer` will instantiate an internal allocator. + +Similarly, `StringBuffer` is a typedef of `GenericStringBuffer >`. + +# File Streams {#FileStreams} + +When parsing a JSON from file, you may read the whole JSON into memory and use ``StringStream`` above. + +However, if the JSON is big, or memory is limited, you can use `FileReadStream`. It only read a part of JSON from file into buffer, and then let the part be parsed. If it runs out of characters in the buffer, it will read the next part from file. + +## FileReadStream (Input) {#FileReadStream} + +`FileReadStream` reads the file via a `FILE` pointer. And user need to provide a buffer. + +~~~~~~~~~~cpp +#include "rapidjson/filereadstream.h" +#include + +using namespace rapidjson; + +FILE* fp = fopen("big.json", "rb"); // non-Windows use "r" + +char readBuffer[65536]; +FileReadStream is(fp, readBuffer, sizeof(readBuffer)); + +Document d; +d.ParseStream(is); + +fclose(fp); +~~~~~~~~~~ + +Different from string streams, `FileReadStream` is byte stream. It does not handle encodings. If the file is not UTF-8, the byte stream can be wrapped in a `EncodedInputStream`. It will be discussed very soon. + +Apart from reading file, user can also use `FileReadStream` to read `stdin`. + +## FileWriteStream (Output) {#FileWriteStream} + +`FileWriteStream` is buffered output stream. Its usage is very similar to `FileReadStream`. + +~~~~~~~~~~cpp +#include "rapidjson/filewritestream.h" +#include + +using namespace rapidjson; + +Document d; +d.Parse(json); +// ... + +FILE* fp = fopen("output.json", "wb"); // non-Windows use "w" + +char writeBuffer[65536]; +FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); + +Writer writer(os); +d.Accept(writer); + +fclose(fp); +~~~~~~~~~~ + +It can also directs the output to `stdout`. + +# iostream Wrapper {#iostreamWrapper} + +Due to users' requests, RapidJSON provided official wrappers for `std::basic_istream` and `std::basic_ostream`. However, please note that the performance will be much lower than the other streams above. + +## IStreamWrapper {#IStreamWrapper} + +`IStreamWrapper` wraps any class drived from `std::istream`, such as `std::istringstream`, `std::stringstream`, `std::ifstream`, `std::fstream`, into RapidJSON's input stream. + +~~~cpp +#include +#include +#include + +using namespace rapidjson; +using namespace std; + +ifstream ifs("test.json"); +IStreamWrapper isw(ifs); + +Document d; +d.ParseStream(isw); +~~~ + +For classes derived from `std::wistream`, use `WIStreamWrapper`. + +## OStreamWrapper {#OStreamWrapper} + +Similarly, `OStreamWrapper` wraps any class derived from `std::ostream`, such as `std::ostringstream`, `std::stringstream`, `std::ofstream`, `std::fstream`, into RapidJSON's input stream. + +~~~cpp +#include +#include +#include +#include + +using namespace rapidjson; +using namespace std; + +Document d; +d.Parse(json); + +// ... + +ofstream ofs("output.json"); +OStreamWrapper osw(ofs); + +Writer writer(osw); +d.Accept(writer); +~~~ + +For classes derived from `std::wostream`, use `WOStreamWrapper`. + +# Encoded Streams {#EncodedStreams} + +Encoded streams do not contain JSON itself, but they wrap byte streams to provide basic encoding/decoding function. + +As mentioned above, UTF-8 byte streams can be read directly. However, UTF-16 and UTF-32 have endian issue. To handle endian correctly, it needs to convert bytes into characters (e.g. `wchar_t` for UTF-16) while reading, and characters into bytes while writing. + +Besides, it also need to handle [byte order mark (BOM)](http://en.wikipedia.org/wiki/Byte_order_mark). When reading from a byte stream, it is needed to detect or just consume the BOM if exists. When writing to a byte stream, it can optionally write BOM. + +If the encoding of stream is known in compile-time, you may use `EncodedInputStream` and `EncodedOutputStream`. If the stream can be UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE JSON, and it is only known in runtime, you may use `AutoUTFInputStream` and `AutoUTFOutputStream`. These streams are defined in `rapidjson/encodedstream.h`. + +Note that, these encoded streams can be applied to streams other than file. For example, you may have a file in memory, or a custom byte stream, be wrapped in encoded streams. + +## EncodedInputStream {#EncodedInputStream} + +`EncodedInputStream` has two template parameters. The first one is a `Encoding` class, such as `UTF8`, `UTF16LE`, defined in `rapidjson/encodings.h`. The second one is the class of stream to be wrapped. + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/filereadstream.h" // FileReadStream +#include "rapidjson/encodedstream.h" // EncodedInputStream +#include + +using namespace rapidjson; + +FILE* fp = fopen("utf16le.json", "rb"); // non-Windows use "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +EncodedInputStream, FileReadStream> eis(bis); // wraps bis into eis + +Document d; // Document is GenericDocument > +d.ParseStream<0, UTF16LE<> >(eis); // Parses UTF-16LE file into UTF-8 in memory + +fclose(fp); +~~~~~~~~~~ + +## EncodedOutputStream {#EncodedOutputStream} + +`EncodedOutputStream` is similar but it has a `bool putBOM` parameter in the constructor, controlling whether to write BOM into output byte stream. + +~~~~~~~~~~cpp +#include "rapidjson/filewritestream.h" // FileWriteStream +#include "rapidjson/encodedstream.h" // EncodedOutputStream +#include + +Document d; // Document is GenericDocument > +// ... + +FILE* fp = fopen("output_utf32le.json", "wb"); // non-Windows use "w" + +char writeBuffer[256]; +FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer)); + +typedef EncodedOutputStream, FileWriteStream> OutputStream; +OutputStream eos(bos, true); // Write BOM + +Writer, UTF8<>> writer(eos); +d.Accept(writer); // This generates UTF32-LE file from UTF-8 in memory + +fclose(fp); +~~~~~~~~~~ + +## AutoUTFInputStream {#AutoUTFInputStream} + +Sometimes an application may want to handle all supported JSON encoding. `AutoUTFInputStream` will detection encoding by BOM first. If BOM is unavailable, it will use characteristics of valid JSON to make detection. If neither method success, it falls back to the UTF type provided in constructor. + +Since the characters (code units) may be 8-bit, 16-bit or 32-bit. `AutoUTFInputStream` requires a character type which can hold at least 32-bit. We may use `unsigned`, as in the template parameter: + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/filereadstream.h" // FileReadStream +#include "rapidjson/encodedstream.h" // AutoUTFInputStream +#include + +using namespace rapidjson; + +FILE* fp = fopen("any.json", "rb"); // non-Windows use "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +AutoUTFInputStream eis(bis); // wraps bis into eis + +Document d; // Document is GenericDocument > +d.ParseStream<0, AutoUTF >(eis); // This parses any UTF file into UTF-8 in memory + +fclose(fp); +~~~~~~~~~~ + +When specifying the encoding of stream, uses `AutoUTF` as in `ParseStream()` above. + +You can obtain the type of UTF via `UTFType GetType()`. And check whether a BOM is found by `HasBOM()` + +## AutoUTFOutputStream {#AutoUTFOutputStream} + +Similarly, to choose encoding for output during runtime, we can use `AutoUTFOutputStream`. This class is not automatic *per se*. You need to specify the UTF type and whether to write BOM in runtime. + +~~~~~~~~~~cpp +using namespace rapidjson; + +void WriteJSONFile(FILE* fp, UTFType type, bool putBOM, const Document& d) { + char writeBuffer[256]; + FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer)); + + typedef AutoUTFOutputStream OutputStream; + OutputStream eos(bos, type, putBOM); + + Writer, AutoUTF<> > writer; + d.Accept(writer); +} +~~~~~~~~~~ + +`AutoUTFInputStream` and `AutoUTFOutputStream` is more convenient than `EncodedInputStream` and `EncodedOutputStream`. They just incur a little bit runtime overheads. + +# Custom Stream {#CustomStream} + +In addition to memory/file streams, user can create their own stream classes which fits RapidJSON's API. For example, you may create network stream, stream from compressed file, etc. + +RapidJSON combines different types using templates. A class containing all required interface can be a stream. The Stream interface is defined in comments of `rapidjson/rapidjson.h`: + +~~~~~~~~~~cpp +concept Stream { + typename Ch; //!< Character type of the stream. + + //! Read the current character from stream without moving the read cursor. + Ch Peek() const; + + //! Read the current character from stream and moving the read cursor to next character. + Ch Take(); + + //! Get the current read cursor. + //! \return Number of characters read from start. + size_t Tell(); + + //! Begin writing operation at the current read pointer. + //! \return The begin writer pointer. + Ch* PutBegin(); + + //! Write a character. + void Put(Ch c); + + //! Flush the buffer. + void Flush(); + + //! End the writing operation. + //! \param begin The begin write pointer returned by PutBegin(). + //! \return Number of characters written. + size_t PutEnd(Ch* begin); +} +~~~~~~~~~~ + +For input stream, they must implement `Peek()`, `Take()` and `Tell()`. +For output stream, they must implement `Put()` and `Flush()`. +There are two special interface, `PutBegin()` and `PutEnd()`, which are only for *in situ* parsing. Normal streams do not implement them. However, if the interface is not needed for a particular stream, it is still need to a dummy implementation, otherwise will generate compilation error. + +## Example: istream wrapper {#ExampleIStreamWrapper} + +The following example is a simple wrapper of `std::istream`, which only implements 3 functions. + +~~~~~~~~~~cpp +class MyIStreamWrapper { +public: + typedef char Ch; + + MyIStreamWrapper(std::istream& is) : is_(is) { + } + + Ch Peek() const { // 1 + int c = is_.peek(); + return c == std::char_traits::eof() ? '\0' : (Ch)c; + } + + Ch Take() { // 2 + int c = is_.get(); + return c == std::char_traits::eof() ? '\0' : (Ch)c; + } + + size_t Tell() const { return (size_t)is_.tellg(); } // 3 + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch) { assert(false); } + void Flush() { assert(false); } + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + MyIStreamWrapper(const MyIStreamWrapper&); + MyIStreamWrapper& operator=(const MyIStreamWrapper&); + + std::istream& is_; +}; +~~~~~~~~~~ + +User can use it to wrap instances of `std::stringstream`, `std::ifstream`. + +~~~~~~~~~~cpp +const char* json = "[1,2,3,4]"; +std::stringstream ss(json); +MyIStreamWrapper is(ss); + +Document d; +d.ParseStream(is); +~~~~~~~~~~ + +Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library. + +## Example: ostream wrapper {#ExampleOStreamWrapper} + +The following example is a simple wrapper of `std::istream`, which only implements 2 functions. + +~~~~~~~~~~cpp +class MyOStreamWrapper { +public: + typedef char Ch; + + MyOStreamWrapper(std::ostream& os) : os_(os) { + } + + Ch Peek() const { assert(false); return '\0'; } + Ch Take() { assert(false); return '\0'; } + size_t Tell() const { } + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch c) { os_.put(c); } // 1 + void Flush() { os_.flush(); } // 2 + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + MyOStreamWrapper(const MyOStreamWrapper&); + MyOStreamWrapper& operator=(const MyOStreamWrapper&); + + std::ostream& os_; +}; +~~~~~~~~~~ + +User can use it to wrap instances of `std::stringstream`, `std::ofstream`. + +~~~~~~~~~~cpp +Document d; +// ... + +std::stringstream ss; +MyOStreamWrapper os(ss); + +Writer writer(os); +d.Accept(writer); +~~~~~~~~~~ + +Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library. + +# Summary {#Summary} + +This section describes stream classes available in RapidJSON. Memory streams are simple. File stream can reduce the memory required during JSON parsing and generation, if the JSON is stored in file system. Encoded streams converts between byte streams and character streams. Finally, user may create custom streams using a simple interface. diff --git a/thirdparty/rapidjson-1.1.0/doc/stream.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/stream.zh-cn.md new file mode 100644 index 0000000000..f2c54f798e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/stream.zh-cn.md @@ -0,0 +1,426 @@ +# 流 + +在 RapidJSON 中,`rapidjson::Stream` 是用於读写 JSON 的概念(概念是指 C++ 的 concept)。在这里我们先介绍如何使用 RapidJSON 提供的各种流。然后再看看如何自行定义流。 + +[TOC] + +# 内存流 {#MemoryStreams} + +内存流把 JSON 存储在内存之中。 + +## StringStream(输入){#StringStream} + +`StringStream` 是最基本的输入流,它表示一个完整的、只读的、存储于内存的 JSON。它在 `rapidjson/rapidjson.h` 中定义。 + +~~~~~~~~~~cpp +#include "rapidjson/document.h" // 会包含 "rapidjson/rapidjson.h" + +using namespace rapidjson; + +// ... +const char json[] = "[1, 2, 3, 4]"; +StringStream s(json); + +Document d; +d.ParseStream(s); +~~~~~~~~~~ + +由于这是非常常用的用法,RapidJSON 提供 `Document::Parse(const char*)` 去做完全相同的事情: + +~~~~~~~~~~cpp +// ... +const char json[] = "[1, 2, 3, 4]"; +Document d; +d.Parse(json); +~~~~~~~~~~ + +需要注意,`StringStream` 是 `GenericStringStream >` 的 typedef,使用者可用其他编码类去代表流所使用的字符集。 + +## StringBuffer(输出){#StringBuffer} + +`StringBuffer` 是一个简单的输出流。它分配一个内存缓冲区,供写入整个 JSON。可使用 `GetString()` 来获取该缓冲区。 + +~~~~~~~~~~cpp +#include "rapidjson/stringbuffer.h" + +StringBuffer buffer; +Writer writer(buffer); +d.Accept(writer); + +const char* output = buffer.GetString(); +~~~~~~~~~~ + +当缓冲区满溢,它将自动增加容量。缺省容量是 256 个字符(UTF8 是 256 字节,UTF16 是 512 字节等)。使用者能自行提供分配器及初始容量。 + +~~~~~~~~~~cpp +StringBuffer buffer1(0, 1024); // 使用它的分配器,初始大小 = 1024 +StringBuffer buffer2(allocator, 1024); +~~~~~~~~~~ + +如无设置分配器,`StringBuffer` 会自行实例化一个内部分配器。 + +相似地,`StringBuffer` 是 `GenericStringBuffer >` 的 typedef。 + +# 文件流 {#FileStreams} + +当要从文件解析一个 JSON,你可以把整个 JSON 读入内存并使用上述的 `StringStream`。 + +然而,若 JSON 很大,或是内存有限,你可以改用 `FileReadStream`。它只会从文件读取一部分至缓冲区,然后让那部分被解析。若缓冲区的字符都被读完,它会再从文件读取下一部分。 + +## FileReadStream(输入) {#FileReadStream} + +`FileReadStream` 通过 `FILE` 指针读取文件。使用者需要提供一个缓冲区。 + +~~~~~~~~~~cpp +#include "rapidjson/filereadstream.h" +#include + +using namespace rapidjson; + +FILE* fp = fopen("big.json", "rb"); // 非 Windows 平台使用 "r" + +char readBuffer[65536]; +FileReadStream is(fp, readBuffer, sizeof(readBuffer)); + +Document d; +d.ParseStream(is); + +fclose(fp); +~~~~~~~~~~ + +与 `StringStreams` 不一样,`FileReadStream` 是一个字节流。它不处理编码。若文件并非 UTF-8 编码,可以把字节流用 `EncodedInputStream` 包装。我们很快会讨论这个问题。 + +除了读取文件,使用者也可以使用 `FileReadStream` 来读取 `stdin`。 + +## FileWriteStream(输出){#FileWriteStream} + +`FileWriteStream` 是一个含缓冲功能的输出流。它的用法与 `FileReadStream` 非常相似。 + +~~~~~~~~~~cpp +#include "rapidjson/filewritestream.h" +#include + +using namespace rapidjson; + +Document d; +d.Parse(json); +// ... + +FILE* fp = fopen("output.json", "wb"); // 非 Windows 平台使用 "w" + +char writeBuffer[65536]; +FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); + +Writer writer(os); +d.Accept(writer); + +fclose(fp); +~~~~~~~~~~ + +它也可以把输出导向 `stdout`。 + +# iostream 包装类 {#iostreamWrapper} + +基于用户的要求,RapidJSON 提供了正式的 `std::basic_istream` 和 `std::basic_ostream` 包装类。然而,请注意其性能会大大低于以上的其他流。 + +## IStreamWrapper {#IStreamWrapper} + +`IStreamWrapper` 把任何继承自 `std::istream` 的类(如 `std::istringstream`、`std::stringstream`、`std::ifstream`、`std::fstream`)包装成 RapidJSON 的输入流。 + +~~~cpp +#include +#include +#include + +using namespace rapidjson; +using namespace std; + +ifstream ifs("test.json"); +IStreamWrapper isw(ifs); + +Document d; +d.ParseStream(isw); +~~~ + +对于继承自 `std::wistream` 的类,则使用 `WIStreamWrapper`。 + +## OStreamWrapper {#OStreamWrapper} + +相似地,`OStreamWrapper` 把任何继承自 `std::ostream` 的类(如 `std::ostringstream`、`std::stringstream`、`std::ofstream`、`std::fstream`)包装成 RapidJSON 的输出流。 + +~~~cpp +#include +#include +#include +#include + +using namespace rapidjson; +using namespace std; + +Document d; +d.Parse(json); + +// ... + +ofstream ofs("output.json"); +OStreamWrapper osw(ofs); + +Writer writer(osw); +d.Accept(writer); +~~~ + +对于继承自 `std::wistream` 的类,则使用 `WIStreamWrapper`。 + +# 编码流 {#EncodedStreams} + +编码流(encoded streams)本身不存储 JSON,它们是通过包装字节流来提供基本的编码/解码功能。 + +如上所述,我们可以直接读入 UTF-8 字节流。然而,UTF-16 及 UTF-32 有字节序(endian)问题。要正确地处理字节序,需要在读取时把字节转换成字符(如对 UTF-16 使用 `wchar_t`),以及在写入时把字符转换为字节。 + +除此以外,我们也需要处理 [字节顺序标记(byte order mark, BOM)](http://en.wikipedia.org/wiki/Byte_order_mark)。当从一个字节流读取时,需要检测 BOM,或者仅仅是把存在的 BOM 消去。当把 JSON 写入字节流时,也可选择写入 BOM。 + +若一个流的编码在编译期已知,你可使用 `EncodedInputStream` 及 `EncodedOutputStream`。若一个流可能存储 UTF-8、UTF-16LE、UTF-16BE、UTF-32LE、UTF-32BE 的 JSON,并且编码只能在运行时得知,你便可以使用 `AutoUTFInputStream` 及 `AutoUTFOutputStream`。这些流定义在 `rapidjson/encodedstream.h`。 + +注意到,这些编码流可以施于文件以外的流。例如,你可以用编码流包装内存中的文件或自定义的字节流。 + +## EncodedInputStream {#EncodedInputStream} + +`EncodedInputStream` 含两个模板参数。第一个是 `Encoding` 类型,例如定义于 `rapidjson/encodings.h` 的 `UTF8`、`UTF16LE`。第二个参数是被包装的流的类型。 + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/filereadstream.h" // FileReadStream +#include "rapidjson/encodedstream.h" // EncodedInputStream +#include + +using namespace rapidjson; + +FILE* fp = fopen("utf16le.json", "rb"); // 非 Windows 平台使用 "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +EncodedInputStream, FileReadStream> eis(bis); // 用 eis 包装 bis + +Document d; // Document 为 GenericDocument > +d.ParseStream<0, UTF16LE<> >(eis); // 把 UTF-16LE 文件解析至内存中的 UTF-8 + +fclose(fp); +~~~~~~~~~~ + +## EncodedOutputStream {#EncodedOutputStream} + +`EncodedOutputStream` 也是相似的,但它的构造函数有一个 `bool putBOM` 参数,用于控制是否在输出字节流写入 BOM。 + +~~~~~~~~~~cpp +#include "rapidjson/filewritestream.h" // FileWriteStream +#include "rapidjson/encodedstream.h" // EncodedOutputStream +#include + +Document d; // Document 为 GenericDocument > +// ... + +FILE* fp = fopen("output_utf32le.json", "wb"); // 非 Windows 平台使用 "w" + +char writeBuffer[256]; +FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer)); + +typedef EncodedOutputStream, FileWriteStream> OutputStream; +OutputStream eos(bos, true); // 写入 BOM + +Writer, UTF8<>> writer(eos); +d.Accept(writer); // 这里从内存的 UTF-8 生成 UTF32-LE 文件 + +fclose(fp); +~~~~~~~~~~ + +## AutoUTFInputStream {#AutoUTFInputStream} + +有时候,应用软件可能需要㲃理所有可支持的 JSON 编码。`AutoUTFInputStream` 会先使用 BOM 来检测编码。若 BOM 不存在,它便会使用合法 JSON 的特性来检测。若两种方法都失败,它就会倒退至构造函数提供的 UTF 类型。 + +由于字符(编码单元/code unit)可能是 8 位、16 位或 32 位,`AutoUTFInputStream` 需要一个能至少储存 32 位的字符类型。我们可以使用 `unsigned` 作为模板参数: + +~~~~~~~~~~cpp +#include "rapidjson/document.h" +#include "rapidjson/filereadstream.h" // FileReadStream +#include "rapidjson/encodedstream.h" // AutoUTFInputStream +#include + +using namespace rapidjson; + +FILE* fp = fopen("any.json", "rb"); // 非 Windows 平台使用 "r" + +char readBuffer[256]; +FileReadStream bis(fp, readBuffer, sizeof(readBuffer)); + +AutoUTFInputStream eis(bis); // 用 eis 包装 bis + +Document d; // Document 为 GenericDocument > +d.ParseStream<0, AutoUTF >(eis); // 把任何 UTF 编码的文件解析至内存中的 UTF-8 + +fclose(fp); +~~~~~~~~~~ + +当要指定流的编码,可使用上面例子中 `ParseStream()` 的参数 `AutoUTF`。 + +你可以使用 `UTFType GetType()` 去获取 UTF 类型,并且用 `HasBOM()` 检测输入流是否含有 BOM。 + +## AutoUTFOutputStream {#AutoUTFOutputStream} + +相似地,要在运行时选择输出的编码,我们可使用 `AutoUTFOutputStream`。这个类本身并非「自动」。你需要在运行时指定 UTF 类型,以及是否写入 BOM。 + +~~~~~~~~~~cpp +using namespace rapidjson; + +void WriteJSONFile(FILE* fp, UTFType type, bool putBOM, const Document& d) { + char writeBuffer[256]; + FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer)); + + typedef AutoUTFOutputStream OutputStream; + OutputStream eos(bos, type, putBOM); + + Writer, AutoUTF<> > writer; + d.Accept(writer); +} +~~~~~~~~~~ + +`AutoUTFInputStream`/`AutoUTFOutputStream` 是比 `EncodedInputStream`/`EncodedOutputStream` 方便。但前者会产生一点运行期额外开销。 + +# 自定义流 {#CustomStream} + +除了内存/文件流,使用者可创建自行定义适配 RapidJSON API 的流类。例如,你可以创建网络流、从压缩文件读取的流等等。 + +RapidJSON 利用模板结合不同的类型。只要一个类包含所有所需的接口,就可以作为一个流。流的接合定义在 `rapidjson/rapidjson.h` 的注释里: + +~~~~~~~~~~cpp +concept Stream { + typename Ch; //!< 流的字符类型 + + //! 从流读取当前字符,不移动读取指针(read cursor) + Ch Peek() const; + + //! 从流读取当前字符,移动读取指针至下一字符。 + Ch Take(); + + //! 获取读取指针。 + //! \return 从开始以来所读过的字符数量。 + size_t Tell(); + + //! 从当前读取指针开始写入操作。 + //! \return 返回开始写入的指针。 + Ch* PutBegin(); + + //! 写入一个字符。 + void Put(Ch c); + + //! 清空缓冲区。 + void Flush(); + + //! 完成写作操作。 + //! \param begin PutBegin() 返回的开始写入指针。 + //! \return 已写入的字符数量。 + size_t PutEnd(Ch* begin); +} +~~~~~~~~~~ + +输入流必须实现 `Peek()`、`Take()` 及 `Tell()`。 +输出流必须实现 `Put()` 及 `Flush()`。 +`PutBegin()` 及 `PutEnd()` 是特殊的接口,仅用于原位(*in situ*)解析。一般的流不需实现它们。然而,即使接口不需用于某些流,仍然需要提供空实现,否则会产生编译错误。 + +## 例子:istream 的包装类 {#ExampleIStreamWrapper} + +以下的简单例子是 `std::istream` 的包装类,它只需现 3 个函数。 + +~~~~~~~~~~cpp +class MyIStreamWrapper { +public: + typedef char Ch; + + MyIStreamWrapper(std::istream& is) : is_(is) { + } + + Ch Peek() const { // 1 + int c = is_.peek(); + return c == std::char_traits::eof() ? '\0' : (Ch)c; + } + + Ch Take() { // 2 + int c = is_.get(); + return c == std::char_traits::eof() ? '\0' : (Ch)c; + } + + size_t Tell() const { return (size_t)is_.tellg(); } // 3 + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch) { assert(false); } + void Flush() { assert(false); } + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + MyIStreamWrapper(const MyIStreamWrapper&); + MyIStreamWrapper& operator=(const MyIStreamWrapper&); + + std::istream& is_; +}; +~~~~~~~~~~ + +使用者能用它来包装 `std::stringstream`、`std::ifstream` 的实例。 + +~~~~~~~~~~cpp +const char* json = "[1,2,3,4]"; +std::stringstream ss(json); +MyIStreamWrapper is(ss); + +Document d; +d.ParseStream(is); +~~~~~~~~~~ + +但要注意,由于标准库的内部开销问,此实现的性能可能不如 RapidJSON 的内存/文件流。 + +## 例子:ostream 的包装类 {#ExampleOStreamWrapper} + +以下的例子是 `std::istream` 的包装类,它只需实现 2 个函数。 + +~~~~~~~~~~cpp +class MyOStreamWrapper { +public: + typedef char Ch; + + OStreamWrapper(std::ostream& os) : os_(os) { + } + + Ch Peek() const { assert(false); return '\0'; } + Ch Take() { assert(false); return '\0'; } + size_t Tell() const { } + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch c) { os_.put(c); } // 1 + void Flush() { os_.flush(); } // 2 + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + MyOStreamWrapper(const MyOStreamWrapper&); + MyOStreamWrapper& operator=(const MyOStreamWrapper&); + + std::ostream& os_; +}; +~~~~~~~~~~ + +使用者能用它来包装 `std::stringstream`、`std::ofstream` 的实例。 + +~~~~~~~~~~cpp +Document d; +// ... + +std::stringstream ss; +MyOStreamWrapper os(ss); + +Writer writer(os); +d.Accept(writer); +~~~~~~~~~~ + +但要注意,由于标准库的内部开销问,此实现的性能可能不如 RapidJSON 的内存/文件流。 + +# 总结 {#Summary} + +本节描述了 RapidJSON 提供的各种流的类。内存流很简单。若 JSON 存储在文件中,文件流可减少 JSON 解析及生成所需的内存量。编码流在字节流和字符流之间作转换。最后,使用者可使用一个简单接口创建自定义的流。 diff --git a/thirdparty/rapidjson-1.1.0/doc/tutorial.md b/thirdparty/rapidjson-1.1.0/doc/tutorial.md new file mode 100644 index 0000000000..cb76b4b0b7 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/tutorial.md @@ -0,0 +1,536 @@ +# Tutorial + +This tutorial introduces the basics of the Document Object Model(DOM) API. + +As shown in [Usage at a glance](@ref index), a JSON can be parsed into DOM, and then the DOM can be queried and modified easily, and finally be converted back to JSON. + +[TOC] + +# Value & Document {#ValueDocument} + +Each JSON value is stored in a type called `Value`. A `Document`, representing the DOM, contains the root `Value` of the DOM tree. All public types and functions of RapidJSON are defined in the `rapidjson` namespace. + +# Query Value {#QueryValue} + +In this section, we will use excerpt of `example/tutorial/tutorial.cpp`. + +Assumes we have a JSON stored in a C string (`const char* json`): +~~~~~~~~~~js +{ + "hello": "world", + "t": true , + "f": false, + "n": null, + "i": 123, + "pi": 3.1416, + "a": [1, 2, 3, 4] +} +~~~~~~~~~~ + +Parse it into a `Document`: +~~~~~~~~~~cpp +#include "rapidjson/document.h" + +using namespace rapidjson; + +// ... +Document document; +document.Parse(json); +~~~~~~~~~~ + +The JSON is now parsed into `document` as a *DOM tree*: + +![DOM in the tutorial](diagram/tutorial.png) + +Since the update to RFC 7159, the root of a conforming JSON document can be any JSON value. In earlier RFC 4627, only objects or arrays were allowed as root values. In this case, the root is an object. +~~~~~~~~~~cpp +assert(document.IsObject()); +~~~~~~~~~~ + +Let's query whether a `"hello"` member exists in the root object. Since a `Value` can contain different types of value, we may need to verify its type and use suitable API to obtain the value. In this example, `"hello"` member associates with a JSON string. +~~~~~~~~~~cpp +assert(document.HasMember("hello")); +assert(document["hello"].IsString()); +printf("hello = %s\n", document["hello"].GetString()); +~~~~~~~~~~ + +~~~~~~~~~~ +world +~~~~~~~~~~ + +JSON true/false values are represented as `bool`. +~~~~~~~~~~cpp +assert(document["t"].IsBool()); +printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); +~~~~~~~~~~ + +~~~~~~~~~~ +true +~~~~~~~~~~ + +JSON null can be queryed by `IsNull()`. +~~~~~~~~~~cpp +printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); +~~~~~~~~~~ + +~~~~~~~~~~ +null +~~~~~~~~~~ + +JSON number type represents all numeric values. However, C++ needs more specific type for manipulation. + +~~~~~~~~~~cpp +assert(document["i"].IsNumber()); + +// In this case, IsUint()/IsInt64()/IsUInt64() also return true. +assert(document["i"].IsInt()); +printf("i = %d\n", document["i"].GetInt()); +// Alternative (int)document["i"] + +assert(document["pi"].IsNumber()); +assert(document["pi"].IsDouble()); +printf("pi = %g\n", document["pi"].GetDouble()); +~~~~~~~~~~ + +~~~~~~~~~~ +i = 123 +pi = 3.1416 +~~~~~~~~~~ + +JSON array contains a number of elements. +~~~~~~~~~~cpp +// Using a reference for consecutive access is handy and faster. +const Value& a = document["a"]; +assert(a.IsArray()); +for (SizeType i = 0; i < a.Size(); i++) // Uses SizeType instead of size_t + printf("a[%d] = %d\n", i, a[i].GetInt()); +~~~~~~~~~~ + +~~~~~~~~~~ +a[0] = 1 +a[1] = 2 +a[2] = 3 +a[3] = 4 +~~~~~~~~~~ + +Note that, RapidJSON does not automatically convert values between JSON types. If a value is a string, it is invalid to call `GetInt()`, for example. In debug mode it will fail an assertion. In release mode, the behavior is undefined. + +In the following, details about querying individual types are discussed. + +## Query Array {#QueryArray} + +By default, `SizeType` is typedef of `unsigned`. In most systems, array is limited to store up to 2^32-1 elements. + +You may access the elements in array by integer literal, for example, `a[0]`, `a[1]`, `a[2]`. + +Array is similar to `std::vector`, instead of using indices, you may also use iterator to access all the elements. +~~~~~~~~~~cpp +for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) + printf("%d ", itr->GetInt()); +~~~~~~~~~~ + +And other familiar query functions: +* `SizeType Capacity() const` +* `bool Empty() const` + +### Range-based For Loop (New in v1.1.0) + +When C++11 is enabled, you can use range-based for loop to access all elements in an array. + +~~~~~~~~~~cpp +for (auto& v : a.GetArray()) + printf("%d ", v.GetInt()); +~~~~~~~~~~ + +## Query Object {#QueryObject} + +Similar to array, we can access all object members by iterator: + +~~~~~~~~~~cpp +static const char* kTypeNames[] = + { "Null", "False", "True", "Object", "Array", "String", "Number" }; + +for (Value::ConstMemberIterator itr = document.MemberBegin(); + itr != document.MemberEnd(); ++itr) +{ + printf("Type of member %s is %s\n", + itr->name.GetString(), kTypeNames[itr->value.GetType()]); +} +~~~~~~~~~~ + +~~~~~~~~~~ +Type of member hello is String +Type of member t is True +Type of member f is False +Type of member n is Null +Type of member i is Number +Type of member pi is Number +Type of member a is Array +~~~~~~~~~~ + +Note that, when `operator[](const char*)` cannot find the member, it will fail an assertion. + +If we are unsure whether a member exists, we need to call `HasMember()` before calling `operator[](const char*)`. However, this incurs two lookup. A better way is to call `FindMember()`, which can check the existence of member and obtain its value at once: + +~~~~~~~~~~cpp +Value::ConstMemberIterator itr = document.FindMember("hello"); +if (itr != document.MemberEnd()) + printf("%s\n", itr->value.GetString()); +~~~~~~~~~~ + +### Range-based For Loop (New in v1.1.0) + +When C++11 is enabled, you can use range-based for loop to access all members in an object. + +~~~~~~~~~~cpp +for (auto& m : document.GetObject()) + printf("Type of member %s is %s\n", + m.name.GetString(), kTypeNames[m.value.GetType()]); +~~~~~~~~~~ + +## Querying Number {#QueryNumber} + +JSON provide a single numerical type called Number. Number can be integer or real numbers. RFC 4627 says the range of Number is specified by parser. + +As C++ provides several integer and floating point number types, the DOM tries to handle these with widest possible range and good performance. + +When a Number is parsed, it is stored in the DOM as either one of the following type: + +Type | Description +-----------|--------------------------------------- +`unsigned` | 32-bit unsigned integer +`int` | 32-bit signed integer +`uint64_t` | 64-bit unsigned integer +`int64_t` | 64-bit signed integer +`double` | 64-bit double precision floating point + +When querying a number, you can check whether the number can be obtained as target type: + +Checking | Obtaining +------------------|--------------------- +`bool IsNumber()` | N/A +`bool IsUint()` | `unsigned GetUint()` +`bool IsInt()` | `int GetInt()` +`bool IsUint64()` | `uint64_t GetUint64()` +`bool IsInt64()` | `int64_t GetInt64()` +`bool IsDouble()` | `double GetDouble()` + +Note that, an integer value may be obtained in various ways without conversion. For example, A value `x` containing 123 will make `x.IsInt() == x.IsUint() == x.IsInt64() == x.IsUint64() == true`. But a value `y` containing -3000000000 will only makes `x.IsInt64() == true`. + +When obtaining the numeric values, `GetDouble()` will convert internal integer representation to a `double`. Note that, `int` and `unsigned` can be safely convert to `double`, but `int64_t` and `uint64_t` may lose precision (since mantissa of `double` is only 52-bits). + +## Query String {#QueryString} + +In addition to `GetString()`, the `Value` class also contains `GetStringLength()`. Here explains why. + +According to RFC 4627, JSON strings can contain Unicode character `U+0000`, which must be escaped as `"\u0000"`. The problem is that, C/C++ often uses null-terminated string, which treats ``\0'` as the terminator symbol. + +To conform RFC 4627, RapidJSON supports string containing `U+0000`. If you need to handle this, you can use `GetStringLength()` API to obtain the correct length of string. + +For example, after parsing a the following JSON to `Document d`: + +~~~~~~~~~~js +{ "s" : "a\u0000b" } +~~~~~~~~~~ +The correct length of the value `"a\u0000b"` is 3. But `strlen()` returns 1. + +`GetStringLength()` can also improve performance, as user may often need to call `strlen()` for allocating buffer. + +Besides, `std::string` also support a constructor: + +~~~~~~~~~~cpp +string(const char* s, size_t count); +~~~~~~~~~~ + +which accepts the length of string as parameter. This constructor supports storing null character within the string, and should also provide better performance. + +## Comparing values + +You can use `==` and `!=` to compare values. Two values are equal if and only if they are have same type and contents. You can also compare values with primitive types. Here is an example. + +~~~~~~~~~~cpp +if (document["hello"] == document["n"]) /*...*/; // Compare values +if (document["hello"] == "world") /*...*/; // Compare value with literal string +if (document["i"] != 123) /*...*/; // Compare with integers +if (document["pi"] != 3.14) /*...*/; // Compare with double. +~~~~~~~~~~ + +Array/object compares their elements/members in order. They are equal if and only if their whole subtrees are equal. + +Note that, currently if an object contains duplicated named member, comparing equality with any object is always `false`. + +# Create/Modify Values {#CreateModifyValues} + +There are several ways to create values. After a DOM tree is created and/or modified, it can be saved as JSON again using `Writer`. + +## Change Value Type {#ChangeValueType} +When creating a Value or Document by default constructor, its type is Null. To change its type, call `SetXXX()` or assignment operator, for example: + +~~~~~~~~~~cpp +Document d; // Null +d.SetObject(); + +Value v; // Null +v.SetInt(10); +v = 10; // Shortcut, same as above +~~~~~~~~~~ + +### Overloaded Constructors +There are also overloaded constructors for several types: + +~~~~~~~~~~cpp +Value b(true); // calls Value(bool) +Value i(-123); // calls Value(int) +Value u(123u); // calls Value(unsigned) +Value d(1.5); // calls Value(double) +~~~~~~~~~~ + +To create empty object or array, you may use `SetObject()`/`SetArray()` after default constructor, or using the `Value(Type)` in one shot: + +~~~~~~~~~~cpp +Value o(kObjectType); +Value a(kArrayType); +~~~~~~~~~~ + +## Move Semantics {#MoveSemantics} + +A very special decision during design of RapidJSON is that, assignment of value does not copy the source value to destination value. Instead, the value from source is moved to the destination. For example, + +~~~~~~~~~~cpp +Value a(123); +Value b(456); +b = a; // a becomes a Null value, b becomes number 123. +~~~~~~~~~~ + +![Assignment with move semantics.](diagram/move1.png) + +Why? What is the advantage of this semantics? + +The simple answer is performance. For fixed size JSON types (Number, True, False, Null), copying them is fast and easy. However, For variable size JSON types (String, Array, Object), copying them will incur a lot of overheads. And these overheads are often unnoticed. Especially when we need to create temporary object, copy it to another variable, and then destruct it. + +For example, if normal *copy* semantics was used: + +~~~~~~~~~~cpp +Document d; +Value o(kObjectType); +{ + Value contacts(kArrayType); + // adding elements to contacts array. + // ... + o.AddMember("contacts", contacts, d.GetAllocator()); // deep clone contacts (may be with lots of allocations) + // destruct contacts. +} +~~~~~~~~~~ + +![Copy semantics makes a lots of copy operations.](diagram/move2.png) + +The object `o` needs to allocate a buffer of same size as contacts, makes a deep clone of it, and then finally contacts is destructed. This will incur a lot of unnecessary allocations/deallocations and memory copying. + +There are solutions to prevent actual copying these data, such as reference counting and garbage collection(GC). + +To make RapidJSON simple and fast, we chose to use *move* semantics for assignment. It is similar to `std::auto_ptr` which transfer ownership during assignment. Move is much faster and simpler, it just destructs the original value, `memcpy()` the source to destination, and finally sets the source as Null type. + +So, with move semantics, the above example becomes: + +~~~~~~~~~~cpp +Document d; +Value o(kObjectType); +{ + Value contacts(kArrayType); + // adding elements to contacts array. + o.AddMember("contacts", contacts, d.GetAllocator()); // just memcpy() of contacts itself to the value of new member (16 bytes) + // contacts became Null here. Its destruction is trivial. +} +~~~~~~~~~~ + +![Move semantics makes no copying.](diagram/move3.png) + +This is called move assignment operator in C++11. As RapidJSON supports C++03, it adopts move semantics using assignment operator, and all other modifying function like `AddMember()`, `PushBack()`. + +### Move semantics and temporary values {#TemporaryValues} + +Sometimes, it is convenient to construct a Value in place, before passing it to one of the "moving" functions, like `PushBack()` or `AddMember()`. As temporary objects can't be converted to proper Value references, the convenience function `Move()` is available: + +~~~~~~~~~~cpp +Value a(kArrayType); +Document::AllocatorType& allocator = document.GetAllocator(); +// a.PushBack(Value(42), allocator); // will not compile +a.PushBack(Value().SetInt(42), allocator); // fluent API +a.PushBack(Value(42).Move(), allocator); // same as above +~~~~~~~~~~ + +## Create String {#CreateString} +RapidJSON provide two strategies for storing string. + +1. copy-string: allocates a buffer, and then copy the source data into it. +2. const-string: simply store a pointer of string. + +Copy-string is always safe because it owns a copy of the data. Const-string can be used for storing string literal, and in-situ parsing which we will mentioned in Document section. + +To make memory allocation customizable, RapidJSON requires user to pass an instance of allocator, whenever an operation may require allocation. This design is needed to prevent storing a allocator (or Document) pointer per Value. + +Therefore, when we assign a copy-string, we call this overloaded `SetString()` with allocator: + +~~~~~~~~~~cpp +Document document; +Value author; +char buffer[10]; +int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // dynamically created string. +author.SetString(buffer, len, document.GetAllocator()); +memset(buffer, 0, sizeof(buffer)); +// author.GetString() still contains "Milo Yip" after buffer is destroyed +~~~~~~~~~~ + +In this example, we get the allocator from a `Document` instance. This is a common idiom when using RapidJSON. But you may use other instances of allocator. + +Besides, the above `SetString()` requires length. This can handle null characters within a string. There is another `SetString()` overloaded function without the length parameter. And it assumes the input is null-terminated and calls a `strlen()`-like function to obtain the length. + +Finally, for string literal or string with safe life-cycle can use const-string version of `SetString()`, which lacks allocator parameter. For string literals (or constant character arrays), simply passing the literal as parameter is safe and efficient: + +~~~~~~~~~~cpp +Value s; +s.SetString("rapidjson"); // can contain null character, length derived at compile time +s = "rapidjson"; // shortcut, same as above +~~~~~~~~~~ + +For character pointer, the RapidJSON requires to mark it as safe before using it without copying. This can be achieved by using the `StringRef` function: + +~~~~~~~~~cpp +const char * cstr = getenv("USER"); +size_t cstr_len = ...; // in case length is available +Value s; +// s.SetString(cstr); // will not compile +s.SetString(StringRef(cstr)); // ok, assume safe lifetime, null-terminated +s = StringRef(cstr); // shortcut, same as above +s.SetString(StringRef(cstr,cstr_len)); // faster, can contain null character +s = StringRef(cstr,cstr_len); // shortcut, same as above + +~~~~~~~~~ + +## Modify Array {#ModifyArray} +Value with array type provides similar APIs as `std::vector`. + +* `Clear()` +* `Reserve(SizeType, Allocator&)` +* `Value& PushBack(Value&, Allocator&)` +* `template GenericValue& PushBack(T, Allocator&)` +* `Value& PopBack()` +* `ValueIterator Erase(ConstValueIterator pos)` +* `ValueIterator Erase(ConstValueIterator first, ConstValueIterator last)` + +Note that, `Reserve(...)` and `PushBack(...)` may allocate memory for the array elements, therefore require an allocator. + +Here is an example of `PushBack()`: + +~~~~~~~~~~cpp +Value a(kArrayType); +Document::AllocatorType& allocator = document.GetAllocator(); + +for (int i = 5; i <= 10; i++) + a.PushBack(i, allocator); // allocator is needed for potential realloc(). + +// Fluent interface +a.PushBack("Lua", allocator).PushBack("Mio", allocator); +~~~~~~~~~~ + +Differs from STL, `PushBack()`/`PopBack()` returns the array reference itself. This is called _fluent interface_. + +If you want to add a non-constant string or a string without sufficient lifetime (see [Create String](#CreateString)) to the array, you need to create a string Value by using the copy-string API. To avoid the need for an intermediate variable, you can use a [temporary value](#TemporaryValues) in place: + +~~~~~~~~~~cpp +// in-place Value parameter +contact.PushBack(Value("copy", document.GetAllocator()).Move(), // copy string + document.GetAllocator()); + +// explicit parameters +Value val("key", document.GetAllocator()); // copy string +contact.PushBack(val, document.GetAllocator()); +~~~~~~~~~~ + +## Modify Object {#ModifyObject} +Object is a collection of key-value pairs (members). Each key must be a string value. To modify an object, either add or remove members. THe following APIs are for adding members: + +* `Value& AddMember(Value&, Value&, Allocator& allocator)` +* `Value& AddMember(StringRefType, Value&, Allocator&)` +* `template Value& AddMember(StringRefType, T value, Allocator&)` + +Here is an example. + +~~~~~~~~~~cpp +Value contact(kObject); +contact.AddMember("name", "Milo", document.GetAllocator()); +contact.AddMember("married", true, document.GetAllocator()); +~~~~~~~~~~ + +The name parameter with `StringRefType` is similar to the interface of `SetString` function for string values. These overloads are used to avoid the need for copying the `name` string, as constant key names are very common in JSON objects. + +If you need to create a name from a non-constant string or a string without sufficient lifetime (see [Create String](#CreateString)), you need to create a string Value by using the copy-string API. To avoid the need for an intermediate variable, you can use a [temporary value](#TemporaryValues) in place: + +~~~~~~~~~~cpp +// in-place Value parameter +contact.AddMember(Value("copy", document.GetAllocator()).Move(), // copy string + Value().Move(), // null value + document.GetAllocator()); + +// explicit parameters +Value key("key", document.GetAllocator()); // copy string name +Value val(42); // some value +contact.AddMember(key, val, document.GetAllocator()); +~~~~~~~~~~ + +For removing members, there are several choices: + +* `bool RemoveMember(const Ch* name)`: Remove a member by search its name (linear time complexity). +* `bool RemoveMember(const Value& name)`: same as above but `name` is a Value. +* `MemberIterator RemoveMember(MemberIterator)`: Remove a member by iterator (_constant_ time complexity). +* `MemberIterator EraseMember(MemberIterator)`: similar to the above but it preserves order of members (linear time complexity). +* `MemberIterator EraseMember(MemberIterator first, MemberIterator last)`: remove a range of members, preserves order (linear time complexity). + +`MemberIterator RemoveMember(MemberIterator)` uses a "move-last" trick to achieve constant time complexity. Basically the member at iterator is destructed, and then the last element is moved to that position. So the order of the remaining members are changed. + +## Deep Copy Value {#DeepCopyValue} +If we really need to copy a DOM tree, we can use two APIs for deep copy: constructor with allocator, and `CopyFrom()`. + +~~~~~~~~~~cpp +Document d; +Document::AllocatorType& a = d.GetAllocator(); +Value v1("foo"); +// Value v2(v1); // not allowed + +Value v2(v1, a); // make a copy +assert(v1.IsString()); // v1 untouched +d.SetArray().PushBack(v1, a).PushBack(v2, a); +assert(v1.IsNull() && v2.IsNull()); // both moved to d + +v2.CopyFrom(d, a); // copy whole document to v2 +assert(d.IsArray() && d.Size() == 2); // d untouched +v1.SetObject().AddMember("array", v2, a); +d.PushBack(v1, a); +~~~~~~~~~~ + +## Swap Values {#SwapValues} + +`Swap()` is also provided. + +~~~~~~~~~~cpp +Value a(123); +Value b("Hello"); +a.Swap(b); +assert(a.IsString()); +assert(b.IsInt()); +~~~~~~~~~~ + +Swapping two DOM trees is fast (constant time), despite the complexity of the trees. + +# What's next {#WhatsNext} + +This tutorial shows the basics of DOM tree query and manipulation. There are several important concepts in RapidJSON: + +1. [Streams](doc/stream.md) are channels for reading/writing JSON, which can be a in-memory string, or file stream, etc. User can also create their streams. +2. [Encoding](doc/encoding.md) defines which character encoding is used in streams and memory. RapidJSON also provide Unicode conversion/validation internally. +3. [DOM](doc/dom.md)'s basics are already covered in this tutorial. Uncover more advanced features such as *in situ* parsing, other parsing options and advanced usages. +4. [SAX](doc/sax.md) is the foundation of parsing/generating facility in RapidJSON. Learn how to use `Reader`/`Writer` to implement even faster applications. Also try `PrettyWriter` to format the JSON. +5. [Performance](doc/performance.md) shows some in-house and third-party benchmarks. +6. [Internals](doc/internals.md) describes some internal designs and techniques of RapidJSON. + +You may also refer to the [FAQ](doc/faq.md), API documentation, examples and unit tests. diff --git a/thirdparty/rapidjson-1.1.0/doc/tutorial.zh-cn.md b/thirdparty/rapidjson-1.1.0/doc/tutorial.zh-cn.md new file mode 100644 index 0000000000..61fb0b2439 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/doc/tutorial.zh-cn.md @@ -0,0 +1,534 @@ +# 教程 + +本教程简介文件对象模型(Document Object Model, DOM)API。 + +如 [用法一览](../readme.zh-cn.md#用法一览) 中所示,可以解析一个 JSON 至 DOM,然后就可以轻松查询及修改 DOM,并最终转换回 JSON。 + +[TOC] + +# Value 及 Document {#ValueDocument} + +每个 JSON 值都储存为 `Value` 类,而 `Document` 类则表示整个 DOM,它存储了一个 DOM 树的根 `Value`。RapidJSON 的所有公开类型及函数都在 `rapidjson` 命名空间中。 + +# 查询 Value {#QueryValue} + +在本节中,我们会使用到 `example/tutorial/tutorial.cpp` 中的代码片段。 + +假设我们用 C 语言的字符串储存一个 JSON(`const char* json`): +~~~~~~~~~~js +{ + "hello": "world", + "t": true , + "f": false, + "n": null, + "i": 123, + "pi": 3.1416, + "a": [1, 2, 3, 4] +} +~~~~~~~~~~ + +把它解析至一个 `Document`: +~~~~~~~~~~cpp +#include "rapidjson/document.h" + +using namespace rapidjson; + +// ... +Document document; +document.Parse(json); +~~~~~~~~~~ + +那么现在该 JSON 就会被解析至 `document` 中,成为一棵 *DOM 树 *: + +![教程中的 DOM](diagram/tutorial.png) + +自从 RFC 7159 作出更新,合法 JSON 文件的根可以是任何类型的 JSON 值。而在较早的 RFC 4627 中,根值只允许是 Object 或 Array。而在上述例子中,根是一个 Object。 +~~~~~~~~~~cpp +assert(document.IsObject()); +~~~~~~~~~~ + +让我们查询一下根 Object 中有没有 `"hello"` 成员。由于一个 `Value` 可包含不同类型的值,我们可能需要验证它的类型,并使用合适的 API 去获取其值。在此例中,`"hello"` 成员关联到一个 JSON String。 +~~~~~~~~~~cpp +assert(document.HasMember("hello")); +assert(document["hello"].IsString()); +printf("hello = %s\n", document["hello"].GetString()); +~~~~~~~~~~ + +~~~~~~~~~~ +world +~~~~~~~~~~ + +JSON True/False 值是以 `bool` 表示的。 +~~~~~~~~~~cpp +assert(document["t"].IsBool()); +printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); +~~~~~~~~~~ + +~~~~~~~~~~ +true +~~~~~~~~~~ + +JSON Null 值可用 `IsNull()` 查询。 +~~~~~~~~~~cpp +printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); +~~~~~~~~~~ + +~~~~~~~~~~ +null +~~~~~~~~~~ + +JSON Number 类型表示所有数值。然而,C++ 需要使用更专门的类型。 + +~~~~~~~~~~cpp +assert(document["i"].IsNumber()); + +// 在此情况下,IsUint()/IsInt64()/IsUInt64() 也会返回 true +assert(document["i"].IsInt()); +printf("i = %d\n", document["i"].GetInt()); +// 另一种用法: (int)document["i"] + +assert(document["pi"].IsNumber()); +assert(document["pi"].IsDouble()); +printf("pi = %g\n", document["pi"].GetDouble()); +~~~~~~~~~~ + +~~~~~~~~~~ +i = 123 +pi = 3.1416 +~~~~~~~~~~ + +JSON Array 包含一些元素。 +~~~~~~~~~~cpp +// 使用引用来连续访问,方便之余还更高效。 +const Value& a = document["a"]; +assert(a.IsArray()); +for (SizeType i = 0; i < a.Size(); i++) // 使用 SizeType 而不是 size_t + printf("a[%d] = %d\n", i, a[i].GetInt()); +~~~~~~~~~~ + +~~~~~~~~~~ +a[0] = 1 +a[1] = 2 +a[2] = 3 +a[3] = 4 +~~~~~~~~~~ + +注意,RapidJSON 并不自动转换各种 JSON 类型。例如,对一个 String 的 Value 调用 `GetInt()` 是非法的。在调试模式下,它会被断言失败。在发布模式下,其行为是未定义的。 + +以下将会讨论有关查询各类型的细节。 + +## 查询 Array {#QueryArray} + +缺省情况下,`SizeType` 是 `unsigned` 的 typedef。在多数系统中,Array 最多能存储 2^32-1 个元素。 + +你可以用整数字面量访问元素,如 `a[0]`、`a[1]`、`a[2]`。 + +Array 与 `std::vector` 相似,除了使用索引,也可使用迭代器来访问所有元素。 +~~~~~~~~~~cpp +for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) + printf("%d ", itr->GetInt()); +~~~~~~~~~~ + +还有一些熟悉的查询函数: +* `SizeType Capacity() const` +* `bool Empty() const` + +### 范围 for 循环 (v1.1.0 中的新功能) + +当使用 C++11 功能时,你可使用范围 for 循环去访问 Array 内的所有元素。 + +~~~~~~~~~~cpp +for (auto& v : a.GetArray()) + printf("%d ", v.GetInt()); +~~~~~~~~~~ + +## 查询 Object {#QueryObject} + +和 Array 相似,我们可以用迭代器去访问所有 Object 成员: + +~~~~~~~~~~cpp +static const char* kTypeNames[] = + { "Null", "False", "True", "Object", "Array", "String", "Number" }; + +for (Value::ConstMemberIterator itr = document.MemberBegin(); + itr != document.MemberEnd(); ++itr) +{ + printf("Type of member %s is %s\n", + itr->name.GetString(), kTypeNames[itr->value.GetType()]); +} +~~~~~~~~~~ + +~~~~~~~~~~ +Type of member hello is String +Type of member t is True +Type of member f is False +Type of member n is Null +Type of member i is Number +Type of member pi is Number +Type of member a is Array +~~~~~~~~~~ + +注意,当 `operator[](const char*)` 找不到成员,它会断言失败。 + +若我们不确定一个成员是否存在,便需要在调用 `operator[](const char*)` 前先调用 `HasMember()`。然而,这会导致两次查找。更好的做法是调用 `FindMember()`,它能同时检查成员是否存在并返回它的 Value: + +~~~~~~~~~~cpp +Value::ConstMemberIterator itr = document.FindMember("hello"); +if (itr != document.MemberEnd()) + printf("%s\n", itr->value.GetString()); +~~~~~~~~~~ + +### 范围 for 循环 (v1.1.0 中的新功能) + +当使用 C++11 功能时,你可使用范围 for 循环去访问 Object 内的所有成员。 + +~~~~~~~~~~cpp +for (auto& m : document.GetObject()) + printf("Type of member %s is %s\n", + m.name.GetString(), kTypeNames[m.value.GetType()]); +~~~~~~~~~~ + +## 查询 Number {#QueryNumber} + +JSON 只提供一种数值类型──Number。数字可以是整数或实数。RFC 4627 规定数字的范围由解析器指定。 + +由于 C++ 提供多种整数及浮点数类型,DOM 尝试尽量提供最广的范围及良好性能。 + +当解析一个 Number 时, 它会被存储在 DOM 之中,成为下列其中一个类型: + +类型 | 描述 +-----------|--------------------------------------- +`unsigned` | 32 位无号整数 +`int` | 32 位有号整数 +`uint64_t` | 64 位无号整数 +`int64_t` | 64 位有号整数 +`double` | 64 位双精度浮点数 + +当查询一个 Number 时, 你可以检查该数字是否能以目标类型来提取: + +查检 | 提取 +------------------|--------------------- +`bool IsNumber()` | 不适用 +`bool IsUint()` | `unsigned GetUint()` +`bool IsInt()` | `int GetInt()` +`bool IsUint64()` | `uint64_t GetUint64()` +`bool IsInt64()` | `int64_t GetInt64()` +`bool IsDouble()` | `double GetDouble()` + +注意,一个整数可能用几种类型来提取,而无需转换。例如,一个名为 `x` 的 Value 包含 123,那么 `x.IsInt() == x.IsUint() == x.IsInt64() == x.IsUint64() == true`。但如果一个名为 `y` 的 Value 包含 -3000000000,那么仅会令 `x.IsInt64() == true`。 + +当要提取 Number 类型,`GetDouble()` 是会把内部整数的表示转换成 `double`。注意 `int` 和 `unsigned` 可以安全地转换至 `double`,但 `int64_t` 及 `uint64_t` 可能会丧失精度(因为 `double` 的尾数只有 52 位)。 + +## 查询 String {#QueryString} + +除了 `GetString()`,`Value` 类也有一个 `GetStringLength()`。这里会解释个中原因。 + +根据 RFC 4627,JSON String 可包含 Unicode 字符 `U+0000`,在 JSON 中会表示为 `"\u0000"`。问题是,C/C++ 通常使用空字符结尾字符串(null-terminated string),这种字符串把 ``\0'` 作为结束符号。 + +为了符合 RFC 4627,RapidJSON 支持包含 `U+0000` 的 String。若你需要处理这些 String,便可使用 `GetStringLength()` 去获得正确的字符串长度。 + +例如,当解析以下的 JSON 至 `Document d` 之后: + +~~~~~~~~~~js +{ "s" : "a\u0000b" } +~~~~~~~~~~ +`"a\u0000b"` 值的正确长度应该是 3。但 `strlen()` 会返回 1。 + +`GetStringLength()` 也可以提高性能,因为用户可能需要调用 `strlen()` 去分配缓冲。 + +此外,`std::string` 也支持这个构造函数: + +~~~~~~~~~~cpp +string(const char* s, size_t count); +~~~~~~~~~~ + +此构造函数接受字符串长度作为参数。它支持在字符串中存储空字符,也应该会有更好的性能。 + +## 比较两个 Value + +你可使用 `==` 及 `!=` 去比较两个 Value。当且仅当两个 Value 的类型及内容相同,它们才当作相等。你也可以比较 Value 和它的原生类型值。以下是一个例子。 + +~~~~~~~~~~cpp +if (document["hello"] == document["n"]) /*...*/; // 比较两个值 +if (document["hello"] == "world") /*...*/; // 与字符串家面量作比较 +if (document["i"] != 123) /*...*/; // 与整数作比较 +if (document["pi"] != 3.14) /*...*/; // 与 double 作比较 +~~~~~~~~~~ + +Array/Object 顺序以它们的元素/成员作比较。当且仅当它们的整个子树相等,它们才当作相等。 + +注意,现时若一个 Object 含有重复命名的成员,它与任何 Object 作比较都总会返回 `false`。 + +# 创建/修改值 {#CreateModifyValues} + +有多种方法去创建值。 当一个 DOM 树被创建或修改后,可使用 `Writer` 再次存储为 JSON。 + +## 改变 Value 类型 {#ChangeValueType} +当使用默认构造函数创建一个 Value 或 Document,它的类型便会是 Null。要改变其类型,需调用 `SetXXX()` 或赋值操作,例如: + +~~~~~~~~~~cpp +Document d; // Null +d.SetObject(); + +Value v; // Null +v.SetInt(10); +v = 10; // 简写,和上面的相同 +~~~~~~~~~~ + +### 构造函数的各个重载 +几个类型也有重载构造函数: + +~~~~~~~~~~cpp +Value b(true); // 调用 Value(bool) +Value i(-123); // 调用 Value(int) +Value u(123u); // 调用 Value(unsigned) +Value d(1.5); // 调用 Value(double) +~~~~~~~~~~ + +要重建空 Object 或 Array,可在默认构造函数后使用 `SetObject()`/`SetArray()`,或一次性使用 `Value(Type)`: + +~~~~~~~~~~cpp +Value o(kObjectType); +Value a(kArrayType); +~~~~~~~~~~ + +## 转移语意(Move Semantics) {#MoveSemantics} + +在设计 RapidJSON 时有一个非常特别的决定,就是 Value 赋值并不是把来源 Value 复制至目的 Value,而是把把来源 Value 转移(move)至目的 Value。例如: + +~~~~~~~~~~cpp +Value a(123); +Value b(456); +b = a; // a 变成 Null,b 变成数字 123。 +~~~~~~~~~~ + +![使用移动语意赋值。](diagram/move1.png) + +为什么?此语意有何优点? + +最简单的答案就是性能。对于固定大小的 JSON 类型(Number、True、False、Null),复制它们是简单快捷。然而,对于可变大小的 JSON 类型(String、Array、Object),复制它们会产生大量开销,而且这些开销常常不被察觉。尤其是当我们需要创建临时 Object,把它复制至另一变量,然后再析构它。 + +例如,若使用正常 * 复制 * 语意: + +~~~~~~~~~~cpp +Value o(kObjectType); +{ + Value contacts(kArrayType); + // 把元素加进 contacts 数组。 + // ... + o.AddMember("contacts", contacts, d.GetAllocator()); // 深度复制 contacts (可能有大量内存分配) + // 析构 contacts。 +} +~~~~~~~~~~ + +![复制语意产生大量的复制操作。](diagram/move2.png) + +那个 `o` Object 需要分配一个和 contacts 相同大小的缓冲区,对 conacts 做深度复制,并最终要析构 contacts。这样会产生大量无必要的内存分配/释放,以及内存复制。 + +有一些方案可避免实质地复制这些数据,例如引用计数(reference counting)、垃圾回收(garbage collection, GC)。 + +为了使 RapidJSON 简单及快速,我们选择了对赋值采用 * 转移 * 语意。这方法与 `std::auto_ptr` 相似,都是在赋值时转移拥有权。转移快得多简单得多,只需要析构原来的 Value,把来源 `memcpy()` 至目标,最后把来源设置为 Null 类型。 + +因此,使用转移语意后,上面的例子变成: + +~~~~~~~~~~cpp +Value o(kObjectType); +{ + Value contacts(kArrayType); + // adding elements to contacts array. + o.AddMember("contacts", contacts, d.GetAllocator()); // 只需 memcpy() contacts 本身至新成员的 Value(16 字节) + // contacts 在这里变成 Null。它的析构是平凡的。 +} +~~~~~~~~~~ + +![转移语意不需复制。](diagram/move3.png) + +在 C++11 中这称为转移赋值操作(move assignment operator)。由于 RapidJSON 支持 C++03,它在赋值操作采用转移语意,其它修改形函数如 `AddMember()`, `PushBack()` 也采用转移语意。 + +### 转移语意及临时值 {#TemporaryValues} + +有时候,我们想直接构造一个 Value 并传递给一个“转移”函数(如 `PushBack()`、`AddMember()`)。由于临时对象是不能转换为正常的 Value 引用,我们加入了一个方便的 `Move()` 函数: + +~~~~~~~~~~cpp +Value a(kArrayType); +Document::AllocatorType& allocator = document.GetAllocator(); +// a.PushBack(Value(42), allocator); // 不能通过编译 +a.PushBack(Value().SetInt(42), allocator); // fluent API +a.PushBack(Value(42).Move(), allocator); // 和上一行相同 +~~~~~~~~~~ + +## 创建 String {#CreateString} +RapidJSON 提供两个 String 的存储策略。 + +1. copy-string: 分配缓冲区,然后把来源数据复制至它。 +2. const-string: 简单地储存字符串的指针。 + +Copy-string 总是安全的,因为它拥有数据的克隆。Const-string 可用于存储字符串字面量,以及用于在 DOM 一节中将会提到的 in-situ 解析中。 + +为了让用户自定义内存分配方式,当一个操作可能需要内存分配时,RapidJSON 要求用户传递一个 allocator 实例作为 API 参数。此设计避免了在每个 Value 存储 allocator(或 document)的指针。 + +因此,当我们把一个 copy-string 赋值时, 调用含有 allocator 的 `SetString()` 重载函数: + +~~~~~~~~~~cpp +Document document; +Value author; +char buffer[10]; +int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // 动态创建的字符串。 +author.SetString(buffer, len, document.GetAllocator()); +memset(buffer, 0, sizeof(buffer)); +// 清空 buffer 后 author.GetString() 仍然包含 "Milo Yip" +~~~~~~~~~~ + +在此例子中,我们使用 `Document` 实例的 allocator。这是使用 RapidJSON 时常用的惯用法。但你也可以用其他 allocator 实例。 + +另外,上面的 `SetString()` 需要长度参数。这个 API 能处理含有空字符的字符串。另一个 `SetString()` 重载函数没有长度参数,它假设输入是空字符结尾的,并会调用类似 `strlen()` 的函数去获取长度。 + +最后,对于字符串字面量或有安全生命周期的字符串,可以使用 const-string 版本的 `SetString()`,它没有 allocator 参数。对于字符串家面量(或字符数组常量),只需简单地传递字面量,又安全又高效: + +~~~~~~~~~~cpp +Value s; +s.SetString("rapidjson"); // 可包含空字符,长度在编译萁推导 +s = "rapidjson"; // 上行的缩写 +~~~~~~~~~~ + +对于字符指针,RapidJSON 需要作一个标记,代表它不复制也是安全的。可以使用 `StringRef` 函数: + +~~~~~~~~~cpp +const char * cstr = getenv("USER"); +size_t cstr_len = ...; // 如果有长度 +Value s; +// s.SetString(cstr); // 这不能通过编译 +s.SetString(StringRef(cstr)); // 可以,假设它的生命周期安全,并且是以空字符结尾的 +s = StringRef(cstr); // 上行的缩写 +s.SetString(StringRef(cstr, cstr_len));// 更快,可处理空字符 +s = StringRef(cstr, cstr_len); // 上行的缩写 + +~~~~~~~~~ + +## 修改 Array {#ModifyArray} +Array 类型的 Value 提供与 `std::vector` 相似的 API。 + +* `Clear()` +* `Reserve(SizeType, Allocator&)` +* `Value& PushBack(Value&, Allocator&)` +* `template GenericValue& PushBack(T, Allocator&)` +* `Value& PopBack()` +* `ValueIterator Erase(ConstValueIterator pos)` +* `ValueIterator Erase(ConstValueIterator first, ConstValueIterator last)` + +注意,`Reserve(...)` 及 `PushBack(...)` 可能会为数组元素分配内存,所以需要一个 allocator。 + +以下是 `PushBack()` 的例子: + +~~~~~~~~~~cpp +Value a(kArrayType); +Document::AllocatorType& allocator = document.GetAllocator(); + +for (int i = 5; i <= 10; i++) + a.PushBack(i, allocator); // 可能需要调用 realloc() 所以需要 allocator + +// 流畅接口(Fluent interface) +a.PushBack("Lua", allocator).PushBack("Mio", allocator); +~~~~~~~~~~ + +与 STL 不一样的是,`PushBack()`/`PopBack()` 返回 Array 本身的引用。这称为流畅接口(_fluent interface_)。 + +如果你想在 Array 中加入一个非常量字符串,或是一个没有足够生命周期的字符串(见 [Create String](#CreateString)),你需要使用 copy-string API 去创建一个 String。为了避免加入中间变量,可以就地使用一个 [临时值](#TemporaryValues): + +~~~~~~~~~~cpp +// 就地 Value 参数 +contact.PushBack(Value("copy", document.GetAllocator()).Move(), // copy string + document.GetAllocator()); + +// 显式 Value 参数 +Value val("key", document.GetAllocator()); // copy string +contact.PushBack(val, document.GetAllocator()); +~~~~~~~~~~ + +## 修改 Object {#ModifyObject} +Object 是键值对的集合。每个键必须为 String。要修改 Object,方法是增加或移除成员。以下的 API 用来增加城员: + +* `Value& AddMember(Value&, Value&, Allocator& allocator)` +* `Value& AddMember(StringRefType, Value&, Allocator&)` +* `template Value& AddMember(StringRefType, T value, Allocator&)` + +以下是一个例子。 + +~~~~~~~~~~cpp +Value contact(kObject); +contact.AddMember("name", "Milo", document.GetAllocator()); +contact.AddMember("married", true, document.GetAllocator()); +~~~~~~~~~~ + +使用 `StringRefType` 作为 name 参数的重载版本与字符串的 `SetString` 的接口相似。 这些重载是为了避免复制 `name` 字符串,因为 JSON object 中经常会使用常数键名。 + +如果你需要从非常数字符串或生命周期不足的字符串创建键名(见 [创建 String](#CreateString)),你需要使用 copy-string API。为了避免中间变量,可以就地使用 [临时值](#TemporaryValues): + +~~~~~~~~~~cpp +// 就地 Value 参数 +contact.AddMember(Value("copy", document.GetAllocator()).Move(), // copy string + Value().Move(), // null value + document.GetAllocator()); + +// 显式参数 +Value key("key", document.GetAllocator()); // copy string name +Value val(42); // 某 Value +contact.AddMember(key, val, document.GetAllocator()); +~~~~~~~~~~ + +移除成员有几个选择: + +* `bool RemoveMember(const Ch* name)`:使用键名来移除成员(线性时间复杂度)。 +* `bool RemoveMember(const Value& name)`:除了 `name` 是一个 Value,和上一行相同。 +* `MemberIterator RemoveMember(MemberIterator)`:使用迭代器移除成员(_ 常数 _ 时间复杂度)。 +* `MemberIterator EraseMember(MemberIterator)`:和上行相似但维持成员次序(线性时间复杂度)。 +* `MemberIterator EraseMember(MemberIterator first, MemberIterator last)`:移除一个范围内的成员,维持次序(线性时间复杂度)。 + +`MemberIterator RemoveMember(MemberIterator)` 使用了“转移最后”手法来达成常数时间复杂度。基本上就是析构迭代器位置的成员,然后把最后的成员转移至迭代器位置。因此,成员的次序会被改变。 + +## 深复制 Value {#DeepCopyValue} +若我们真的要复制一个 DOM 树,我们可使用两个 APIs 作深复制:含 allocator 的构造函数及 `CopyFrom()`。 + +~~~~~~~~~~cpp +Document d; +Document::AllocatorType& a = d.GetAllocator(); +Value v1("foo"); +// Value v2(v1); // 不容许 + +Value v2(v1, a); // 制造一个克隆 +assert(v1.IsString()); // v1 不变 +d.SetArray().PushBack(v1, a).PushBack(v2, a); +assert(v1.IsNull() && v2.IsNull()); // 两个都转移动 d + +v2.CopyFrom(d, a); // 把整个 document 复制至 v2 +assert(d.IsArray() && d.Size() == 2); // d 不变 +v1.SetObject().AddMember("array", v2, a); +d.PushBack(v1, a); +~~~~~~~~~~ + +## 交换 Value {#SwapValues} + +RapidJSON 也提供 `Swap()`。 + +~~~~~~~~~~cpp +Value a(123); +Value b("Hello"); +a.Swap(b); +assert(a.IsString()); +assert(b.IsInt()); +~~~~~~~~~~ + +无论两棵 DOM 树有多复杂,交换是很快的(常数时间)。 + +# 下一部分 {#WhatsNext} + +本教程展示了如何询查及修改 DOM 树。RapidJSON 还有一个重要概念: + +1. [流](doc/stream.zh-cn.md) 是读写 JSON 的通道。流可以是内存字符串、文件流等。用户也可以自定义流。 +2. [编码](doc/encoding.zh-cn.md) 定义在流或内存中使用的字符编码。RapidJSON 也在内部提供 Unicode 转换及校验功能。 +3. [DOM](doc/dom.zh-cn.md) 的基本功能已在本教程里介绍。还有更高级的功能,如原位(*in situ*)解析、其他解析选项及高级用法。 +4. [SAX](doc/sax.zh-cn.md) 是 RapidJSON 解析/生成功能的基础。学习使用 `Reader`/`Writer` 去实现更高性能的应用程序。也可以使用 `PrettyWriter` 去格式化 JSON。 +5. [性能](doc/performance.zh-cn.md) 展示一些我们做的及第三方的性能测试。 +6. [技术内幕](doc/internals.md) 讲述一些 RapidJSON 内部的设计及技术。 + +你也可以参考 [常见问题](doc/faq.zh-cn.md)、API 文档、例子及单元测试。 diff --git a/thirdparty/rapidjson-1.1.0/docker/debian/Dockerfile b/thirdparty/rapidjson-1.1.0/docker/debian/Dockerfile new file mode 100644 index 0000000000..76f0235e5b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/docker/debian/Dockerfile @@ -0,0 +1,8 @@ +# BUILD: docker build -t rapidjson-debian . +# RUN: docker run -it -v "$PWD"/../..:/rapidjson rapidjson-debian + +FROM debian:jessie + +RUN apt-get update && apt-get install -y g++ cmake doxygen valgrind + +ENTRYPOINT ["/bin/bash"] diff --git a/thirdparty/rapidjson-1.1.0/example/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/example/CMakeLists.txt new file mode 100644 index 0000000000..4d448ccc0f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/CMakeLists.txt @@ -0,0 +1,42 @@ +cmake_minimum_required(VERSION 2.8) + +if(POLICY CMP0054) + cmake_policy(SET CMP0054 NEW) +endif() + +set(EXAMPLES + capitalize + condense + filterkey + filterkeydom + jsonx + messagereader + parsebyparts + pretty + prettyauto + schemavalidator + serialize + simpledom + simplereader + simplewriter + tutorial) + +include_directories("../include/") + +add_definitions(-D__STDC_FORMAT_MACROS) + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread -Werror -Wall -Wextra -Weffc++ -Wswitch-default") +elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wall -Wextra -Weffc++ -Wswitch-default -Wfloat-equal -Wimplicit-fallthrough -Weverything") +endif() + +foreach (example ${EXAMPLES}) + add_executable(${example} ${example}/${example}.cpp) +endforeach() + +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_link_libraries(parsebyparts pthread) +endif() + +add_custom_target(examples ALL DEPENDS ${EXAMPLES}) diff --git a/thirdparty/rapidjson-1.1.0/example/capitalize/capitalize.cpp b/thirdparty/rapidjson-1.1.0/example/capitalize/capitalize.cpp new file mode 100644 index 0000000000..7da37e9c50 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/capitalize/capitalize.cpp @@ -0,0 +1,67 @@ +// JSON condenser example + +// This example parses JSON from stdin with validation, +// and re-output the JSON content to stdout with all string capitalized, and without whitespace. + +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include +#include + +using namespace rapidjson; + +template +struct CapitalizeFilter { + CapitalizeFilter(OutputHandler& out) : out_(out), buffer_() {} + + bool Null() { return out_.Null(); } + bool Bool(bool b) { return out_.Bool(b); } + bool Int(int i) { return out_.Int(i); } + bool Uint(unsigned u) { return out_.Uint(u); } + bool Int64(int64_t i) { return out_.Int64(i); } + bool Uint64(uint64_t u) { return out_.Uint64(u); } + bool Double(double d) { return out_.Double(d); } + bool RawNumber(const char* str, SizeType length, bool copy) { return out_.RawNumber(str, length, copy); } + bool String(const char* str, SizeType length, bool) { + buffer_.clear(); + for (SizeType i = 0; i < length; i++) + buffer_.push_back(static_cast(std::toupper(str[i]))); + return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string + } + bool StartObject() { return out_.StartObject(); } + bool Key(const char* str, SizeType length, bool copy) { return String(str, length, copy); } + bool EndObject(SizeType memberCount) { return out_.EndObject(memberCount); } + bool StartArray() { return out_.StartArray(); } + bool EndArray(SizeType elementCount) { return out_.EndArray(elementCount); } + + OutputHandler& out_; + std::vector buffer_; + +private: + CapitalizeFilter(const CapitalizeFilter&); + CapitalizeFilter& operator=(const CapitalizeFilter&); +}; + +int main(int, char*[]) { + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + CapitalizeFilter > filter(writer); + if (!reader.Parse(is, filter)) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/condense/condense.cpp b/thirdparty/rapidjson-1.1.0/example/condense/condense.cpp new file mode 100644 index 0000000000..46dc350439 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/condense/condense.cpp @@ -0,0 +1,32 @@ +// JSON condenser example + +// This example parses JSON text from stdin with validation, +// and re-output the JSON content to stdout without whitespace. + +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" + +using namespace rapidjson; + +int main(int, char*[]) { + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + if (!reader.Parse(is, writer)) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/filterkey/filterkey.cpp b/thirdparty/rapidjson-1.1.0/example/filterkey/filterkey.cpp new file mode 100644 index 0000000000..c34a050dc8 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/filterkey/filterkey.cpp @@ -0,0 +1,135 @@ +// JSON filterkey example with SAX-style API. + +// This example parses JSON text from stdin with validation. +// During parsing, specified key will be filtered using a SAX handler. +// It re-output the JSON content to stdout without whitespace. + +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include + +using namespace rapidjson; + +// This handler forwards event into an output handler, with filtering the descendent events of specified key. +template +class FilterKeyHandler { +public: + typedef char Ch; + + FilterKeyHandler(OutputHandler& outputHandler, const Ch* keyString, SizeType keyLength) : + outputHandler_(outputHandler), keyString_(keyString), keyLength_(keyLength), filterValueDepth_(), filteredKeyCount_() + {} + + bool Null() { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Null() && EndValue(); } + bool Bool(bool b) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Bool(b) && EndValue(); } + bool Int(int i) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Int(i) && EndValue(); } + bool Uint(unsigned u) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Uint(u) && EndValue(); } + bool Int64(int64_t i) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Int64(i) && EndValue(); } + bool Uint64(uint64_t u) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Uint64(u) && EndValue(); } + bool Double(double d) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Double(d) && EndValue(); } + bool RawNumber(const Ch* str, SizeType len, bool copy) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.RawNumber(str, len, copy) && EndValue(); } + bool String (const Ch* str, SizeType len, bool copy) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.String (str, len, copy) && EndValue(); } + + bool StartObject() { + if (filterValueDepth_ > 0) { + filterValueDepth_++; + return true; + } + else { + filteredKeyCount_.push(0); + return outputHandler_.StartObject(); + } + } + + bool Key(const Ch* str, SizeType len, bool copy) { + if (filterValueDepth_ > 0) + return true; + else if (len == keyLength_ && std::memcmp(str, keyString_, len) == 0) { + filterValueDepth_ = 1; + return true; + } + else { + ++filteredKeyCount_.top(); + return outputHandler_.Key(str, len, copy); + } + } + + bool EndObject(SizeType) { + if (filterValueDepth_ > 0) { + filterValueDepth_--; + return EndValue(); + } + else { + // Use our own filtered memberCount + SizeType memberCount = filteredKeyCount_.top(); + filteredKeyCount_.pop(); + return outputHandler_.EndObject(memberCount) && EndValue(); + } + } + + bool StartArray() { + if (filterValueDepth_ > 0) { + filterValueDepth_++; + return true; + } + else + return outputHandler_.StartArray(); + } + + bool EndArray(SizeType elementCount) { + if (filterValueDepth_ > 0) { + filterValueDepth_--; + return EndValue(); + } + else + return outputHandler_.EndArray(elementCount) && EndValue(); + } + +private: + FilterKeyHandler(const FilterKeyHandler&); + FilterKeyHandler& operator=(const FilterKeyHandler&); + + bool EndValue() { + if (filterValueDepth_ == 1) // Just at the end of value after filtered key + filterValueDepth_ = 0; + return true; + } + + OutputHandler& outputHandler_; + const char* keyString_; + const SizeType keyLength_; + unsigned filterValueDepth_; + std::stack filteredKeyCount_; +}; + +int main(int argc, char* argv[]) { + if (argc != 2) { + fprintf(stderr, "filterkey key < input.json > output.json\n"); + return 1; + } + + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // Prepare Filter + FilterKeyHandler > filter(writer, argv[1], static_cast(strlen(argv[1]))); + + // JSON reader parse from the input stream, filter handler filters the events, and forward to writer. + // i.e. the events flow is: reader -> filter -> writer + if (!reader.Parse(is, filter)) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/filterkeydom/filterkeydom.cpp b/thirdparty/rapidjson-1.1.0/example/filterkeydom/filterkeydom.cpp new file mode 100644 index 0000000000..732cc81f13 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/filterkeydom/filterkeydom.cpp @@ -0,0 +1,170 @@ +// JSON filterkey example which populates filtered SAX events into a Document. + +// This example parses JSON text from stdin with validation. +// During parsing, specified key will be filtered using a SAX handler. +// And finally the filtered events are used to populate a Document. +// As an example, the document is written to standard output. + +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include + +using namespace rapidjson; + +// This handler forwards event into an output handler, with filtering the descendent events of specified key. +template +class FilterKeyHandler { +public: + typedef char Ch; + + FilterKeyHandler(OutputHandler& outputHandler, const Ch* keyString, SizeType keyLength) : + outputHandler_(outputHandler), keyString_(keyString), keyLength_(keyLength), filterValueDepth_(), filteredKeyCount_() + {} + + bool Null() { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Null() && EndValue(); } + bool Bool(bool b) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Bool(b) && EndValue(); } + bool Int(int i) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Int(i) && EndValue(); } + bool Uint(unsigned u) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Uint(u) && EndValue(); } + bool Int64(int64_t i) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Int64(i) && EndValue(); } + bool Uint64(uint64_t u) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Uint64(u) && EndValue(); } + bool Double(double d) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.Double(d) && EndValue(); } + bool RawNumber(const Ch* str, SizeType len, bool copy) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.RawNumber(str, len, copy) && EndValue(); } + bool String (const Ch* str, SizeType len, bool copy) { return filterValueDepth_ > 0 ? EndValue() : outputHandler_.String (str, len, copy) && EndValue(); } + + bool StartObject() { + if (filterValueDepth_ > 0) { + filterValueDepth_++; + return true; + } + else { + filteredKeyCount_.push(0); + return outputHandler_.StartObject(); + } + } + + bool Key(const Ch* str, SizeType len, bool copy) { + if (filterValueDepth_ > 0) + return true; + else if (len == keyLength_ && std::memcmp(str, keyString_, len) == 0) { + filterValueDepth_ = 1; + return true; + } + else { + ++filteredKeyCount_.top(); + return outputHandler_.Key(str, len, copy); + } + } + + bool EndObject(SizeType) { + if (filterValueDepth_ > 0) { + filterValueDepth_--; + return EndValue(); + } + else { + // Use our own filtered memberCount + SizeType memberCount = filteredKeyCount_.top(); + filteredKeyCount_.pop(); + return outputHandler_.EndObject(memberCount) && EndValue(); + } + } + + bool StartArray() { + if (filterValueDepth_ > 0) { + filterValueDepth_++; + return true; + } + else + return outputHandler_.StartArray(); + } + + bool EndArray(SizeType elementCount) { + if (filterValueDepth_ > 0) { + filterValueDepth_--; + return EndValue(); + } + else + return outputHandler_.EndArray(elementCount) && EndValue(); + } + +private: + FilterKeyHandler(const FilterKeyHandler&); + FilterKeyHandler& operator=(const FilterKeyHandler&); + + bool EndValue() { + if (filterValueDepth_ == 1) // Just at the end of value after filtered key + filterValueDepth_ = 0; + return true; + } + + OutputHandler& outputHandler_; + const char* keyString_; + const SizeType keyLength_; + unsigned filterValueDepth_; + std::stack filteredKeyCount_; +}; + +// Implements a generator for Document::Populate() +template +class FilterKeyReader { +public: + typedef char Ch; + + FilterKeyReader(InputStream& is, const Ch* keyString, SizeType keyLength) : + is_(is), keyString_(keyString), keyLength_(keyLength), parseResult_() + {} + + // SAX event flow: reader -> filter -> handler + template + bool operator()(Handler& handler) { + FilterKeyHandler filter(handler, keyString_, keyLength_); + Reader reader; + parseResult_ = reader.Parse(is_, filter); + return parseResult_; + } + + const ParseResult& GetParseResult() const { return parseResult_; } + +private: + FilterKeyReader(const FilterKeyReader&); + FilterKeyReader& operator=(const FilterKeyReader&); + + InputStream& is_; + const char* keyString_; + const SizeType keyLength_; + ParseResult parseResult_; +}; + +int main(int argc, char* argv[]) { + if (argc != 2) { + fprintf(stderr, "filterkeydom key < input.json > output.json\n"); + return 1; + } + + // Prepare input stream. + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare Filter + FilterKeyReader reader(is, argv[1], static_cast(strlen(argv[1]))); + + // Populates the filtered events from reader + Document document; + document.Populate(reader); + ParseResult pr = reader.GetParseResult(); + if (!pr) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(pr.Offset()), GetParseError_En(pr.Code())); + return 1; + } + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + Writer writer(os); + + // Write the document to standard output + document.Accept(writer); + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/jsonx/jsonx.cpp b/thirdparty/rapidjson-1.1.0/example/jsonx/jsonx.cpp new file mode 100644 index 0000000000..1346b578c3 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/jsonx/jsonx.cpp @@ -0,0 +1,207 @@ +// JSON to JSONx conversion exmaple, using SAX API. +// JSONx is an IBM standard format to represent JSON as XML. +// https://www-01.ibm.com/support/knowledgecenter/SS9H2Y_7.1.0/com.ibm.dp.doc/json_jsonx.html +// This example parses JSON text from stdin with validation, +// and convert to JSONx format to stdout. +// Need compile with -D__STDC_FORMAT_MACROS for defining PRId64 and PRIu64 macros. + +#include "rapidjson/reader.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" +#include + +using namespace rapidjson; + +// For simplicity, this example only read/write in UTF-8 encoding +template +class JsonxWriter { +public: + JsonxWriter(OutputStream& os) : os_(os), name_(), level_(0), hasName_(false) { + } + + bool Null() { + return WriteStartElement("null", true); + } + + bool Bool(bool b) { + return + WriteStartElement("boolean") && + WriteString(b ? "true" : "false") && + WriteEndElement("boolean"); + } + + bool Int(int i) { + char buffer[12]; + return WriteNumberElement(buffer, sprintf(buffer, "%d", i)); + } + + bool Uint(unsigned i) { + char buffer[11]; + return WriteNumberElement(buffer, sprintf(buffer, "%u", i)); + } + + bool Int64(int64_t i) { + char buffer[21]; + return WriteNumberElement(buffer, sprintf(buffer, "%" PRId64, i)); + } + + bool Uint64(uint64_t i) { + char buffer[21]; + return WriteNumberElement(buffer, sprintf(buffer, "%" PRIu64, i)); + } + + bool Double(double d) { + char buffer[30]; + return WriteNumberElement(buffer, sprintf(buffer, "%.17g", d)); + } + + bool RawNumber(const char* str, SizeType length, bool) { + return + WriteStartElement("number") && + WriteEscapedText(str, length) && + WriteEndElement("number"); + } + + bool String(const char* str, SizeType length, bool) { + return + WriteStartElement("string") && + WriteEscapedText(str, length) && + WriteEndElement("string"); + } + + bool StartObject() { + return WriteStartElement("object"); + } + + bool Key(const char* str, SizeType length, bool) { + // backup key to name_ + name_.Clear(); + for (SizeType i = 0; i < length; i++) + name_.Put(str[i]); + hasName_ = true; + return true; + } + + bool EndObject(SizeType) { + return WriteEndElement("object"); + } + + bool StartArray() { + return WriteStartElement("array"); + } + + bool EndArray(SizeType) { + return WriteEndElement("array"); + } + +private: + bool WriteString(const char* s) { + while (*s) + os_.Put(*s++); + return true; + } + + bool WriteEscapedAttributeValue(const char* s, size_t length) { + for (size_t i = 0; i < length; i++) { + switch (s[i]) { + case '&': WriteString("&"); break; + case '<': WriteString("<"); break; + case '"': WriteString("""); break; + default: os_.Put(s[i]); break; + } + } + return true; + } + + bool WriteEscapedText(const char* s, size_t length) { + for (size_t i = 0; i < length; i++) { + switch (s[i]) { + case '&': WriteString("&"); break; + case '<': WriteString("<"); break; + default: os_.Put(s[i]); break; + } + } + return true; + } + + bool WriteStartElement(const char* type, bool emptyElement = false) { + if (level_ == 0) + if (!WriteString("")) + return false; + + if (!WriteString(""); + else { + level_++; + return WriteString(">"); + } + } + + bool WriteEndElement(const char* type) { + if (!WriteString("")) + return false; + + // For the last end tag, flush the output stream. + if (--level_ == 0) + os_.Flush(); + + return true; + } + + bool WriteNumberElement(const char* buffer, int length) { + if (!WriteStartElement("number")) + return false; + for (int j = 0; j < length; j++) + os_.Put(buffer[j]); + return WriteEndElement("number"); + } + + OutputStream& os_; + StringBuffer name_; + unsigned level_; + bool hasName_; +}; + +int main(int, char*[]) { + // Prepare JSON reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare JSON writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + JsonxWriter writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + if (!reader.Parse(is, writer)) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/messagereader/messagereader.cpp b/thirdparty/rapidjson-1.1.0/example/messagereader/messagereader.cpp new file mode 100644 index 0000000000..3399bc9400 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/messagereader/messagereader.cpp @@ -0,0 +1,105 @@ +// Reading a message JSON with Reader (SAX-style API). +// The JSON should be an object with key-string pairs. + +#include "rapidjson/reader.h" +#include "rapidjson/error/en.h" +#include +#include +#include + +using namespace std; +using namespace rapidjson; + +typedef map MessageMap; + +#if defined(__GNUC__) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(switch-enum) +#endif + +struct MessageHandler + : public BaseReaderHandler, MessageHandler> { + MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {} + + bool StartObject() { + switch (state_) { + case kExpectObjectStart: + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool String(const char* str, SizeType length, bool) { + switch (state_) { + case kExpectNameOrObjectEnd: + name_ = string(str, length); + state_ = kExpectValue; + return true; + case kExpectValue: + messages_.insert(MessageMap::value_type(name_, string(str, length))); + state_ = kExpectNameOrObjectEnd; + return true; + default: + return false; + } + } + + bool EndObject(SizeType) { return state_ == kExpectNameOrObjectEnd; } + + bool Default() { return false; } // All other events are invalid. + + MessageMap messages_; + enum State { + kExpectObjectStart, + kExpectNameOrObjectEnd, + kExpectValue + }state_; + std::string name_; +}; + +#if defined(__GNUC__) +RAPIDJSON_DIAG_POP +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +static void ParseMessages(const char* json, MessageMap& messages) { + Reader reader; + MessageHandler handler; + StringStream ss(json); + if (reader.Parse(ss, handler)) + messages.swap(handler.messages_); // Only change it if success. + else { + ParseErrorCode e = reader.GetParseErrorCode(); + size_t o = reader.GetErrorOffset(); + cout << "Error: " << GetParseError_En(e) << endl;; + cout << " at offset " << o << " near '" << string(json).substr(o, 10) << "...'" << endl; + } +} + +int main() { + MessageMap messages; + + const char* json1 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\" }"; + cout << json1 << endl; + ParseMessages(json1, messages); + + for (MessageMap::const_iterator itr = messages.begin(); itr != messages.end(); ++itr) + cout << itr->first << ": " << itr->second << endl; + + cout << endl << "Parse a JSON with invalid schema." << endl; + const char* json2 = "{ \"greeting\" : \"Hello!\", \"farewell\" : \"bye-bye!\", \"foo\" : {} }"; + cout << json2 << endl; + ParseMessages(json2, messages); + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/parsebyparts/parsebyparts.cpp b/thirdparty/rapidjson-1.1.0/example/parsebyparts/parsebyparts.cpp new file mode 100644 index 0000000000..57eed005de --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/parsebyparts/parsebyparts.cpp @@ -0,0 +1,173 @@ +// Example of parsing JSON to document by parts. + +// Using C++11 threads +// Temporarily disable for clang (older version) due to incompatibility with libstdc++ +#if (__cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1700)) && !defined(__clang__) + +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" +#include "rapidjson/writer.h" +#include "rapidjson/ostreamwrapper.h" +#include +#include +#include +#include + +using namespace rapidjson; + +template +class AsyncDocumentParser { +public: + AsyncDocumentParser(Document& d) + : stream_(*this) + , d_(d) + , parseThread_(&AsyncDocumentParser::Parse, this) + , mutex_() + , notEmpty_() + , finish_() + , completed_() + {} + + ~AsyncDocumentParser() { + if (!parseThread_.joinable()) + return; + + { + std::unique_lock lock(mutex_); + + // Wait until the buffer is read up (or parsing is completed) + while (!stream_.Empty() && !completed_) + finish_.wait(lock); + + // Automatically append '\0' as the terminator in the stream. + static const char terminator[] = ""; + stream_.src_ = terminator; + stream_.end_ = terminator + 1; + notEmpty_.notify_one(); // unblock the AsyncStringStream + } + + parseThread_.join(); + } + + void ParsePart(const char* buffer, size_t length) { + std::unique_lock lock(mutex_); + + // Wait until the buffer is read up (or parsing is completed) + while (!stream_.Empty() && !completed_) + finish_.wait(lock); + + // Stop further parsing if the parsing process is completed. + if (completed_) + return; + + // Set the buffer to stream and unblock the AsyncStringStream + stream_.src_ = buffer; + stream_.end_ = buffer + length; + notEmpty_.notify_one(); + } + +private: + void Parse() { + d_.ParseStream(stream_); + + // The stream may not be fully read, notify finish anyway to unblock ParsePart() + std::unique_lock lock(mutex_); + completed_ = true; // Parsing process is completed + finish_.notify_one(); // Unblock ParsePart() or destructor if they are waiting. + } + + struct AsyncStringStream { + typedef char Ch; + + AsyncStringStream(AsyncDocumentParser& parser) : parser_(parser), src_(), end_(), count_() {} + + char Peek() const { + std::unique_lock lock(parser_.mutex_); + + // If nothing in stream, block to wait. + while (Empty()) + parser_.notEmpty_.wait(lock); + + return *src_; + } + + char Take() { + std::unique_lock lock(parser_.mutex_); + + // If nothing in stream, block to wait. + while (Empty()) + parser_.notEmpty_.wait(lock); + + count_++; + char c = *src_++; + + // If all stream is read up, notify that the stream is finish. + if (Empty()) + parser_.finish_.notify_one(); + + return c; + } + + size_t Tell() const { return count_; } + + // Not implemented + char* PutBegin() { return 0; } + void Put(char) {} + void Flush() {} + size_t PutEnd(char*) { return 0; } + + bool Empty() const { return src_ == end_; } + + AsyncDocumentParser& parser_; + const char* src_; //!< Current read position. + const char* end_; //!< End of buffer + size_t count_; //!< Number of characters taken so far. + }; + + AsyncStringStream stream_; + Document& d_; + std::thread parseThread_; + std::mutex mutex_; + std::condition_variable notEmpty_; + std::condition_variable finish_; + bool completed_; +}; + +int main() { + Document d; + + { + AsyncDocumentParser<> parser(d); + + const char json1[] = " { \"hello\" : \"world\", \"t\" : tr"; + //const char json1[] = " { \"hello\" : \"world\", \"t\" : trX"; // Fot test parsing error + const char json2[] = "ue, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.14"; + const char json3[] = "16, \"a\":[1, 2, 3, 4] } "; + + parser.ParsePart(json1, sizeof(json1) - 1); + parser.ParsePart(json2, sizeof(json2) - 1); + parser.ParsePart(json3, sizeof(json3) - 1); + } + + if (d.HasParseError()) { + std::cout << "Error at offset " << d.GetErrorOffset() << ": " << GetParseError_En(d.GetParseError()) << std::endl; + return EXIT_FAILURE; + } + + // Stringify the JSON to cout + OStreamWrapper os(std::cout); + Writer writer(os); + d.Accept(writer); + std::cout << std::endl; + + return EXIT_SUCCESS; +} + +#else // Not supporting C++11 + +#include +int main() { + std::cout << "This example requires C++11 compiler" << std::endl; +} + +#endif diff --git a/thirdparty/rapidjson-1.1.0/example/pretty/pretty.cpp b/thirdparty/rapidjson-1.1.0/example/pretty/pretty.cpp new file mode 100644 index 0000000000..2feff5d02e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/pretty/pretty.cpp @@ -0,0 +1,30 @@ +// JSON pretty formatting example +// This example can only handle UTF-8. For handling other encodings, see prettyauto example. + +#include "rapidjson/reader.h" +#include "rapidjson/prettywriter.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/error/en.h" + +using namespace rapidjson; + +int main(int, char*[]) { + // Prepare reader and input stream. + Reader reader; + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + + // Prepare writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + PrettyWriter writer(os); + + // JSON reader parse from the input stream and let writer generate the output. + if (!reader.Parse(is, writer)) { + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/prettyauto/prettyauto.cpp b/thirdparty/rapidjson-1.1.0/example/prettyauto/prettyauto.cpp new file mode 100644 index 0000000000..1687bae555 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/prettyauto/prettyauto.cpp @@ -0,0 +1,56 @@ +// JSON pretty formatting example +// This example can handle UTF-8/UTF-16LE/UTF-16BE/UTF-32LE/UTF-32BE. +// The input firstly convert to UTF8, and then write to the original encoding with pretty formatting. + +#include "rapidjson/reader.h" +#include "rapidjson/prettywriter.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/encodedstream.h" // NEW +#include "rapidjson/error/en.h" +#ifdef _WIN32 +#include +#include +#endif + +using namespace rapidjson; + +int main(int, char*[]) { +#ifdef _WIN32 + // Prevent Windows converting between CR+LF and LF + _setmode(_fileno(stdin), _O_BINARY); // NEW + _setmode(_fileno(stdout), _O_BINARY); // NEW +#endif + + // Prepare reader and input stream. + //Reader reader; + GenericReader, UTF8<> > reader; // CHANGED + char readBuffer[65536]; + FileReadStream is(stdin, readBuffer, sizeof(readBuffer)); + AutoUTFInputStream eis(is); // NEW + + // Prepare writer and output stream. + char writeBuffer[65536]; + FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer)); + +#if 1 + // Use the same Encoding of the input. Also use BOM according to input. + typedef AutoUTFOutputStream OutputStream; // NEW + OutputStream eos(os, eis.GetType(), eis.HasBOM()); // NEW + PrettyWriter, AutoUTF > writer(eos); // CHANGED +#else + // You may also use static bound encoding type, such as output to UTF-16LE with BOM + typedef EncodedOutputStream,FileWriteStream> OutputStream; // NEW + OutputStream eos(os, true); // NEW + PrettyWriter, UTF16LE<> > writer(eos); // CHANGED +#endif + + // JSON reader parse from the input stream and let writer generate the output. + //if (!reader.Parse(is, writer)) { + if (!reader.Parse(eis, writer)) { // CHANGED + fprintf(stderr, "\nError(%u): %s\n", static_cast(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode())); + return 1; + } + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/schemavalidator/schemavalidator.cpp b/thirdparty/rapidjson-1.1.0/example/schemavalidator/schemavalidator.cpp new file mode 100644 index 0000000000..ce36ea95f0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/schemavalidator/schemavalidator.cpp @@ -0,0 +1,72 @@ +// Schema Validator example + +// The example validates JSON text from stdin with a JSON schema specified in the argument. + +#include "rapidjson/error/en.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/schema.h" +#include "rapidjson/stringbuffer.h" + +using namespace rapidjson; + +int main(int argc, char *argv[]) { + if (argc != 2) { + fprintf(stderr, "Usage: schemavalidator schema.json < input.json\n"); + return EXIT_FAILURE; + } + + // Read a JSON schema from file into Document + Document d; + char buffer[4096]; + + { + FILE *fp = fopen(argv[1], "r"); + if (!fp) { + printf("Schema file '%s' not found\n", argv[1]); + return -1; + } + FileReadStream fs(fp, buffer, sizeof(buffer)); + d.ParseStream(fs); + if (d.HasParseError()) { + fprintf(stderr, "Schema file '%s' is not a valid JSON\n", argv[1]); + fprintf(stderr, "Error(offset %u): %s\n", + static_cast(d.GetErrorOffset()), + GetParseError_En(d.GetParseError())); + fclose(fp); + return EXIT_FAILURE; + } + fclose(fp); + } + + // Then convert the Document into SchemaDocument + SchemaDocument sd(d); + + // Use reader to parse the JSON in stdin, and forward SAX events to validator + SchemaValidator validator(sd); + Reader reader; + FileReadStream is(stdin, buffer, sizeof(buffer)); + if (!reader.Parse(is, validator) && reader.GetParseErrorCode() != kParseErrorTermination) { + // Schema validator error would cause kParseErrorTermination, which will handle it in next step. + fprintf(stderr, "Input is not a valid JSON\n"); + fprintf(stderr, "Error(offset %u): %s\n", + static_cast(reader.GetErrorOffset()), + GetParseError_En(reader.GetParseErrorCode())); + } + + // Check the validation result + if (validator.IsValid()) { + printf("Input JSON is valid.\n"); + return EXIT_SUCCESS; + } + else { + printf("Input JSON is invalid.\n"); + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + fprintf(stderr, "Invalid schema: %s\n", sb.GetString()); + fprintf(stderr, "Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + fprintf(stderr, "Invalid document: %s\n", sb.GetString()); + return EXIT_FAILURE; + } +} diff --git a/thirdparty/rapidjson-1.1.0/example/serialize/serialize.cpp b/thirdparty/rapidjson-1.1.0/example/serialize/serialize.cpp new file mode 100644 index 0000000000..12d87151e6 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/serialize/serialize.cpp @@ -0,0 +1,173 @@ +// Serialize example +// This example shows writing JSON string with writer directly. + +#include "rapidjson/prettywriter.h" // for stringify JSON +#include +#include +#include + +using namespace rapidjson; + +class Person { +public: + Person(const std::string& name, unsigned age) : name_(name), age_(age) {} + Person(const Person& rhs) : name_(rhs.name_), age_(rhs.age_) {} + virtual ~Person(); + + Person& operator=(const Person& rhs) { + name_ = rhs.name_; + age_ = rhs.age_; + return *this; + } + +protected: + template + void Serialize(Writer& writer) const { + // This base class just write out name-value pairs, without wrapping within an object. + writer.String("name"); +#if RAPIDJSON_HAS_STDSTRING + writer.String(name_); +#else + writer.String(name_.c_str(), static_cast(name_.length())); // Supplying length of string is faster. +#endif + writer.String("age"); + writer.Uint(age_); + } + +private: + std::string name_; + unsigned age_; +}; + +Person::~Person() { +} + +class Education { +public: + Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {} + Education(const Education& rhs) : school_(rhs.school_), GPA_(rhs.GPA_) {} + + template + void Serialize(Writer& writer) const { + writer.StartObject(); + + writer.String("school"); +#if RAPIDJSON_HAS_STDSTRING + writer.String(school_); +#else + writer.String(school_.c_str(), static_cast(school_.length())); +#endif + + writer.String("GPA"); + writer.Double(GPA_); + + writer.EndObject(); + } + +private: + std::string school_; + double GPA_; +}; + +class Dependent : public Person { +public: + Dependent(const std::string& name, unsigned age, Education* education = 0) : Person(name, age), education_(education) {} + Dependent(const Dependent& rhs) : Person(rhs), education_(0) { education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); } + virtual ~Dependent(); + + Dependent& operator=(const Dependent& rhs) { + if (this == &rhs) + return *this; + delete education_; + education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); + return *this; + } + + template + void Serialize(Writer& writer) const { + writer.StartObject(); + + Person::Serialize(writer); + + writer.String("education"); + if (education_) + education_->Serialize(writer); + else + writer.Null(); + + writer.EndObject(); + } + +private: + + Education *education_; +}; + +Dependent::~Dependent() { + delete education_; +} + +class Employee : public Person { +public: + Employee(const std::string& name, unsigned age, bool married) : Person(name, age), dependents_(), married_(married) {} + Employee(const Employee& rhs) : Person(rhs), dependents_(rhs.dependents_), married_(rhs.married_) {} + virtual ~Employee(); + + Employee& operator=(const Employee& rhs) { + static_cast(*this) = rhs; + dependents_ = rhs.dependents_; + married_ = rhs.married_; + return *this; + } + + void AddDependent(const Dependent& dependent) { + dependents_.push_back(dependent); + } + + template + void Serialize(Writer& writer) const { + writer.StartObject(); + + Person::Serialize(writer); + + writer.String("married"); + writer.Bool(married_); + + writer.String(("dependents")); + writer.StartArray(); + for (std::vector::const_iterator dependentItr = dependents_.begin(); dependentItr != dependents_.end(); ++dependentItr) + dependentItr->Serialize(writer); + writer.EndArray(); + + writer.EndObject(); + } + +private: + std::vector dependents_; + bool married_; +}; + +Employee::~Employee() { +} + +int main(int, char*[]) { + std::vector employees; + + employees.push_back(Employee("Milo YIP", 34, true)); + employees.back().AddDependent(Dependent("Lua YIP", 3, new Education("Happy Kindergarten", 3.5))); + employees.back().AddDependent(Dependent("Mio YIP", 1)); + + employees.push_back(Employee("Percy TSE", 30, false)); + + StringBuffer sb; + PrettyWriter writer(sb); + + writer.StartArray(); + for (std::vector::const_iterator employeeItr = employees.begin(); employeeItr != employees.end(); ++employeeItr) + employeeItr->Serialize(writer); + writer.EndArray(); + + puts(sb.GetString()); + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/simpledom/simpledom.cpp b/thirdparty/rapidjson-1.1.0/example/simpledom/simpledom.cpp new file mode 100644 index 0000000000..80384199a9 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/simpledom/simpledom.cpp @@ -0,0 +1,29 @@ +// JSON simple example +// This example does not handle errors. + +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; + +int main() { + // 1. Parse a JSON string into DOM. + const char* json = "{\"project\":\"rapidjson\",\"stars\":10}"; + Document d; + d.Parse(json); + + // 2. Modify it by DOM. + Value& s = d["stars"]; + s.SetInt(s.GetInt() + 1); + + // 3. Stringify the DOM + StringBuffer buffer; + Writer writer(buffer); + d.Accept(writer); + + // Output {"project":"rapidjson","stars":11} + std::cout << buffer.GetString() << std::endl; + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/simplereader/simplereader.cpp b/thirdparty/rapidjson-1.1.0/example/simplereader/simplereader.cpp new file mode 100644 index 0000000000..5aae8a1c0a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/simplereader/simplereader.cpp @@ -0,0 +1,42 @@ +#include "rapidjson/reader.h" +#include + +using namespace rapidjson; +using namespace std; + +struct MyHandler { + bool Null() { cout << "Null()" << endl; return true; } + bool Bool(bool b) { cout << "Bool(" << boolalpha << b << ")" << endl; return true; } + bool Int(int i) { cout << "Int(" << i << ")" << endl; return true; } + bool Uint(unsigned u) { cout << "Uint(" << u << ")" << endl; return true; } + bool Int64(int64_t i) { cout << "Int64(" << i << ")" << endl; return true; } + bool Uint64(uint64_t u) { cout << "Uint64(" << u << ")" << endl; return true; } + bool Double(double d) { cout << "Double(" << d << ")" << endl; return true; } + bool RawNumber(const char* str, SizeType length, bool copy) { + cout << "Number(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool String(const char* str, SizeType length, bool copy) { + cout << "String(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool StartObject() { cout << "StartObject()" << endl; return true; } + bool Key(const char* str, SizeType length, bool copy) { + cout << "Key(" << str << ", " << length << ", " << boolalpha << copy << ")" << endl; + return true; + } + bool EndObject(SizeType memberCount) { cout << "EndObject(" << memberCount << ")" << endl; return true; } + bool StartArray() { cout << "StartArray()" << endl; return true; } + bool EndArray(SizeType elementCount) { cout << "EndArray(" << elementCount << ")" << endl; return true; } +}; + +int main() { + const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + + MyHandler handler; + Reader reader; + StringStream ss(json); + reader.Parse(ss, handler); + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/simplewriter/simplewriter.cpp b/thirdparty/rapidjson-1.1.0/example/simplewriter/simplewriter.cpp new file mode 100644 index 0000000000..8d1275c292 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/simplewriter/simplewriter.cpp @@ -0,0 +1,36 @@ +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; +using namespace std; + +int main() { + StringBuffer s; + Writer writer(s); + + writer.StartObject(); // Between StartObject()/EndObject(), + writer.Key("hello"); // output a key, + writer.String("world"); // follow by a value. + writer.Key("t"); + writer.Bool(true); + writer.Key("f"); + writer.Bool(false); + writer.Key("n"); + writer.Null(); + writer.Key("i"); + writer.Uint(123); + writer.Key("pi"); + writer.Double(3.1416); + writer.Key("a"); + writer.StartArray(); // Between StartArray()/EndArray(), + for (unsigned i = 0; i < 4; i++) + writer.Uint(i); // all values are elements of the array. + writer.EndArray(); + writer.EndObject(); + + // {"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]} + cout << s.GetString() << endl; + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/example/tutorial/tutorial.cpp b/thirdparty/rapidjson-1.1.0/example/tutorial/tutorial.cpp new file mode 100644 index 0000000000..c8bfcc14c1 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/example/tutorial/tutorial.cpp @@ -0,0 +1,151 @@ +// Hello World example +// This example shows basic usage of DOM-style API. + +#include "rapidjson/document.h" // rapidjson's DOM-style API +#include "rapidjson/prettywriter.h" // for stringify JSON +#include + +using namespace rapidjson; +using namespace std; + +int main(int, char*[]) { + //////////////////////////////////////////////////////////////////////////// + // 1. Parse a JSON text string to a document. + + const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + printf("Original JSON:\n %s\n", json); + + Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. + +#if 0 + // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream(). + if (document.Parse(json).HasParseError()) + return 1; +#else + // In-situ parsing, decode strings directly in the source string. Source must be string. + char buffer[sizeof(json)]; + memcpy(buffer, json, sizeof(json)); + if (document.ParseInsitu(buffer).HasParseError()) + return 1; +#endif + + printf("\nParsing to document succeeded.\n"); + + //////////////////////////////////////////////////////////////////////////// + // 2. Access values in document. + + printf("\nAccess values in document:\n"); + assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. + + assert(document.HasMember("hello")); + assert(document["hello"].IsString()); + printf("hello = %s\n", document["hello"].GetString()); + + // Since version 0.2, you can use single lookup to check the existing of member and its value: + Value::MemberIterator hello = document.FindMember("hello"); + assert(hello != document.MemberEnd()); + assert(hello->value.IsString()); + assert(strcmp("world", hello->value.GetString()) == 0); + (void)hello; + + assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue(). + printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); + + assert(document["f"].IsBool()); + printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); + + printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); + + assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type. + assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true. + printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] + + assert(document["pi"].IsNumber()); + assert(document["pi"].IsDouble()); + printf("pi = %g\n", document["pi"].GetDouble()); + + { + const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster. + assert(a.IsArray()); + for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t. + printf("a[%d] = %d\n", i, a[i].GetInt()); + + int y = a[0].GetInt(); + (void)y; + + // Iterating array with iterators + printf("a = "); + for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) + printf("%d ", itr->GetInt()); + printf("\n"); + } + + // Iterating object members + static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; + for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) + printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); + + //////////////////////////////////////////////////////////////////////////// + // 3. Modify values in document. + + // Change i to a bigger number + { + uint64_t f20 = 1; // compute factorial of 20 + for (uint64_t j = 1; j <= 20; j++) + f20 *= j; + document["i"] = f20; // Alternate form: document["i"].SetUint64(f20) + assert(!document["i"].IsInt()); // No longer can be cast as int or uint. + } + + // Adding values to array. + { + Value& a = document["a"]; // This time we uses non-const reference. + Document::AllocatorType& allocator = document.GetAllocator(); + for (int i = 5; i <= 10; i++) + a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. + + // Fluent API + a.PushBack("Lua", allocator).PushBack("Mio", allocator); + } + + // Making string values. + + // This version of SetString() just store the pointer to the string. + // So it is for literal and string that exists within value's life-cycle. + { + document["hello"] = "rapidjson"; // This will invoke strlen() + // Faster version: + // document["hello"].SetString("rapidjson", 9); + } + + // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer. + Value author; + { + char buffer2[10]; + int len = sprintf(buffer2, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. + + author.SetString(buffer2, static_cast(len), document.GetAllocator()); + // Shorter but slower version: + // document["hello"].SetString(buffer, document.GetAllocator()); + + // Constructor version: + // Value author(buffer, len, document.GetAllocator()); + // Value author(buffer, document.GetAllocator()); + memset(buffer2, 0, sizeof(buffer2)); // For demonstration purpose. + } + // Variable 'buffer' is unusable now but 'author' has already made a copy. + document.AddMember("author", author, document.GetAllocator()); + + assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. + + //////////////////////////////////////////////////////////////////////////// + // 4. Stringify JSON + + printf("\nModified JSON with reformatting:\n"); + StringBuffer sb; + PrettyWriter writer(sb); + document.Accept(writer); // Accept() traverses the DOM and generates Handler events. + puts(sb.GetString()); + + return 0; +} diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/allocators.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/allocators.h new file mode 100644 index 0000000000..98affe03fb --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/allocators.h @@ -0,0 +1,271 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ALLOCATORS_H_ +#define RAPIDJSON_ALLOCATORS_H_ + +#include "rapidjson.h" + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// Allocator + +/*! \class rapidjson::Allocator + \brief Concept for allocating, resizing and freeing memory block. + + Note that Malloc() and Realloc() are non-static but Free() is static. + + So if an allocator need to support Free(), it needs to put its pointer in + the header of memory block. + +\code +concept Allocator { + static const bool kNeedFree; //!< Whether this allocator needs to call Free(). + + // Allocate a memory block. + // \param size of the memory block in bytes. + // \returns pointer to the memory block. + void* Malloc(size_t size); + + // Resize a memory block. + // \param originalPtr The pointer to current memory block. Null pointer is permitted. + // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.) + // \param newSize the new size in bytes. + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize); + + // Free a memory block. + // \param pointer to the memory block. Null pointer is permitted. + static void Free(void *ptr); +}; +\endcode +*/ + +/////////////////////////////////////////////////////////////////////////////// +// CrtAllocator + +//! C-runtime library allocator. +/*! This class is just wrapper for standard C library memory routines. + \note implements Allocator concept +*/ +class CrtAllocator { +public: + static const bool kNeedFree = true; + void* Malloc(size_t size) { + if (size) // behavior of malloc(0) is implementation defined. + return std::malloc(size); + else + return NULL; // standardize to returning NULL. + } + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { + (void)originalSize; + if (newSize == 0) { + std::free(originalPtr); + return NULL; + } + return std::realloc(originalPtr, newSize); + } + static void Free(void *ptr) { std::free(ptr); } +}; + +/////////////////////////////////////////////////////////////////////////////// +// MemoryPoolAllocator + +//! Default memory allocator used by the parser and DOM. +/*! This allocator allocate memory blocks from pre-allocated memory chunks. + + It does not free memory blocks. And Realloc() only allocate new memory. + + The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default. + + User may also supply a buffer as the first chunk. + + If the user-buffer is full then additional chunks are allocated by BaseAllocator. + + The user-buffer is not deallocated by this allocator. + + \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator. + \note implements Allocator concept +*/ +template +class MemoryPoolAllocator { +public: + static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator) + + //! Constructor with chunkSize. + /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. + \param baseAllocator The allocator for allocating memory chunks. + */ + MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : + chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0) + { + } + + //! Constructor with user-supplied buffer. + /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size. + + The user buffer will not be deallocated when this allocator is destructed. + + \param buffer User supplied buffer. + \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader). + \param chunkSize The size of memory chunk. The default is kDefaultChunkSize. + \param baseAllocator The allocator for allocating memory chunks. + */ + MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) : + chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0) + { + RAPIDJSON_ASSERT(buffer != 0); + RAPIDJSON_ASSERT(size > sizeof(ChunkHeader)); + chunkHead_ = reinterpret_cast(buffer); + chunkHead_->capacity = size - sizeof(ChunkHeader); + chunkHead_->size = 0; + chunkHead_->next = 0; + } + + //! Destructor. + /*! This deallocates all memory chunks, excluding the user-supplied buffer. + */ + ~MemoryPoolAllocator() { + Clear(); + RAPIDJSON_DELETE(ownBaseAllocator_); + } + + //! Deallocates all memory chunks, excluding the user-supplied buffer. + void Clear() { + while (chunkHead_ && chunkHead_ != userBuffer_) { + ChunkHeader* next = chunkHead_->next; + baseAllocator_->Free(chunkHead_); + chunkHead_ = next; + } + if (chunkHead_ && chunkHead_ == userBuffer_) + chunkHead_->size = 0; // Clear user buffer + } + + //! Computes the total capacity of allocated memory chunks. + /*! \return total capacity in bytes. + */ + size_t Capacity() const { + size_t capacity = 0; + for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) + capacity += c->capacity; + return capacity; + } + + //! Computes the memory blocks allocated. + /*! \return total used bytes. + */ + size_t Size() const { + size_t size = 0; + for (ChunkHeader* c = chunkHead_; c != 0; c = c->next) + size += c->size; + return size; + } + + //! Allocates a memory block. (concept Allocator) + void* Malloc(size_t size) { + if (!size) + return NULL; + + size = RAPIDJSON_ALIGN(size); + if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity) + if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size)) + return NULL; + + void *buffer = reinterpret_cast(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size; + chunkHead_->size += size; + return buffer; + } + + //! Resizes a memory block (concept Allocator) + void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { + if (originalPtr == 0) + return Malloc(newSize); + + if (newSize == 0) + return NULL; + + originalSize = RAPIDJSON_ALIGN(originalSize); + newSize = RAPIDJSON_ALIGN(newSize); + + // Do not shrink if new size is smaller than original + if (originalSize >= newSize) + return originalPtr; + + // Simply expand it if it is the last allocation and there is sufficient space + if (originalPtr == reinterpret_cast(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) { + size_t increment = static_cast(newSize - originalSize); + if (chunkHead_->size + increment <= chunkHead_->capacity) { + chunkHead_->size += increment; + return originalPtr; + } + } + + // Realloc process: allocate and copy memory, do not free original buffer. + if (void* newBuffer = Malloc(newSize)) { + if (originalSize) + std::memcpy(newBuffer, originalPtr, originalSize); + return newBuffer; + } + else + return NULL; + } + + //! Frees a memory block (concept Allocator) + static void Free(void *ptr) { (void)ptr; } // Do nothing + +private: + //! Copy constructor is not permitted. + MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */; + //! Copy assignment operator is not permitted. + MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */; + + //! Creates a new chunk. + /*! \param capacity Capacity of the chunk in bytes. + \return true if success. + */ + bool AddChunk(size_t capacity) { + if (!baseAllocator_) + ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator()); + if (ChunkHeader* chunk = reinterpret_cast(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) { + chunk->capacity = capacity; + chunk->size = 0; + chunk->next = chunkHead_; + chunkHead_ = chunk; + return true; + } + else + return false; + } + + static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity. + + //! Chunk header for perpending to each chunk. + /*! Chunks are stored as a singly linked list. + */ + struct ChunkHeader { + size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself). + size_t size; //!< Current size of allocated memory in bytes. + ChunkHeader *next; //!< Next chunk in the linked list. + }; + + ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation. + size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated. + void *userBuffer_; //!< User supplied buffer. + BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks. + BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object. +}; + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_ENCODINGS_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/document.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/document.h new file mode 100644 index 0000000000..e3e20dfbdc --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/document.h @@ -0,0 +1,2575 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_DOCUMENT_H_ +#define RAPIDJSON_DOCUMENT_H_ + +/*! \file document.h */ + +#include "reader.h" +#include "internal/meta.h" +#include "internal/strfunc.h" +#include "memorystream.h" +#include "encodedstream.h" +#include // placement new +#include + +RAPIDJSON_DIAG_PUSH +#ifdef _MSC_VER +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_OFF(padded) +RAPIDJSON_DIAG_OFF(switch-enum) +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +#ifdef __GNUC__ +RAPIDJSON_DIAG_OFF(effc++) +#if __GNUC__ >= 6 +RAPIDJSON_DIAG_OFF(terminate) // ignore throwing RAPIDJSON_ASSERT in RAPIDJSON_NOEXCEPT functions +#endif +#endif // __GNUC__ + +#ifndef RAPIDJSON_NOMEMBERITERATORCLASS +#include // std::iterator, std::random_access_iterator_tag +#endif + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS +#include // std::move +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +// Forward declaration. +template +class GenericValue; + +template +class GenericDocument; + +//! Name-value pair in a JSON object value. +/*! + This class was internal to GenericValue. It used to be a inner struct. + But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct. + https://code.google.com/p/rapidjson/issues/detail?id=64 +*/ +template +struct GenericMember { + GenericValue name; //!< name of member (must be a string) + GenericValue value; //!< value of member. +}; + +/////////////////////////////////////////////////////////////////////////////// +// GenericMemberIterator + +#ifndef RAPIDJSON_NOMEMBERITERATORCLASS + +//! (Constant) member iterator for a JSON object value +/*! + \tparam Const Is this a constant iterator? + \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) + \tparam Allocator Allocator type for allocating memory of object, array and string. + + This class implements a Random Access Iterator for GenericMember elements + of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements]. + + \note This iterator implementation is mainly intended to avoid implicit + conversions from iterator values to \c NULL, + e.g. from GenericValue::FindMember. + + \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a + pointer-based implementation, if your platform doesn't provide + the C++ header. + + \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator + */ +template +class GenericMemberIterator + : public std::iterator >::Type> { + + friend class GenericValue; + template friend class GenericMemberIterator; + + typedef GenericMember PlainType; + typedef typename internal::MaybeAddConst::Type ValueType; + typedef std::iterator BaseType; + +public: + //! Iterator type itself + typedef GenericMemberIterator Iterator; + //! Constant iterator type + typedef GenericMemberIterator ConstIterator; + //! Non-constant iterator type + typedef GenericMemberIterator NonConstIterator; + + //! Pointer to (const) GenericMember + typedef typename BaseType::pointer Pointer; + //! Reference to (const) GenericMember + typedef typename BaseType::reference Reference; + //! Signed integer type (e.g. \c ptrdiff_t) + typedef typename BaseType::difference_type DifferenceType; + + //! Default constructor (singular value) + /*! Creates an iterator pointing to no element. + \note All operations, except for comparisons, are undefined on such values. + */ + GenericMemberIterator() : ptr_() {} + + //! Iterator conversions to more const + /*! + \param it (Non-const) iterator to copy from + + Allows the creation of an iterator from another GenericMemberIterator + that is "less const". Especially, creating a non-constant iterator + from a constant iterator are disabled: + \li const -> non-const (not ok) + \li const -> const (ok) + \li non-const -> const (ok) + \li non-const -> non-const (ok) + + \note If the \c Const template parameter is already \c false, this + constructor effectively defines a regular copy-constructor. + Otherwise, the copy constructor is implicitly defined. + */ + GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {} + Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; } + + //! @name stepping + //@{ + Iterator& operator++(){ ++ptr_; return *this; } + Iterator& operator--(){ --ptr_; return *this; } + Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; } + Iterator operator--(int){ Iterator old(*this); --ptr_; return old; } + //@} + + //! @name increment/decrement + //@{ + Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); } + Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); } + + Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; } + Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; } + //@} + + //! @name relations + //@{ + bool operator==(ConstIterator that) const { return ptr_ == that.ptr_; } + bool operator!=(ConstIterator that) const { return ptr_ != that.ptr_; } + bool operator<=(ConstIterator that) const { return ptr_ <= that.ptr_; } + bool operator>=(ConstIterator that) const { return ptr_ >= that.ptr_; } + bool operator< (ConstIterator that) const { return ptr_ < that.ptr_; } + bool operator> (ConstIterator that) const { return ptr_ > that.ptr_; } + //@} + + //! @name dereference + //@{ + Reference operator*() const { return *ptr_; } + Pointer operator->() const { return ptr_; } + Reference operator[](DifferenceType n) const { return ptr_[n]; } + //@} + + //! Distance + DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; } + +private: + //! Internal constructor from plain pointer + explicit GenericMemberIterator(Pointer p) : ptr_(p) {} + + Pointer ptr_; //!< raw pointer +}; + +#else // RAPIDJSON_NOMEMBERITERATORCLASS + +// class-based member iterator implementation disabled, use plain pointers + +template +struct GenericMemberIterator; + +//! non-const GenericMemberIterator +template +struct GenericMemberIterator { + //! use plain pointer as iterator type + typedef GenericMember* Iterator; +}; +//! const GenericMemberIterator +template +struct GenericMemberIterator { + //! use plain const pointer as iterator type + typedef const GenericMember* Iterator; +}; + +#endif // RAPIDJSON_NOMEMBERITERATORCLASS + +/////////////////////////////////////////////////////////////////////////////// +// GenericStringRef + +//! Reference to a constant string (not taking a copy) +/*! + \tparam CharType character type of the string + + This helper class is used to automatically infer constant string + references for string literals, especially from \c const \b (!) + character arrays. + + The main use is for creating JSON string values without copying the + source string via an \ref Allocator. This requires that the referenced + string pointers have a sufficient lifetime, which exceeds the lifetime + of the associated GenericValue. + + \b Example + \code + Value v("foo"); // ok, no need to copy & calculate length + const char foo[] = "foo"; + v.SetString(foo); // ok + + const char* bar = foo; + // Value x(bar); // not ok, can't rely on bar's lifetime + Value x(StringRef(bar)); // lifetime explicitly guaranteed by user + Value y(StringRef(bar, 3)); // ok, explicitly pass length + \endcode + + \see StringRef, GenericValue::SetString +*/ +template +struct GenericStringRef { + typedef CharType Ch; //!< character type of the string + + //! Create string reference from \c const character array +#ifndef __clang__ // -Wdocumentation + /*! + This constructor implicitly creates a constant string reference from + a \c const character array. It has better performance than + \ref StringRef(const CharType*) by inferring the string \ref length + from the array length, and also supports strings containing null + characters. + + \tparam N length of the string, automatically inferred + + \param str Constant character array, lifetime assumed to be longer + than the use of the string in e.g. a GenericValue + + \post \ref s == str + + \note Constant complexity. + \note There is a hidden, private overload to disallow references to + non-const character arrays to be created via this constructor. + By this, e.g. function-scope arrays used to be filled via + \c snprintf are excluded from consideration. + In such cases, the referenced string should be \b copied to the + GenericValue instead. + */ +#endif + template + GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT + : s(str), length(N-1) {} + + //! Explicitly create string reference from \c const character pointer +#ifndef __clang__ // -Wdocumentation + /*! + This constructor can be used to \b explicitly create a reference to + a constant string pointer. + + \see StringRef(const CharType*) + + \param str Constant character pointer, lifetime assumed to be longer + than the use of the string in e.g. a GenericValue + + \post \ref s == str + + \note There is a hidden, private overload to disallow references to + non-const character arrays to be created via this constructor. + By this, e.g. function-scope arrays used to be filled via + \c snprintf are excluded from consideration. + In such cases, the referenced string should be \b copied to the + GenericValue instead. + */ +#endif + explicit GenericStringRef(const CharType* str) + : s(str), length(internal::StrLen(str)){ RAPIDJSON_ASSERT(s != 0); } + + //! Create constant string reference from pointer and length +#ifndef __clang__ // -Wdocumentation + /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue + \param len length of the string, excluding the trailing NULL terminator + + \post \ref s == str && \ref length == len + \note Constant complexity. + */ +#endif + GenericStringRef(const CharType* str, SizeType len) + : s(str), length(len) { RAPIDJSON_ASSERT(s != 0); } + + GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {} + + GenericStringRef& operator=(const GenericStringRef& rhs) { s = rhs.s; length = rhs.length; } + + //! implicit conversion to plain CharType pointer + operator const Ch *() const { return s; } + + const Ch* const s; //!< plain CharType pointer + const SizeType length; //!< length of the string (excluding the trailing NULL terminator) + +private: + //! Disallow construction from non-const array + template + GenericStringRef(CharType (&str)[N]) /* = delete */; +}; + +//! Mark a character pointer as constant string +/*! Mark a plain character pointer as a "string literal". This function + can be used to avoid copying a character string to be referenced as a + value in a JSON GenericValue object, if the string's lifetime is known + to be valid long enough. + \tparam CharType Character type of the string + \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue + \return GenericStringRef string reference object + \relatesalso GenericStringRef + + \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember +*/ +template +inline GenericStringRef StringRef(const CharType* str) { + return GenericStringRef(str, internal::StrLen(str)); +} + +//! Mark a character pointer as constant string +/*! Mark a plain character pointer as a "string literal". This function + can be used to avoid copying a character string to be referenced as a + value in a JSON GenericValue object, if the string's lifetime is known + to be valid long enough. + + This version has better performance with supplied length, and also + supports string containing null characters. + + \tparam CharType character type of the string + \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue + \param length The length of source string. + \return GenericStringRef string reference object + \relatesalso GenericStringRef +*/ +template +inline GenericStringRef StringRef(const CharType* str, size_t length) { + return GenericStringRef(str, SizeType(length)); +} + +#if RAPIDJSON_HAS_STDSTRING +//! Mark a string object as constant string +/*! Mark a string object (e.g. \c std::string) as a "string literal". + This function can be used to avoid copying a string to be referenced as a + value in a JSON GenericValue object, if the string's lifetime is known + to be valid long enough. + + \tparam CharType character type of the string + \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue + \return GenericStringRef string reference object + \relatesalso GenericStringRef + \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. +*/ +template +inline GenericStringRef StringRef(const std::basic_string& str) { + return GenericStringRef(str.data(), SizeType(str.size())); +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// GenericValue type traits +namespace internal { + +template +struct IsGenericValueImpl : FalseType {}; + +// select candidates according to nested encoding and allocator types +template struct IsGenericValueImpl::Type, typename Void::Type> + : IsBaseOf, T>::Type {}; + +// helper to match arbitrary GenericValue instantiations, including derived classes +template struct IsGenericValue : IsGenericValueImpl::Type {}; + +} // namespace internal + +/////////////////////////////////////////////////////////////////////////////// +// TypeHelper + +namespace internal { + +template +struct TypeHelper {}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsBool(); } + static bool Get(const ValueType& v) { return v.GetBool(); } + static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); } + static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsInt(); } + static int Get(const ValueType& v) { return v.GetInt(); } + static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); } + static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsUint(); } + static unsigned Get(const ValueType& v) { return v.GetUint(); } + static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); } + static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsInt64(); } + static int64_t Get(const ValueType& v) { return v.GetInt64(); } + static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); } + static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsUint64(); } + static uint64_t Get(const ValueType& v) { return v.GetUint64(); } + static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); } + static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsDouble(); } + static double Get(const ValueType& v) { return v.GetDouble(); } + static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); } + static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); } +}; + +template +struct TypeHelper { + static bool Is(const ValueType& v) { return v.IsFloat(); } + static float Get(const ValueType& v) { return v.GetFloat(); } + static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); } + static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); } +}; + +template +struct TypeHelper { + typedef const typename ValueType::Ch* StringType; + static bool Is(const ValueType& v) { return v.IsString(); } + static StringType Get(const ValueType& v) { return v.GetString(); } + static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); } + static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } +}; + +#if RAPIDJSON_HAS_STDSTRING +template +struct TypeHelper > { + typedef std::basic_string StringType; + static bool Is(const ValueType& v) { return v.IsString(); } + static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); } + static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); } +}; +#endif + +template +struct TypeHelper { + typedef typename ValueType::Array ArrayType; + static bool Is(const ValueType& v) { return v.IsArray(); } + static ArrayType Get(ValueType& v) { return v.GetArray(); } + static ValueType& Set(ValueType& v, ArrayType data) { return v = data; } + static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; } +}; + +template +struct TypeHelper { + typedef typename ValueType::ConstArray ArrayType; + static bool Is(const ValueType& v) { return v.IsArray(); } + static ArrayType Get(const ValueType& v) { return v.GetArray(); } +}; + +template +struct TypeHelper { + typedef typename ValueType::Object ObjectType; + static bool Is(const ValueType& v) { return v.IsObject(); } + static ObjectType Get(ValueType& v) { return v.GetObject(); } + static ValueType& Set(ValueType& v, ObjectType data) { return v = data; } + static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { v = data; } +}; + +template +struct TypeHelper { + typedef typename ValueType::ConstObject ObjectType; + static bool Is(const ValueType& v) { return v.IsObject(); } + static ObjectType Get(const ValueType& v) { return v.GetObject(); } +}; + +} // namespace internal + +// Forward declarations +template class GenericArray; +template class GenericObject; + +/////////////////////////////////////////////////////////////////////////////// +// GenericValue + +//! Represents a JSON value. Use Value for UTF8 encoding and default allocator. +/*! + A JSON value can be one of 7 types. This class is a variant type supporting + these types. + + Use the Value if UTF8 and default allocator + + \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document) + \tparam Allocator Allocator type for allocating memory of object, array and string. +*/ +template > +class GenericValue { +public: + //! Name-value pair in an object. + typedef GenericMember Member; + typedef Encoding EncodingType; //!< Encoding type from template parameter. + typedef Allocator AllocatorType; //!< Allocator type from template parameter. + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + typedef GenericStringRef StringRefType; //!< Reference to a constant string + typedef typename GenericMemberIterator::Iterator MemberIterator; //!< Member iterator for iterating in object. + typedef typename GenericMemberIterator::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object. + typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array. + typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array. + typedef GenericValue ValueType; //!< Value type of itself. + typedef GenericArray Array; + typedef GenericArray ConstArray; + typedef GenericObject Object; + typedef GenericObject ConstObject; + + //!@name Constructors and destructor. + //@{ + + //! Default constructor creates a null value. + GenericValue() RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Move constructor in C++11 + GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) { + rhs.data_.f.flags = kNullFlag; // give up contents + } +#endif + +private: + //! Copy constructor is not permitted. + GenericValue(const GenericValue& rhs); + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Moving from a GenericDocument is not permitted. + template + GenericValue(GenericDocument&& rhs); + + //! Move assignment from a GenericDocument is not permitted. + template + GenericValue& operator=(GenericDocument&& rhs); +#endif + +public: + + //! Constructor with JSON value type. + /*! This creates a Value of specified type with default content. + \param type Type of the value. + \note Default content for number is zero. + */ + explicit GenericValue(Type type) RAPIDJSON_NOEXCEPT : data_() { + static const uint16_t defaultFlags[7] = { + kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag, + kNumberAnyFlag + }; + RAPIDJSON_ASSERT(type <= kNumberType); + data_.f.flags = defaultFlags[type]; + + // Use ShortString to store empty string. + if (type == kStringType) + data_.ss.SetLength(0); + } + + //! Explicit copy constructor (with allocator) + /*! Creates a copy of a Value by using the given Allocator + \tparam SourceAllocator allocator of \c rhs + \param rhs Value to copy from (read-only) + \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator(). + \see CopyFrom() + */ + template< typename SourceAllocator > + GenericValue(const GenericValue& rhs, Allocator & allocator); + + //! Constructor for boolean value. + /*! \param b Boolean value + \note This constructor is limited to \em real boolean values and rejects + implicitly converted types like arbitrary pointers. Use an explicit cast + to \c bool, if you want to construct a boolean JSON value in such cases. + */ +#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen + template + explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame))) RAPIDJSON_NOEXCEPT // See #472 +#else + explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT +#endif + : data_() { + // safe-guard against failing SFINAE + RAPIDJSON_STATIC_ASSERT((internal::IsSame::Value)); + data_.f.flags = b ? kTrueFlag : kFalseFlag; + } + + //! Constructor for int value. + explicit GenericValue(int i) RAPIDJSON_NOEXCEPT : data_() { + data_.n.i64 = i; + data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag; + } + + //! Constructor for unsigned value. + explicit GenericValue(unsigned u) RAPIDJSON_NOEXCEPT : data_() { + data_.n.u64 = u; + data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag); + } + + //! Constructor for int64_t value. + explicit GenericValue(int64_t i64) RAPIDJSON_NOEXCEPT : data_() { + data_.n.i64 = i64; + data_.f.flags = kNumberInt64Flag; + if (i64 >= 0) { + data_.f.flags |= kNumberUint64Flag; + if (!(static_cast(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) + data_.f.flags |= kUintFlag; + if (!(static_cast(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) + data_.f.flags |= kIntFlag; + } + else if (i64 >= static_cast(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) + data_.f.flags |= kIntFlag; + } + + //! Constructor for uint64_t value. + explicit GenericValue(uint64_t u64) RAPIDJSON_NOEXCEPT : data_() { + data_.n.u64 = u64; + data_.f.flags = kNumberUint64Flag; + if (!(u64 & RAPIDJSON_UINT64_C2(0x80000000, 0x00000000))) + data_.f.flags |= kInt64Flag; + if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000))) + data_.f.flags |= kUintFlag; + if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000))) + data_.f.flags |= kIntFlag; + } + + //! Constructor for double value. + explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; } + + //! Constructor for constant string (i.e. do not make a copy of string) + GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); } + + //! Constructor for constant string (i.e. do not make a copy of string) + explicit GenericValue(StringRefType s) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); } + + //! Constructor for copy-string (i.e. do make a copy of string) + GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); } + + //! Constructor for copy-string (i.e. do make a copy of string) + GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } + +#if RAPIDJSON_HAS_STDSTRING + //! Constructor for copy-string from a string object (i.e. do make a copy of string) + /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. + */ + GenericValue(const std::basic_string& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); } +#endif + + //! Constructor for Array. + /*! + \param a An array obtained by \c GetArray(). + \note \c Array is always pass-by-value. + \note the source array is moved into this value and the sourec array becomes empty. + */ + GenericValue(Array a) RAPIDJSON_NOEXCEPT : data_(a.value_.data_) { + a.value_.data_ = Data(); + a.value_.data_.f.flags = kArrayFlag; + } + + //! Constructor for Object. + /*! + \param o An object obtained by \c GetObject(). + \note \c Object is always pass-by-value. + \note the source object is moved into this value and the sourec object becomes empty. + */ + GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) { + o.value_.data_ = Data(); + o.value_.data_.f.flags = kObjectFlag; + } + + //! Destructor. + /*! Need to destruct elements of array, members of object, or copy-string. + */ + ~GenericValue() { + if (Allocator::kNeedFree) { // Shortcut by Allocator's trait + switch(data_.f.flags) { + case kArrayFlag: + { + GenericValue* e = GetElementsPointer(); + for (GenericValue* v = e; v != e + data_.a.size; ++v) + v->~GenericValue(); + Allocator::Free(e); + } + break; + + case kObjectFlag: + for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) + m->~Member(); + Allocator::Free(GetMembersPointer()); + break; + + case kCopyStringFlag: + Allocator::Free(const_cast(GetStringPointer())); + break; + + default: + break; // Do nothing for other types. + } + } + } + + //@} + + //!@name Assignment operators + //@{ + + //! Assignment with move semantics. + /*! \param rhs Source of the assignment. It will become a null value after assignment. + */ + GenericValue& operator=(GenericValue& rhs) RAPIDJSON_NOEXCEPT { + RAPIDJSON_ASSERT(this != &rhs); + this->~GenericValue(); + RawAssign(rhs); + return *this; + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Move assignment in C++11 + GenericValue& operator=(GenericValue&& rhs) RAPIDJSON_NOEXCEPT { + return *this = rhs.Move(); + } +#endif + + //! Assignment of constant string reference (no copy) + /*! \param str Constant string reference to be assigned + \note This overload is needed to avoid clashes with the generic primitive type assignment overload below. + \see GenericStringRef, operator=(T) + */ + GenericValue& operator=(StringRefType str) RAPIDJSON_NOEXCEPT { + GenericValue s(str); + return *this = s; + } + + //! Assignment with primitive types. + /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t + \param value The value to be assigned. + + \note The source type \c T explicitly disallows all pointer types, + especially (\c const) \ref Ch*. This helps avoiding implicitly + referencing character strings with insufficient lifetime, use + \ref SetString(const Ch*, Allocator&) (for copying) or + \ref StringRef() (to explicitly mark the pointer as constant) instead. + All other pointer types would implicitly convert to \c bool, + use \ref SetBool() instead. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer), (GenericValue&)) + operator=(T value) { + GenericValue v(value); + return *this = v; + } + + //! Deep-copy assignment from Value + /*! Assigns a \b copy of the Value to the current Value object + \tparam SourceAllocator Allocator type of \c rhs + \param rhs Value to copy from (read-only) + \param allocator Allocator to use for copying + */ + template + GenericValue& CopyFrom(const GenericValue& rhs, Allocator& allocator) { + RAPIDJSON_ASSERT(static_cast(this) != static_cast(&rhs)); + this->~GenericValue(); + new (this) GenericValue(rhs, allocator); + return *this; + } + + //! Exchange the contents of this value with those of other. + /*! + \param other Another value. + \note Constant complexity. + */ + GenericValue& Swap(GenericValue& other) RAPIDJSON_NOEXCEPT { + GenericValue temp; + temp.RawAssign(*this); + RawAssign(other); + other.RawAssign(temp); + return *this; + } + + //! free-standing swap function helper + /*! + Helper function to enable support for common swap implementation pattern based on \c std::swap: + \code + void swap(MyClass& a, MyClass& b) { + using std::swap; + swap(a.value, b.value); + // ... + } + \endcode + \see Swap() + */ + friend inline void swap(GenericValue& a, GenericValue& b) RAPIDJSON_NOEXCEPT { a.Swap(b); } + + //! Prepare Value for move semantics + /*! \return *this */ + GenericValue& Move() RAPIDJSON_NOEXCEPT { return *this; } + //@} + + //!@name Equal-to and not-equal-to operators + //@{ + //! Equal-to operator + /*! + \note If an object contains duplicated named member, comparing equality with any object is always \c false. + \note Linear time complexity (number of all values in the subtree and total lengths of all strings). + */ + template + bool operator==(const GenericValue& rhs) const { + typedef GenericValue RhsType; + if (GetType() != rhs.GetType()) + return false; + + switch (GetType()) { + case kObjectType: // Warning: O(n^2) inner-loop + if (data_.o.size != rhs.data_.o.size) + return false; + for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) { + typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name); + if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value) + return false; + } + return true; + + case kArrayType: + if (data_.a.size != rhs.data_.a.size) + return false; + for (SizeType i = 0; i < data_.a.size; i++) + if ((*this)[i] != rhs[i]) + return false; + return true; + + case kStringType: + return StringEqual(rhs); + + case kNumberType: + if (IsDouble() || rhs.IsDouble()) { + double a = GetDouble(); // May convert from integer to double. + double b = rhs.GetDouble(); // Ditto + return a >= b && a <= b; // Prevent -Wfloat-equal + } + else + return data_.n.u64 == rhs.data_.n.u64; + + default: + return true; + } + } + + //! Equal-to operator with const C-string pointer + bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); } + +#if RAPIDJSON_HAS_STDSTRING + //! Equal-to operator with string object + /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. + */ + bool operator==(const std::basic_string& rhs) const { return *this == GenericValue(StringRef(rhs)); } +#endif + + //! Equal-to operator with primitive types + /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false + */ + template RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr,internal::IsGenericValue >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); } + + //! Not-equal-to operator + /*! \return !(*this == rhs) + */ + template + bool operator!=(const GenericValue& rhs) const { return !(*this == rhs); } + + //! Not-equal-to operator with const C-string pointer + bool operator!=(const Ch* rhs) const { return !(*this == rhs); } + + //! Not-equal-to operator with arbitrary types + /*! \return !(*this == rhs) + */ + template RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); } + + //! Equal-to operator with arbitrary types (symmetric version) + /*! \return (rhs == lhs) + */ + template friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; } + + //! Not-Equal-to operator with arbitrary types (symmetric version) + /*! \return !(rhs == lhs) + */ + template friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); } + //@} + + //!@name Type + //@{ + + Type GetType() const { return static_cast(data_.f.flags & kTypeMask); } + bool IsNull() const { return data_.f.flags == kNullFlag; } + bool IsFalse() const { return data_.f.flags == kFalseFlag; } + bool IsTrue() const { return data_.f.flags == kTrueFlag; } + bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; } + bool IsObject() const { return data_.f.flags == kObjectFlag; } + bool IsArray() const { return data_.f.flags == kArrayFlag; } + bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; } + bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; } + bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; } + bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; } + bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; } + bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; } + bool IsString() const { return (data_.f.flags & kStringFlag) != 0; } + + // Checks whether a number can be losslessly converted to a double. + bool IsLosslessDouble() const { + if (!IsNumber()) return false; + if (IsUint64()) { + uint64_t u = GetUint64(); + volatile double d = static_cast(u); + return (d >= 0.0) + && (d < static_cast(std::numeric_limits::max())) + && (u == static_cast(d)); + } + if (IsInt64()) { + int64_t i = GetInt64(); + volatile double d = static_cast(i); + return (d >= static_cast(std::numeric_limits::min())) + && (d < static_cast(std::numeric_limits::max())) + && (i == static_cast(d)); + } + return true; // double, int, uint are always lossless + } + + // Checks whether a number is a float (possible lossy). + bool IsFloat() const { + if ((data_.f.flags & kDoubleFlag) == 0) + return false; + double d = GetDouble(); + return d >= -3.4028234e38 && d <= 3.4028234e38; + } + // Checks whether a number can be losslessly converted to a float. + bool IsLosslessFloat() const { + if (!IsNumber()) return false; + double a = GetDouble(); + if (a < static_cast(-std::numeric_limits::max()) + || a > static_cast(std::numeric_limits::max())) + return false; + double b = static_cast(static_cast(a)); + return a >= b && a <= b; // Prevent -Wfloat-equal + } + + //@} + + //!@name Null + //@{ + + GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; } + + //@} + + //!@name Bool + //@{ + + bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; } + //!< Set boolean value + /*! \post IsBool() == true */ + GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; } + + //@} + + //!@name Object + //@{ + + //! Set this value as an empty object. + /*! \post IsObject() == true */ + GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; } + + //! Get the number of members in the object. + SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; } + + //! Check whether the object is empty. + bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; } + + //! Get a value from an object associated with the name. + /*! \pre IsObject() == true + \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType)) + \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7. + Since 0.2, if the name is not correct, it will assert. + If user is unsure whether a member exists, user should use HasMember() first. + A better approach is to use FindMember(). + \note Linear time complexity. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(GenericValue&)) operator[](T* name) { + GenericValue n(StringRef(name)); + return (*this)[n]; + } + template + RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast(*this)[name]; } + + //! Get a value from an object associated with the name. + /*! \pre IsObject() == true + \tparam SourceAllocator Allocator of the \c name value + + \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen(). + And it can also handle strings with embedded null characters. + + \note Linear time complexity. + */ + template + GenericValue& operator[](const GenericValue& name) { + MemberIterator member = FindMember(name); + if (member != MemberEnd()) + return member->value; + else { + RAPIDJSON_ASSERT(false); // see above note + + // This will generate -Wexit-time-destructors in clang + // static GenericValue NullValue; + // return NullValue; + + // Use static buffer and placement-new to prevent destruction + static char buffer[sizeof(GenericValue)]; + return *new (buffer) GenericValue(); + } + } + template + const GenericValue& operator[](const GenericValue& name) const { return const_cast(*this)[name]; } + +#if RAPIDJSON_HAS_STDSTRING + //! Get a value from an object associated with name (string object). + GenericValue& operator[](const std::basic_string& name) { return (*this)[GenericValue(StringRef(name))]; } + const GenericValue& operator[](const std::basic_string& name) const { return (*this)[GenericValue(StringRef(name))]; } +#endif + + //! Const member iterator + /*! \pre IsObject() == true */ + ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); } + //! Const \em past-the-end member iterator + /*! \pre IsObject() == true */ + ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); } + //! Member iterator + /*! \pre IsObject() == true */ + MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); } + //! \em Past-the-end member iterator + /*! \pre IsObject() == true */ + MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); } + + //! Check whether a member exists in the object. + /*! + \param name Member name to be searched. + \pre IsObject() == true + \return Whether a member with that name exists. + \note It is better to use FindMember() directly if you need the obtain the value as well. + \note Linear time complexity. + */ + bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); } + +#if RAPIDJSON_HAS_STDSTRING + //! Check whether a member exists in the object with string object. + /*! + \param name Member name to be searched. + \pre IsObject() == true + \return Whether a member with that name exists. + \note It is better to use FindMember() directly if you need the obtain the value as well. + \note Linear time complexity. + */ + bool HasMember(const std::basic_string& name) const { return FindMember(name) != MemberEnd(); } +#endif + + //! Check whether a member exists in the object with GenericValue name. + /*! + This version is faster because it does not need a StrLen(). It can also handle string with null character. + \param name Member name to be searched. + \pre IsObject() == true + \return Whether a member with that name exists. + \note It is better to use FindMember() directly if you need the obtain the value as well. + \note Linear time complexity. + */ + template + bool HasMember(const GenericValue& name) const { return FindMember(name) != MemberEnd(); } + + //! Find member by name. + /*! + \param name Member name to be searched. + \pre IsObject() == true + \return Iterator to member, if it exists. + Otherwise returns \ref MemberEnd(). + + \note Earlier versions of Rapidjson returned a \c NULL pointer, in case + the requested member doesn't exist. For consistency with e.g. + \c std::map, this has been changed to MemberEnd() now. + \note Linear time complexity. + */ + MemberIterator FindMember(const Ch* name) { + GenericValue n(StringRef(name)); + return FindMember(n); + } + + ConstMemberIterator FindMember(const Ch* name) const { return const_cast(*this).FindMember(name); } + + //! Find member by name. + /*! + This version is faster because it does not need a StrLen(). It can also handle string with null character. + \param name Member name to be searched. + \pre IsObject() == true + \return Iterator to member, if it exists. + Otherwise returns \ref MemberEnd(). + + \note Earlier versions of Rapidjson returned a \c NULL pointer, in case + the requested member doesn't exist. For consistency with e.g. + \c std::map, this has been changed to MemberEnd() now. + \note Linear time complexity. + */ + template + MemberIterator FindMember(const GenericValue& name) { + RAPIDJSON_ASSERT(IsObject()); + RAPIDJSON_ASSERT(name.IsString()); + MemberIterator member = MemberBegin(); + for ( ; member != MemberEnd(); ++member) + if (name.StringEqual(member->name)) + break; + return member; + } + template ConstMemberIterator FindMember(const GenericValue& name) const { return const_cast(*this).FindMember(name); } + +#if RAPIDJSON_HAS_STDSTRING + //! Find member by string object name. + /*! + \param name Member name to be searched. + \pre IsObject() == true + \return Iterator to member, if it exists. + Otherwise returns \ref MemberEnd(). + */ + MemberIterator FindMember(const std::basic_string& name) { return FindMember(GenericValue(StringRef(name))); } + ConstMemberIterator FindMember(const std::basic_string& name) const { return FindMember(GenericValue(StringRef(name))); } +#endif + + //! Add a member (name-value pair) to the object. + /*! \param name A string value as name of member. + \param value Value of any type. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \note The ownership of \c name and \c value will be transferred to this object on success. + \pre IsObject() && name.IsString() + \post name.IsNull() && value.IsNull() + \note Amortized Constant time complexity. + */ + GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) { + RAPIDJSON_ASSERT(IsObject()); + RAPIDJSON_ASSERT(name.IsString()); + + ObjectData& o = data_.o; + if (o.size >= o.capacity) { + if (o.capacity == 0) { + o.capacity = kDefaultObjectCapacity; + SetMembersPointer(reinterpret_cast(allocator.Malloc(o.capacity * sizeof(Member)))); + } + else { + SizeType oldCapacity = o.capacity; + o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5 + SetMembersPointer(reinterpret_cast(allocator.Realloc(GetMembersPointer(), oldCapacity * sizeof(Member), o.capacity * sizeof(Member)))); + } + } + Member* members = GetMembersPointer(); + members[o.size].name.RawAssign(name); + members[o.size].value.RawAssign(value); + o.size++; + return *this; + } + + //! Add a constant string value as member (name-value pair) to the object. + /*! \param name A string value as name of member. + \param value constant string reference as value of member. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \pre IsObject() + \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. + \note Amortized Constant time complexity. + */ + GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) { + GenericValue v(value); + return AddMember(name, v, allocator); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Add a string object as member (name-value pair) to the object. + /*! \param name A string value as name of member. + \param value constant string reference as value of member. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \pre IsObject() + \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below. + \note Amortized Constant time complexity. + */ + GenericValue& AddMember(GenericValue& name, std::basic_string& value, Allocator& allocator) { + GenericValue v(value, allocator); + return AddMember(name, v, allocator); + } +#endif + + //! Add any primitive value as member (name-value pair) to the object. + /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t + \param name A string value as name of member. + \param value Value of primitive type \c T as value of member + \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \pre IsObject() + + \note The source type \c T explicitly disallows all pointer types, + especially (\c const) \ref Ch*. This helps avoiding implicitly + referencing character strings with insufficient lifetime, use + \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref + AddMember(StringRefType, StringRefType, Allocator&). + All other pointer types would implicitly convert to \c bool, + use an explicit cast instead, if needed. + \note Amortized Constant time complexity. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) + AddMember(GenericValue& name, T value, Allocator& allocator) { + GenericValue v(value); + return AddMember(name, v, allocator); + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) { + return AddMember(name, value, allocator); + } + GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) { + return AddMember(name, value, allocator); + } + GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) { + return AddMember(name, value, allocator); + } + GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) { + GenericValue n(name); + return AddMember(n, value, allocator); + } +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + + + //! Add a member (name-value pair) to the object. + /*! \param name A constant string reference as name of member. + \param value Value of any type. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \note The ownership of \c value will be transferred to this object on success. + \pre IsObject() + \post value.IsNull() + \note Amortized Constant time complexity. + */ + GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) { + GenericValue n(name); + return AddMember(n, value, allocator); + } + + //! Add a constant string value as member (name-value pair) to the object. + /*! \param name A constant string reference as name of member. + \param value constant string reference as value of member. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \pre IsObject() + \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below. + \note Amortized Constant time complexity. + */ + GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) { + GenericValue v(value); + return AddMember(name, v, allocator); + } + + //! Add any primitive value as member (name-value pair) to the object. + /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t + \param name A constant string reference as name of member. + \param value Value of primitive type \c T as value of member + \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \pre IsObject() + + \note The source type \c T explicitly disallows all pointer types, + especially (\c const) \ref Ch*. This helps avoiding implicitly + referencing character strings with insufficient lifetime, use + \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref + AddMember(StringRefType, StringRefType, Allocator&). + All other pointer types would implicitly convert to \c bool, + use an explicit cast instead, if needed. + \note Amortized Constant time complexity. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) + AddMember(StringRefType name, T value, Allocator& allocator) { + GenericValue n(name); + return AddMember(n, value, allocator); + } + + //! Remove all members in the object. + /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged. + \note Linear time complexity. + */ + void RemoveAllMembers() { + RAPIDJSON_ASSERT(IsObject()); + for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m) + m->~Member(); + data_.o.size = 0; + } + + //! Remove a member in object by its name. + /*! \param name Name of member to be removed. + \return Whether the member existed. + \note This function may reorder the object members. Use \ref + EraseMember(ConstMemberIterator) if you need to preserve the + relative order of the remaining members. + \note Linear time complexity. + */ + bool RemoveMember(const Ch* name) { + GenericValue n(StringRef(name)); + return RemoveMember(n); + } + +#if RAPIDJSON_HAS_STDSTRING + bool RemoveMember(const std::basic_string& name) { return RemoveMember(GenericValue(StringRef(name))); } +#endif + + template + bool RemoveMember(const GenericValue& name) { + MemberIterator m = FindMember(name); + if (m != MemberEnd()) { + RemoveMember(m); + return true; + } + else + return false; + } + + //! Remove a member in object by iterator. + /*! \param m member iterator (obtained by FindMember() or MemberBegin()). + \return the new iterator after removal. + \note This function may reorder the object members. Use \ref + EraseMember(ConstMemberIterator) if you need to preserve the + relative order of the remaining members. + \note Constant time complexity. + */ + MemberIterator RemoveMember(MemberIterator m) { + RAPIDJSON_ASSERT(IsObject()); + RAPIDJSON_ASSERT(data_.o.size > 0); + RAPIDJSON_ASSERT(GetMembersPointer() != 0); + RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd()); + + MemberIterator last(GetMembersPointer() + (data_.o.size - 1)); + if (data_.o.size > 1 && m != last) + *m = *last; // Move the last one to this place + else + m->~Member(); // Only one left, just destroy + --data_.o.size; + return m; + } + + //! Remove a member from an object by iterator. + /*! \param pos iterator to the member to remove + \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd() + \return Iterator following the removed element. + If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned. + \note This function preserves the relative order of the remaining object + members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator). + \note Linear time complexity. + */ + MemberIterator EraseMember(ConstMemberIterator pos) { + return EraseMember(pos, pos +1); + } + + //! Remove members in the range [first, last) from an object. + /*! \param first iterator to the first member to remove + \param last iterator following the last member to remove + \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd() + \return Iterator following the last removed element. + \note This function preserves the relative order of the remaining object + members. + \note Linear time complexity. + */ + MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) { + RAPIDJSON_ASSERT(IsObject()); + RAPIDJSON_ASSERT(data_.o.size > 0); + RAPIDJSON_ASSERT(GetMembersPointer() != 0); + RAPIDJSON_ASSERT(first >= MemberBegin()); + RAPIDJSON_ASSERT(first <= last); + RAPIDJSON_ASSERT(last <= MemberEnd()); + + MemberIterator pos = MemberBegin() + (first - MemberBegin()); + for (MemberIterator itr = pos; itr != last; ++itr) + itr->~Member(); + std::memmove(&*pos, &*last, static_cast(MemberEnd() - last) * sizeof(Member)); + data_.o.size -= static_cast(last - first); + return pos; + } + + //! Erase a member in object by its name. + /*! \param name Name of member to be removed. + \return Whether the member existed. + \note Linear time complexity. + */ + bool EraseMember(const Ch* name) { + GenericValue n(StringRef(name)); + return EraseMember(n); + } + +#if RAPIDJSON_HAS_STDSTRING + bool EraseMember(const std::basic_string& name) { return EraseMember(GenericValue(StringRef(name))); } +#endif + + template + bool EraseMember(const GenericValue& name) { + MemberIterator m = FindMember(name); + if (m != MemberEnd()) { + EraseMember(m); + return true; + } + else + return false; + } + + Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); } + ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); } + + //@} + + //!@name Array + //@{ + + //! Set this value as an empty array. + /*! \post IsArray == true */ + GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; } + + //! Get the number of elements in array. + SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; } + + //! Get the capacity of array. + SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; } + + //! Check whether the array is empty. + bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; } + + //! Remove all elements in the array. + /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged. + \note Linear time complexity. + */ + void Clear() { + RAPIDJSON_ASSERT(IsArray()); + GenericValue* e = GetElementsPointer(); + for (GenericValue* v = e; v != e + data_.a.size; ++v) + v->~GenericValue(); + data_.a.size = 0; + } + + //! Get an element from array by index. + /*! \pre IsArray() == true + \param index Zero-based index of element. + \see operator[](T*) + */ + GenericValue& operator[](SizeType index) { + RAPIDJSON_ASSERT(IsArray()); + RAPIDJSON_ASSERT(index < data_.a.size); + return GetElementsPointer()[index]; + } + const GenericValue& operator[](SizeType index) const { return const_cast(*this)[index]; } + + //! Element iterator + /*! \pre IsArray() == true */ + ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); } + //! \em Past-the-end element iterator + /*! \pre IsArray() == true */ + ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; } + //! Constant element iterator + /*! \pre IsArray() == true */ + ConstValueIterator Begin() const { return const_cast(*this).Begin(); } + //! Constant \em past-the-end element iterator + /*! \pre IsArray() == true */ + ConstValueIterator End() const { return const_cast(*this).End(); } + + //! Request the array to have enough capacity to store elements. + /*! \param newCapacity The capacity that the array at least need to have. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \note Linear time complexity. + */ + GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) { + RAPIDJSON_ASSERT(IsArray()); + if (newCapacity > data_.a.capacity) { + SetElementsPointer(reinterpret_cast(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue)))); + data_.a.capacity = newCapacity; + } + return *this; + } + + //! Append a GenericValue at the end of the array. + /*! \param value Value to be appended. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \pre IsArray() == true + \post value.IsNull() == true + \return The value itself for fluent API. + \note The ownership of \c value will be transferred to this array on success. + \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. + \note Amortized constant time complexity. + */ + GenericValue& PushBack(GenericValue& value, Allocator& allocator) { + RAPIDJSON_ASSERT(IsArray()); + if (data_.a.size >= data_.a.capacity) + Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator); + GetElementsPointer()[data_.a.size++].RawAssign(value); + return *this; + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericValue& PushBack(GenericValue&& value, Allocator& allocator) { + return PushBack(value, allocator); + } +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + + //! Append a constant string reference at the end of the array. + /*! \param value Constant string reference to be appended. + \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator(). + \pre IsArray() == true + \return The value itself for fluent API. + \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. + \note Amortized constant time complexity. + \see GenericStringRef + */ + GenericValue& PushBack(StringRefType value, Allocator& allocator) { + return (*this).template PushBack(value, allocator); + } + + //! Append a primitive value at the end of the array. + /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t + \param value Value of primitive type T to be appended. + \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator(). + \pre IsArray() == true + \return The value itself for fluent API. + \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient. + + \note The source type \c T explicitly disallows all pointer types, + especially (\c const) \ref Ch*. This helps avoiding implicitly + referencing character strings with insufficient lifetime, use + \ref PushBack(GenericValue&, Allocator&) or \ref + PushBack(StringRefType, Allocator&). + All other pointer types would implicitly convert to \c bool, + use an explicit cast instead, if needed. + \note Amortized constant time complexity. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericValue&)) + PushBack(T value, Allocator& allocator) { + GenericValue v(value); + return PushBack(v, allocator); + } + + //! Remove the last element in the array. + /*! + \note Constant time complexity. + */ + GenericValue& PopBack() { + RAPIDJSON_ASSERT(IsArray()); + RAPIDJSON_ASSERT(!Empty()); + GetElementsPointer()[--data_.a.size].~GenericValue(); + return *this; + } + + //! Remove an element of array by iterator. + /*! + \param pos iterator to the element to remove + \pre IsArray() == true && \ref Begin() <= \c pos < \ref End() + \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned. + \note Linear time complexity. + */ + ValueIterator Erase(ConstValueIterator pos) { + return Erase(pos, pos + 1); + } + + //! Remove elements in the range [first, last) of the array. + /*! + \param first iterator to the first element to remove + \param last iterator following the last element to remove + \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End() + \return Iterator following the last removed element. + \note Linear time complexity. + */ + ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) { + RAPIDJSON_ASSERT(IsArray()); + RAPIDJSON_ASSERT(data_.a.size > 0); + RAPIDJSON_ASSERT(GetElementsPointer() != 0); + RAPIDJSON_ASSERT(first >= Begin()); + RAPIDJSON_ASSERT(first <= last); + RAPIDJSON_ASSERT(last <= End()); + ValueIterator pos = Begin() + (first - Begin()); + for (ValueIterator itr = pos; itr != last; ++itr) + itr->~GenericValue(); + std::memmove(pos, last, static_cast(End() - last) * sizeof(GenericValue)); + data_.a.size -= static_cast(last - first); + return pos; + } + + Array GetArray() { RAPIDJSON_ASSERT(IsArray()); return Array(*this); } + ConstArray GetArray() const { RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); } + + //@} + + //!@name Number + //@{ + + int GetInt() const { RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; } + unsigned GetUint() const { RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; } + int64_t GetInt64() const { RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; } + uint64_t GetUint64() const { RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; } + + //! Get the value as double type. + /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless. + */ + double GetDouble() const { + RAPIDJSON_ASSERT(IsNumber()); + if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion. + if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double + if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double + if ((data_.f.flags & kInt64Flag) != 0) return static_cast(data_.n.i64); // int64_t -> double (may lose precision) + RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast(data_.n.u64); // uint64_t -> double (may lose precision) + } + + //! Get the value as float type. + /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless. + */ + float GetFloat() const { + return static_cast(GetDouble()); + } + + GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; } + GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; } + GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; } + GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; } + GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; } + GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(f); return *this; } + + //@} + + //!@name String + //@{ + + const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); } + + //! Get the length of string. + /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength(). + */ + SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); } + + //! Set this value as a string without copying source string. + /*! This version has better performance with supplied length, and also support string containing null character. + \param s source string pointer. + \param length The length of source string, excluding the trailing null terminator. + \return The value itself for fluent API. + \post IsString() == true && GetString() == s && GetStringLength() == length + \see SetString(StringRefType) + */ + GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); } + + //! Set this value as a string without copying source string. + /*! \param s source string reference + \return The value itself for fluent API. + \post IsString() == true && GetString() == s && GetStringLength() == s.length + */ + GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; } + + //! Set this value as a string by copying from source string. + /*! This version has better performance with supplied length, and also support string containing null character. + \param s source string. + \param length The length of source string, excluding the trailing null terminator. + \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length + */ + GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(StringRef(s, length), allocator); return *this; } + + //! Set this value as a string by copying from source string. + /*! \param s source string. + \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length + */ + GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(s, internal::StrLen(s), allocator); } + +#if RAPIDJSON_HAS_STDSTRING + //! Set this value as a string by copying from source string. + /*! \param s source string. + \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator(). + \return The value itself for fluent API. + \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size() + \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. + */ + GenericValue& SetString(const std::basic_string& s, Allocator& allocator) { return SetString(s.data(), SizeType(s.size()), allocator); } +#endif + + //@} + + //!@name Array + //@{ + + //! Templated version for checking whether this value is type T. + /*! + \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string + */ + template + bool Is() const { return internal::TypeHelper::Is(*this); } + + template + T Get() const { return internal::TypeHelper::Get(*this); } + + template + T Get() { return internal::TypeHelper::Get(*this); } + + template + ValueType& Set(const T& data) { return internal::TypeHelper::Set(*this, data); } + + template + ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper::Set(*this, data, allocator); } + + //@} + + //! Generate events of this value to a Handler. + /*! This function adopts the GoF visitor pattern. + Typical usage is to output this JSON value as JSON text via Writer, which is a Handler. + It can also be used to deep clone this value via GenericDocument, which is also a Handler. + \tparam Handler type of handler. + \param handler An object implementing concept Handler. + */ + template + bool Accept(Handler& handler) const { + switch(GetType()) { + case kNullType: return handler.Null(); + case kFalseType: return handler.Bool(false); + case kTrueType: return handler.Bool(true); + + case kObjectType: + if (RAPIDJSON_UNLIKELY(!handler.StartObject())) + return false; + for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) { + RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator. + if (RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0))) + return false; + if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler))) + return false; + } + return handler.EndObject(data_.o.size); + + case kArrayType: + if (RAPIDJSON_UNLIKELY(!handler.StartArray())) + return false; + for (const GenericValue* v = Begin(); v != End(); ++v) + if (RAPIDJSON_UNLIKELY(!v->Accept(handler))) + return false; + return handler.EndArray(data_.a.size); + + case kStringType: + return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0); + + default: + RAPIDJSON_ASSERT(GetType() == kNumberType); + if (IsDouble()) return handler.Double(data_.n.d); + else if (IsInt()) return handler.Int(data_.n.i.i); + else if (IsUint()) return handler.Uint(data_.n.u.u); + else if (IsInt64()) return handler.Int64(data_.n.i64); + else return handler.Uint64(data_.n.u64); + } + } + +private: + template friend class GenericValue; + template friend class GenericDocument; + + enum { + kBoolFlag = 0x0008, + kNumberFlag = 0x0010, + kIntFlag = 0x0020, + kUintFlag = 0x0040, + kInt64Flag = 0x0080, + kUint64Flag = 0x0100, + kDoubleFlag = 0x0200, + kStringFlag = 0x0400, + kCopyFlag = 0x0800, + kInlineStrFlag = 0x1000, + + // Initial flags of different types. + kNullFlag = kNullType, + kTrueFlag = kTrueType | kBoolFlag, + kFalseFlag = kFalseType | kBoolFlag, + kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag, + kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag, + kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag, + kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag, + kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag, + kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag, + kConstStringFlag = kStringType | kStringFlag, + kCopyStringFlag = kStringType | kStringFlag | kCopyFlag, + kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag, + kObjectFlag = kObjectType, + kArrayFlag = kArrayType, + + kTypeMask = 0x07 + }; + + static const SizeType kDefaultArrayCapacity = 16; + static const SizeType kDefaultObjectCapacity = 16; + + struct Flag { +#if RAPIDJSON_48BITPOINTER_OPTIMIZATION + char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer +#elif RAPIDJSON_64BIT + char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes +#else + char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes +#endif + uint16_t flags; + }; + + struct String { + SizeType length; + SizeType hashcode; //!< reserved + const Ch* str; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars + // (excluding the terminating zero) and store a value to determine the length of the contained + // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string + // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as + // the string terminator as well. For getting the string length back from that value just use + // "MaxSize - str[LenPos]". + // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode, + // 13-chars strings for RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings). + struct ShortString { + enum { MaxChars = sizeof(static_cast(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize }; + Ch str[MaxChars]; + + inline static bool Usable(SizeType len) { return (MaxSize >= len); } + inline void SetLength(SizeType len) { str[LenPos] = static_cast(MaxSize - len); } + inline SizeType GetLength() const { return static_cast(MaxSize - str[LenPos]); } + }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + // By using proper binary layout, retrieval of different integer types do not need conversions. + union Number { +#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN + struct I { + int i; + char padding[4]; + }i; + struct U { + unsigned u; + char padding2[4]; + }u; +#else + struct I { + char padding[4]; + int i; + }i; + struct U { + char padding2[4]; + unsigned u; + }u; +#endif + int64_t i64; + uint64_t u64; + double d; + }; // 8 bytes + + struct ObjectData { + SizeType size; + SizeType capacity; + Member* members; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + struct ArrayData { + SizeType size; + SizeType capacity; + GenericValue* elements; + }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode + + union Data { + String s; + ShortString ss; + Number n; + ObjectData o; + ArrayData a; + Flag f; + }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with RAPIDJSON_48BITPOINTER_OPTIMIZATION + + RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return RAPIDJSON_GETPOINTER(Ch, data_.s.str); } + RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); } + RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); } + RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); } + RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return RAPIDJSON_GETPOINTER(Member, data_.o.members); } + RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return RAPIDJSON_SETPOINTER(Member, data_.o.members, members); } + + // Initialize this value as array with initial data, without calling destructor. + void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) { + data_.f.flags = kArrayFlag; + if (count) { + GenericValue* e = static_cast(allocator.Malloc(count * sizeof(GenericValue))); + SetElementsPointer(e); + std::memcpy(e, values, count * sizeof(GenericValue)); + } + else + SetElementsPointer(0); + data_.a.size = data_.a.capacity = count; + } + + //! Initialize this value as object with initial data, without calling destructor. + void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) { + data_.f.flags = kObjectFlag; + if (count) { + Member* m = static_cast(allocator.Malloc(count * sizeof(Member))); + SetMembersPointer(m); + std::memcpy(m, members, count * sizeof(Member)); + } + else + SetMembersPointer(0); + data_.o.size = data_.o.capacity = count; + } + + //! Initialize this value as constant string, without calling destructor. + void SetStringRaw(StringRefType s) RAPIDJSON_NOEXCEPT { + data_.f.flags = kConstStringFlag; + SetStringPointer(s); + data_.s.length = s.length; + } + + //! Initialize this value as copy string with initial data, without calling destructor. + void SetStringRaw(StringRefType s, Allocator& allocator) { + Ch* str = 0; + if (ShortString::Usable(s.length)) { + data_.f.flags = kShortStringFlag; + data_.ss.SetLength(s.length); + str = data_.ss.str; + } else { + data_.f.flags = kCopyStringFlag; + data_.s.length = s.length; + str = static_cast(allocator.Malloc((s.length + 1) * sizeof(Ch))); + SetStringPointer(str); + } + std::memcpy(str, s, s.length * sizeof(Ch)); + str[s.length] = '\0'; + } + + //! Assignment without calling destructor + void RawAssign(GenericValue& rhs) RAPIDJSON_NOEXCEPT { + data_ = rhs.data_; + // data_.f.flags = rhs.data_.f.flags; + rhs.data_.f.flags = kNullFlag; + } + + template + bool StringEqual(const GenericValue& rhs) const { + RAPIDJSON_ASSERT(IsString()); + RAPIDJSON_ASSERT(rhs.IsString()); + + const SizeType len1 = GetStringLength(); + const SizeType len2 = rhs.GetStringLength(); + if(len1 != len2) { return false; } + + const Ch* const str1 = GetString(); + const Ch* const str2 = rhs.GetString(); + if(str1 == str2) { return true; } // fast path for constant string + + return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0); + } + + Data data_; +}; + +//! GenericValue with UTF8 encoding +typedef GenericValue > Value; + +/////////////////////////////////////////////////////////////////////////////// +// GenericDocument + +//! A document for parsing JSON text as DOM. +/*! + \note implements Handler concept + \tparam Encoding Encoding for both parsing and string storage. + \tparam Allocator Allocator for allocating memory for the DOM + \tparam StackAllocator Allocator for allocating memory for stack during parsing. + \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue. +*/ +template , typename StackAllocator = CrtAllocator> +class GenericDocument : public GenericValue { +public: + typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding. + typedef GenericValue ValueType; //!< Value type of the document. + typedef Allocator AllocatorType; //!< Allocator type from template parameter. + + //! Constructor + /*! Creates an empty document of specified type. + \param type Mandatory type of object to create. + \param allocator Optional allocator for allocating memory. + \param stackCapacity Optional initial capacity of stack in bytes. + \param stackAllocator Optional allocator for allocating memory for stack. + */ + explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : + GenericValue(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() + { + if (!allocator_) + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + } + + //! Constructor + /*! Creates an empty document which type is Null. + \param allocator Optional allocator for allocating memory. + \param stackCapacity Optional initial capacity of stack in bytes. + \param stackAllocator Optional allocator for allocating memory for stack. + */ + GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) : + allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_() + { + if (!allocator_) + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Move constructor in C++11 + GenericDocument(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT + : ValueType(std::forward(rhs)), // explicit cast to avoid prohibited move from Document + allocator_(rhs.allocator_), + ownAllocator_(rhs.ownAllocator_), + stack_(std::move(rhs.stack_)), + parseResult_(rhs.parseResult_) + { + rhs.allocator_ = 0; + rhs.ownAllocator_ = 0; + rhs.parseResult_ = ParseResult(); + } +#endif + + ~GenericDocument() { + Destroy(); + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Move assignment in C++11 + GenericDocument& operator=(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT + { + // The cast to ValueType is necessary here, because otherwise it would + // attempt to call GenericValue's templated assignment operator. + ValueType::operator=(std::forward(rhs)); + + // Calling the destructor here would prematurely call stack_'s destructor + Destroy(); + + allocator_ = rhs.allocator_; + ownAllocator_ = rhs.ownAllocator_; + stack_ = std::move(rhs.stack_); + parseResult_ = rhs.parseResult_; + + rhs.allocator_ = 0; + rhs.ownAllocator_ = 0; + rhs.parseResult_ = ParseResult(); + + return *this; + } +#endif + + //! Exchange the contents of this document with those of another. + /*! + \param rhs Another document. + \note Constant complexity. + \see GenericValue::Swap + */ + GenericDocument& Swap(GenericDocument& rhs) RAPIDJSON_NOEXCEPT { + ValueType::Swap(rhs); + stack_.Swap(rhs.stack_); + internal::Swap(allocator_, rhs.allocator_); + internal::Swap(ownAllocator_, rhs.ownAllocator_); + internal::Swap(parseResult_, rhs.parseResult_); + return *this; + } + + //! free-standing swap function helper + /*! + Helper function to enable support for common swap implementation pattern based on \c std::swap: + \code + void swap(MyClass& a, MyClass& b) { + using std::swap; + swap(a.doc, b.doc); + // ... + } + \endcode + \see Swap() + */ + friend inline void swap(GenericDocument& a, GenericDocument& b) RAPIDJSON_NOEXCEPT { a.Swap(b); } + + //! Populate this document by a generator which produces SAX events. + /*! \tparam Generator A functor with bool f(Handler) prototype. + \param g Generator functor which sends SAX events to the parameter. + \return The document itself for fluent API. + */ + template + GenericDocument& Populate(Generator& g) { + ClearStackOnExit scope(*this); + if (g(*this)) { + RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object + ValueType::operator=(*stack_.template Pop(1));// Move value from stack to document + } + return *this; + } + + //!@name Parse from stream + //!@{ + + //! Parse JSON text from an input stream (with Encoding conversion) + /*! \tparam parseFlags Combination of \ref ParseFlag. + \tparam SourceEncoding Encoding of input stream + \tparam InputStream Type of input stream, implementing Stream concept + \param is Input stream to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseStream(InputStream& is) { + GenericReader reader( + stack_.HasAllocator() ? &stack_.GetAllocator() : 0); + ClearStackOnExit scope(*this); + parseResult_ = reader.template Parse(is, *this); + if (parseResult_) { + RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object + ValueType::operator=(*stack_.template Pop(1));// Move value from stack to document + } + return *this; + } + + //! Parse JSON text from an input stream + /*! \tparam parseFlags Combination of \ref ParseFlag. + \tparam InputStream Type of input stream, implementing Stream concept + \param is Input stream to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseStream(InputStream& is) { + return ParseStream(is); + } + + //! Parse JSON text from an input stream (with \ref kParseDefaultFlags) + /*! \tparam InputStream Type of input stream, implementing Stream concept + \param is Input stream to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseStream(InputStream& is) { + return ParseStream(is); + } + //!@} + + //!@name Parse in-place from mutable string + //!@{ + + //! Parse JSON text from a mutable string + /*! \tparam parseFlags Combination of \ref ParseFlag. + \param str Mutable zero-terminated string to be parsed. + \return The document itself for fluent API. + */ + template + GenericDocument& ParseInsitu(Ch* str) { + GenericInsituStringStream s(str); + return ParseStream(s); + } + + //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags) + /*! \param str Mutable zero-terminated string to be parsed. + \return The document itself for fluent API. + */ + GenericDocument& ParseInsitu(Ch* str) { + return ParseInsitu(str); + } + //!@} + + //!@name Parse from read-only string + //!@{ + + //! Parse JSON text from a read-only string (with Encoding conversion) + /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). + \tparam SourceEncoding Transcoding from input Encoding + \param str Read-only zero-terminated string to be parsed. + */ + template + GenericDocument& Parse(const typename SourceEncoding::Ch* str) { + RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); + GenericStringStream s(str); + return ParseStream(s); + } + + //! Parse JSON text from a read-only string + /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag). + \param str Read-only zero-terminated string to be parsed. + */ + template + GenericDocument& Parse(const Ch* str) { + return Parse(str); + } + + //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags) + /*! \param str Read-only zero-terminated string to be parsed. + */ + GenericDocument& Parse(const Ch* str) { + return Parse(str); + } + + template + GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) { + RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag)); + MemoryStream ms(static_cast(str), length * sizeof(typename SourceEncoding::Ch)); + EncodedInputStream is(ms); + ParseStream(is); + return *this; + } + + template + GenericDocument& Parse(const Ch* str, size_t length) { + return Parse(str, length); + } + + GenericDocument& Parse(const Ch* str, size_t length) { + return Parse(str, length); + } + +#if RAPIDJSON_HAS_STDSTRING + template + GenericDocument& Parse(const std::basic_string& str) { + // c_str() is constant complexity according to standard. Should be faster than Parse(const char*, size_t) + return Parse(str.c_str()); + } + + template + GenericDocument& Parse(const std::basic_string& str) { + return Parse(str.c_str()); + } + + GenericDocument& Parse(const std::basic_string& str) { + return Parse(str); + } +#endif // RAPIDJSON_HAS_STDSTRING + + //!@} + + //!@name Handling parse errors + //!@{ + + //! Whether a parse error has occured in the last parsing. + bool HasParseError() const { return parseResult_.IsError(); } + + //! Get the \ref ParseErrorCode of last parsing. + ParseErrorCode GetParseError() const { return parseResult_.Code(); } + + //! Get the position of last parsing error in input, 0 otherwise. + size_t GetErrorOffset() const { return parseResult_.Offset(); } + + //! Implicit conversion to get the last parse result +#ifndef __clang // -Wdocumentation + /*! \return \ref ParseResult of the last parse operation + + \code + Document doc; + ParseResult ok = doc.Parse(json); + if (!ok) + printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset()); + \endcode + */ +#endif + operator ParseResult() const { return parseResult_; } + //!@} + + //! Get the allocator of this document. + Allocator& GetAllocator() { + RAPIDJSON_ASSERT(allocator_); + return *allocator_; + } + + //! Get the capacity of stack in bytes. + size_t GetStackCapacity() const { return stack_.GetCapacity(); } + +private: + // clear stack on any exit from ParseStream, e.g. due to exception + struct ClearStackOnExit { + explicit ClearStackOnExit(GenericDocument& d) : d_(d) {} + ~ClearStackOnExit() { d_.ClearStack(); } + private: + ClearStackOnExit(const ClearStackOnExit&); + ClearStackOnExit& operator=(const ClearStackOnExit&); + GenericDocument& d_; + }; + + // callers of the following private Handler functions + // template friend class GenericReader; // for parsing + template friend class GenericValue; // for deep copying + +public: + // Implementation of Handler + bool Null() { new (stack_.template Push()) ValueType(); return true; } + bool Bool(bool b) { new (stack_.template Push()) ValueType(b); return true; } + bool Int(int i) { new (stack_.template Push()) ValueType(i); return true; } + bool Uint(unsigned i) { new (stack_.template Push()) ValueType(i); return true; } + bool Int64(int64_t i) { new (stack_.template Push()) ValueType(i); return true; } + bool Uint64(uint64_t i) { new (stack_.template Push()) ValueType(i); return true; } + bool Double(double d) { new (stack_.template Push()) ValueType(d); return true; } + + bool RawNumber(const Ch* str, SizeType length, bool copy) { + if (copy) + new (stack_.template Push()) ValueType(str, length, GetAllocator()); + else + new (stack_.template Push()) ValueType(str, length); + return true; + } + + bool String(const Ch* str, SizeType length, bool copy) { + if (copy) + new (stack_.template Push()) ValueType(str, length, GetAllocator()); + else + new (stack_.template Push()) ValueType(str, length); + return true; + } + + bool StartObject() { new (stack_.template Push()) ValueType(kObjectType); return true; } + + bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); } + + bool EndObject(SizeType memberCount) { + typename ValueType::Member* members = stack_.template Pop(memberCount); + stack_.template Top()->SetObjectRaw(members, memberCount, GetAllocator()); + return true; + } + + bool StartArray() { new (stack_.template Push()) ValueType(kArrayType); return true; } + + bool EndArray(SizeType elementCount) { + ValueType* elements = stack_.template Pop(elementCount); + stack_.template Top()->SetArrayRaw(elements, elementCount, GetAllocator()); + return true; + } + +private: + //! Prohibit copying + GenericDocument(const GenericDocument&); + //! Prohibit assignment + GenericDocument& operator=(const GenericDocument&); + + void ClearStack() { + if (Allocator::kNeedFree) + while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects) + (stack_.template Pop(1))->~ValueType(); + else + stack_.Clear(); + stack_.ShrinkToFit(); + } + + void Destroy() { + RAPIDJSON_DELETE(ownAllocator_); + } + + static const size_t kDefaultStackCapacity = 1024; + Allocator* allocator_; + Allocator* ownAllocator_; + internal::Stack stack_; + ParseResult parseResult_; +}; + +//! GenericDocument with UTF8 encoding +typedef GenericDocument > Document; + +// defined here due to the dependency on GenericDocument +template +template +inline +GenericValue::GenericValue(const GenericValue& rhs, Allocator& allocator) +{ + switch (rhs.GetType()) { + case kObjectType: + case kArrayType: { // perform deep copy via SAX Handler + GenericDocument d(&allocator); + rhs.Accept(d); + RawAssign(*d.stack_.template Pop(1)); + } + break; + case kStringType: + if (rhs.data_.f.flags == kConstStringFlag) { + data_.f.flags = rhs.data_.f.flags; + data_ = *reinterpret_cast(&rhs.data_); + } else { + SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator); + } + break; + default: + data_.f.flags = rhs.data_.f.flags; + data_ = *reinterpret_cast(&rhs.data_); + break; + } +} + +//! Helper class for accessing Value of array type. +/*! + Instance of this helper class is obtained by \c GenericValue::GetArray(). + In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. +*/ +template +class GenericArray { +public: + typedef GenericArray ConstArray; + typedef GenericArray Array; + typedef ValueT PlainType; + typedef typename internal::MaybeAddConst::Type ValueType; + typedef ValueType* ValueIterator; // This may be const or non-const iterator + typedef const ValueT* ConstValueIterator; + typedef typename ValueType::AllocatorType AllocatorType; + typedef typename ValueType::StringRefType StringRefType; + + template + friend class GenericValue; + + GenericArray(const GenericArray& rhs) : value_(rhs.value_) {} + GenericArray& operator=(const GenericArray& rhs) { value_ = rhs.value_; return *this; } + ~GenericArray() {} + + SizeType Size() const { return value_.Size(); } + SizeType Capacity() const { return value_.Capacity(); } + bool Empty() const { return value_.Empty(); } + void Clear() const { value_.Clear(); } + ValueType& operator[](SizeType index) const { return value_[index]; } + ValueIterator Begin() const { return value_.Begin(); } + ValueIterator End() const { return value_.End(); } + GenericArray Reserve(SizeType newCapacity, AllocatorType &allocator) const { value_.Reserve(newCapacity, allocator); return *this; } + GenericArray PushBack(ValueType& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericArray PushBack(ValueType&& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericArray PushBack(StringRefType value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } + template RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (const GenericArray&)) PushBack(T value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; } + GenericArray PopBack() const { value_.PopBack(); return *this; } + ValueIterator Erase(ConstValueIterator pos) const { return value_.Erase(pos); } + ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) const { return value_.Erase(first, last); } + +#if RAPIDJSON_HAS_CXX11_RANGE_FOR + ValueIterator begin() const { return value_.Begin(); } + ValueIterator end() const { return value_.End(); } +#endif + +private: + GenericArray(); + GenericArray(ValueType& value) : value_(value) {} + ValueType& value_; +}; + +//! Helper class for accessing Value of object type. +/*! + Instance of this helper class is obtained by \c GenericValue::GetObject(). + In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1. +*/ +template +class GenericObject { +public: + typedef GenericObject ConstObject; + typedef GenericObject Object; + typedef ValueT PlainType; + typedef typename internal::MaybeAddConst::Type ValueType; + typedef GenericMemberIterator MemberIterator; // This may be const or non-const iterator + typedef GenericMemberIterator ConstMemberIterator; + typedef typename ValueType::AllocatorType AllocatorType; + typedef typename ValueType::StringRefType StringRefType; + typedef typename ValueType::EncodingType EncodingType; + typedef typename ValueType::Ch Ch; + + template + friend class GenericValue; + + GenericObject(const GenericObject& rhs) : value_(rhs.value_) {} + GenericObject& operator=(const GenericObject& rhs) { value_ = rhs.value_; return *this; } + ~GenericObject() {} + + SizeType MemberCount() const { return value_.MemberCount(); } + bool ObjectEmpty() const { return value_.ObjectEmpty(); } + template ValueType& operator[](T* name) const { return value_[name]; } + template ValueType& operator[](const GenericValue& name) const { return value_[name]; } +#if RAPIDJSON_HAS_STDSTRING + ValueType& operator[](const std::basic_string& name) const { return value_[name]; } +#endif + MemberIterator MemberBegin() const { return value_.MemberBegin(); } + MemberIterator MemberEnd() const { return value_.MemberEnd(); } + bool HasMember(const Ch* name) const { return value_.HasMember(name); } +#if RAPIDJSON_HAS_STDSTRING + bool HasMember(const std::basic_string& name) const { return value_.HasMember(name); } +#endif + template bool HasMember(const GenericValue& name) const { return value_.HasMember(name); } + MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); } + template MemberIterator FindMember(const GenericValue& name) const { return value_.FindMember(name); } +#if RAPIDJSON_HAS_STDSTRING + MemberIterator FindMember(const std::basic_string& name) const { return value_.FindMember(name); } +#endif + GenericObject AddMember(ValueType& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + GenericObject AddMember(ValueType& name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } +#if RAPIDJSON_HAS_STDSTRING + GenericObject AddMember(ValueType& name, std::basic_string& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } +#endif + template RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) AddMember(ValueType& name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericObject AddMember(ValueType&& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + GenericObject AddMember(ValueType&& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + GenericObject AddMember(ValueType& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + GenericObject AddMember(StringRefType name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + template RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; } + void RemoveAllMembers() { return value_.RemoveAllMembers(); } + bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); } +#if RAPIDJSON_HAS_STDSTRING + bool RemoveMember(const std::basic_string& name) const { return value_.RemoveMember(name); } +#endif + template bool RemoveMember(const GenericValue& name) const { return value_.RemoveMember(name); } + MemberIterator RemoveMember(MemberIterator m) const { return value_.RemoveMember(m); } + MemberIterator EraseMember(ConstMemberIterator pos) const { return value_.EraseMember(pos); } + MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) const { return value_.EraseMember(first, last); } + bool EraseMember(const Ch* name) const { return value_.EraseMember(name); } +#if RAPIDJSON_HAS_STDSTRING + bool EraseMember(const std::basic_string& name) const { return EraseMember(ValueType(StringRef(name))); } +#endif + template bool EraseMember(const GenericValue& name) const { return value_.EraseMember(name); } + +#if RAPIDJSON_HAS_CXX11_RANGE_FOR + MemberIterator begin() const { return value_.MemberBegin(); } + MemberIterator end() const { return value_.MemberEnd(); } +#endif + +private: + GenericObject(); + GenericObject(ValueType& value) : value_(value) {} + ValueType& value_; +}; + +RAPIDJSON_NAMESPACE_END +RAPIDJSON_DIAG_POP + +#endif // RAPIDJSON_DOCUMENT_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/encodedstream.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/encodedstream.h new file mode 100644 index 0000000000..145068386a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/encodedstream.h @@ -0,0 +1,299 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ENCODEDSTREAM_H_ +#define RAPIDJSON_ENCODEDSTREAM_H_ + +#include "stream.h" +#include "memorystream.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Input byte stream wrapper with a statically bound encoding. +/*! + \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE. + \tparam InputByteStream Type of input byte stream. For example, FileReadStream. +*/ +template +class EncodedInputStream { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); +public: + typedef typename Encoding::Ch Ch; + + EncodedInputStream(InputByteStream& is) : is_(is) { + current_ = Encoding::TakeBOM(is_); + } + + Ch Peek() const { return current_; } + Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; } + size_t Tell() const { return is_.Tell(); } + + // Not implemented + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + EncodedInputStream(const EncodedInputStream&); + EncodedInputStream& operator=(const EncodedInputStream&); + + InputByteStream& is_; + Ch current_; +}; + +//! Specialized for UTF8 MemoryStream. +template <> +class EncodedInputStream, MemoryStream> { +public: + typedef UTF8<>::Ch Ch; + + EncodedInputStream(MemoryStream& is) : is_(is) { + if (static_cast(is_.Peek()) == 0xEFu) is_.Take(); + if (static_cast(is_.Peek()) == 0xBBu) is_.Take(); + if (static_cast(is_.Peek()) == 0xBFu) is_.Take(); + } + Ch Peek() const { return is_.Peek(); } + Ch Take() { return is_.Take(); } + size_t Tell() const { return is_.Tell(); } + + // Not implemented + void Put(Ch) {} + void Flush() {} + Ch* PutBegin() { return 0; } + size_t PutEnd(Ch*) { return 0; } + + MemoryStream& is_; + +private: + EncodedInputStream(const EncodedInputStream&); + EncodedInputStream& operator=(const EncodedInputStream&); +}; + +//! Output byte stream wrapper with statically bound encoding. +/*! + \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE. + \tparam OutputByteStream Type of input byte stream. For example, FileWriteStream. +*/ +template +class EncodedOutputStream { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); +public: + typedef typename Encoding::Ch Ch; + + EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) { + if (putBOM) + Encoding::PutBOM(os_); + } + + void Put(Ch c) { Encoding::Put(os_, c); } + void Flush() { os_.Flush(); } + + // Not implemented + Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;} + Ch Take() { RAPIDJSON_ASSERT(false); return 0;} + size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + EncodedOutputStream(const EncodedOutputStream&); + EncodedOutputStream& operator=(const EncodedOutputStream&); + + OutputByteStream& os_; +}; + +#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x + +//! Input stream wrapper with dynamically bound encoding and automatic encoding detection. +/*! + \tparam CharType Type of character for reading. + \tparam InputByteStream type of input byte stream to be wrapped. +*/ +template +class AutoUTFInputStream { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); +public: + typedef CharType Ch; + + //! Constructor. + /*! + \param is input stream to be wrapped. + \param type UTF encoding type if it is not detected from the stream. + */ + AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) { + RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE); + DetectType(); + static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) }; + takeFunc_ = f[type_]; + current_ = takeFunc_(*is_); + } + + UTFType GetType() const { return type_; } + bool HasBOM() const { return hasBOM_; } + + Ch Peek() const { return current_; } + Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; } + size_t Tell() const { return is_->Tell(); } + + // Not implemented + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + AutoUTFInputStream(const AutoUTFInputStream&); + AutoUTFInputStream& operator=(const AutoUTFInputStream&); + + // Detect encoding type with BOM or RFC 4627 + void DetectType() { + // BOM (Byte Order Mark): + // 00 00 FE FF UTF-32BE + // FF FE 00 00 UTF-32LE + // FE FF UTF-16BE + // FF FE UTF-16LE + // EF BB BF UTF-8 + + const unsigned char* c = reinterpret_cast(is_->Peek4()); + if (!c) + return; + + unsigned bom = static_cast(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24)); + hasBOM_ = false; + if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } + else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } + else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); } + else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); } + else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); } + + // RFC 4627: Section 3 + // "Since the first two characters of a JSON text will always be ASCII + // characters [RFC0020], it is possible to determine whether an octet + // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking + // at the pattern of nulls in the first four octets." + // 00 00 00 xx UTF-32BE + // 00 xx 00 xx UTF-16BE + // xx 00 00 00 UTF-32LE + // xx 00 xx 00 UTF-16LE + // xx xx xx xx UTF-8 + + if (!hasBOM_) { + unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); + switch (pattern) { + case 0x08: type_ = kUTF32BE; break; + case 0x0A: type_ = kUTF16BE; break; + case 0x01: type_ = kUTF32LE; break; + case 0x05: type_ = kUTF16LE; break; + case 0x0F: type_ = kUTF8; break; + default: break; // Use type defined by user. + } + } + + // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. + if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2); + if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4); + } + + typedef Ch (*TakeFunc)(InputByteStream& is); + InputByteStream* is_; + UTFType type_; + Ch current_; + TakeFunc takeFunc_; + bool hasBOM_; +}; + +//! Output stream wrapper with dynamically bound encoding and automatic encoding detection. +/*! + \tparam CharType Type of character for writing. + \tparam OutputByteStream type of output byte stream to be wrapped. +*/ +template +class AutoUTFOutputStream { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); +public: + typedef CharType Ch; + + //! Constructor. + /*! + \param os output stream to be wrapped. + \param type UTF encoding type. + \param putBOM Whether to write BOM at the beginning of the stream. + */ + AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) { + RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE); + + // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. + if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2); + if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4); + + static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) }; + putFunc_ = f[type_]; + + if (putBOM) + PutBOM(); + } + + UTFType GetType() const { return type_; } + + void Put(Ch c) { putFunc_(*os_, c); } + void Flush() { os_->Flush(); } + + // Not implemented + Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;} + Ch Take() { RAPIDJSON_ASSERT(false); return 0;} + size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + AutoUTFOutputStream(const AutoUTFOutputStream&); + AutoUTFOutputStream& operator=(const AutoUTFOutputStream&); + + void PutBOM() { + typedef void (*PutBOMFunc)(OutputByteStream&); + static const PutBOMFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(PutBOM) }; + f[type_](*os_); + } + + typedef void (*PutFunc)(OutputByteStream&, Ch); + + OutputByteStream* os_; + UTFType type_; + PutFunc putFunc_; +}; + +#undef RAPIDJSON_ENCODINGS_FUNC + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/encodings.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/encodings.h new file mode 100644 index 0000000000..baa7c2b17f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/encodings.h @@ -0,0 +1,716 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ENCODINGS_H_ +#define RAPIDJSON_ENCODINGS_H_ + +#include "rapidjson.h" + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data +RAPIDJSON_DIAG_OFF(4702) // unreachable code +#elif defined(__GNUC__) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +RAPIDJSON_DIAG_OFF(overflow) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// Encoding + +/*! \class rapidjson::Encoding + \brief Concept for encoding of Unicode characters. + +\code +concept Encoding { + typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition. + + enum { supportUnicode = 1 }; // or 0 if not supporting unicode + + //! \brief Encode a Unicode codepoint to an output stream. + //! \param os Output stream. + //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively. + template + static void Encode(OutputStream& os, unsigned codepoint); + + //! \brief Decode a Unicode codepoint from an input stream. + //! \param is Input stream. + //! \param codepoint Output of the unicode codepoint. + //! \return true if a valid codepoint can be decoded from the stream. + template + static bool Decode(InputStream& is, unsigned* codepoint); + + //! \brief Validate one Unicode codepoint from an encoded stream. + //! \param is Input stream to obtain codepoint. + //! \param os Output for copying one codepoint. + //! \return true if it is valid. + //! \note This function just validating and copying the codepoint without actually decode it. + template + static bool Validate(InputStream& is, OutputStream& os); + + // The following functions are deal with byte streams. + + //! Take a character from input byte stream, skip BOM if exist. + template + static CharType TakeBOM(InputByteStream& is); + + //! Take a character from input byte stream. + template + static Ch Take(InputByteStream& is); + + //! Put BOM to output byte stream. + template + static void PutBOM(OutputByteStream& os); + + //! Put a character to output byte stream. + template + static void Put(OutputByteStream& os, Ch c); +}; +\endcode +*/ + +/////////////////////////////////////////////////////////////////////////////// +// UTF8 + +//! UTF-8 encoding. +/*! http://en.wikipedia.org/wiki/UTF-8 + http://tools.ietf.org/html/rfc3629 + \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char. + \note implements Encoding concept +*/ +template +struct UTF8 { + typedef CharType Ch; + + enum { supportUnicode = 1 }; + + template + static void Encode(OutputStream& os, unsigned codepoint) { + if (codepoint <= 0x7F) + os.Put(static_cast(codepoint & 0xFF)); + else if (codepoint <= 0x7FF) { + os.Put(static_cast(0xC0 | ((codepoint >> 6) & 0xFF))); + os.Put(static_cast(0x80 | ((codepoint & 0x3F)))); + } + else if (codepoint <= 0xFFFF) { + os.Put(static_cast(0xE0 | ((codepoint >> 12) & 0xFF))); + os.Put(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + os.Put(static_cast(0x80 | (codepoint & 0x3F))); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + os.Put(static_cast(0xF0 | ((codepoint >> 18) & 0xFF))); + os.Put(static_cast(0x80 | ((codepoint >> 12) & 0x3F))); + os.Put(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + os.Put(static_cast(0x80 | (codepoint & 0x3F))); + } + } + + template + static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { + if (codepoint <= 0x7F) + PutUnsafe(os, static_cast(codepoint & 0xFF)); + else if (codepoint <= 0x7FF) { + PutUnsafe(os, static_cast(0xC0 | ((codepoint >> 6) & 0xFF))); + PutUnsafe(os, static_cast(0x80 | ((codepoint & 0x3F)))); + } + else if (codepoint <= 0xFFFF) { + PutUnsafe(os, static_cast(0xE0 | ((codepoint >> 12) & 0xFF))); + PutUnsafe(os, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + PutUnsafe(os, static_cast(0x80 | (codepoint & 0x3F))); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + PutUnsafe(os, static_cast(0xF0 | ((codepoint >> 18) & 0xFF))); + PutUnsafe(os, static_cast(0x80 | ((codepoint >> 12) & 0x3F))); + PutUnsafe(os, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + PutUnsafe(os, static_cast(0x80 | (codepoint & 0x3F))); + } + } + + template + static bool Decode(InputStream& is, unsigned* codepoint) { +#define COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast(c) & 0x3Fu) +#define TRANS(mask) result &= ((GetRange(static_cast(c)) & mask) != 0) +#define TAIL() COPY(); TRANS(0x70) + typename InputStream::Ch c = is.Take(); + if (!(c & 0x80)) { + *codepoint = static_cast(c); + return true; + } + + unsigned char type = GetRange(static_cast(c)); + if (type >= 32) { + *codepoint = 0; + } else { + *codepoint = (0xFF >> type) & static_cast(c); + } + bool result = true; + switch (type) { + case 2: TAIL(); return result; + case 3: TAIL(); TAIL(); return result; + case 4: COPY(); TRANS(0x50); TAIL(); return result; + case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result; + case 6: TAIL(); TAIL(); TAIL(); return result; + case 10: COPY(); TRANS(0x20); TAIL(); return result; + case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result; + default: return false; + } +#undef COPY +#undef TRANS +#undef TAIL + } + + template + static bool Validate(InputStream& is, OutputStream& os) { +#define COPY() os.Put(c = is.Take()) +#define TRANS(mask) result &= ((GetRange(static_cast(c)) & mask) != 0) +#define TAIL() COPY(); TRANS(0x70) + Ch c; + COPY(); + if (!(c & 0x80)) + return true; + + bool result = true; + switch (GetRange(static_cast(c))) { + case 2: TAIL(); return result; + case 3: TAIL(); TAIL(); return result; + case 4: COPY(); TRANS(0x50); TAIL(); return result; + case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result; + case 6: TAIL(); TAIL(); TAIL(); return result; + case 10: COPY(); TRANS(0x20); TAIL(); return result; + case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result; + default: return false; + } +#undef COPY +#undef TRANS +#undef TAIL + } + + static unsigned char GetRange(unsigned char c) { + // Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + // With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types. + static const unsigned char type[] = { + 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, + 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, + 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, + 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, + 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, + 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, + 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, + 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, + 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, + 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, + }; + return type[c]; + } + + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + typename InputByteStream::Ch c = Take(is); + if (static_cast(c) != 0xEFu) return c; + c = is.Take(); + if (static_cast(c) != 0xBBu) return c; + c = is.Take(); + if (static_cast(c) != 0xBFu) return c; + c = is.Take(); + return c; + } + + template + static Ch Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + return static_cast(is.Take()); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(0xEFu)); + os.Put(static_cast(0xBBu)); + os.Put(static_cast(0xBFu)); + } + + template + static void Put(OutputByteStream& os, Ch c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(c)); + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// UTF16 + +//! UTF-16 encoding. +/*! http://en.wikipedia.org/wiki/UTF-16 + http://tools.ietf.org/html/rfc2781 + \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead. + \note implements Encoding concept + + \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. + For streaming, use UTF16LE and UTF16BE, which handle endianness. +*/ +template +struct UTF16 { + typedef CharType Ch; + RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2); + + enum { supportUnicode = 1 }; + + template + static void Encode(OutputStream& os, unsigned codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); + if (codepoint <= 0xFFFF) { + RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair + os.Put(static_cast(codepoint)); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + unsigned v = codepoint - 0x10000; + os.Put(static_cast((v >> 10) | 0xD800)); + os.Put((v & 0x3FF) | 0xDC00); + } + } + + + template + static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); + if (codepoint <= 0xFFFF) { + RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair + PutUnsafe(os, static_cast(codepoint)); + } + else { + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + unsigned v = codepoint - 0x10000; + PutUnsafe(os, static_cast((v >> 10) | 0xD800)); + PutUnsafe(os, (v & 0x3FF) | 0xDC00); + } + } + + template + static bool Decode(InputStream& is, unsigned* codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); + typename InputStream::Ch c = is.Take(); + if (c < 0xD800 || c > 0xDFFF) { + *codepoint = static_cast(c); + return true; + } + else if (c <= 0xDBFF) { + *codepoint = (static_cast(c) & 0x3FF) << 10; + c = is.Take(); + *codepoint |= (static_cast(c) & 0x3FF); + *codepoint += 0x10000; + return c >= 0xDC00 && c <= 0xDFFF; + } + return false; + } + + template + static bool Validate(InputStream& is, OutputStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2); + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2); + typename InputStream::Ch c; + os.Put(static_cast(c = is.Take())); + if (c < 0xD800 || c > 0xDFFF) + return true; + else if (c <= 0xDBFF) { + os.Put(c = is.Take()); + return c >= 0xDC00 && c <= 0xDFFF; + } + return false; + } +}; + +//! UTF-16 little endian encoding. +template +struct UTF16LE : UTF16 { + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + CharType c = Take(is); + return static_cast(c) == 0xFEFFu ? Take(is) : c; + } + + template + static CharType Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + unsigned c = static_cast(is.Take()); + c |= static_cast(static_cast(is.Take())) << 8; + return static_cast(c); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(0xFFu)); + os.Put(static_cast(0xFEu)); + } + + template + static void Put(OutputByteStream& os, CharType c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(static_cast(c) & 0xFFu)); + os.Put(static_cast((static_cast(c) >> 8) & 0xFFu)); + } +}; + +//! UTF-16 big endian encoding. +template +struct UTF16BE : UTF16 { + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + CharType c = Take(is); + return static_cast(c) == 0xFEFFu ? Take(is) : c; + } + + template + static CharType Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + unsigned c = static_cast(static_cast(is.Take())) << 8; + c |= static_cast(is.Take()); + return static_cast(c); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(0xFEu)); + os.Put(static_cast(0xFFu)); + } + + template + static void Put(OutputByteStream& os, CharType c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast((static_cast(c) >> 8) & 0xFFu)); + os.Put(static_cast(static_cast(c) & 0xFFu)); + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// UTF32 + +//! UTF-32 encoding. +/*! http://en.wikipedia.org/wiki/UTF-32 + \tparam CharType Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead. + \note implements Encoding concept + + \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness. + For streaming, use UTF32LE and UTF32BE, which handle endianness. +*/ +template +struct UTF32 { + typedef CharType Ch; + RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4); + + enum { supportUnicode = 1 }; + + template + static void Encode(OutputStream& os, unsigned codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + os.Put(codepoint); + } + + template + static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4); + RAPIDJSON_ASSERT(codepoint <= 0x10FFFF); + PutUnsafe(os, codepoint); + } + + template + static bool Decode(InputStream& is, unsigned* codepoint) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); + Ch c = is.Take(); + *codepoint = c; + return c <= 0x10FFFF; + } + + template + static bool Validate(InputStream& is, OutputStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4); + Ch c; + os.Put(c = is.Take()); + return c <= 0x10FFFF; + } +}; + +//! UTF-32 little endian enocoding. +template +struct UTF32LE : UTF32 { + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + CharType c = Take(is); + return static_cast(c) == 0x0000FEFFu ? Take(is) : c; + } + + template + static CharType Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + unsigned c = static_cast(is.Take()); + c |= static_cast(static_cast(is.Take())) << 8; + c |= static_cast(static_cast(is.Take())) << 16; + c |= static_cast(static_cast(is.Take())) << 24; + return static_cast(c); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(0xFFu)); + os.Put(static_cast(0xFEu)); + os.Put(static_cast(0x00u)); + os.Put(static_cast(0x00u)); + } + + template + static void Put(OutputByteStream& os, CharType c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(c & 0xFFu)); + os.Put(static_cast((c >> 8) & 0xFFu)); + os.Put(static_cast((c >> 16) & 0xFFu)); + os.Put(static_cast((c >> 24) & 0xFFu)); + } +}; + +//! UTF-32 big endian encoding. +template +struct UTF32BE : UTF32 { + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + CharType c = Take(is); + return static_cast(c) == 0x0000FEFFu ? Take(is) : c; + } + + template + static CharType Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + unsigned c = static_cast(static_cast(is.Take())) << 24; + c |= static_cast(static_cast(is.Take())) << 16; + c |= static_cast(static_cast(is.Take())) << 8; + c |= static_cast(static_cast(is.Take())); + return static_cast(c); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(0x00u)); + os.Put(static_cast(0x00u)); + os.Put(static_cast(0xFEu)); + os.Put(static_cast(0xFFu)); + } + + template + static void Put(OutputByteStream& os, CharType c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast((c >> 24) & 0xFFu)); + os.Put(static_cast((c >> 16) & 0xFFu)); + os.Put(static_cast((c >> 8) & 0xFFu)); + os.Put(static_cast(c & 0xFFu)); + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// ASCII + +//! ASCII encoding. +/*! http://en.wikipedia.org/wiki/ASCII + \tparam CharType Code unit for storing 7-bit ASCII data. Default is char. + \note implements Encoding concept +*/ +template +struct ASCII { + typedef CharType Ch; + + enum { supportUnicode = 0 }; + + template + static void Encode(OutputStream& os, unsigned codepoint) { + RAPIDJSON_ASSERT(codepoint <= 0x7F); + os.Put(static_cast(codepoint & 0xFF)); + } + + template + static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { + RAPIDJSON_ASSERT(codepoint <= 0x7F); + PutUnsafe(os, static_cast(codepoint & 0xFF)); + } + + template + static bool Decode(InputStream& is, unsigned* codepoint) { + uint8_t c = static_cast(is.Take()); + *codepoint = c; + return c <= 0X7F; + } + + template + static bool Validate(InputStream& is, OutputStream& os) { + uint8_t c = static_cast(is.Take()); + os.Put(static_cast(c)); + return c <= 0x7F; + } + + template + static CharType TakeBOM(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + uint8_t c = static_cast(Take(is)); + return static_cast(c); + } + + template + static Ch Take(InputByteStream& is) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1); + return static_cast(is.Take()); + } + + template + static void PutBOM(OutputByteStream& os) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + (void)os; + } + + template + static void Put(OutputByteStream& os, Ch c) { + RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1); + os.Put(static_cast(c)); + } +}; + +/////////////////////////////////////////////////////////////////////////////// +// AutoUTF + +//! Runtime-specified UTF encoding type of a stream. +enum UTFType { + kUTF8 = 0, //!< UTF-8. + kUTF16LE = 1, //!< UTF-16 little endian. + kUTF16BE = 2, //!< UTF-16 big endian. + kUTF32LE = 3, //!< UTF-32 little endian. + kUTF32BE = 4 //!< UTF-32 big endian. +}; + +//! Dynamically select encoding according to stream's runtime-specified UTF encoding type. +/*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType(). +*/ +template +struct AutoUTF { + typedef CharType Ch; + + enum { supportUnicode = 1 }; + +#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8::x, UTF16LE::x, UTF16BE::x, UTF32LE::x, UTF32BE::x + + template + RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) { + typedef void (*EncodeFunc)(OutputStream&, unsigned); + static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Encode) }; + (*f[os.GetType()])(os, codepoint); + } + + template + RAPIDJSON_FORCEINLINE static void EncodeUnsafe(OutputStream& os, unsigned codepoint) { + typedef void (*EncodeFunc)(OutputStream&, unsigned); + static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(EncodeUnsafe) }; + (*f[os.GetType()])(os, codepoint); + } + + template + RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) { + typedef bool (*DecodeFunc)(InputStream&, unsigned*); + static const DecodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Decode) }; + return (*f[is.GetType()])(is, codepoint); + } + + template + RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { + typedef bool (*ValidateFunc)(InputStream&, OutputStream&); + static const ValidateFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Validate) }; + return (*f[is.GetType()])(is, os); + } + +#undef RAPIDJSON_ENCODINGS_FUNC +}; + +/////////////////////////////////////////////////////////////////////////////// +// Transcoder + +//! Encoding conversion. +template +struct Transcoder { + //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream. + template + RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) { + unsigned codepoint; + if (!SourceEncoding::Decode(is, &codepoint)) + return false; + TargetEncoding::Encode(os, codepoint); + return true; + } + + template + RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) { + unsigned codepoint; + if (!SourceEncoding::Decode(is, &codepoint)) + return false; + TargetEncoding::EncodeUnsafe(os, codepoint); + return true; + } + + //! Validate one Unicode codepoint from an encoded stream. + template + RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { + return Transcode(is, os); // Since source/target encoding is different, must transcode. + } +}; + +// Forward declaration. +template +inline void PutUnsafe(Stream& stream, typename Stream::Ch c); + +//! Specialization of Transcoder with same source and target encoding. +template +struct Transcoder { + template + RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) { + os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class. + return true; + } + + template + RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) { + PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is different from primary template class. + return true; + } + + template + RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) { + return Encoding::Validate(is, os); // source/target encoding are the same + } +}; + +RAPIDJSON_NAMESPACE_END + +#if defined(__GNUC__) || defined(_MSC_VER) +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_ENCODINGS_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/error/en.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/error/en.h new file mode 100644 index 0000000000..2db838bff2 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/error/en.h @@ -0,0 +1,74 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ERROR_EN_H_ +#define RAPIDJSON_ERROR_EN_H_ + +#include "error.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(switch-enum) +RAPIDJSON_DIAG_OFF(covered-switch-default) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Maps error code of parsing into error message. +/*! + \ingroup RAPIDJSON_ERRORS + \param parseErrorCode Error code obtained in parsing. + \return the error message. + \note User can make a copy of this function for localization. + Using switch-case is safer for future modification of error codes. +*/ +inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) { + switch (parseErrorCode) { + case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error."); + + case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty."); + case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values."); + + case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value."); + + case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member."); + case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member."); + case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member."); + + case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element."); + + case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string."); + case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid."); + case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string."); + case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string."); + case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string."); + + case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double."); + case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number."); + case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number."); + + case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error."); + case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error."); + + default: return RAPIDJSON_ERROR_STRING("Unknown error."); + } +} + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_ERROR_EN_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/error/error.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/error/error.h new file mode 100644 index 0000000000..95cb31a72f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/error/error.h @@ -0,0 +1,155 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ERROR_ERROR_H_ +#define RAPIDJSON_ERROR_ERROR_H_ + +#include "../rapidjson.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +#endif + +/*! \file error.h */ + +/*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */ + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ERROR_CHARTYPE + +//! Character type of error messages. +/*! \ingroup RAPIDJSON_ERRORS + The default character type is \c char. + On Windows, user can define this macro as \c TCHAR for supporting both + unicode/non-unicode settings. +*/ +#ifndef RAPIDJSON_ERROR_CHARTYPE +#define RAPIDJSON_ERROR_CHARTYPE char +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ERROR_STRING + +//! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[]. +/*! \ingroup RAPIDJSON_ERRORS + By default this conversion macro does nothing. + On Windows, user can define this macro as \c _T(x) for supporting both + unicode/non-unicode settings. +*/ +#ifndef RAPIDJSON_ERROR_STRING +#define RAPIDJSON_ERROR_STRING(x) x +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// ParseErrorCode + +//! Error code of parsing. +/*! \ingroup RAPIDJSON_ERRORS + \see GenericReader::Parse, GenericReader::GetParseErrorCode +*/ +enum ParseErrorCode { + kParseErrorNone = 0, //!< No error. + + kParseErrorDocumentEmpty, //!< The document is empty. + kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values. + + kParseErrorValueInvalid, //!< Invalid value. + + kParseErrorObjectMissName, //!< Missing a name for object member. + kParseErrorObjectMissColon, //!< Missing a colon after a name of object member. + kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member. + + kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element. + + kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string. + kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid. + kParseErrorStringEscapeInvalid, //!< Invalid escape character in string. + kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string. + kParseErrorStringInvalidEncoding, //!< Invalid encoding in string. + + kParseErrorNumberTooBig, //!< Number too big to be stored in double. + kParseErrorNumberMissFraction, //!< Miss fraction part in number. + kParseErrorNumberMissExponent, //!< Miss exponent in number. + + kParseErrorTermination, //!< Parsing was terminated. + kParseErrorUnspecificSyntaxError //!< Unspecific syntax error. +}; + +//! Result of parsing (wraps ParseErrorCode) +/*! + \ingroup RAPIDJSON_ERRORS + \code + Document doc; + ParseResult ok = doc.Parse("[42]"); + if (!ok) { + fprintf(stderr, "JSON parse error: %s (%u)", + GetParseError_En(ok.Code()), ok.Offset()); + exit(EXIT_FAILURE); + } + \endcode + \see GenericReader::Parse, GenericDocument::Parse +*/ +struct ParseResult { +public: + //! Default constructor, no error. + ParseResult() : code_(kParseErrorNone), offset_(0) {} + //! Constructor to set an error. + ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {} + + //! Get the error code. + ParseErrorCode Code() const { return code_; } + //! Get the error offset, if \ref IsError(), 0 otherwise. + size_t Offset() const { return offset_; } + + //! Conversion to \c bool, returns \c true, iff !\ref IsError(). + operator bool() const { return !IsError(); } + //! Whether the result is an error. + bool IsError() const { return code_ != kParseErrorNone; } + + bool operator==(const ParseResult& that) const { return code_ == that.code_; } + bool operator==(ParseErrorCode code) const { return code_ == code; } + friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; } + + //! Reset error code. + void Clear() { Set(kParseErrorNone); } + //! Update error code and offset. + void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; } + +private: + ParseErrorCode code_; + size_t offset_; +}; + +//! Function pointer type of GetParseError(). +/*! \ingroup RAPIDJSON_ERRORS + + This is the prototype for \c GetParseError_X(), where \c X is a locale. + User can dynamically change locale in runtime, e.g.: +\code + GetParseErrorFunc GetParseError = GetParseError_En; // or whatever + const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode()); +\endcode +*/ +typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode); + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_ERROR_ERROR_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/filereadstream.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/filereadstream.h new file mode 100644 index 0000000000..b56ea13b34 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/filereadstream.h @@ -0,0 +1,99 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_FILEREADSTREAM_H_ +#define RAPIDJSON_FILEREADSTREAM_H_ + +#include "stream.h" +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +RAPIDJSON_DIAG_OFF(unreachable-code) +RAPIDJSON_DIAG_OFF(missing-noreturn) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! File byte stream for input using fread(). +/*! + \note implements Stream concept +*/ +class FileReadStream { +public: + typedef char Ch; //!< Character type (byte). + + //! Constructor. + /*! + \param fp File pointer opened for read. + \param buffer user-supplied buffer. + \param bufferSize size of buffer in bytes. Must >=4 bytes. + */ + FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) { + RAPIDJSON_ASSERT(fp_ != 0); + RAPIDJSON_ASSERT(bufferSize >= 4); + Read(); + } + + Ch Peek() const { return *current_; } + Ch Take() { Ch c = *current_; Read(); return c; } + size_t Tell() const { return count_ + static_cast(current_ - buffer_); } + + // Not implemented + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + + // For encoding detection only. + const Ch* Peek4() const { + return (current_ + 4 <= bufferLast_) ? current_ : 0; + } + +private: + void Read() { + if (current_ < bufferLast_) + ++current_; + else if (!eof_) { + count_ += readCount_; + readCount_ = fread(buffer_, 1, bufferSize_, fp_); + bufferLast_ = buffer_ + readCount_ - 1; + current_ = buffer_; + + if (readCount_ < bufferSize_) { + buffer_[readCount_] = '\0'; + ++bufferLast_; + eof_ = true; + } + } + } + + std::FILE* fp_; + Ch *buffer_; + size_t bufferSize_; + Ch *bufferLast_; + Ch *current_; + size_t readCount_; + size_t count_; //!< Number of characters read + bool eof_; +}; + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/filewritestream.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/filewritestream.h new file mode 100644 index 0000000000..6378dd60ed --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/filewritestream.h @@ -0,0 +1,104 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_FILEWRITESTREAM_H_ +#define RAPIDJSON_FILEWRITESTREAM_H_ + +#include "stream.h" +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(unreachable-code) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Wrapper of C file stream for input using fread(). +/*! + \note implements Stream concept +*/ +class FileWriteStream { +public: + typedef char Ch; //!< Character type. Only support char. + + FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { + RAPIDJSON_ASSERT(fp_ != 0); + } + + void Put(char c) { + if (current_ >= bufferEnd_) + Flush(); + + *current_++ = c; + } + + void PutN(char c, size_t n) { + size_t avail = static_cast(bufferEnd_ - current_); + while (n > avail) { + std::memset(current_, c, avail); + current_ += avail; + Flush(); + n -= avail; + avail = static_cast(bufferEnd_ - current_); + } + + if (n > 0) { + std::memset(current_, c, n); + current_ += n; + } + } + + void Flush() { + if (current_ != buffer_) { + size_t result = fwrite(buffer_, 1, static_cast(current_ - buffer_), fp_); + if (result < static_cast(current_ - buffer_)) { + // failure deliberately ignored at this time + // added to avoid warn_unused_result build errors + } + current_ = buffer_; + } + } + + // Not implemented + char Peek() const { RAPIDJSON_ASSERT(false); return 0; } + char Take() { RAPIDJSON_ASSERT(false); return 0; } + size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } + char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + // Prohibit copy constructor & assignment operator. + FileWriteStream(const FileWriteStream&); + FileWriteStream& operator=(const FileWriteStream&); + + std::FILE* fp_; + char *buffer_; + char *bufferEnd_; + char *current_; +}; + +//! Implement specialized version of PutN() with memset() for better performance. +template<> +inline void PutN(FileWriteStream& stream, char c, size_t n) { + stream.PutN(c, n); +} + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_FILESTREAM_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/fwd.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/fwd.h new file mode 100644 index 0000000000..e8104e841b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/fwd.h @@ -0,0 +1,151 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_FWD_H_ +#define RAPIDJSON_FWD_H_ + +#include "rapidjson.h" + +RAPIDJSON_NAMESPACE_BEGIN + +// encodings.h + +template struct UTF8; +template struct UTF16; +template struct UTF16BE; +template struct UTF16LE; +template struct UTF32; +template struct UTF32BE; +template struct UTF32LE; +template struct ASCII; +template struct AutoUTF; + +template +struct Transcoder; + +// allocators.h + +class CrtAllocator; + +template +class MemoryPoolAllocator; + +// stream.h + +template +struct GenericStringStream; + +typedef GenericStringStream > StringStream; + +template +struct GenericInsituStringStream; + +typedef GenericInsituStringStream > InsituStringStream; + +// stringbuffer.h + +template +class GenericStringBuffer; + +typedef GenericStringBuffer, CrtAllocator> StringBuffer; + +// filereadstream.h + +class FileReadStream; + +// filewritestream.h + +class FileWriteStream; + +// memorybuffer.h + +template +struct GenericMemoryBuffer; + +typedef GenericMemoryBuffer MemoryBuffer; + +// memorystream.h + +struct MemoryStream; + +// reader.h + +template +struct BaseReaderHandler; + +template +class GenericReader; + +typedef GenericReader, UTF8, CrtAllocator> Reader; + +// writer.h + +template +class Writer; + +// prettywriter.h + +template +class PrettyWriter; + +// document.h + +template +struct GenericMember; + +template +class GenericMemberIterator; + +template +struct GenericStringRef; + +template +class GenericValue; + +typedef GenericValue, MemoryPoolAllocator > Value; + +template +class GenericDocument; + +typedef GenericDocument, MemoryPoolAllocator, CrtAllocator> Document; + +// pointer.h + +template +class GenericPointer; + +typedef GenericPointer Pointer; + +// schema.h + +template +class IGenericRemoteSchemaDocumentProvider; + +template +class GenericSchemaDocument; + +typedef GenericSchemaDocument SchemaDocument; +typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; + +template < + typename SchemaDocumentType, + typename OutputHandler, + typename StateAllocator> +class GenericSchemaValidator; + +typedef GenericSchemaValidator, void>, CrtAllocator> SchemaValidator; + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_RAPIDJSONFWD_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/biginteger.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/biginteger.h new file mode 100644 index 0000000000..9d3e88c998 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/biginteger.h @@ -0,0 +1,290 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_BIGINTEGER_H_ +#define RAPIDJSON_BIGINTEGER_H_ + +#include "../rapidjson.h" + +#if defined(_MSC_VER) && defined(_M_AMD64) +#include // for _umul128 +#pragma intrinsic(_umul128) +#endif + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +class BigInteger { +public: + typedef uint64_t Type; + + BigInteger(const BigInteger& rhs) : count_(rhs.count_) { + std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); + } + + explicit BigInteger(uint64_t u) : count_(1) { + digits_[0] = u; + } + + BigInteger(const char* decimals, size_t length) : count_(1) { + RAPIDJSON_ASSERT(length > 0); + digits_[0] = 0; + size_t i = 0; + const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19 + while (length >= kMaxDigitPerIteration) { + AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration); + length -= kMaxDigitPerIteration; + i += kMaxDigitPerIteration; + } + + if (length > 0) + AppendDecimal64(decimals + i, decimals + i + length); + } + + BigInteger& operator=(const BigInteger &rhs) + { + if (this != &rhs) { + count_ = rhs.count_; + std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type)); + } + return *this; + } + + BigInteger& operator=(uint64_t u) { + digits_[0] = u; + count_ = 1; + return *this; + } + + BigInteger& operator+=(uint64_t u) { + Type backup = digits_[0]; + digits_[0] += u; + for (size_t i = 0; i < count_ - 1; i++) { + if (digits_[i] >= backup) + return *this; // no carry + backup = digits_[i + 1]; + digits_[i + 1] += 1; + } + + // Last carry + if (digits_[count_ - 1] < backup) + PushBack(1); + + return *this; + } + + BigInteger& operator*=(uint64_t u) { + if (u == 0) return *this = 0; + if (u == 1) return *this; + if (*this == 1) return *this = u; + + uint64_t k = 0; + for (size_t i = 0; i < count_; i++) { + uint64_t hi; + digits_[i] = MulAdd64(digits_[i], u, k, &hi); + k = hi; + } + + if (k > 0) + PushBack(k); + + return *this; + } + + BigInteger& operator*=(uint32_t u) { + if (u == 0) return *this = 0; + if (u == 1) return *this; + if (*this == 1) return *this = u; + + uint64_t k = 0; + for (size_t i = 0; i < count_; i++) { + const uint64_t c = digits_[i] >> 32; + const uint64_t d = digits_[i] & 0xFFFFFFFF; + const uint64_t uc = u * c; + const uint64_t ud = u * d; + const uint64_t p0 = ud + k; + const uint64_t p1 = uc + (p0 >> 32); + digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32); + k = p1 >> 32; + } + + if (k > 0) + PushBack(k); + + return *this; + } + + BigInteger& operator<<=(size_t shift) { + if (IsZero() || shift == 0) return *this; + + size_t offset = shift / kTypeBit; + size_t interShift = shift % kTypeBit; + RAPIDJSON_ASSERT(count_ + offset <= kCapacity); + + if (interShift == 0) { + std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type)); + count_ += offset; + } + else { + digits_[count_] = 0; + for (size_t i = count_; i > 0; i--) + digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift)); + digits_[offset] = digits_[0] << interShift; + count_ += offset; + if (digits_[count_]) + count_++; + } + + std::memset(digits_, 0, offset * sizeof(Type)); + + return *this; + } + + bool operator==(const BigInteger& rhs) const { + return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0; + } + + bool operator==(const Type rhs) const { + return count_ == 1 && digits_[0] == rhs; + } + + BigInteger& MultiplyPow5(unsigned exp) { + static const uint32_t kPow5[12] = { + 5, + 5 * 5, + 5 * 5 * 5, + 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, + 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 + }; + if (exp == 0) return *this; + for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27 + for (; exp >= 13; exp -= 13) *this *= static_cast(1220703125u); // 5^13 + if (exp > 0) *this *= kPow5[exp - 1]; + return *this; + } + + // Compute absolute difference of this and rhs. + // Assume this != rhs + bool Difference(const BigInteger& rhs, BigInteger* out) const { + int cmp = Compare(rhs); + RAPIDJSON_ASSERT(cmp != 0); + const BigInteger *a, *b; // Makes a > b + bool ret; + if (cmp < 0) { a = &rhs; b = this; ret = true; } + else { a = this; b = &rhs; ret = false; } + + Type borrow = 0; + for (size_t i = 0; i < a->count_; i++) { + Type d = a->digits_[i] - borrow; + if (i < b->count_) + d -= b->digits_[i]; + borrow = (d > a->digits_[i]) ? 1 : 0; + out->digits_[i] = d; + if (d != 0) + out->count_ = i + 1; + } + + return ret; + } + + int Compare(const BigInteger& rhs) const { + if (count_ != rhs.count_) + return count_ < rhs.count_ ? -1 : 1; + + for (size_t i = count_; i-- > 0;) + if (digits_[i] != rhs.digits_[i]) + return digits_[i] < rhs.digits_[i] ? -1 : 1; + + return 0; + } + + size_t GetCount() const { return count_; } + Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; } + bool IsZero() const { return count_ == 1 && digits_[0] == 0; } + +private: + void AppendDecimal64(const char* begin, const char* end) { + uint64_t u = ParseUint64(begin, end); + if (IsZero()) + *this = u; + else { + unsigned exp = static_cast(end - begin); + (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u + } + } + + void PushBack(Type digit) { + RAPIDJSON_ASSERT(count_ < kCapacity); + digits_[count_++] = digit; + } + + static uint64_t ParseUint64(const char* begin, const char* end) { + uint64_t r = 0; + for (const char* p = begin; p != end; ++p) { + RAPIDJSON_ASSERT(*p >= '0' && *p <= '9'); + r = r * 10u + static_cast(*p - '0'); + } + return r; + } + + // Assume a * b + k < 2^128 + static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) { +#if defined(_MSC_VER) && defined(_M_AMD64) + uint64_t low = _umul128(a, b, outHigh) + k; + if (low < k) + (*outHigh)++; + return low; +#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) + __extension__ typedef unsigned __int128 uint128; + uint128 p = static_cast(a) * static_cast(b); + p += k; + *outHigh = static_cast(p >> 64); + return static_cast(p); +#else + const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32; + uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1; + x1 += (x0 >> 32); // can't give carry + x1 += x2; + if (x1 < x2) + x3 += (static_cast(1) << 32); + uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF); + uint64_t hi = x3 + (x1 >> 32); + + lo += k; + if (lo < k) + hi++; + *outHigh = hi; + return lo; +#endif + } + + static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000 + static const size_t kCapacity = kBitCount / sizeof(Type); + static const size_t kTypeBit = sizeof(Type) * 8; + + Type digits_[kCapacity]; + size_t count_; +}; + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_BIGINTEGER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/diyfp.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/diyfp.h new file mode 100644 index 0000000000..c9fefdc613 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/diyfp.h @@ -0,0 +1,258 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +// This is a C++ header-only implementation of Grisu2 algorithm from the publication: +// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with +// integers." ACM Sigplan Notices 45.6 (2010): 233-243. + +#ifndef RAPIDJSON_DIYFP_H_ +#define RAPIDJSON_DIYFP_H_ + +#include "../rapidjson.h" + +#if defined(_MSC_VER) && defined(_M_AMD64) +#include +#pragma intrinsic(_BitScanReverse64) +#pragma intrinsic(_umul128) +#endif + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +#endif + +struct DiyFp { + DiyFp() : f(), e() {} + + DiyFp(uint64_t fp, int exp) : f(fp), e(exp) {} + + explicit DiyFp(double d) { + union { + double d; + uint64_t u64; + } u = { d }; + + int biased_e = static_cast((u.u64 & kDpExponentMask) >> kDpSignificandSize); + uint64_t significand = (u.u64 & kDpSignificandMask); + if (biased_e != 0) { + f = significand + kDpHiddenBit; + e = biased_e - kDpExponentBias; + } + else { + f = significand; + e = kDpMinExponent + 1; + } + } + + DiyFp operator-(const DiyFp& rhs) const { + return DiyFp(f - rhs.f, e); + } + + DiyFp operator*(const DiyFp& rhs) const { +#if defined(_MSC_VER) && defined(_M_AMD64) + uint64_t h; + uint64_t l = _umul128(f, rhs.f, &h); + if (l & (uint64_t(1) << 63)) // rounding + h++; + return DiyFp(h, e + rhs.e + 64); +#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__) + __extension__ typedef unsigned __int128 uint128; + uint128 p = static_cast(f) * static_cast(rhs.f); + uint64_t h = static_cast(p >> 64); + uint64_t l = static_cast(p); + if (l & (uint64_t(1) << 63)) // rounding + h++; + return DiyFp(h, e + rhs.e + 64); +#else + const uint64_t M32 = 0xFFFFFFFF; + const uint64_t a = f >> 32; + const uint64_t b = f & M32; + const uint64_t c = rhs.f >> 32; + const uint64_t d = rhs.f & M32; + const uint64_t ac = a * c; + const uint64_t bc = b * c; + const uint64_t ad = a * d; + const uint64_t bd = b * d; + uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32); + tmp += 1U << 31; /// mult_round + return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64); +#endif + } + + DiyFp Normalize() const { +#if defined(_MSC_VER) && defined(_M_AMD64) + unsigned long index; + _BitScanReverse64(&index, f); + return DiyFp(f << (63 - index), e - (63 - index)); +#elif defined(__GNUC__) && __GNUC__ >= 4 + int s = __builtin_clzll(f); + return DiyFp(f << s, e - s); +#else + DiyFp res = *this; + while (!(res.f & (static_cast(1) << 63))) { + res.f <<= 1; + res.e--; + } + return res; +#endif + } + + DiyFp NormalizeBoundary() const { + DiyFp res = *this; + while (!(res.f & (kDpHiddenBit << 1))) { + res.f <<= 1; + res.e--; + } + res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); + res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); + return res; + } + + void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { + DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); + DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); + mi.f <<= mi.e - pl.e; + mi.e = pl.e; + *plus = pl; + *minus = mi; + } + + double ToDouble() const { + union { + double d; + uint64_t u64; + }u; + const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 : + static_cast(e + kDpExponentBias); + u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize); + return u.d; + } + + static const int kDiySignificandSize = 64; + static const int kDpSignificandSize = 52; + static const int kDpExponentBias = 0x3FF + kDpSignificandSize; + static const int kDpMaxExponent = 0x7FF - kDpExponentBias; + static const int kDpMinExponent = -kDpExponentBias; + static const int kDpDenormalExponent = -kDpExponentBias + 1; + static const uint64_t kDpExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); + static const uint64_t kDpSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); + static const uint64_t kDpHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); + + uint64_t f; + int e; +}; + +inline DiyFp GetCachedPowerByIndex(size_t index) { + // 10^-348, 10^-340, ..., 10^340 + static const uint64_t kCachedPowers_F[] = { + RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76), + RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea), + RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df), + RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f), + RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c), + RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5), + RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d), + RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637), + RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7), + RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5), + RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b), + RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996), + RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6), + RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8), + RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053), + RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd), + RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94), + RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b), + RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac), + RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3), + RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb), + RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c), + RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000), + RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984), + RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70), + RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245), + RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8), + RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a), + RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea), + RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85), + RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2), + RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3), + RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25), + RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece), + RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5), + RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a), + RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c), + RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a), + RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129), + RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429), + RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d), + RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841), + RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9), + RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b) + }; + static const int16_t kCachedPowers_E[] = { + -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, + -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, + -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, + -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, + -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, + 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, + 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, + 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, + 907, 933, 960, 986, 1013, 1039, 1066 + }; + return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]); +} + +inline DiyFp GetCachedPower(int e, int* K) { + + //int k = static_cast(ceil((-61 - e) * 0.30102999566398114)) + 374; + double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive + int k = static_cast(dk); + if (dk - k > 0.0) + k++; + + unsigned index = static_cast((k >> 3) + 1); + *K = -(-348 + static_cast(index << 3)); // decimal exponent no need lookup table + + return GetCachedPowerByIndex(index); +} + +inline DiyFp GetCachedPower10(int exp, int *outExp) { + unsigned index = (static_cast(exp) + 348u) / 8u; + *outExp = -348 + static_cast(index) * 8; + return GetCachedPowerByIndex(index); + } + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +RAPIDJSON_DIAG_OFF(padded) +#endif + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_DIYFP_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/dtoa.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/dtoa.h new file mode 100644 index 0000000000..8d6350e626 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/dtoa.h @@ -0,0 +1,245 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +// This is a C++ header-only implementation of Grisu2 algorithm from the publication: +// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with +// integers." ACM Sigplan Notices 45.6 (2010): 233-243. + +#ifndef RAPIDJSON_DTOA_ +#define RAPIDJSON_DTOA_ + +#include "itoa.h" // GetDigitsLut() +#include "diyfp.h" +#include "ieee754.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +RAPIDJSON_DIAG_OFF(array-bounds) // some gcc versions generate wrong warnings https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124 +#endif + +inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { + while (rest < wp_w && delta - rest >= ten_kappa && + (rest + ten_kappa < wp_w || /// closer + wp_w - rest > rest + ten_kappa - wp_w)) { + buffer[len - 1]--; + rest += ten_kappa; + } +} + +inline unsigned CountDecimalDigit32(uint32_t n) { + // Simple pure C++ implementation was faster than __builtin_clz version in this situation. + if (n < 10) return 1; + if (n < 100) return 2; + if (n < 1000) return 3; + if (n < 10000) return 4; + if (n < 100000) return 5; + if (n < 1000000) return 6; + if (n < 10000000) return 7; + if (n < 100000000) return 8; + // Will not reach 10 digits in DigitGen() + //if (n < 1000000000) return 9; + //return 10; + return 9; +} + +inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { + static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); + const DiyFp wp_w = Mp - W; + uint32_t p1 = static_cast(Mp.f >> -one.e); + uint64_t p2 = Mp.f & (one.f - 1); + unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9] + *len = 0; + + while (kappa > 0) { + uint32_t d = 0; + switch (kappa) { + case 9: d = p1 / 100000000; p1 %= 100000000; break; + case 8: d = p1 / 10000000; p1 %= 10000000; break; + case 7: d = p1 / 1000000; p1 %= 1000000; break; + case 6: d = p1 / 100000; p1 %= 100000; break; + case 5: d = p1 / 10000; p1 %= 10000; break; + case 4: d = p1 / 1000; p1 %= 1000; break; + case 3: d = p1 / 100; p1 %= 100; break; + case 2: d = p1 / 10; p1 %= 10; break; + case 1: d = p1; p1 = 0; break; + default:; + } + if (d || *len) + buffer[(*len)++] = static_cast('0' + static_cast(d)); + kappa--; + uint64_t tmp = (static_cast(p1) << -one.e) + p2; + if (tmp <= delta) { + *K += kappa; + GrisuRound(buffer, *len, delta, tmp, static_cast(kPow10[kappa]) << -one.e, wp_w.f); + return; + } + } + + // kappa = 0 + for (;;) { + p2 *= 10; + delta *= 10; + char d = static_cast(p2 >> -one.e); + if (d || *len) + buffer[(*len)++] = static_cast('0' + d); + p2 &= one.f - 1; + kappa--; + if (p2 < delta) { + *K += kappa; + int index = -static_cast(kappa); + GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast(kappa)] : 0)); + return; + } + } +} + +inline void Grisu2(double value, char* buffer, int* length, int* K) { + const DiyFp v(value); + DiyFp w_m, w_p; + v.NormalizedBoundaries(&w_m, &w_p); + + const DiyFp c_mk = GetCachedPower(w_p.e, K); + const DiyFp W = v.Normalize() * c_mk; + DiyFp Wp = w_p * c_mk; + DiyFp Wm = w_m * c_mk; + Wm.f++; + Wp.f--; + DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); +} + +inline char* WriteExponent(int K, char* buffer) { + if (K < 0) { + *buffer++ = '-'; + K = -K; + } + + if (K >= 100) { + *buffer++ = static_cast('0' + static_cast(K / 100)); + K %= 100; + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else if (K >= 10) { + const char* d = GetDigitsLut() + K * 2; + *buffer++ = d[0]; + *buffer++ = d[1]; + } + else + *buffer++ = static_cast('0' + static_cast(K)); + + return buffer; +} + +inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { + const int kk = length + k; // 10^(kk-1) <= v < 10^kk + + if (0 <= k && kk <= 21) { + // 1234e7 -> 12340000000 + for (int i = length; i < kk; i++) + buffer[i] = '0'; + buffer[kk] = '.'; + buffer[kk + 1] = '0'; + return &buffer[kk + 2]; + } + else if (0 < kk && kk <= 21) { + // 1234e-2 -> 12.34 + std::memmove(&buffer[kk + 1], &buffer[kk], static_cast(length - kk)); + buffer[kk] = '.'; + if (0 > k + maxDecimalPlaces) { + // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 + // Remove extra trailing zeros (at least one) after truncation. + for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) + if (buffer[i] != '0') + return &buffer[i + 1]; + return &buffer[kk + 2]; // Reserve one zero + } + else + return &buffer[length + 1]; + } + else if (-6 < kk && kk <= 0) { + // 1234e-6 -> 0.001234 + const int offset = 2 - kk; + std::memmove(&buffer[offset], &buffer[0], static_cast(length)); + buffer[0] = '0'; + buffer[1] = '.'; + for (int i = 2; i < offset; i++) + buffer[i] = '0'; + if (length - kk > maxDecimalPlaces) { + // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 + // Remove extra trailing zeros (at least one) after truncation. + for (int i = maxDecimalPlaces + 1; i > 2; i--) + if (buffer[i] != '0') + return &buffer[i + 1]; + return &buffer[3]; // Reserve one zero + } + else + return &buffer[length + offset]; + } + else if (kk < -maxDecimalPlaces) { + // Truncate to zero + buffer[0] = '0'; + buffer[1] = '.'; + buffer[2] = '0'; + return &buffer[3]; + } + else if (length == 1) { + // 1e30 + buffer[1] = 'e'; + return WriteExponent(kk - 1, &buffer[2]); + } + else { + // 1234e30 -> 1.234e33 + std::memmove(&buffer[2], &buffer[1], static_cast(length - 1)); + buffer[1] = '.'; + buffer[length + 1] = 'e'; + return WriteExponent(kk - 1, &buffer[0 + length + 2]); + } +} + +inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { + RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); + Double d(value); + if (d.IsZero()) { + if (d.Sign()) + *buffer++ = '-'; // -0.0, Issue #289 + buffer[0] = '0'; + buffer[1] = '.'; + buffer[2] = '0'; + return &buffer[3]; + } + else { + if (value < 0) { + *buffer++ = '-'; + value = -value; + } + int length, K; + Grisu2(value, buffer, &length, &K); + return Prettify(buffer, length, K, maxDecimalPlaces); + } +} + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_DTOA_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/ieee754.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/ieee754.h new file mode 100644 index 0000000000..82bb0b99e5 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/ieee754.h @@ -0,0 +1,78 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_IEEE754_ +#define RAPIDJSON_IEEE754_ + +#include "../rapidjson.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +class Double { +public: + Double() {} + Double(double d) : d_(d) {} + Double(uint64_t u) : u_(u) {} + + double Value() const { return d_; } + uint64_t Uint64Value() const { return u_; } + + double NextPositiveDouble() const { + RAPIDJSON_ASSERT(!Sign()); + return Double(u_ + 1).Value(); + } + + bool Sign() const { return (u_ & kSignMask) != 0; } + uint64_t Significand() const { return u_ & kSignificandMask; } + int Exponent() const { return static_cast(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); } + + bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; } + bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; } + bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; } + bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; } + bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; } + + uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); } + int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; } + uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; } + + static unsigned EffectiveSignificandSize(int order) { + if (order >= -1021) + return 53; + else if (order <= -1074) + return 0; + else + return static_cast(order) + 1074; + } + +private: + static const int kSignificandSize = 52; + static const int kExponentBias = 0x3FF; + static const int kDenormalExponent = 1 - kExponentBias; + static const uint64_t kSignMask = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); + static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); + static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); + static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); + + union { + double d_; + uint64_t u_; + }; +}; + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_IEEE754_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/itoa.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/itoa.h new file mode 100644 index 0000000000..01a4e7e72d --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/itoa.h @@ -0,0 +1,304 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ITOA_ +#define RAPIDJSON_ITOA_ + +#include "../rapidjson.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +inline const char* GetDigitsLut() { + static const char cDigitsLut[200] = { + '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9', + '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9', + '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9', + '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9', + '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9', + '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9', + '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9', + '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9', + '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9', + '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9' + }; + return cDigitsLut; +} + +inline char* u32toa(uint32_t value, char* buffer) { + const char* cDigitsLut = GetDigitsLut(); + + if (value < 10000) { + const uint32_t d1 = (value / 100) << 1; + const uint32_t d2 = (value % 100) << 1; + + if (value >= 1000) + *buffer++ = cDigitsLut[d1]; + if (value >= 100) + *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 10) + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + } + else if (value < 100000000) { + // value = bbbbcccc + const uint32_t b = value / 10000; + const uint32_t c = value % 10000; + + const uint32_t d1 = (b / 100) << 1; + const uint32_t d2 = (b % 100) << 1; + + const uint32_t d3 = (c / 100) << 1; + const uint32_t d4 = (c % 100) << 1; + + if (value >= 10000000) + *buffer++ = cDigitsLut[d1]; + if (value >= 1000000) + *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 100000) + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + + *buffer++ = cDigitsLut[d3]; + *buffer++ = cDigitsLut[d3 + 1]; + *buffer++ = cDigitsLut[d4]; + *buffer++ = cDigitsLut[d4 + 1]; + } + else { + // value = aabbbbcccc in decimal + + const uint32_t a = value / 100000000; // 1 to 42 + value %= 100000000; + + if (a >= 10) { + const unsigned i = a << 1; + *buffer++ = cDigitsLut[i]; + *buffer++ = cDigitsLut[i + 1]; + } + else + *buffer++ = static_cast('0' + static_cast(a)); + + const uint32_t b = value / 10000; // 0 to 9999 + const uint32_t c = value % 10000; // 0 to 9999 + + const uint32_t d1 = (b / 100) << 1; + const uint32_t d2 = (b % 100) << 1; + + const uint32_t d3 = (c / 100) << 1; + const uint32_t d4 = (c % 100) << 1; + + *buffer++ = cDigitsLut[d1]; + *buffer++ = cDigitsLut[d1 + 1]; + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + *buffer++ = cDigitsLut[d3]; + *buffer++ = cDigitsLut[d3 + 1]; + *buffer++ = cDigitsLut[d4]; + *buffer++ = cDigitsLut[d4 + 1]; + } + return buffer; +} + +inline char* i32toa(int32_t value, char* buffer) { + uint32_t u = static_cast(value); + if (value < 0) { + *buffer++ = '-'; + u = ~u + 1; + } + + return u32toa(u, buffer); +} + +inline char* u64toa(uint64_t value, char* buffer) { + const char* cDigitsLut = GetDigitsLut(); + const uint64_t kTen8 = 100000000; + const uint64_t kTen9 = kTen8 * 10; + const uint64_t kTen10 = kTen8 * 100; + const uint64_t kTen11 = kTen8 * 1000; + const uint64_t kTen12 = kTen8 * 10000; + const uint64_t kTen13 = kTen8 * 100000; + const uint64_t kTen14 = kTen8 * 1000000; + const uint64_t kTen15 = kTen8 * 10000000; + const uint64_t kTen16 = kTen8 * kTen8; + + if (value < kTen8) { + uint32_t v = static_cast(value); + if (v < 10000) { + const uint32_t d1 = (v / 100) << 1; + const uint32_t d2 = (v % 100) << 1; + + if (v >= 1000) + *buffer++ = cDigitsLut[d1]; + if (v >= 100) + *buffer++ = cDigitsLut[d1 + 1]; + if (v >= 10) + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + } + else { + // value = bbbbcccc + const uint32_t b = v / 10000; + const uint32_t c = v % 10000; + + const uint32_t d1 = (b / 100) << 1; + const uint32_t d2 = (b % 100) << 1; + + const uint32_t d3 = (c / 100) << 1; + const uint32_t d4 = (c % 100) << 1; + + if (value >= 10000000) + *buffer++ = cDigitsLut[d1]; + if (value >= 1000000) + *buffer++ = cDigitsLut[d1 + 1]; + if (value >= 100000) + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + + *buffer++ = cDigitsLut[d3]; + *buffer++ = cDigitsLut[d3 + 1]; + *buffer++ = cDigitsLut[d4]; + *buffer++ = cDigitsLut[d4 + 1]; + } + } + else if (value < kTen16) { + const uint32_t v0 = static_cast(value / kTen8); + const uint32_t v1 = static_cast(value % kTen8); + + const uint32_t b0 = v0 / 10000; + const uint32_t c0 = v0 % 10000; + + const uint32_t d1 = (b0 / 100) << 1; + const uint32_t d2 = (b0 % 100) << 1; + + const uint32_t d3 = (c0 / 100) << 1; + const uint32_t d4 = (c0 % 100) << 1; + + const uint32_t b1 = v1 / 10000; + const uint32_t c1 = v1 % 10000; + + const uint32_t d5 = (b1 / 100) << 1; + const uint32_t d6 = (b1 % 100) << 1; + + const uint32_t d7 = (c1 / 100) << 1; + const uint32_t d8 = (c1 % 100) << 1; + + if (value >= kTen15) + *buffer++ = cDigitsLut[d1]; + if (value >= kTen14) + *buffer++ = cDigitsLut[d1 + 1]; + if (value >= kTen13) + *buffer++ = cDigitsLut[d2]; + if (value >= kTen12) + *buffer++ = cDigitsLut[d2 + 1]; + if (value >= kTen11) + *buffer++ = cDigitsLut[d3]; + if (value >= kTen10) + *buffer++ = cDigitsLut[d3 + 1]; + if (value >= kTen9) + *buffer++ = cDigitsLut[d4]; + if (value >= kTen8) + *buffer++ = cDigitsLut[d4 + 1]; + + *buffer++ = cDigitsLut[d5]; + *buffer++ = cDigitsLut[d5 + 1]; + *buffer++ = cDigitsLut[d6]; + *buffer++ = cDigitsLut[d6 + 1]; + *buffer++ = cDigitsLut[d7]; + *buffer++ = cDigitsLut[d7 + 1]; + *buffer++ = cDigitsLut[d8]; + *buffer++ = cDigitsLut[d8 + 1]; + } + else { + const uint32_t a = static_cast(value / kTen16); // 1 to 1844 + value %= kTen16; + + if (a < 10) + *buffer++ = static_cast('0' + static_cast(a)); + else if (a < 100) { + const uint32_t i = a << 1; + *buffer++ = cDigitsLut[i]; + *buffer++ = cDigitsLut[i + 1]; + } + else if (a < 1000) { + *buffer++ = static_cast('0' + static_cast(a / 100)); + + const uint32_t i = (a % 100) << 1; + *buffer++ = cDigitsLut[i]; + *buffer++ = cDigitsLut[i + 1]; + } + else { + const uint32_t i = (a / 100) << 1; + const uint32_t j = (a % 100) << 1; + *buffer++ = cDigitsLut[i]; + *buffer++ = cDigitsLut[i + 1]; + *buffer++ = cDigitsLut[j]; + *buffer++ = cDigitsLut[j + 1]; + } + + const uint32_t v0 = static_cast(value / kTen8); + const uint32_t v1 = static_cast(value % kTen8); + + const uint32_t b0 = v0 / 10000; + const uint32_t c0 = v0 % 10000; + + const uint32_t d1 = (b0 / 100) << 1; + const uint32_t d2 = (b0 % 100) << 1; + + const uint32_t d3 = (c0 / 100) << 1; + const uint32_t d4 = (c0 % 100) << 1; + + const uint32_t b1 = v1 / 10000; + const uint32_t c1 = v1 % 10000; + + const uint32_t d5 = (b1 / 100) << 1; + const uint32_t d6 = (b1 % 100) << 1; + + const uint32_t d7 = (c1 / 100) << 1; + const uint32_t d8 = (c1 % 100) << 1; + + *buffer++ = cDigitsLut[d1]; + *buffer++ = cDigitsLut[d1 + 1]; + *buffer++ = cDigitsLut[d2]; + *buffer++ = cDigitsLut[d2 + 1]; + *buffer++ = cDigitsLut[d3]; + *buffer++ = cDigitsLut[d3 + 1]; + *buffer++ = cDigitsLut[d4]; + *buffer++ = cDigitsLut[d4 + 1]; + *buffer++ = cDigitsLut[d5]; + *buffer++ = cDigitsLut[d5 + 1]; + *buffer++ = cDigitsLut[d6]; + *buffer++ = cDigitsLut[d6 + 1]; + *buffer++ = cDigitsLut[d7]; + *buffer++ = cDigitsLut[d7 + 1]; + *buffer++ = cDigitsLut[d8]; + *buffer++ = cDigitsLut[d8 + 1]; + } + + return buffer; +} + +inline char* i64toa(int64_t value, char* buffer) { + uint64_t u = static_cast(value); + if (value < 0) { + *buffer++ = '-'; + u = ~u + 1; + } + + return u64toa(u, buffer); +} + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_ITOA_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/meta.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/meta.h new file mode 100644 index 0000000000..5a9aaa4286 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/meta.h @@ -0,0 +1,181 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_INTERNAL_META_H_ +#define RAPIDJSON_INTERNAL_META_H_ + +#include "../rapidjson.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif +#if defined(_MSC_VER) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(6334) +#endif + +#if RAPIDJSON_HAS_CXX11_TYPETRAITS +#include +#endif + +//@cond RAPIDJSON_INTERNAL +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +// Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching +template struct Void { typedef void Type; }; + +/////////////////////////////////////////////////////////////////////////////// +// BoolType, TrueType, FalseType +// +template struct BoolType { + static const bool Value = Cond; + typedef BoolType Type; +}; +typedef BoolType TrueType; +typedef BoolType FalseType; + + +/////////////////////////////////////////////////////////////////////////////// +// SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr +// + +template struct SelectIfImpl { template struct Apply { typedef T1 Type; }; }; +template <> struct SelectIfImpl { template struct Apply { typedef T2 Type; }; }; +template struct SelectIfCond : SelectIfImpl::template Apply {}; +template struct SelectIf : SelectIfCond {}; + +template struct AndExprCond : FalseType {}; +template <> struct AndExprCond : TrueType {}; +template struct OrExprCond : TrueType {}; +template <> struct OrExprCond : FalseType {}; + +template struct BoolExpr : SelectIf::Type {}; +template struct NotExpr : SelectIf::Type {}; +template struct AndExpr : AndExprCond::Type {}; +template struct OrExpr : OrExprCond::Type {}; + + +/////////////////////////////////////////////////////////////////////////////// +// AddConst, MaybeAddConst, RemoveConst +template struct AddConst { typedef const T Type; }; +template struct MaybeAddConst : SelectIfCond {}; +template struct RemoveConst { typedef T Type; }; +template struct RemoveConst { typedef T Type; }; + + +/////////////////////////////////////////////////////////////////////////////// +// IsSame, IsConst, IsMoreConst, IsPointer +// +template struct IsSame : FalseType {}; +template struct IsSame : TrueType {}; + +template struct IsConst : FalseType {}; +template struct IsConst : TrueType {}; + +template +struct IsMoreConst + : AndExpr::Type, typename RemoveConst::Type>, + BoolType::Value >= IsConst::Value> >::Type {}; + +template struct IsPointer : FalseType {}; +template struct IsPointer : TrueType {}; + +/////////////////////////////////////////////////////////////////////////////// +// IsBaseOf +// +#if RAPIDJSON_HAS_CXX11_TYPETRAITS + +template struct IsBaseOf + : BoolType< ::std::is_base_of::value> {}; + +#else // simplified version adopted from Boost + +template struct IsBaseOfImpl { + RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0); + RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0); + + typedef char (&Yes)[1]; + typedef char (&No) [2]; + + template + static Yes Check(const D*, T); + static No Check(const B*, int); + + struct Host { + operator const B*() const; + operator const D*(); + }; + + enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) }; +}; + +template struct IsBaseOf + : OrExpr, BoolExpr > >::Type {}; + +#endif // RAPIDJSON_HAS_CXX11_TYPETRAITS + + +////////////////////////////////////////////////////////////////////////// +// EnableIf / DisableIf +// +template struct EnableIfCond { typedef T Type; }; +template struct EnableIfCond { /* empty */ }; + +template struct DisableIfCond { typedef T Type; }; +template struct DisableIfCond { /* empty */ }; + +template +struct EnableIf : EnableIfCond {}; + +template +struct DisableIf : DisableIfCond {}; + +// SFINAE helpers +struct SfinaeTag {}; +template struct RemoveSfinaeTag; +template struct RemoveSfinaeTag { typedef T Type; }; + +#define RAPIDJSON_REMOVEFPTR_(type) \ + typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \ + < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type + +#define RAPIDJSON_ENABLEIF(cond) \ + typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ + ::Type * = NULL + +#define RAPIDJSON_DISABLEIF(cond) \ + typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ + ::Type * = NULL + +#define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \ + typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \ + ::Type + +#define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \ + typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \ + ::Type + +} // namespace internal +RAPIDJSON_NAMESPACE_END +//@endcond + +#if defined(__GNUC__) || defined(_MSC_VER) +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_INTERNAL_META_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/pow10.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/pow10.h new file mode 100644 index 0000000000..02f475d705 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/pow10.h @@ -0,0 +1,55 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_POW10_ +#define RAPIDJSON_POW10_ + +#include "../rapidjson.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +//! Computes integer powers of 10 in double (10.0^n). +/*! This function uses lookup table for fast and accurate results. + \param n non-negative exponent. Must <= 308. + \return 10.0^n +*/ +inline double Pow10(int n) { + static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes + 1e+0, + 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20, + 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40, + 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60, + 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80, + 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100, + 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120, + 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140, + 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160, + 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180, + 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200, + 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220, + 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240, + 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260, + 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280, + 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300, + 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308 + }; + RAPIDJSON_ASSERT(n >= 0 && n <= 308); + return e[n]; +} + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_POW10_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/regex.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/regex.h new file mode 100644 index 0000000000..422a5240bf --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/regex.h @@ -0,0 +1,701 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_INTERNAL_REGEX_H_ +#define RAPIDJSON_INTERNAL_REGEX_H_ + +#include "../allocators.h" +#include "../stream.h" +#include "stack.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +RAPIDJSON_DIAG_OFF(switch-enum) +RAPIDJSON_DIAG_OFF(implicit-fallthrough) +#endif + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +#endif + +#ifndef RAPIDJSON_REGEX_VERBOSE +#define RAPIDJSON_REGEX_VERBOSE 0 +#endif + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +/////////////////////////////////////////////////////////////////////////////// +// GenericRegex + +static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1 +static const SizeType kRegexInvalidRange = ~SizeType(0); + +//! Regular expression engine with subset of ECMAscript grammar. +/*! + Supported regular expression syntax: + - \c ab Concatenation + - \c a|b Alternation + - \c a? Zero or one + - \c a* Zero or more + - \c a+ One or more + - \c a{3} Exactly 3 times + - \c a{3,} At least 3 times + - \c a{3,5} 3 to 5 times + - \c (ab) Grouping + - \c ^a At the beginning + - \c a$ At the end + - \c . Any character + - \c [abc] Character classes + - \c [a-c] Character class range + - \c [a-z0-9_] Character class combination + - \c [^abc] Negated character classes + - \c [^a-c] Negated character class range + - \c [\b] Backspace (U+0008) + - \c \\| \\\\ ... Escape characters + - \c \\f Form feed (U+000C) + - \c \\n Line feed (U+000A) + - \c \\r Carriage return (U+000D) + - \c \\t Tab (U+0009) + - \c \\v Vertical tab (U+000B) + + \note This is a Thompson NFA engine, implemented with reference to + Cox, Russ. "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby,...).", + https://swtch.com/~rsc/regexp/regexp1.html +*/ +template +class GenericRegex { +public: + typedef typename Encoding::Ch Ch; + + GenericRegex(const Ch* source, Allocator* allocator = 0) : + states_(allocator, 256), ranges_(allocator, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(), + stateSet_(), state0_(allocator, 0), state1_(allocator, 0), anchorBegin_(), anchorEnd_() + { + GenericStringStream ss(source); + DecodedStream > ds(ss); + Parse(ds); + } + + ~GenericRegex() { + Allocator::Free(stateSet_); + } + + bool IsValid() const { + return root_ != kRegexInvalidState; + } + + template + bool Match(InputStream& is) const { + return SearchWithAnchoring(is, true, true); + } + + bool Match(const Ch* s) const { + GenericStringStream is(s); + return Match(is); + } + + template + bool Search(InputStream& is) const { + return SearchWithAnchoring(is, anchorBegin_, anchorEnd_); + } + + bool Search(const Ch* s) const { + GenericStringStream is(s); + return Search(is); + } + +private: + enum Operator { + kZeroOrOne, + kZeroOrMore, + kOneOrMore, + kConcatenation, + kAlternation, + kLeftParenthesis + }; + + static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.' + static const unsigned kRangeCharacterClass = 0xFFFFFFFE; + static const unsigned kRangeNegationFlag = 0x80000000; + + struct Range { + unsigned start; // + unsigned end; + SizeType next; + }; + + struct State { + SizeType out; //!< Equals to kInvalid for matching state + SizeType out1; //!< Equals to non-kInvalid for split + SizeType rangeStart; + unsigned codepoint; + }; + + struct Frag { + Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {} + SizeType start; + SizeType out; //!< link-list of all output states + SizeType minIndex; + }; + + template + class DecodedStream { + public: + DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); } + unsigned Peek() { return codepoint_; } + unsigned Take() { + unsigned c = codepoint_; + if (c) // No further decoding when '\0' + Decode(); + return c; + } + + private: + void Decode() { + if (!Encoding::Decode(ss_, &codepoint_)) + codepoint_ = 0; + } + + SourceStream& ss_; + unsigned codepoint_; + }; + + State& GetState(SizeType index) { + RAPIDJSON_ASSERT(index < stateCount_); + return states_.template Bottom()[index]; + } + + const State& GetState(SizeType index) const { + RAPIDJSON_ASSERT(index < stateCount_); + return states_.template Bottom()[index]; + } + + Range& GetRange(SizeType index) { + RAPIDJSON_ASSERT(index < rangeCount_); + return ranges_.template Bottom()[index]; + } + + const Range& GetRange(SizeType index) const { + RAPIDJSON_ASSERT(index < rangeCount_); + return ranges_.template Bottom()[index]; + } + + template + void Parse(DecodedStream& ds) { + Allocator allocator; + Stack operandStack(&allocator, 256); // Frag + Stack operatorStack(&allocator, 256); // Operator + Stack atomCountStack(&allocator, 256); // unsigned (Atom per parenthesis) + + *atomCountStack.template Push() = 0; + + unsigned codepoint; + while (ds.Peek() != 0) { + switch (codepoint = ds.Take()) { + case '^': + anchorBegin_ = true; + break; + + case '$': + anchorEnd_ = true; + break; + + case '|': + while (!operatorStack.Empty() && *operatorStack.template Top() < kAlternation) + if (!Eval(operandStack, *operatorStack.template Pop(1))) + return; + *operatorStack.template Push() = kAlternation; + *atomCountStack.template Top() = 0; + break; + + case '(': + *operatorStack.template Push() = kLeftParenthesis; + *atomCountStack.template Push() = 0; + break; + + case ')': + while (!operatorStack.Empty() && *operatorStack.template Top() != kLeftParenthesis) + if (!Eval(operandStack, *operatorStack.template Pop(1))) + return; + if (operatorStack.Empty()) + return; + operatorStack.template Pop(1); + atomCountStack.template Pop(1); + ImplicitConcatenation(atomCountStack, operatorStack); + break; + + case '?': + if (!Eval(operandStack, kZeroOrOne)) + return; + break; + + case '*': + if (!Eval(operandStack, kZeroOrMore)) + return; + break; + + case '+': + if (!Eval(operandStack, kOneOrMore)) + return; + break; + + case '{': + { + unsigned n, m; + if (!ParseUnsigned(ds, &n)) + return; + + if (ds.Peek() == ',') { + ds.Take(); + if (ds.Peek() == '}') + m = kInfinityQuantifier; + else if (!ParseUnsigned(ds, &m) || m < n) + return; + } + else + m = n; + + if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}') + return; + ds.Take(); + } + break; + + case '.': + PushOperand(operandStack, kAnyCharacterClass); + ImplicitConcatenation(atomCountStack, operatorStack); + break; + + case '[': + { + SizeType range; + if (!ParseRange(ds, &range)) + return; + SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, kRangeCharacterClass); + GetState(s).rangeStart = range; + *operandStack.template Push() = Frag(s, s, s); + } + ImplicitConcatenation(atomCountStack, operatorStack); + break; + + case '\\': // Escape character + if (!CharacterEscape(ds, &codepoint)) + return; // Unsupported escape character + // fall through to default + + default: // Pattern character + PushOperand(operandStack, codepoint); + ImplicitConcatenation(atomCountStack, operatorStack); + } + } + + while (!operatorStack.Empty()) + if (!Eval(operandStack, *operatorStack.template Pop(1))) + return; + + // Link the operand to matching state. + if (operandStack.GetSize() == sizeof(Frag)) { + Frag* e = operandStack.template Pop(1); + Patch(e->out, NewState(kRegexInvalidState, kRegexInvalidState, 0)); + root_ = e->start; + +#if RAPIDJSON_REGEX_VERBOSE + printf("root: %d\n", root_); + for (SizeType i = 0; i < stateCount_ ; i++) { + State& s = GetState(i); + printf("[%2d] out: %2d out1: %2d c: '%c'\n", i, s.out, s.out1, (char)s.codepoint); + } + printf("\n"); +#endif + } + + // Preallocate buffer for SearchWithAnchoring() + RAPIDJSON_ASSERT(stateSet_ == 0); + if (stateCount_ > 0) { + stateSet_ = static_cast(states_.GetAllocator().Malloc(GetStateSetSize())); + state0_.template Reserve(stateCount_); + state1_.template Reserve(stateCount_); + } + } + + SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) { + State* s = states_.template Push(); + s->out = out; + s->out1 = out1; + s->codepoint = codepoint; + s->rangeStart = kRegexInvalidRange; + return stateCount_++; + } + + void PushOperand(Stack& operandStack, unsigned codepoint) { + SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, codepoint); + *operandStack.template Push() = Frag(s, s, s); + } + + void ImplicitConcatenation(Stack& atomCountStack, Stack& operatorStack) { + if (*atomCountStack.template Top()) + *operatorStack.template Push() = kConcatenation; + (*atomCountStack.template Top())++; + } + + SizeType Append(SizeType l1, SizeType l2) { + SizeType old = l1; + while (GetState(l1).out != kRegexInvalidState) + l1 = GetState(l1).out; + GetState(l1).out = l2; + return old; + } + + void Patch(SizeType l, SizeType s) { + for (SizeType next; l != kRegexInvalidState; l = next) { + next = GetState(l).out; + GetState(l).out = s; + } + } + + bool Eval(Stack& operandStack, Operator op) { + switch (op) { + case kConcatenation: + RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2); + { + Frag e2 = *operandStack.template Pop(1); + Frag e1 = *operandStack.template Pop(1); + Patch(e1.out, e2.start); + *operandStack.template Push() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex)); + } + return true; + + case kAlternation: + if (operandStack.GetSize() >= sizeof(Frag) * 2) { + Frag e2 = *operandStack.template Pop(1); + Frag e1 = *operandStack.template Pop(1); + SizeType s = NewState(e1.start, e2.start, 0); + *operandStack.template Push() = Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex)); + return true; + } + return false; + + case kZeroOrOne: + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + *operandStack.template Push() = Frag(s, Append(e.out, s), e.minIndex); + return true; + } + return false; + + case kZeroOrMore: + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + Patch(e.out, s); + *operandStack.template Push() = Frag(s, s, e.minIndex); + return true; + } + return false; + + default: + RAPIDJSON_ASSERT(op == kOneOrMore); + if (operandStack.GetSize() >= sizeof(Frag)) { + Frag e = *operandStack.template Pop(1); + SizeType s = NewState(kRegexInvalidState, e.start, 0); + Patch(e.out, s); + *operandStack.template Push() = Frag(e.start, s, e.minIndex); + return true; + } + return false; + } + } + + bool EvalQuantifier(Stack& operandStack, unsigned n, unsigned m) { + RAPIDJSON_ASSERT(n <= m); + RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag)); + + if (n == 0) { + if (m == 0) // a{0} not support + return false; + else if (m == kInfinityQuantifier) + Eval(operandStack, kZeroOrMore); // a{0,} -> a* + else { + Eval(operandStack, kZeroOrOne); // a{0,5} -> a? + for (unsigned i = 0; i < m - 1; i++) + CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a? + for (unsigned i = 0; i < m - 1; i++) + Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a? + } + return true; + } + + for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a + CloneTopOperand(operandStack); + + if (m == kInfinityQuantifier) + Eval(operandStack, kOneOrMore); // a{3,} -> a a a+ + else if (m > n) { + CloneTopOperand(operandStack); // a{3,5} -> a a a a + Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a? + for (unsigned i = n; i < m - 1; i++) + CloneTopOperand(operandStack); // a{3,5} -> a a a a? a? + for (unsigned i = n; i < m; i++) + Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a? + } + + for (unsigned i = 0; i < n - 1; i++) + Eval(operandStack, kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a? + + return true; + } + + static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; } + + void CloneTopOperand(Stack& operandStack) { + const Frag src = *operandStack.template Top(); // Copy constructor to prevent invalidation + SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_) + State* s = states_.template Push(count); + memcpy(s, &GetState(src.minIndex), count * sizeof(State)); + for (SizeType j = 0; j < count; j++) { + if (s[j].out != kRegexInvalidState) + s[j].out += count; + if (s[j].out1 != kRegexInvalidState) + s[j].out1 += count; + } + *operandStack.template Push() = Frag(src.start + count, src.out + count, src.minIndex + count); + stateCount_ += count; + } + + template + bool ParseUnsigned(DecodedStream& ds, unsigned* u) { + unsigned r = 0; + if (ds.Peek() < '0' || ds.Peek() > '9') + return false; + while (ds.Peek() >= '0' && ds.Peek() <= '9') { + if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295 + return false; // overflow + r = r * 10 + (ds.Take() - '0'); + } + *u = r; + return true; + } + + template + bool ParseRange(DecodedStream& ds, SizeType* range) { + bool isBegin = true; + bool negate = false; + int step = 0; + SizeType start = kRegexInvalidRange; + SizeType current = kRegexInvalidRange; + unsigned codepoint; + while ((codepoint = ds.Take()) != 0) { + if (isBegin) { + isBegin = false; + if (codepoint == '^') { + negate = true; + continue; + } + } + + switch (codepoint) { + case ']': + if (start == kRegexInvalidRange) + return false; // Error: nothing inside [] + if (step == 2) { // Add trailing '-' + SizeType r = NewRange('-'); + RAPIDJSON_ASSERT(current != kRegexInvalidRange); + GetRange(current).next = r; + } + if (negate) + GetRange(start).start |= kRangeNegationFlag; + *range = start; + return true; + + case '\\': + if (ds.Peek() == 'b') { + ds.Take(); + codepoint = 0x0008; // Escape backspace character + } + else if (!CharacterEscape(ds, &codepoint)) + return false; + // fall through to default + + default: + switch (step) { + case 1: + if (codepoint == '-') { + step++; + break; + } + // fall through to step 0 for other characters + + case 0: + { + SizeType r = NewRange(codepoint); + if (current != kRegexInvalidRange) + GetRange(current).next = r; + if (start == kRegexInvalidRange) + start = r; + current = r; + } + step = 1; + break; + + default: + RAPIDJSON_ASSERT(step == 2); + GetRange(current).end = codepoint; + step = 0; + } + } + } + return false; + } + + SizeType NewRange(unsigned codepoint) { + Range* r = ranges_.template Push(); + r->start = r->end = codepoint; + r->next = kRegexInvalidRange; + return rangeCount_++; + } + + template + bool CharacterEscape(DecodedStream& ds, unsigned* escapedCodepoint) { + unsigned codepoint; + switch (codepoint = ds.Take()) { + case '^': + case '$': + case '|': + case '(': + case ')': + case '?': + case '*': + case '+': + case '.': + case '[': + case ']': + case '{': + case '}': + case '\\': + *escapedCodepoint = codepoint; return true; + case 'f': *escapedCodepoint = 0x000C; return true; + case 'n': *escapedCodepoint = 0x000A; return true; + case 'r': *escapedCodepoint = 0x000D; return true; + case 't': *escapedCodepoint = 0x0009; return true; + case 'v': *escapedCodepoint = 0x000B; return true; + default: + return false; // Unsupported escape character + } + } + + template + bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) const { + RAPIDJSON_ASSERT(IsValid()); + DecodedStream ds(is); + + state0_.Clear(); + Stack *current = &state0_, *next = &state1_; + const size_t stateSetSize = GetStateSetSize(); + std::memset(stateSet_, 0, stateSetSize); + + bool matched = AddState(*current, root_); + unsigned codepoint; + while (!current->Empty() && (codepoint = ds.Take()) != 0) { + std::memset(stateSet_, 0, stateSetSize); + next->Clear(); + matched = false; + for (const SizeType* s = current->template Bottom(); s != current->template End(); ++s) { + const State& sr = GetState(*s); + if (sr.codepoint == codepoint || + sr.codepoint == kAnyCharacterClass || + (sr.codepoint == kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint))) + { + matched = AddState(*next, sr.out) || matched; + if (!anchorEnd && matched) + return true; + } + if (!anchorBegin) + AddState(*next, root_); + } + internal::Swap(current, next); + } + + return matched; + } + + size_t GetStateSetSize() const { + return (stateCount_ + 31) / 32 * 4; + } + + // Return whether the added states is a match state + bool AddState(Stack& l, SizeType index) const { + RAPIDJSON_ASSERT(index != kRegexInvalidState); + + const State& s = GetState(index); + if (s.out1 != kRegexInvalidState) { // Split + bool matched = AddState(l, s.out); + return AddState(l, s.out1) || matched; + } + else if (!(stateSet_[index >> 5] & (1 << (index & 31)))) { + stateSet_[index >> 5] |= (1 << (index & 31)); + *l.template PushUnsafe() = index; + } + return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation. + } + + bool MatchRange(SizeType rangeIndex, unsigned codepoint) const { + bool yes = (GetRange(rangeIndex).start & kRangeNegationFlag) == 0; + while (rangeIndex != kRegexInvalidRange) { + const Range& r = GetRange(rangeIndex); + if (codepoint >= (r.start & ~kRangeNegationFlag) && codepoint <= r.end) + return yes; + rangeIndex = r.next; + } + return !yes; + } + + Stack states_; + Stack ranges_; + SizeType root_; + SizeType stateCount_; + SizeType rangeCount_; + + static const unsigned kInfinityQuantifier = ~0u; + + // For SearchWithAnchoring() + uint32_t* stateSet_; // allocated by states_.GetAllocator() + mutable Stack state0_; + mutable Stack state1_; + bool anchorBegin_; + bool anchorEnd_; +}; + +typedef GenericRegex > Regex; + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_INTERNAL_REGEX_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/stack.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/stack.h new file mode 100644 index 0000000000..022c9aab41 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/stack.h @@ -0,0 +1,230 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_INTERNAL_STACK_H_ +#define RAPIDJSON_INTERNAL_STACK_H_ + +#include "../allocators.h" +#include "swap.h" + +#if defined(__clang__) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +/////////////////////////////////////////////////////////////////////////////// +// Stack + +//! A type-unsafe stack for storing different types of data. +/*! \tparam Allocator Allocator for allocating stack memory. +*/ +template +class Stack { +public: + // Optimization note: Do not allocate memory for stack_ in constructor. + // Do it lazily when first Push() -> Expand() -> Resize(). + Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) { + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + Stack(Stack&& rhs) + : allocator_(rhs.allocator_), + ownAllocator_(rhs.ownAllocator_), + stack_(rhs.stack_), + stackTop_(rhs.stackTop_), + stackEnd_(rhs.stackEnd_), + initialCapacity_(rhs.initialCapacity_) + { + rhs.allocator_ = 0; + rhs.ownAllocator_ = 0; + rhs.stack_ = 0; + rhs.stackTop_ = 0; + rhs.stackEnd_ = 0; + rhs.initialCapacity_ = 0; + } +#endif + + ~Stack() { + Destroy(); + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + Stack& operator=(Stack&& rhs) { + if (&rhs != this) + { + Destroy(); + + allocator_ = rhs.allocator_; + ownAllocator_ = rhs.ownAllocator_; + stack_ = rhs.stack_; + stackTop_ = rhs.stackTop_; + stackEnd_ = rhs.stackEnd_; + initialCapacity_ = rhs.initialCapacity_; + + rhs.allocator_ = 0; + rhs.ownAllocator_ = 0; + rhs.stack_ = 0; + rhs.stackTop_ = 0; + rhs.stackEnd_ = 0; + rhs.initialCapacity_ = 0; + } + return *this; + } +#endif + + void Swap(Stack& rhs) RAPIDJSON_NOEXCEPT { + internal::Swap(allocator_, rhs.allocator_); + internal::Swap(ownAllocator_, rhs.ownAllocator_); + internal::Swap(stack_, rhs.stack_); + internal::Swap(stackTop_, rhs.stackTop_); + internal::Swap(stackEnd_, rhs.stackEnd_); + internal::Swap(initialCapacity_, rhs.initialCapacity_); + } + + void Clear() { stackTop_ = stack_; } + + void ShrinkToFit() { + if (Empty()) { + // If the stack is empty, completely deallocate the memory. + Allocator::Free(stack_); + stack_ = 0; + stackTop_ = 0; + stackEnd_ = 0; + } + else + Resize(GetSize()); + } + + // Optimization note: try to minimize the size of this function for force inline. + // Expansion is run very infrequently, so it is moved to another (probably non-inline) function. + template + RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) { + // Expand the stack if needed + if (RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_)) + Expand(count); + } + + template + RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) { + Reserve(count); + return PushUnsafe(count); + } + + template + RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) { + RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_); + T* ret = reinterpret_cast(stackTop_); + stackTop_ += sizeof(T) * count; + return ret; + } + + template + T* Pop(size_t count) { + RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T)); + stackTop_ -= count * sizeof(T); + return reinterpret_cast(stackTop_); + } + + template + T* Top() { + RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); + return reinterpret_cast(stackTop_ - sizeof(T)); + } + + template + const T* Top() const { + RAPIDJSON_ASSERT(GetSize() >= sizeof(T)); + return reinterpret_cast(stackTop_ - sizeof(T)); + } + + template + T* End() { return reinterpret_cast(stackTop_); } + + template + const T* End() const { return reinterpret_cast(stackTop_); } + + template + T* Bottom() { return reinterpret_cast(stack_); } + + template + const T* Bottom() const { return reinterpret_cast(stack_); } + + bool HasAllocator() const { + return allocator_ != 0; + } + + Allocator& GetAllocator() { + RAPIDJSON_ASSERT(allocator_); + return *allocator_; + } + + bool Empty() const { return stackTop_ == stack_; } + size_t GetSize() const { return static_cast(stackTop_ - stack_); } + size_t GetCapacity() const { return static_cast(stackEnd_ - stack_); } + +private: + template + void Expand(size_t count) { + // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity. + size_t newCapacity; + if (stack_ == 0) { + if (!allocator_) + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + newCapacity = initialCapacity_; + } else { + newCapacity = GetCapacity(); + newCapacity += (newCapacity + 1) / 2; + } + size_t newSize = GetSize() + sizeof(T) * count; + if (newCapacity < newSize) + newCapacity = newSize; + + Resize(newCapacity); + } + + void Resize(size_t newCapacity) { + const size_t size = GetSize(); // Backup the current size + stack_ = static_cast(allocator_->Realloc(stack_, GetCapacity(), newCapacity)); + stackTop_ = stack_ + size; + stackEnd_ = stack_ + newCapacity; + } + + void Destroy() { + Allocator::Free(stack_); + RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack + } + + // Prohibit copy constructor & assignment operator. + Stack(const Stack&); + Stack& operator=(const Stack&); + + Allocator* allocator_; + Allocator* ownAllocator_; + char *stack_; + char *stackTop_; + char *stackEnd_; + size_t initialCapacity_; +}; + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#if defined(__clang__) +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_STACK_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strfunc.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strfunc.h new file mode 100644 index 0000000000..2edfae5267 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strfunc.h @@ -0,0 +1,55 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_ +#define RAPIDJSON_INTERNAL_STRFUNC_H_ + +#include "../stream.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +//! Custom strlen() which works on different character types. +/*! \tparam Ch Character type (e.g. char, wchar_t, short) + \param s Null-terminated input string. + \return Number of characters in the string. + \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints. +*/ +template +inline SizeType StrLen(const Ch* s) { + const Ch* p = s; + while (*p) ++p; + return SizeType(p - s); +} + +//! Returns number of code points in a encoded string. +template +bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) { + GenericStringStream is(s); + const typename Encoding::Ch* end = s + length; + SizeType count = 0; + while (is.src_ < end) { + unsigned codepoint; + if (!Encoding::Decode(is, &codepoint)) + return false; + count++; + } + *outCount = count; + return true; +} + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_INTERNAL_STRFUNC_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strtod.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strtod.h new file mode 100644 index 0000000000..289c413b07 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/strtod.h @@ -0,0 +1,269 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_STRTOD_ +#define RAPIDJSON_STRTOD_ + +#include "ieee754.h" +#include "biginteger.h" +#include "diyfp.h" +#include "pow10.h" + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +inline double FastPath(double significand, int exp) { + if (exp < -308) + return 0.0; + else if (exp >= 0) + return significand * internal::Pow10(exp); + else + return significand / internal::Pow10(-exp); +} + +inline double StrtodNormalPrecision(double d, int p) { + if (p < -308) { + // Prevent expSum < -308, making Pow10(p) = 0 + d = FastPath(d, -308); + d = FastPath(d, p + 308); + } + else + d = FastPath(d, p); + return d; +} + +template +inline T Min3(T a, T b, T c) { + T m = a; + if (m > b) m = b; + if (m > c) m = c; + return m; +} + +inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) { + const Double db(b); + const uint64_t bInt = db.IntegerSignificand(); + const int bExp = db.IntegerExponent(); + const int hExp = bExp - 1; + + int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0; + + // Adjust for decimal exponent + if (dExp >= 0) { + dS_Exp2 += dExp; + dS_Exp5 += dExp; + } + else { + bS_Exp2 -= dExp; + bS_Exp5 -= dExp; + hS_Exp2 -= dExp; + hS_Exp5 -= dExp; + } + + // Adjust for binary exponent + if (bExp >= 0) + bS_Exp2 += bExp; + else { + dS_Exp2 -= bExp; + hS_Exp2 -= bExp; + } + + // Adjust for half ulp exponent + if (hExp >= 0) + hS_Exp2 += hExp; + else { + dS_Exp2 -= hExp; + bS_Exp2 -= hExp; + } + + // Remove common power of two factor from all three scaled values + int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2); + dS_Exp2 -= common_Exp2; + bS_Exp2 -= common_Exp2; + hS_Exp2 -= common_Exp2; + + BigInteger dS = d; + dS.MultiplyPow5(static_cast(dS_Exp5)) <<= static_cast(dS_Exp2); + + BigInteger bS(bInt); + bS.MultiplyPow5(static_cast(bS_Exp5)) <<= static_cast(bS_Exp2); + + BigInteger hS(1); + hS.MultiplyPow5(static_cast(hS_Exp5)) <<= static_cast(hS_Exp2); + + BigInteger delta(0); + dS.Difference(bS, &delta); + + return delta.Compare(hS); +} + +inline bool StrtodFast(double d, int p, double* result) { + // Use fast path for string-to-double conversion if possible + // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/ + if (p > 22 && p < 22 + 16) { + // Fast Path Cases In Disguise + d *= internal::Pow10(p - 22); + p = 22; + } + + if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1 + *result = FastPath(d, p); + return true; + } + else + return false; +} + +// Compute an approximation and see if it is within 1/2 ULP +inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) { + uint64_t significand = 0; + size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999 + for (; i < length; i++) { + if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || + (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5')) + break; + significand = significand * 10u + static_cast(decimals[i] - '0'); + } + + if (i < length && decimals[i] >= '5') // Rounding + significand++; + + size_t remaining = length - i; + const unsigned kUlpShift = 3; + const unsigned kUlp = 1 << kUlpShift; + int64_t error = (remaining == 0) ? 0 : kUlp / 2; + + DiyFp v(significand, 0); + v = v.Normalize(); + error <<= -v.e; + + const int dExp = static_cast(decimalPosition) - static_cast(i) + exp; + + int actualExp; + DiyFp cachedPower = GetCachedPower10(dExp, &actualExp); + if (actualExp != dExp) { + static const DiyFp kPow10[] = { + DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1 + DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2 + DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3 + DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4 + DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5 + DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6 + DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7 + }; + int adjustment = dExp - actualExp - 1; + RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7); + v = v * kPow10[adjustment]; + if (length + static_cast(adjustment)> 19u) // has more digits than decimal digits in 64-bit + error += kUlp / 2; + } + + v = v * cachedPower; + + error += kUlp + (error == 0 ? 0 : 1); + + const int oldExp = v.e; + v = v.Normalize(); + error <<= oldExp - v.e; + + const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e); + unsigned precisionSize = 64 - effectiveSignificandSize; + if (precisionSize + kUlpShift >= 64) { + unsigned scaleExp = (precisionSize + kUlpShift) - 63; + v.f >>= scaleExp; + v.e += scaleExp; + error = (error >> scaleExp) + 1 + static_cast(kUlp); + precisionSize -= scaleExp; + } + + DiyFp rounded(v.f >> precisionSize, v.e + static_cast(precisionSize)); + const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp; + const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp; + if (precisionBits >= halfWay + static_cast(error)) { + rounded.f++; + if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340) + rounded.f >>= 1; + rounded.e++; + } + } + + *result = rounded.ToDouble(); + + return halfWay - static_cast(error) >= precisionBits || precisionBits >= halfWay + static_cast(error); +} + +inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) { + const BigInteger dInt(decimals, length); + const int dExp = static_cast(decimalPosition) - static_cast(length) + exp; + Double a(approx); + int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp); + if (cmp < 0) + return a.Value(); // within half ULP + else if (cmp == 0) { + // Round towards even + if (a.Significand() & 1) + return a.NextPositiveDouble(); + else + return a.Value(); + } + else // adjustment + return a.NextPositiveDouble(); +} + +inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) { + RAPIDJSON_ASSERT(d >= 0.0); + RAPIDJSON_ASSERT(length >= 1); + + double result; + if (StrtodFast(d, p, &result)) + return result; + + // Trim leading zeros + while (*decimals == '0' && length > 1) { + length--; + decimals++; + decimalPosition--; + } + + // Trim trailing zeros + while (decimals[length - 1] == '0' && length > 1) { + length--; + decimalPosition--; + exp++; + } + + // Trim right-most digits + const int kMaxDecimalDigit = 780; + if (static_cast(length) > kMaxDecimalDigit) { + int delta = (static_cast(length) - kMaxDecimalDigit); + exp += delta; + decimalPosition -= static_cast(delta); + length = kMaxDecimalDigit; + } + + // If too small, underflow to zero + if (int(length) + exp < -324) + return 0.0; + + if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result)) + return result; + + // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison + return StrtodBigInteger(result, decimals, length, decimalPosition, exp); +} + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_STRTOD_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/swap.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/swap.h new file mode 100644 index 0000000000..666e49f97b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/internal/swap.h @@ -0,0 +1,46 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_INTERNAL_SWAP_H_ +#define RAPIDJSON_INTERNAL_SWAP_H_ + +#include "../rapidjson.h" + +#if defined(__clang__) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +RAPIDJSON_NAMESPACE_BEGIN +namespace internal { + +//! Custom swap() to avoid dependency on C++ header +/*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only. + \note This has the same semantics as std::swap(). +*/ +template +inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT { + T tmp = a; + a = b; + b = tmp; +} + +} // namespace internal +RAPIDJSON_NAMESPACE_END + +#if defined(__clang__) +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_INTERNAL_SWAP_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/istreamwrapper.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/istreamwrapper.h new file mode 100644 index 0000000000..f5fe28977e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/istreamwrapper.h @@ -0,0 +1,115 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_ISTREAMWRAPPER_H_ +#define RAPIDJSON_ISTREAMWRAPPER_H_ + +#include "stream.h" +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Wrapper of \c std::basic_istream into RapidJSON's Stream concept. +/*! + The classes can be wrapped including but not limited to: + + - \c std::istringstream + - \c std::stringstream + - \c std::wistringstream + - \c std::wstringstream + - \c std::ifstream + - \c std::fstream + - \c std::wifstream + - \c std::wfstream + + \tparam StreamType Class derived from \c std::basic_istream. +*/ + +template +class BasicIStreamWrapper { +public: + typedef typename StreamType::char_type Ch; + BasicIStreamWrapper(StreamType& stream) : stream_(stream), count_(), peekBuffer_() {} + + Ch Peek() const { + typename StreamType::int_type c = stream_.peek(); + return RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast(c) : '\0'; + } + + Ch Take() { + typename StreamType::int_type c = stream_.get(); + if (RAPIDJSON_LIKELY(c != StreamType::traits_type::eof())) { + count_++; + return static_cast(c); + } + else + return '\0'; + } + + // tellg() may return -1 when failed. So we count by ourself. + size_t Tell() const { return count_; } + + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + + // For encoding detection only. + const Ch* Peek4() const { + RAPIDJSON_ASSERT(sizeof(Ch) == 1); // Only usable for byte stream. + int i; + bool hasError = false; + for (i = 0; i < 4; ++i) { + typename StreamType::int_type c = stream_.get(); + if (c == StreamType::traits_type::eof()) { + hasError = true; + stream_.clear(); + break; + } + peekBuffer_[i] = static_cast(c); + } + for (--i; i >= 0; --i) + stream_.putback(peekBuffer_[i]); + return !hasError ? peekBuffer_ : 0; + } + +private: + BasicIStreamWrapper(const BasicIStreamWrapper&); + BasicIStreamWrapper& operator=(const BasicIStreamWrapper&); + + StreamType& stream_; + size_t count_; //!< Number of characters read. Note: + mutable Ch peekBuffer_[4]; +}; + +typedef BasicIStreamWrapper IStreamWrapper; +typedef BasicIStreamWrapper WIStreamWrapper; + +#if defined(__clang__) || defined(_MSC_VER) +RAPIDJSON_DIAG_POP +#endif + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_ISTREAMWRAPPER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/memorybuffer.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/memorybuffer.h new file mode 100644 index 0000000000..39bee1dec1 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/memorybuffer.h @@ -0,0 +1,70 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_MEMORYBUFFER_H_ +#define RAPIDJSON_MEMORYBUFFER_H_ + +#include "stream.h" +#include "internal/stack.h" + +RAPIDJSON_NAMESPACE_BEGIN + +//! Represents an in-memory output byte stream. +/*! + This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream. + + It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file. + + Differences between MemoryBuffer and StringBuffer: + 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer. + 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator. + + \tparam Allocator type for allocating memory buffer. + \note implements Stream concept +*/ +template +struct GenericMemoryBuffer { + typedef char Ch; // byte + + GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} + + void Put(Ch c) { *stack_.template Push() = c; } + void Flush() {} + + void Clear() { stack_.Clear(); } + void ShrinkToFit() { stack_.ShrinkToFit(); } + Ch* Push(size_t count) { return stack_.template Push(count); } + void Pop(size_t count) { stack_.template Pop(count); } + + const Ch* GetBuffer() const { + return stack_.template Bottom(); + } + + size_t GetSize() const { return stack_.GetSize(); } + + static const size_t kDefaultCapacity = 256; + mutable internal::Stack stack_; +}; + +typedef GenericMemoryBuffer<> MemoryBuffer; + +//! Implement specialized version of PutN() with memset() for better performance. +template<> +inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) { + std::memset(memoryBuffer.stack_.Push(n), c, n * sizeof(c)); +} + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_MEMORYBUFFER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/memorystream.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/memorystream.h new file mode 100644 index 0000000000..1d71d8a4f0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/memorystream.h @@ -0,0 +1,71 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_MEMORYSTREAM_H_ +#define RAPIDJSON_MEMORYSTREAM_H_ + +#include "stream.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(unreachable-code) +RAPIDJSON_DIAG_OFF(missing-noreturn) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Represents an in-memory input byte stream. +/*! + This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream. + + It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file. + + Differences between MemoryStream and StringStream: + 1. StringStream has encoding but MemoryStream is a byte stream. + 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source. + 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4(). + \note implements Stream concept +*/ +struct MemoryStream { + typedef char Ch; // byte + + MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {} + + Ch Peek() const { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; } + Ch Take() { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; } + size_t Tell() const { return static_cast(src_ - begin_); } + + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + + // For encoding detection only. + const Ch* Peek4() const { + return Tell() + 4 <= size_ ? src_ : 0; + } + + const Ch* src_; //!< Current read position. + const Ch* begin_; //!< Original head of the string. + const Ch* end_; //!< End of stream. + size_t size_; //!< Size of the stream. +}; + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_MEMORYBUFFER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/inttypes.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/inttypes.h new file mode 100644 index 0000000000..18111286bf --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/inttypes.h @@ -0,0 +1,316 @@ +// ISO C9x compliant inttypes.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006-2013 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. Neither the name of the product nor the names of its contributors may +// be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +// The above software in this distribution may have been modified by +// THL A29 Limited ("Tencent Modifications"). +// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_INTTYPES_H_ // [ +#define _MSC_INTTYPES_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include "stdint.h" + +// miloyip: VC supports inttypes.h since VC2013 +#if _MSC_VER >= 1800 +#include +#else + +// 7.8 Format conversion of integer types + +typedef struct { + intmax_t quot; + intmax_t rem; +} imaxdiv_t; + +// 7.8.1 Macros for format specifiers + +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 + +// The fprintf macros for signed integers are: +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" + +// The fprintf macros for unsigned integers are: +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" + +// The fscanf macros for signed integers are: +#define SCNd8 "d" +#define SCNi8 "i" +#define SCNdLEAST8 "d" +#define SCNiLEAST8 "i" +#define SCNdFAST8 "d" +#define SCNiFAST8 "i" + +#define SCNd16 "hd" +#define SCNi16 "hi" +#define SCNdLEAST16 "hd" +#define SCNiLEAST16 "hi" +#define SCNdFAST16 "hd" +#define SCNiFAST16 "hi" + +#define SCNd32 "ld" +#define SCNi32 "li" +#define SCNdLEAST32 "ld" +#define SCNiLEAST32 "li" +#define SCNdFAST32 "ld" +#define SCNiFAST32 "li" + +#define SCNd64 "I64d" +#define SCNi64 "I64i" +#define SCNdLEAST64 "I64d" +#define SCNiLEAST64 "I64i" +#define SCNdFAST64 "I64d" +#define SCNiFAST64 "I64i" + +#define SCNdMAX "I64d" +#define SCNiMAX "I64i" + +#ifdef _WIN64 // [ +# define SCNdPTR "I64d" +# define SCNiPTR "I64i" +#else // _WIN64 ][ +# define SCNdPTR "ld" +# define SCNiPTR "li" +#endif // _WIN64 ] + +// The fscanf macros for unsigned integers are: +#define SCNo8 "o" +#define SCNu8 "u" +#define SCNx8 "x" +#define SCNX8 "X" +#define SCNoLEAST8 "o" +#define SCNuLEAST8 "u" +#define SCNxLEAST8 "x" +#define SCNXLEAST8 "X" +#define SCNoFAST8 "o" +#define SCNuFAST8 "u" +#define SCNxFAST8 "x" +#define SCNXFAST8 "X" + +#define SCNo16 "ho" +#define SCNu16 "hu" +#define SCNx16 "hx" +#define SCNX16 "hX" +#define SCNoLEAST16 "ho" +#define SCNuLEAST16 "hu" +#define SCNxLEAST16 "hx" +#define SCNXLEAST16 "hX" +#define SCNoFAST16 "ho" +#define SCNuFAST16 "hu" +#define SCNxFAST16 "hx" +#define SCNXFAST16 "hX" + +#define SCNo32 "lo" +#define SCNu32 "lu" +#define SCNx32 "lx" +#define SCNX32 "lX" +#define SCNoLEAST32 "lo" +#define SCNuLEAST32 "lu" +#define SCNxLEAST32 "lx" +#define SCNXLEAST32 "lX" +#define SCNoFAST32 "lo" +#define SCNuFAST32 "lu" +#define SCNxFAST32 "lx" +#define SCNXFAST32 "lX" + +#define SCNo64 "I64o" +#define SCNu64 "I64u" +#define SCNx64 "I64x" +#define SCNX64 "I64X" +#define SCNoLEAST64 "I64o" +#define SCNuLEAST64 "I64u" +#define SCNxLEAST64 "I64x" +#define SCNXLEAST64 "I64X" +#define SCNoFAST64 "I64o" +#define SCNuFAST64 "I64u" +#define SCNxFAST64 "I64x" +#define SCNXFAST64 "I64X" + +#define SCNoMAX "I64o" +#define SCNuMAX "I64u" +#define SCNxMAX "I64x" +#define SCNXMAX "I64X" + +#ifdef _WIN64 // [ +# define SCNoPTR "I64o" +# define SCNuPTR "I64u" +# define SCNxPTR "I64x" +# define SCNXPTR "I64X" +#else // _WIN64 ][ +# define SCNoPTR "lo" +# define SCNuPTR "lu" +# define SCNxPTR "lx" +# define SCNXPTR "lX" +#endif // _WIN64 ] + +#endif // __STDC_FORMAT_MACROS ] + +// 7.8.2 Functions for greatest-width integer types + +// 7.8.2.1 The imaxabs function +#define imaxabs _abs64 + +// 7.8.2.2 The imaxdiv function + +// This is modified version of div() function from Microsoft's div.c found +// in %MSVC.NET%\crt\src\div.c +#ifdef STATIC_IMAXDIV // [ +static +#else // STATIC_IMAXDIV ][ +_inline +#endif // STATIC_IMAXDIV ] +imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) +{ + imaxdiv_t result; + + result.quot = numer / denom; + result.rem = numer % denom; + + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } + + return result; +} + +// 7.8.2.3 The strtoimax and strtoumax functions +#define strtoimax _strtoi64 +#define strtoumax _strtoui64 + +// 7.8.2.4 The wcstoimax and wcstoumax functions +#define wcstoimax _wcstoi64 +#define wcstoumax _wcstoui64 + +#endif // _MSC_VER >= 1800 + +#endif // _MSC_INTTYPES_H_ ] diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/stdint.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/stdint.h new file mode 100644 index 0000000000..3d4477b9a0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/msinttypes/stdint.h @@ -0,0 +1,300 @@ +// ISO C9x compliant stdint.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006-2013 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. Neither the name of the product nor the names of its contributors may +// be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +// The above software in this distribution may have been modified by +// THL A29 Limited ("Tencent Modifications"). +// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_STDINT_H_ // [ +#define _MSC_STDINT_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +// miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010. +#if _MSC_VER >= 1600 // [ +#include + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 + +#undef INT8_C +#undef INT16_C +#undef INT32_C +#undef INT64_C +#undef UINT8_C +#undef UINT16_C +#undef UINT32_C +#undef UINT64_C + +// 7.18.4.1 Macros for minimum-width integer constants + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +// 7.18.4.2 Macros for greatest-width integer constants +// These #ifndef's are needed to prevent collisions with . +// Check out Issue 9 for the details. +#ifndef INTMAX_C // [ +# define INTMAX_C INT64_C +#endif // INTMAX_C ] +#ifndef UINTMAX_C // [ +# define UINTMAX_C UINT64_C +#endif // UINTMAX_C ] + +#endif // __STDC_CONSTANT_MACROS ] + +#else // ] _MSC_VER >= 1700 [ + +#include + +// For Visual Studio 6 in C++ mode and for many Visual Studio versions when +// compiling for ARM we have to wrap include with 'extern "C++" {}' +// or compiler would give many errors like this: +// error C2733: second C linkage of overloaded function 'wmemchr' not allowed +#if defined(__cplusplus) && !defined(_M_ARM) +extern "C" { +#endif +# include +#if defined(__cplusplus) && !defined(_M_ARM) +} +#endif + +// Define _W64 macros to mark types changing their size, like intptr_t. +#ifndef _W64 +# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300 +# define _W64 __w64 +# else +# define _W64 +# endif +#endif + + +// 7.18.1 Integer types + +// 7.18.1.1 Exact-width integer types + +// Visual Studio 6 and Embedded Visual C++ 4 doesn't +// realize that, e.g. char has the same size as __int8 +// so we give up on __intX for them. +#if (_MSC_VER < 1300) + typedef signed char int8_t; + typedef signed short int16_t; + typedef signed int int32_t; + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; +#else + typedef signed __int8 int8_t; + typedef signed __int16 int16_t; + typedef signed __int32 int32_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; +#endif +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; + + +// 7.18.1.2 Minimum-width integer types +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +// 7.18.1.3 Fastest minimum-width integer types +typedef int8_t int_fast8_t; +typedef int16_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef int64_t int_fast64_t; +typedef uint8_t uint_fast8_t; +typedef uint16_t uint_fast16_t; +typedef uint32_t uint_fast32_t; +typedef uint64_t uint_fast64_t; + +// 7.18.1.4 Integer types capable of holding object pointers +#ifdef _WIN64 // [ + typedef signed __int64 intptr_t; + typedef unsigned __int64 uintptr_t; +#else // _WIN64 ][ + typedef _W64 signed int intptr_t; + typedef _W64 unsigned int uintptr_t; +#endif // _WIN64 ] + +// 7.18.1.5 Greatest-width integer types +typedef int64_t intmax_t; +typedef uint64_t uintmax_t; + + +// 7.18.2 Limits of specified-width integer types + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259 + +// 7.18.2.1 Limits of exact-width integer types +#define INT8_MIN ((int8_t)_I8_MIN) +#define INT8_MAX _I8_MAX +#define INT16_MIN ((int16_t)_I16_MIN) +#define INT16_MAX _I16_MAX +#define INT32_MIN ((int32_t)_I32_MIN) +#define INT32_MAX _I32_MAX +#define INT64_MIN ((int64_t)_I64_MIN) +#define INT64_MAX _I64_MAX +#define UINT8_MAX _UI8_MAX +#define UINT16_MAX _UI16_MAX +#define UINT32_MAX _UI32_MAX +#define UINT64_MAX _UI64_MAX + +// 7.18.2.2 Limits of minimum-width integer types +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MIN INT64_MIN +#define INT_LEAST64_MAX INT64_MAX +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +// 7.18.2.3 Limits of fastest minimum-width integer types +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MIN INT64_MIN +#define INT_FAST64_MAX INT64_MAX +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +// 7.18.2.4 Limits of integer types capable of holding object pointers +#ifdef _WIN64 // [ +# define INTPTR_MIN INT64_MIN +# define INTPTR_MAX INT64_MAX +# define UINTPTR_MAX UINT64_MAX +#else // _WIN64 ][ +# define INTPTR_MIN INT32_MIN +# define INTPTR_MAX INT32_MAX +# define UINTPTR_MAX UINT32_MAX +#endif // _WIN64 ] + +// 7.18.2.5 Limits of greatest-width integer types +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +// 7.18.3 Limits of other integer types + +#ifdef _WIN64 // [ +# define PTRDIFF_MIN _I64_MIN +# define PTRDIFF_MAX _I64_MAX +#else // _WIN64 ][ +# define PTRDIFF_MIN _I32_MIN +# define PTRDIFF_MAX _I32_MAX +#endif // _WIN64 ] + +#define SIG_ATOMIC_MIN INT_MIN +#define SIG_ATOMIC_MAX INT_MAX + +#ifndef SIZE_MAX // [ +# ifdef _WIN64 // [ +# define SIZE_MAX _UI64_MAX +# else // _WIN64 ][ +# define SIZE_MAX _UI32_MAX +# endif // _WIN64 ] +#endif // SIZE_MAX ] + +// WCHAR_MIN and WCHAR_MAX are also defined in +#ifndef WCHAR_MIN // [ +# define WCHAR_MIN 0 +#endif // WCHAR_MIN ] +#ifndef WCHAR_MAX // [ +# define WCHAR_MAX _UI16_MAX +#endif // WCHAR_MAX ] + +#define WINT_MIN 0 +#define WINT_MAX _UI16_MAX + +#endif // __STDC_LIMIT_MACROS ] + + +// 7.18.4 Limits of other integer types + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260 + +// 7.18.4.1 Macros for minimum-width integer constants + +#define INT8_C(val) val##i8 +#define INT16_C(val) val##i16 +#define INT32_C(val) val##i32 +#define INT64_C(val) val##i64 + +#define UINT8_C(val) val##ui8 +#define UINT16_C(val) val##ui16 +#define UINT32_C(val) val##ui32 +#define UINT64_C(val) val##ui64 + +// 7.18.4.2 Macros for greatest-width integer constants +// These #ifndef's are needed to prevent collisions with . +// Check out Issue 9 for the details. +#ifndef INTMAX_C // [ +# define INTMAX_C INT64_C +#endif // INTMAX_C ] +#ifndef UINTMAX_C // [ +# define UINTMAX_C UINT64_C +#endif // UINTMAX_C ] + +#endif // __STDC_CONSTANT_MACROS ] + +#endif // _MSC_VER >= 1600 ] + +#endif // _MSC_STDINT_H_ ] diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/ostreamwrapper.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/ostreamwrapper.h new file mode 100644 index 0000000000..6f4667c08a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/ostreamwrapper.h @@ -0,0 +1,81 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_OSTREAMWRAPPER_H_ +#define RAPIDJSON_OSTREAMWRAPPER_H_ + +#include "stream.h" +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept. +/*! + The classes can be wrapped including but not limited to: + + - \c std::ostringstream + - \c std::stringstream + - \c std::wpstringstream + - \c std::wstringstream + - \c std::ifstream + - \c std::fstream + - \c std::wofstream + - \c std::wfstream + + \tparam StreamType Class derived from \c std::basic_ostream. +*/ + +template +class BasicOStreamWrapper { +public: + typedef typename StreamType::char_type Ch; + BasicOStreamWrapper(StreamType& stream) : stream_(stream) {} + + void Put(Ch c) { + stream_.put(c); + } + + void Flush() { + stream_.flush(); + } + + // Not implemented + char Peek() const { RAPIDJSON_ASSERT(false); return 0; } + char Take() { RAPIDJSON_ASSERT(false); return 0; } + size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; } + char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + BasicOStreamWrapper(const BasicOStreamWrapper&); + BasicOStreamWrapper& operator=(const BasicOStreamWrapper&); + + StreamType& stream_; +}; + +typedef BasicOStreamWrapper OStreamWrapper; +typedef BasicOStreamWrapper WOStreamWrapper; + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_OSTREAMWRAPPER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/pointer.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/pointer.h new file mode 100644 index 0000000000..0206ac1c8b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/pointer.h @@ -0,0 +1,1358 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_POINTER_H_ +#define RAPIDJSON_POINTER_H_ + +#include "document.h" +#include "internal/itoa.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(switch-enum) +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token + +//! Error code of parsing. +/*! \ingroup RAPIDJSON_ERRORS + \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode +*/ +enum PointerParseErrorCode { + kPointerParseErrorNone = 0, //!< The parse is successful + + kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a '/' + kPointerParseErrorInvalidEscape, //!< Invalid escape + kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI fragment + kPointerParseErrorCharacterMustPercentEncode //!< A character must percent encoded in URI fragment +}; + +/////////////////////////////////////////////////////////////////////////////// +// GenericPointer + +//! Represents a JSON Pointer. Use Pointer for UTF8 encoding and default allocator. +/*! + This class implements RFC 6901 "JavaScript Object Notation (JSON) Pointer" + (https://tools.ietf.org/html/rfc6901). + + A JSON pointer is for identifying a specific value in a JSON document + (GenericDocument). It can simplify coding of DOM tree manipulation, because it + can access multiple-level depth of DOM tree with single API call. + + After it parses a string representation (e.g. "/foo/0" or URI fragment + representation (e.g. "#/foo/0") into its internal representation (tokens), + it can be used to resolve a specific value in multiple documents, or sub-tree + of documents. + + Contrary to GenericValue, Pointer can be copy constructed and copy assigned. + Apart from assignment, a Pointer cannot be modified after construction. + + Although Pointer is very convenient, please aware that constructing Pointer + involves parsing and dynamic memory allocation. A special constructor with user- + supplied tokens eliminates these. + + GenericPointer depends on GenericDocument and GenericValue. + + \tparam ValueType The value type of the DOM tree. E.g. GenericValue > + \tparam Allocator The allocator type for allocating memory for internal representation. + + \note GenericPointer uses same encoding of ValueType. + However, Allocator of GenericPointer is independent of Allocator of Value. +*/ +template +class GenericPointer { +public: + typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value + typedef typename ValueType::Ch Ch; //!< Character type from Value + + //! A token is the basic units of internal representation. + /*! + A JSON pointer string representation "/foo/123" is parsed to two tokens: + "foo" and 123. 123 will be represented in both numeric form and string form. + They are resolved according to the actual value type (object or array). + + For token that are not numbers, or the numeric value is out of bound + (greater than limits of SizeType), they are only treated as string form + (i.e. the token's index will be equal to kPointerInvalidIndex). + + This struct is public so that user can create a Pointer without parsing and + allocation, using a special constructor. + */ + struct Token { + const Ch* name; //!< Name of the token. It has null character at the end but it can contain null character. + SizeType length; //!< Length of the name. + SizeType index; //!< A valid array index, if it is not equal to kPointerInvalidIndex. + }; + + //!@name Constructors and destructor. + //@{ + + //! Default constructor. + GenericPointer(Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} + + //! Constructor that parses a string or URI fragment representation. + /*! + \param source A null-terminated, string or URI fragment representation of JSON pointer. + \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. + */ + explicit GenericPointer(const Ch* source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { + Parse(source, internal::StrLen(source)); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Constructor that parses a string or URI fragment representation. + /*! + \param source A string or URI fragment representation of JSON pointer. + \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. + \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING. + */ + explicit GenericPointer(const std::basic_string& source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { + Parse(source.c_str(), source.size()); + } +#endif + + //! Constructor that parses a string or URI fragment representation, with length of the source string. + /*! + \param source A string or URI fragment representation of JSON pointer. + \param length Length of source. + \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one. + \note Slightly faster than the overload without length. + */ + GenericPointer(const Ch* source, size_t length, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { + Parse(source, length); + } + + //! Constructor with user-supplied tokens. + /*! + This constructor let user supplies const array of tokens. + This prevents the parsing process and eliminates allocation. + This is preferred for memory constrained environments. + + \param tokens An constant array of tokens representing the JSON pointer. + \param tokenCount Number of tokens. + + \b Example + \code + #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } + #define INDEX(i) { #i, sizeof(#i) - 1, i } + + static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) }; + static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); + // Equivalent to static const Pointer p("/foo/123"); + + #undef NAME + #undef INDEX + \endcode + */ + GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {} + + //! Copy constructor. + GenericPointer(const GenericPointer& rhs, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) { + *this = rhs; + } + + //! Destructor. + ~GenericPointer() { + if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ is nullptr and tokens_ are not deallocated. + Allocator::Free(tokens_); + RAPIDJSON_DELETE(ownAllocator_); + } + + //! Assignment operator. + GenericPointer& operator=(const GenericPointer& rhs) { + if (this != &rhs) { + // Do not delete ownAllcator + if (nameBuffer_) + Allocator::Free(tokens_); + + tokenCount_ = rhs.tokenCount_; + parseErrorOffset_ = rhs.parseErrorOffset_; + parseErrorCode_ = rhs.parseErrorCode_; + + if (rhs.nameBuffer_) + CopyFromRaw(rhs); // Normally parsed tokens. + else { + tokens_ = rhs.tokens_; // User supplied const tokens. + nameBuffer_ = 0; + } + } + return *this; + } + + //@} + + //!@name Append token + //@{ + + //! Append a token and return a new Pointer + /*! + \param token Token to be appended. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + GenericPointer Append(const Token& token, Allocator* allocator = 0) const { + GenericPointer r; + r.allocator_ = allocator; + Ch *p = r.CopyFromRaw(*this, 1, token.length + 1); + std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch)); + r.tokens_[tokenCount_].name = p; + r.tokens_[tokenCount_].length = token.length; + r.tokens_[tokenCount_].index = token.index; + return r; + } + + //! Append a name token with length, and return a new Pointer + /*! + \param name Name to be appended. + \param length Length of name. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const { + Token token = { name, length, kPointerInvalidIndex }; + return Append(token, allocator); + } + + //! Append a name token without length, and return a new Pointer + /*! + \param name Name (const Ch*) to be appended. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr::Type, Ch> >), (GenericPointer)) + Append(T* name, Allocator* allocator = 0) const { + return Append(name, StrLen(name), allocator); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Append a name token, and return a new Pointer + /*! + \param name Name to be appended. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + GenericPointer Append(const std::basic_string& name, Allocator* allocator = 0) const { + return Append(name.c_str(), static_cast(name.size()), allocator); + } +#endif + + //! Append a index token, and return a new Pointer + /*! + \param index Index to be appended. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + GenericPointer Append(SizeType index, Allocator* allocator = 0) const { + char buffer[21]; + char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer); + SizeType length = static_cast(end - buffer); + buffer[length] = '\0'; + + if (sizeof(Ch) == 1) { + Token token = { reinterpret_cast(buffer), length, index }; + return Append(token, allocator); + } + else { + Ch name[21]; + for (size_t i = 0; i <= length; i++) + name[i] = buffer[i]; + Token token = { name, length, index }; + return Append(token, allocator); + } + } + + //! Append a token by value, and return a new Pointer + /*! + \param token token to be appended. + \param allocator Allocator for the newly return Pointer. + \return A new Pointer with appended token. + */ + GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const { + if (token.IsString()) + return Append(token.GetString(), token.GetStringLength(), allocator); + else { + RAPIDJSON_ASSERT(token.IsUint64()); + RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0)); + return Append(static_cast(token.GetUint64()), allocator); + } + } + + //!@name Handling Parse Error + //@{ + + //! Check whether this is a valid pointer. + bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; } + + //! Get the parsing error offset in code unit. + size_t GetParseErrorOffset() const { return parseErrorOffset_; } + + //! Get the parsing error code. + PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; } + + //@} + + //! Get the allocator of this pointer. + Allocator& GetAllocator() { return *allocator_; } + + //!@name Tokens + //@{ + + //! Get the token array (const version only). + const Token* GetTokens() const { return tokens_; } + + //! Get the number of tokens. + size_t GetTokenCount() const { return tokenCount_; } + + //@} + + //!@name Equality/inequality operators + //@{ + + //! Equality operator. + /*! + \note When any pointers are invalid, always returns false. + */ + bool operator==(const GenericPointer& rhs) const { + if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_) + return false; + + for (size_t i = 0; i < tokenCount_; i++) { + if (tokens_[i].index != rhs.tokens_[i].index || + tokens_[i].length != rhs.tokens_[i].length || + (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0)) + { + return false; + } + } + + return true; + } + + //! Inequality operator. + /*! + \note When any pointers are invalid, always returns true. + */ + bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); } + + //@} + + //!@name Stringify + //@{ + + //! Stringify the pointer into string representation. + /*! + \tparam OutputStream Type of output stream. + \param os The output stream. + */ + template + bool Stringify(OutputStream& os) const { + return Stringify(os); + } + + //! Stringify the pointer into URI fragment representation. + /*! + \tparam OutputStream Type of output stream. + \param os The output stream. + */ + template + bool StringifyUriFragment(OutputStream& os) const { + return Stringify(os); + } + + //@} + + //!@name Create value + //@{ + + //! Create a value in a subtree. + /*! + If the value is not exist, it creates all parent values and a JSON Null value. + So it always succeed and return the newly created or existing value. + + Remind that it may change types of parents according to tokens, so it + potentially removes previously stored values. For example, if a document + was an array, and "/foo" is used to create a value, then the document + will be changed to an object, and all existing array elements are lost. + + \param root Root value of a DOM subtree to be resolved. It can be any value other than document root. + \param allocator Allocator for creating the values if the specified value or its parents are not exist. + \param alreadyExist If non-null, it stores whether the resolved value is already exist. + \return The resolved newly created (a JSON Null value), or already exists value. + */ + ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const { + RAPIDJSON_ASSERT(IsValid()); + ValueType* v = &root; + bool exist = true; + for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { + if (v->IsArray() && t->name[0] == '-' && t->length == 1) { + v->PushBack(ValueType().Move(), allocator); + v = &((*v)[v->Size() - 1]); + exist = false; + } + else { + if (t->index == kPointerInvalidIndex) { // must be object name + if (!v->IsObject()) + v->SetObject(); // Change to Object + } + else { // object name or array index + if (!v->IsArray() && !v->IsObject()) + v->SetArray(); // Change to Array + } + + if (v->IsArray()) { + if (t->index >= v->Size()) { + v->Reserve(t->index + 1, allocator); + while (t->index >= v->Size()) + v->PushBack(ValueType().Move(), allocator); + exist = false; + } + v = &((*v)[t->index]); + } + else { + typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); + if (m == v->MemberEnd()) { + v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator); + v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end + exist = false; + } + else + v = &m->value; + } + } + } + + if (alreadyExist) + *alreadyExist = exist; + + return *v; + } + + //! Creates a value in a document. + /*! + \param document A document to be resolved. + \param alreadyExist If non-null, it stores whether the resolved value is already exist. + \return The resolved newly created, or already exists value. + */ + template + ValueType& Create(GenericDocument& document, bool* alreadyExist = 0) const { + return Create(document, document.GetAllocator(), alreadyExist); + } + + //@} + + //!@name Query value + //@{ + + //! Query a value in a subtree. + /*! + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token. + \return Pointer to the value if it can be resolved. Otherwise null. + + \note + There are only 3 situations when a value cannot be resolved: + 1. A value in the path is not an array nor object. + 2. An object value does not contain the token. + 3. A token is out of range of an array value. + + Use unresolvedTokenIndex to retrieve the token index. + */ + ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const { + RAPIDJSON_ASSERT(IsValid()); + ValueType* v = &root; + for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { + switch (v->GetType()) { + case kObjectType: + { + typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); + if (m == v->MemberEnd()) + break; + v = &m->value; + } + continue; + case kArrayType: + if (t->index == kPointerInvalidIndex || t->index >= v->Size()) + break; + v = &((*v)[t->index]); + continue; + default: + break; + } + + // Error: unresolved token + if (unresolvedTokenIndex) + *unresolvedTokenIndex = static_cast(t - tokens_); + return 0; + } + return v; + } + + //! Query a const value in a const subtree. + /*! + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \return Pointer to the value if it can be resolved. Otherwise null. + */ + const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const { + return Get(const_cast(root), unresolvedTokenIndex); + } + + //@} + + //!@name Query a value with default + //@{ + + //! Query a value in a subtree with default value. + /*! + Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value. + So that this function always succeed. + + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \param defaultValue Default value to be cloned if the value was not exists. + \param allocator Allocator for creating the values if the specified value or its parents are not exist. + \see Create() + */ + ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const { + bool alreadyExist; + Value& v = Create(root, allocator, &alreadyExist); + return alreadyExist ? v : v.CopyFrom(defaultValue, allocator); + } + + //! Query a value in a subtree with default null-terminated string. + ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const { + bool alreadyExist; + Value& v = Create(root, allocator, &alreadyExist); + return alreadyExist ? v : v.SetString(defaultValue, allocator); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Query a value in a subtree with default std::basic_string. + ValueType& GetWithDefault(ValueType& root, const std::basic_string& defaultValue, typename ValueType::AllocatorType& allocator) const { + bool alreadyExist; + Value& v = Create(root, allocator, &alreadyExist); + return alreadyExist ? v : v.SetString(defaultValue, allocator); + } +#endif + + //! Query a value in a subtree with default primitive value. + /*! + \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) + GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const { + return GetWithDefault(root, ValueType(defaultValue).Move(), allocator); + } + + //! Query a value in a document with default value. + template + ValueType& GetWithDefault(GenericDocument& document, const ValueType& defaultValue) const { + return GetWithDefault(document, defaultValue, document.GetAllocator()); + } + + //! Query a value in a document with default null-terminated string. + template + ValueType& GetWithDefault(GenericDocument& document, const Ch* defaultValue) const { + return GetWithDefault(document, defaultValue, document.GetAllocator()); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Query a value in a document with default std::basic_string. + template + ValueType& GetWithDefault(GenericDocument& document, const std::basic_string& defaultValue) const { + return GetWithDefault(document, defaultValue, document.GetAllocator()); + } +#endif + + //! Query a value in a document with default primitive value. + /*! + \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) + GetWithDefault(GenericDocument& document, T defaultValue) const { + return GetWithDefault(document, defaultValue, document.GetAllocator()); + } + + //@} + + //!@name Set a value + //@{ + + //! Set a value in a subtree, with move semantics. + /*! + It creates all parents if they are not exist or types are different to the tokens. + So this function always succeeds but potentially remove existing values. + + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \param value Value to be set. + \param allocator Allocator for creating the values if the specified value or its parents are not exist. + \see Create() + */ + ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator) = value; + } + + //! Set a value in a subtree, with copy semantics. + ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator).CopyFrom(value, allocator); + } + + //! Set a null-terminated string in a subtree. + ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator) = ValueType(value, allocator).Move(); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Set a std::basic_string in a subtree. + ValueType& Set(ValueType& root, const std::basic_string& value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator) = ValueType(value, allocator).Move(); + } +#endif + + //! Set a primitive value in a subtree. + /*! + \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) + Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator) = ValueType(value).Move(); + } + + //! Set a value in a document, with move semantics. + template + ValueType& Set(GenericDocument& document, ValueType& value) const { + return Create(document) = value; + } + + //! Set a value in a document, with copy semantics. + template + ValueType& Set(GenericDocument& document, const ValueType& value) const { + return Create(document).CopyFrom(value, document.GetAllocator()); + } + + //! Set a null-terminated string in a document. + template + ValueType& Set(GenericDocument& document, const Ch* value) const { + return Create(document) = ValueType(value, document.GetAllocator()).Move(); + } + +#if RAPIDJSON_HAS_STDSTRING + //! Sets a std::basic_string in a document. + template + ValueType& Set(GenericDocument& document, const std::basic_string& value) const { + return Create(document) = ValueType(value, document.GetAllocator()).Move(); + } +#endif + + //! Set a primitive value in a document. + /*! + \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool + */ + template + RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (ValueType&)) + Set(GenericDocument& document, T value) const { + return Create(document) = value; + } + + //@} + + //!@name Swap a value + //@{ + + //! Swap a value with a value in a subtree. + /*! + It creates all parents if they are not exist or types are different to the tokens. + So this function always succeeds but potentially remove existing values. + + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \param value Value to be swapped. + \param allocator Allocator for creating the values if the specified value or its parents are not exist. + \see Create() + */ + ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const { + return Create(root, allocator).Swap(value); + } + + //! Swap a value with a value in a document. + template + ValueType& Swap(GenericDocument& document, ValueType& value) const { + return Create(document).Swap(value); + } + + //@} + + //! Erase a value in a subtree. + /*! + \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root. + \return Whether the resolved value is found and erased. + + \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false. + */ + bool Erase(ValueType& root) const { + RAPIDJSON_ASSERT(IsValid()); + if (tokenCount_ == 0) // Cannot erase the root + return false; + + ValueType* v = &root; + const Token* last = tokens_ + (tokenCount_ - 1); + for (const Token *t = tokens_; t != last; ++t) { + switch (v->GetType()) { + case kObjectType: + { + typename ValueType::MemberIterator m = v->FindMember(GenericStringRef(t->name, t->length)); + if (m == v->MemberEnd()) + return false; + v = &m->value; + } + break; + case kArrayType: + if (t->index == kPointerInvalidIndex || t->index >= v->Size()) + return false; + v = &((*v)[t->index]); + break; + default: + return false; + } + } + + switch (v->GetType()) { + case kObjectType: + return v->EraseMember(GenericStringRef(last->name, last->length)); + case kArrayType: + if (last->index == kPointerInvalidIndex || last->index >= v->Size()) + return false; + v->Erase(v->Begin() + last->index); + return true; + default: + return false; + } + } + +private: + //! Clone the content from rhs to this. + /*! + \param rhs Source pointer. + \param extraToken Extra tokens to be allocated. + \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated. + \return Start of non-occupied name buffer, for storing extra names. + */ + Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) { + if (!allocator_) // allocator is independently owned. + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + + size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens + for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t) + nameBufferSize += t->length; + + tokenCount_ = rhs.tokenCount_ + extraToken; + tokens_ = static_cast(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch))); + nameBuffer_ = reinterpret_cast(tokens_ + tokenCount_); + if (rhs.tokenCount_ > 0) { + std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token)); + } + if (nameBufferSize > 0) { + std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch)); + } + + // Adjust pointers to name buffer + std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_; + for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t) + t->name += diff; + + return nameBuffer_ + nameBufferSize; + } + + //! Check whether a character should be percent-encoded. + /*! + According to RFC 3986 2.3 Unreserved Characters. + \param c The character (code unit) to be tested. + */ + bool NeedPercentEncode(Ch c) const { + return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~'); + } + + //! Parse a JSON String or its URI fragment representation into tokens. +#ifndef __clang__ // -Wdocumentation + /*! + \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated. + \param length Length of the source string. + \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped. + */ +#endif + void Parse(const Ch* source, size_t length) { + RAPIDJSON_ASSERT(source != NULL); + RAPIDJSON_ASSERT(nameBuffer_ == 0); + RAPIDJSON_ASSERT(tokens_ == 0); + + // Create own allocator if user did not supply. + if (!allocator_) + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + + // Count number of '/' as tokenCount + tokenCount_ = 0; + for (const Ch* s = source; s != source + length; s++) + if (*s == '/') + tokenCount_++; + + Token* token = tokens_ = static_cast(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch))); + Ch* name = nameBuffer_ = reinterpret_cast(tokens_ + tokenCount_); + size_t i = 0; + + // Detect if it is a URI fragment + bool uriFragment = false; + if (source[i] == '#') { + uriFragment = true; + i++; + } + + if (i != length && source[i] != '/') { + parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus; + goto error; + } + + while (i < length) { + RAPIDJSON_ASSERT(source[i] == '/'); + i++; // consumes '/' + + token->name = name; + bool isNumber = true; + + while (i < length && source[i] != '/') { + Ch c = source[i]; + if (uriFragment) { + // Decoding percent-encoding for URI fragment + if (c == '%') { + PercentDecodeStream is(&source[i], source + length); + GenericInsituStringStream os(name); + Ch* begin = os.PutBegin(); + if (!Transcoder, EncodingType>().Validate(is, os) || !is.IsValid()) { + parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding; + goto error; + } + size_t len = os.PutEnd(begin); + i += is.Tell() - 1; + if (len == 1) + c = *name; + else { + name += len; + isNumber = false; + i++; + continue; + } + } + else if (NeedPercentEncode(c)) { + parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode; + goto error; + } + } + + i++; + + // Escaping "~0" -> '~', "~1" -> '/' + if (c == '~') { + if (i < length) { + c = source[i]; + if (c == '0') c = '~'; + else if (c == '1') c = '/'; + else { + parseErrorCode_ = kPointerParseErrorInvalidEscape; + goto error; + } + i++; + } + else { + parseErrorCode_ = kPointerParseErrorInvalidEscape; + goto error; + } + } + + // First check for index: all of characters are digit + if (c < '0' || c > '9') + isNumber = false; + + *name++ = c; + } + token->length = static_cast(name - token->name); + if (token->length == 0) + isNumber = false; + *name++ = '\0'; // Null terminator + + // Second check for index: more than one digit cannot have leading zero + if (isNumber && token->length > 1 && token->name[0] == '0') + isNumber = false; + + // String to SizeType conversion + SizeType n = 0; + if (isNumber) { + for (size_t j = 0; j < token->length; j++) { + SizeType m = n * 10 + static_cast(token->name[j] - '0'); + if (m < n) { // overflow detection + isNumber = false; + break; + } + n = m; + } + } + + token->index = isNumber ? n : kPointerInvalidIndex; + token++; + } + + RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer + parseErrorCode_ = kPointerParseErrorNone; + return; + + error: + Allocator::Free(tokens_); + nameBuffer_ = 0; + tokens_ = 0; + tokenCount_ = 0; + parseErrorOffset_ = i; + return; + } + + //! Stringify to string or URI fragment representation. + /*! + \tparam uriFragment True for stringifying to URI fragment representation. False for string representation. + \tparam OutputStream type of output stream. + \param os The output stream. + */ + template + bool Stringify(OutputStream& os) const { + RAPIDJSON_ASSERT(IsValid()); + + if (uriFragment) + os.Put('#'); + + for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) { + os.Put('/'); + for (size_t j = 0; j < t->length; j++) { + Ch c = t->name[j]; + if (c == '~') { + os.Put('~'); + os.Put('0'); + } + else if (c == '/') { + os.Put('~'); + os.Put('1'); + } + else if (uriFragment && NeedPercentEncode(c)) { + // Transcode to UTF8 sequence + GenericStringStream source(&t->name[j]); + PercentEncodeStream target(os); + if (!Transcoder >().Validate(source, target)) + return false; + j += source.Tell() - 1; + } + else + os.Put(c); + } + } + return true; + } + + //! A helper stream for decoding a percent-encoded sequence into code unit. + /*! + This stream decodes %XY triplet into code unit (0-255). + If it encounters invalid characters, it sets output code unit as 0 and + mark invalid, and to be checked by IsValid(). + */ + class PercentDecodeStream { + public: + typedef typename ValueType::Ch Ch; + + //! Constructor + /*! + \param source Start of the stream + \param end Past-the-end of the stream. + */ + PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {} + + Ch Take() { + if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet + valid_ = false; + return 0; + } + src_++; + Ch c = 0; + for (int j = 0; j < 2; j++) { + c = static_cast(c << 4); + Ch h = *src_; + if (h >= '0' && h <= '9') c = static_cast(c + h - '0'); + else if (h >= 'A' && h <= 'F') c = static_cast(c + h - 'A' + 10); + else if (h >= 'a' && h <= 'f') c = static_cast(c + h - 'a' + 10); + else { + valid_ = false; + return 0; + } + src_++; + } + return c; + } + + size_t Tell() const { return static_cast(src_ - head_); } + bool IsValid() const { return valid_; } + + private: + const Ch* src_; //!< Current read position. + const Ch* head_; //!< Original head of the string. + const Ch* end_; //!< Past-the-end position. + bool valid_; //!< Whether the parsing is valid. + }; + + //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence. + template + class PercentEncodeStream { + public: + PercentEncodeStream(OutputStream& os) : os_(os) {} + void Put(char c) { // UTF-8 must be byte + unsigned char u = static_cast(c); + static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + os_.Put('%'); + os_.Put(hexDigits[u >> 4]); + os_.Put(hexDigits[u & 15]); + } + private: + OutputStream& os_; + }; + + Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_. + Allocator* ownAllocator_; //!< Allocator owned by this Pointer. + Ch* nameBuffer_; //!< A buffer containing all names in tokens. + Token* tokens_; //!< A list of tokens. + size_t tokenCount_; //!< Number of tokens in tokens_. + size_t parseErrorOffset_; //!< Offset in code unit when parsing fail. + PointerParseErrorCode parseErrorCode_; //!< Parsing error code. +}; + +//! GenericPointer for Value (UTF-8, default allocator). +typedef GenericPointer Pointer; + +//!@name Helper functions for GenericPointer +//@{ + +////////////////////////////////////////////////////////////////////////////// + +template +typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer& pointer, typename T::AllocatorType& a) { + return pointer.Create(root, a); +} + +template +typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Create(root, a); +} + +// No allocator parameter + +template +typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer& pointer) { + return pointer.Create(document); +} + +template +typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) { + return GenericPointer(source, N - 1).Create(document); +} + +////////////////////////////////////////////////////////////////////////////// + +template +typename T::ValueType* GetValueByPointer(T& root, const GenericPointer& pointer, size_t* unresolvedTokenIndex = 0) { + return pointer.Get(root, unresolvedTokenIndex); +} + +template +const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer& pointer, size_t* unresolvedTokenIndex = 0) { + return pointer.Get(root, unresolvedTokenIndex); +} + +template +typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) { + return GenericPointer(source, N - 1).Get(root, unresolvedTokenIndex); +} + +template +const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) { + return GenericPointer(source, N - 1).Get(root, unresolvedTokenIndex); +} + +////////////////////////////////////////////////////////////////////////////// + +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { + return pointer.GetWithDefault(root, defaultValue, a); +} + +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) { + return pointer.GetWithDefault(root, defaultValue, a); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, const std::basic_string& defaultValue, typename T::AllocatorType& a) { + return pointer.GetWithDefault(root, defaultValue, a); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) +GetValueByPointerWithDefault(T& root, const GenericPointer& pointer, T2 defaultValue, typename T::AllocatorType& a) { + return pointer.GetWithDefault(root, defaultValue, a); +} + +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); +} + +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string& defaultValue, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) +GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).GetWithDefault(root, defaultValue, a); +} + +// No allocator parameter + +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::ValueType& defaultValue) { + return pointer.GetWithDefault(document, defaultValue); +} + +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::Ch* defaultValue) { + return pointer.GetWithDefault(document, defaultValue); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, const std::basic_string& defaultValue) { + return pointer.GetWithDefault(document, defaultValue); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) +GetValueByPointerWithDefault(DocumentType& document, const GenericPointer& pointer, T2 defaultValue) { + return pointer.GetWithDefault(document, defaultValue); +} + +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) { + return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); +} + +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) { + return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string& defaultValue) { + return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) +GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) { + return GenericPointer(source, N - 1).GetWithDefault(document, defaultValue); +} + +////////////////////////////////////////////////////////////////////////////// + +template +typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { + return pointer.Set(root, value, a); +} + +template +typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) { + return pointer.Set(root, value, a); +} + +template +typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const typename T::Ch* value, typename T::AllocatorType& a) { + return pointer.Set(root, value, a); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename T::ValueType& SetValueByPointer(T& root, const GenericPointer& pointer, const std::basic_string& value, typename T::AllocatorType& a) { + return pointer.Set(root, value, a); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) +SetValueByPointer(T& root, const GenericPointer& pointer, T2 value, typename T::AllocatorType& a) { + return pointer.Set(root, value, a); +} + +template +typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Set(root, value, a); +} + +template +typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Set(root, value, a); +} + +template +typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Set(root, value, a); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string& value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Set(root, value, a); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename T::ValueType&)) +SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Set(root, value, a); +} + +// No allocator parameter + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, typename DocumentType::ValueType& value) { + return pointer.Set(document, value); +} + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::ValueType& value) { + return pointer.Set(document, value); +} + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const typename DocumentType::Ch* value) { + return pointer.Set(document, value); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer& pointer, const std::basic_string& value) { + return pointer.Set(document, value); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) +SetValueByPointer(DocumentType& document, const GenericPointer& pointer, T2 value) { + return pointer.Set(document, value); +} + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { + return GenericPointer(source, N - 1).Set(document, value); +} + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) { + return GenericPointer(source, N - 1).Set(document, value); +} + +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) { + return GenericPointer(source, N - 1).Set(document, value); +} + +#if RAPIDJSON_HAS_STDSTRING +template +typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string& value) { + return GenericPointer(source, N - 1).Set(document, value); +} +#endif + +template +RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr, internal::IsGenericValue >), (typename DocumentType::ValueType&)) +SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) { + return GenericPointer(source, N - 1).Set(document, value); +} + +////////////////////////////////////////////////////////////////////////////// + +template +typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer& pointer, typename T::ValueType& value, typename T::AllocatorType& a) { + return pointer.Swap(root, value, a); +} + +template +typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) { + return GenericPointer(source, N - 1).Swap(root, value, a); +} + +template +typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer& pointer, typename DocumentType::ValueType& value) { + return pointer.Swap(document, value); +} + +template +typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) { + return GenericPointer(source, N - 1).Swap(document, value); +} + +////////////////////////////////////////////////////////////////////////////// + +template +bool EraseValueByPointer(T& root, const GenericPointer& pointer) { + return pointer.Erase(root); +} + +template +bool EraseValueByPointer(T& root, const CharType(&source)[N]) { + return GenericPointer(source, N - 1).Erase(root); +} + +//@} + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_POINTER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/prettywriter.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/prettywriter.h new file mode 100644 index 0000000000..0dcb0fee92 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/prettywriter.h @@ -0,0 +1,255 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_PRETTYWRITER_H_ +#define RAPIDJSON_PRETTYWRITER_H_ + +#include "writer.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Combination of PrettyWriter format flags. +/*! \see PrettyWriter::SetFormatOptions + */ +enum PrettyFormatOptions { + kFormatDefault = 0, //!< Default pretty formatting. + kFormatSingleLineArray = 1 //!< Format arrays on a single line. +}; + +//! Writer with indentation and spacing. +/*! + \tparam OutputStream Type of ouptut os. + \tparam SourceEncoding Encoding of source string. + \tparam TargetEncoding Encoding of output stream. + \tparam StackAllocator Type of allocator for allocating memory of stack. +*/ +template, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> +class PrettyWriter : public Writer { +public: + typedef Writer Base; + typedef typename Base::Ch Ch; + + //! Constructor + /*! \param os Output stream. + \param allocator User supplied allocator. If it is null, it will create a private one. + \param levelDepth Initial capacity of stack. + */ + explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : + Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {} + + + explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) : + Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {} + + //! Set custom indentation. + /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r'). + \param indentCharCount Number of indent characters for each indentation level. + \note The default indentation is 4 spaces. + */ + PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) { + RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r'); + indentChar_ = indentChar; + indentCharCount_ = indentCharCount; + return *this; + } + + //! Set pretty writer formatting options. + /*! \param options Formatting options. + */ + PrettyWriter& SetFormatOptions(PrettyFormatOptions options) { + formatOptions_ = options; + return *this; + } + + /*! @name Implementation of Handler + \see Handler + */ + //@{ + + bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); } + bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); } + bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); } + bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); } + bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); } + bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); } + bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); } + + bool RawNumber(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + PrettyPrefix(kNumberType); + return Base::WriteString(str, length); + } + + bool String(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + PrettyPrefix(kStringType); + return Base::WriteString(str, length); + } + +#if RAPIDJSON_HAS_STDSTRING + bool String(const std::basic_string& str) { + return String(str.data(), SizeType(str.size())); + } +#endif + + bool StartObject() { + PrettyPrefix(kObjectType); + new (Base::level_stack_.template Push()) typename Base::Level(false); + return Base::WriteStartObject(); + } + + bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } + +#if RAPIDJSON_HAS_STDSTRING + bool Key(const std::basic_string& str) { + return Key(str.data(), SizeType(str.size())); + } +#endif + + bool EndObject(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); + RAPIDJSON_ASSERT(!Base::level_stack_.template Top()->inArray); + bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; + + if (!empty) { + Base::os_->Put('\n'); + WriteIndent(); + } + bool ret = Base::WriteEndObject(); + (void)ret; + RAPIDJSON_ASSERT(ret == true); + if (Base::level_stack_.Empty()) // end of json text + Base::os_->Flush(); + return true; + } + + bool StartArray() { + PrettyPrefix(kArrayType); + new (Base::level_stack_.template Push()) typename Base::Level(true); + return Base::WriteStartArray(); + } + + bool EndArray(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); + RAPIDJSON_ASSERT(Base::level_stack_.template Top()->inArray); + bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; + + if (!empty && !(formatOptions_ & kFormatSingleLineArray)) { + Base::os_->Put('\n'); + WriteIndent(); + } + bool ret = Base::WriteEndArray(); + (void)ret; + RAPIDJSON_ASSERT(ret == true); + if (Base::level_stack_.Empty()) // end of json text + Base::os_->Flush(); + return true; + } + + //@} + + /*! @name Convenience extensions */ + //@{ + + //! Simpler but slower overload. + bool String(const Ch* str) { return String(str, internal::StrLen(str)); } + bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); } + + //@} + + //! Write a raw JSON value. + /*! + For user to write a stringified JSON as a value. + + \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. + \param length Length of the json. + \param type Type of the root of json. + \note When using PrettyWriter::RawValue(), the result json may not be indented correctly. + */ + bool RawValue(const Ch* json, size_t length, Type type) { PrettyPrefix(type); return Base::WriteRawValue(json, length); } + +protected: + void PrettyPrefix(Type type) { + (void)type; + if (Base::level_stack_.GetSize() != 0) { // this value is not at root + typename Base::Level* level = Base::level_stack_.template Top(); + + if (level->inArray) { + if (level->valueCount > 0) { + Base::os_->Put(','); // add comma if it is not the first element in array + if (formatOptions_ & kFormatSingleLineArray) + Base::os_->Put(' '); + } + + if (!(formatOptions_ & kFormatSingleLineArray)) { + Base::os_->Put('\n'); + WriteIndent(); + } + } + else { // in object + if (level->valueCount > 0) { + if (level->valueCount % 2 == 0) { + Base::os_->Put(','); + Base::os_->Put('\n'); + } + else { + Base::os_->Put(':'); + Base::os_->Put(' '); + } + } + else + Base::os_->Put('\n'); + + if (level->valueCount % 2 == 0) + WriteIndent(); + } + if (!level->inArray && level->valueCount % 2 == 0) + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name + level->valueCount++; + } + else { + RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root. + Base::hasRoot_ = true; + } + } + + void WriteIndent() { + size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_; + PutN(*Base::os_, static_cast(indentChar_), count); + } + + Ch indentChar_; + unsigned indentCharCount_; + PrettyFormatOptions formatOptions_; + +private: + // Prohibit copy constructor & assignment operator. + PrettyWriter(const PrettyWriter&); + PrettyWriter& operator=(const PrettyWriter&); +}; + +RAPIDJSON_NAMESPACE_END + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/rapidjson.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/rapidjson.h new file mode 100644 index 0000000000..053b2ce43f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/rapidjson.h @@ -0,0 +1,615 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_RAPIDJSON_H_ +#define RAPIDJSON_RAPIDJSON_H_ + +/*!\file rapidjson.h + \brief common definitions and configuration + + \see RAPIDJSON_CONFIG + */ + +/*! \defgroup RAPIDJSON_CONFIG RapidJSON configuration + \brief Configuration macros for library features + + Some RapidJSON features are configurable to adapt the library to a wide + variety of platforms, environments and usage scenarios. Most of the + features can be configured in terms of overriden or predefined + preprocessor macros at compile-time. + + Some additional customization is available in the \ref RAPIDJSON_ERRORS APIs. + + \note These macros should be given on the compiler command-line + (where applicable) to avoid inconsistent values when compiling + different translation units of a single application. + */ + +#include // malloc(), realloc(), free(), size_t +#include // memset(), memcpy(), memmove(), memcmp() + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_VERSION_STRING +// +// ALWAYS synchronize the following 3 macros with corresponding variables in /CMakeLists.txt. +// + +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +// token stringification +#define RAPIDJSON_STRINGIFY(x) RAPIDJSON_DO_STRINGIFY(x) +#define RAPIDJSON_DO_STRINGIFY(x) #x +//!@endcond + +/*! \def RAPIDJSON_MAJOR_VERSION + \ingroup RAPIDJSON_CONFIG + \brief Major version of RapidJSON in integer. +*/ +/*! \def RAPIDJSON_MINOR_VERSION + \ingroup RAPIDJSON_CONFIG + \brief Minor version of RapidJSON in integer. +*/ +/*! \def RAPIDJSON_PATCH_VERSION + \ingroup RAPIDJSON_CONFIG + \brief Patch version of RapidJSON in integer. +*/ +/*! \def RAPIDJSON_VERSION_STRING + \ingroup RAPIDJSON_CONFIG + \brief Version of RapidJSON in ".." string format. +*/ +#define RAPIDJSON_MAJOR_VERSION 1 +#define RAPIDJSON_MINOR_VERSION 1 +#define RAPIDJSON_PATCH_VERSION 0 +#define RAPIDJSON_VERSION_STRING \ + RAPIDJSON_STRINGIFY(RAPIDJSON_MAJOR_VERSION.RAPIDJSON_MINOR_VERSION.RAPIDJSON_PATCH_VERSION) + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_NAMESPACE_(BEGIN|END) +/*! \def RAPIDJSON_NAMESPACE + \ingroup RAPIDJSON_CONFIG + \brief provide custom rapidjson namespace + + In order to avoid symbol clashes and/or "One Definition Rule" errors + between multiple inclusions of (different versions of) RapidJSON in + a single binary, users can customize the name of the main RapidJSON + namespace. + + In case of a single nesting level, defining \c RAPIDJSON_NAMESPACE + to a custom name (e.g. \c MyRapidJSON) is sufficient. If multiple + levels are needed, both \ref RAPIDJSON_NAMESPACE_BEGIN and \ref + RAPIDJSON_NAMESPACE_END need to be defined as well: + + \code + // in some .cpp file + #define RAPIDJSON_NAMESPACE my::rapidjson + #define RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapidjson { + #define RAPIDJSON_NAMESPACE_END } } + #include "rapidjson/..." + \endcode + + \see rapidjson + */ +/*! \def RAPIDJSON_NAMESPACE_BEGIN + \ingroup RAPIDJSON_CONFIG + \brief provide custom rapidjson namespace (opening expression) + \see RAPIDJSON_NAMESPACE +*/ +/*! \def RAPIDJSON_NAMESPACE_END + \ingroup RAPIDJSON_CONFIG + \brief provide custom rapidjson namespace (closing expression) + \see RAPIDJSON_NAMESPACE +*/ +#ifndef RAPIDJSON_NAMESPACE +#define RAPIDJSON_NAMESPACE rapidjson +#endif +#ifndef RAPIDJSON_NAMESPACE_BEGIN +#define RAPIDJSON_NAMESPACE_BEGIN namespace RAPIDJSON_NAMESPACE { +#endif +#ifndef RAPIDJSON_NAMESPACE_END +#define RAPIDJSON_NAMESPACE_END } +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_HAS_STDSTRING + +#ifndef RAPIDJSON_HAS_STDSTRING +#ifdef RAPIDJSON_DOXYGEN_RUNNING +#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation +#else +#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default +#endif +/*! \def RAPIDJSON_HAS_STDSTRING + \ingroup RAPIDJSON_CONFIG + \brief Enable RapidJSON support for \c std::string + + By defining this preprocessor symbol to \c 1, several convenience functions for using + \ref rapidjson::GenericValue with \c std::string are enabled, especially + for construction and comparison. + + \hideinitializer +*/ +#endif // !defined(RAPIDJSON_HAS_STDSTRING) + +#if RAPIDJSON_HAS_STDSTRING +#include +#endif // RAPIDJSON_HAS_STDSTRING + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_NO_INT64DEFINE + +/*! \def RAPIDJSON_NO_INT64DEFINE + \ingroup RAPIDJSON_CONFIG + \brief Use external 64-bit integer types. + + RapidJSON requires the 64-bit integer types \c int64_t and \c uint64_t types + to be available at global scope. + + If users have their own definition, define RAPIDJSON_NO_INT64DEFINE to + prevent RapidJSON from defining its own types. +*/ +#ifndef RAPIDJSON_NO_INT64DEFINE +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013 +#include "msinttypes/stdint.h" +#include "msinttypes/inttypes.h" +#else +// Other compilers should have this. +#include +#include +#endif +//!@endcond +#ifdef RAPIDJSON_DOXYGEN_RUNNING +#define RAPIDJSON_NO_INT64DEFINE +#endif +#endif // RAPIDJSON_NO_INT64TYPEDEF + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_FORCEINLINE + +#ifndef RAPIDJSON_FORCEINLINE +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#if defined(_MSC_VER) && defined(NDEBUG) +#define RAPIDJSON_FORCEINLINE __forceinline +#elif defined(__GNUC__) && __GNUC__ >= 4 && defined(NDEBUG) +#define RAPIDJSON_FORCEINLINE __attribute__((always_inline)) +#else +#define RAPIDJSON_FORCEINLINE +#endif +//!@endcond +#endif // RAPIDJSON_FORCEINLINE + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ENDIAN +#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine +#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine + +//! Endianness of the machine. +/*! + \def RAPIDJSON_ENDIAN + \ingroup RAPIDJSON_CONFIG + + GCC 4.6 provided macro for detecting endianness of the target machine. But other + compilers may not have this. User can define RAPIDJSON_ENDIAN to either + \ref RAPIDJSON_LITTLEENDIAN or \ref RAPIDJSON_BIGENDIAN. + + Default detection implemented with reference to + \li https://gcc.gnu.org/onlinedocs/gcc-4.6.0/cpp/Common-Predefined-Macros.html + \li http://www.boost.org/doc/libs/1_42_0/boost/detail/endian.hpp +*/ +#ifndef RAPIDJSON_ENDIAN +// Detect with GCC 4.6's macro +# ifdef __BYTE_ORDER__ +# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN +# else +# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN. +# endif // __BYTE_ORDER__ +// Detect with GLIBC's endian.h +# elif defined(__GLIBC__) +# include +# if (__BYTE_ORDER == __LITTLE_ENDIAN) +# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +# elif (__BYTE_ORDER == __BIG_ENDIAN) +# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN +# else +# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN. +# endif // __GLIBC__ +// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro +# elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) +# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +# elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) +# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN +// Detect with architecture macros +# elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__) +# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN +# elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__) +# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +# elif defined(_MSC_VER) && defined(_M_ARM) +# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN +# elif defined(RAPIDJSON_DOXYGEN_RUNNING) +# define RAPIDJSON_ENDIAN +# else +# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN. +# endif +#endif // RAPIDJSON_ENDIAN + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_64BIT + +//! Whether using 64-bit architecture +#ifndef RAPIDJSON_64BIT +#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || defined(_WIN64) || defined(__EMSCRIPTEN__) +#define RAPIDJSON_64BIT 1 +#else +#define RAPIDJSON_64BIT 0 +#endif +#endif // RAPIDJSON_64BIT + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ALIGN + +//! Data alignment of the machine. +/*! \ingroup RAPIDJSON_CONFIG + \param x pointer to align + + Some machines require strict data alignment. Currently the default uses 4 bytes + alignment on 32-bit platforms and 8 bytes alignment for 64-bit platforms. + User can customize by defining the RAPIDJSON_ALIGN function macro. +*/ +#ifndef RAPIDJSON_ALIGN +#if RAPIDJSON_64BIT == 1 +#define RAPIDJSON_ALIGN(x) (((x) + static_cast(7u)) & ~static_cast(7u)) +#else +#define RAPIDJSON_ALIGN(x) (((x) + 3u) & ~3u) +#endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_UINT64_C2 + +//! Construct a 64-bit literal by a pair of 32-bit integer. +/*! + 64-bit literal with or without ULL suffix is prone to compiler warnings. + UINT64_C() is C macro which cause compilation problems. + Use this macro to define 64-bit constants by a pair of 32-bit integer. +*/ +#ifndef RAPIDJSON_UINT64_C2 +#define RAPIDJSON_UINT64_C2(high32, low32) ((static_cast(high32) << 32) | static_cast(low32)) +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_48BITPOINTER_OPTIMIZATION + +//! Use only lower 48-bit address for some pointers. +/*! + \ingroup RAPIDJSON_CONFIG + + This optimization uses the fact that current X86-64 architecture only implement lower 48-bit virtual address. + The higher 16-bit can be used for storing other data. + \c GenericValue uses this optimization to reduce its size form 24 bytes to 16 bytes in 64-bit architecture. +*/ +#ifndef RAPIDJSON_48BITPOINTER_OPTIMIZATION +#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) +#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 1 +#else +#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 0 +#endif +#endif // RAPIDJSON_48BITPOINTER_OPTIMIZATION + +#if RAPIDJSON_48BITPOINTER_OPTIMIZATION == 1 +#if RAPIDJSON_64BIT != 1 +#error RAPIDJSON_48BITPOINTER_OPTIMIZATION can only be set to 1 when RAPIDJSON_64BIT=1 +#endif +#define RAPIDJSON_SETPOINTER(type, p, x) (p = reinterpret_cast((reinterpret_cast(p) & static_cast(RAPIDJSON_UINT64_C2(0xFFFF0000, 0x00000000))) | reinterpret_cast(reinterpret_cast(x)))) +#define RAPIDJSON_GETPOINTER(type, p) (reinterpret_cast(reinterpret_cast(p) & static_cast(RAPIDJSON_UINT64_C2(0x0000FFFF, 0xFFFFFFFF)))) +#else +#define RAPIDJSON_SETPOINTER(type, p, x) (p = (x)) +#define RAPIDJSON_GETPOINTER(type, p) (p) +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD + +/*! \def RAPIDJSON_SIMD + \ingroup RAPIDJSON_CONFIG + \brief Enable SSE2/SSE4.2 optimization. + + RapidJSON supports optimized implementations for some parsing operations + based on the SSE2 or SSE4.2 SIMD extensions on modern Intel-compatible + processors. + + To enable these optimizations, two different symbols can be defined; + \code + // Enable SSE2 optimization. + #define RAPIDJSON_SSE2 + + // Enable SSE4.2 optimization. + #define RAPIDJSON_SSE42 + \endcode + + \c RAPIDJSON_SSE42 takes precedence, if both are defined. + + If any of these symbols is defined, RapidJSON defines the macro + \c RAPIDJSON_SIMD to indicate the availability of the optimized code. +*/ +#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) \ + || defined(RAPIDJSON_DOXYGEN_RUNNING) +#define RAPIDJSON_SIMD +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_NO_SIZETYPEDEFINE + +#ifndef RAPIDJSON_NO_SIZETYPEDEFINE +/*! \def RAPIDJSON_NO_SIZETYPEDEFINE + \ingroup RAPIDJSON_CONFIG + \brief User-provided \c SizeType definition. + + In order to avoid using 32-bit size types for indexing strings and arrays, + define this preprocessor symbol and provide the type rapidjson::SizeType + before including RapidJSON: + \code + #define RAPIDJSON_NO_SIZETYPEDEFINE + namespace rapidjson { typedef ::std::size_t SizeType; } + #include "rapidjson/..." + \endcode + + \see rapidjson::SizeType +*/ +#ifdef RAPIDJSON_DOXYGEN_RUNNING +#define RAPIDJSON_NO_SIZETYPEDEFINE +#endif +RAPIDJSON_NAMESPACE_BEGIN +//! Size type (for string lengths, array sizes, etc.) +/*! RapidJSON uses 32-bit array/string indices even on 64-bit platforms, + instead of using \c size_t. Users may override the SizeType by defining + \ref RAPIDJSON_NO_SIZETYPEDEFINE. +*/ +typedef unsigned SizeType; +RAPIDJSON_NAMESPACE_END +#endif + +// always import std::size_t to rapidjson namespace +RAPIDJSON_NAMESPACE_BEGIN +using std::size_t; +RAPIDJSON_NAMESPACE_END + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_ASSERT + +//! Assertion. +/*! \ingroup RAPIDJSON_CONFIG + By default, rapidjson uses C \c assert() for internal assertions. + User can override it by defining RAPIDJSON_ASSERT(x) macro. + + \note Parsing errors are handled and can be customized by the + \ref RAPIDJSON_ERRORS APIs. +*/ +#ifndef RAPIDJSON_ASSERT +#include +#define RAPIDJSON_ASSERT(x) assert(x) +#endif // RAPIDJSON_ASSERT + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_STATIC_ASSERT + +// Adopt from boost +#ifndef RAPIDJSON_STATIC_ASSERT +#ifndef __clang__ +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#endif +RAPIDJSON_NAMESPACE_BEGIN +template struct STATIC_ASSERTION_FAILURE; +template <> struct STATIC_ASSERTION_FAILURE { enum { value = 1 }; }; +template struct StaticAssertTest {}; +RAPIDJSON_NAMESPACE_END + +#define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y) +#define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y) +#define RAPIDJSON_DO_JOIN2(X, Y) X##Y + +#if defined(__GNUC__) +#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) +#else +#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE +#endif +#ifndef __clang__ +//!@endcond +#endif + +/*! \def RAPIDJSON_STATIC_ASSERT + \brief (Internal) macro to check for conditions at compile-time + \param x compile-time condition + \hideinitializer + */ +#define RAPIDJSON_STATIC_ASSERT(x) \ + typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest< \ + sizeof(::RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE)> \ + RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE +#endif + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY + +//! Compiler branching hint for expression with high probability to be true. +/*! + \ingroup RAPIDJSON_CONFIG + \param x Boolean expression likely to be true. +*/ +#ifndef RAPIDJSON_LIKELY +#if defined(__GNUC__) || defined(__clang__) +#define RAPIDJSON_LIKELY(x) __builtin_expect(!!(x), 1) +#else +#define RAPIDJSON_LIKELY(x) (x) +#endif +#endif + +//! Compiler branching hint for expression with low probability to be true. +/*! + \ingroup RAPIDJSON_CONFIG + \param x Boolean expression unlikely to be true. +*/ +#ifndef RAPIDJSON_UNLIKELY +#if defined(__GNUC__) || defined(__clang__) +#define RAPIDJSON_UNLIKELY(x) __builtin_expect(!!(x), 0) +#else +#define RAPIDJSON_UNLIKELY(x) (x) +#endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Helpers + +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN + +#define RAPIDJSON_MULTILINEMACRO_BEGIN do { +#define RAPIDJSON_MULTILINEMACRO_END \ +} while((void)0, 0) + +// adopted from Boost +#define RAPIDJSON_VERSION_CODE(x,y,z) \ + (((x)*100000) + ((y)*100) + (z)) + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_DIAG_PUSH/POP, RAPIDJSON_DIAG_OFF + +#if defined(__GNUC__) +#define RAPIDJSON_GNUC \ + RAPIDJSON_VERSION_CODE(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__) +#endif + +#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,2,0)) + +#define RAPIDJSON_PRAGMA(x) _Pragma(RAPIDJSON_STRINGIFY(x)) +#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(GCC diagnostic x) +#define RAPIDJSON_DIAG_OFF(x) \ + RAPIDJSON_DIAG_PRAGMA(ignored RAPIDJSON_STRINGIFY(RAPIDJSON_JOIN(-W,x))) + +// push/pop support in Clang and GCC>=4.6 +#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) +#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push) +#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop) +#else // GCC >= 4.2, < 4.6 +#define RAPIDJSON_DIAG_PUSH /* ignored */ +#define RAPIDJSON_DIAG_POP /* ignored */ +#endif + +#elif defined(_MSC_VER) + +// pragma (MSVC specific) +#define RAPIDJSON_PRAGMA(x) __pragma(x) +#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(warning(x)) + +#define RAPIDJSON_DIAG_OFF(x) RAPIDJSON_DIAG_PRAGMA(disable: x) +#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push) +#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop) + +#else + +#define RAPIDJSON_DIAG_OFF(x) /* ignored */ +#define RAPIDJSON_DIAG_PUSH /* ignored */ +#define RAPIDJSON_DIAG_POP /* ignored */ + +#endif // RAPIDJSON_DIAG_* + +/////////////////////////////////////////////////////////////////////////////// +// C++11 features + +#ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS +#if defined(__clang__) +#if __has_feature(cxx_rvalue_references) && \ + (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306) +#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 +#else +#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 +#endif +#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ + (defined(_MSC_VER) && _MSC_VER >= 1600) + +#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1 +#else +#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0 +#endif +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + +#ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT +#if defined(__clang__) +#define RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept) +#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) +// (defined(_MSC_VER) && _MSC_VER >= ????) // not yet supported +#define RAPIDJSON_HAS_CXX11_NOEXCEPT 1 +#else +#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0 +#endif +#endif +#if RAPIDJSON_HAS_CXX11_NOEXCEPT +#define RAPIDJSON_NOEXCEPT noexcept +#else +#define RAPIDJSON_NOEXCEPT /* noexcept */ +#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT + +// no automatic detection, yet +#ifndef RAPIDJSON_HAS_CXX11_TYPETRAITS +#define RAPIDJSON_HAS_CXX11_TYPETRAITS 0 +#endif + +#ifndef RAPIDJSON_HAS_CXX11_RANGE_FOR +#if defined(__clang__) +#define RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for) +#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \ + (defined(_MSC_VER) && _MSC_VER >= 1700) +#define RAPIDJSON_HAS_CXX11_RANGE_FOR 1 +#else +#define RAPIDJSON_HAS_CXX11_RANGE_FOR 0 +#endif +#endif // RAPIDJSON_HAS_CXX11_RANGE_FOR + +//!@endcond + +/////////////////////////////////////////////////////////////////////////////// +// new/delete + +#ifndef RAPIDJSON_NEW +///! customization point for global \c new +#define RAPIDJSON_NEW(x) new x +#endif +#ifndef RAPIDJSON_DELETE +///! customization point for global \c delete +#define RAPIDJSON_DELETE(x) delete x +#endif + +/////////////////////////////////////////////////////////////////////////////// +// Type + +/*! \namespace rapidjson + \brief main RapidJSON namespace + \see RAPIDJSON_NAMESPACE +*/ +RAPIDJSON_NAMESPACE_BEGIN + +//! Type of JSON value +enum Type { + kNullType = 0, //!< null + kFalseType = 1, //!< false + kTrueType = 2, //!< true + kObjectType = 3, //!< object + kArrayType = 4, //!< array + kStringType = 5, //!< string + kNumberType = 6 //!< number +}; + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/reader.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/reader.h new file mode 100644 index 0000000000..19f8849b14 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/reader.h @@ -0,0 +1,1879 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_READER_H_ +#define RAPIDJSON_READER_H_ + +/*! \file reader.h */ + +#include "allocators.h" +#include "stream.h" +#include "encodedstream.h" +#include "internal/meta.h" +#include "internal/stack.h" +#include "internal/strtod.h" +#include + +#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) +#include +#pragma intrinsic(_BitScanForward) +#endif +#ifdef RAPIDJSON_SSE42 +#include +#elif defined(RAPIDJSON_SSE2) +#include +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +RAPIDJSON_DIAG_OFF(4702) // unreachable code +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(old-style-cast) +RAPIDJSON_DIAG_OFF(padded) +RAPIDJSON_DIAG_OFF(switch-enum) +#endif + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#define RAPIDJSON_NOTHING /* deliberately empty */ +#ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN +#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + if (RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \ + RAPIDJSON_MULTILINEMACRO_END +#endif +#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \ + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING) +//!@endcond + +/*! \def RAPIDJSON_PARSE_ERROR_NORETURN + \ingroup RAPIDJSON_ERRORS + \brief Macro to indicate a parse error. + \param parseErrorCode \ref rapidjson::ParseErrorCode of the error + \param offset position of the error in JSON input (\c size_t) + + This macros can be used as a customization point for the internal + error handling mechanism of RapidJSON. + + A common usage model is to throw an exception instead of requiring the + caller to explicitly check the \ref rapidjson::GenericReader::Parse's + return value: + + \code + #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \ + throw ParseException(parseErrorCode, #parseErrorCode, offset) + + #include // std::runtime_error + #include "rapidjson/error/error.h" // rapidjson::ParseResult + + struct ParseException : std::runtime_error, rapidjson::ParseResult { + ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset) + : std::runtime_error(msg), ParseResult(code, offset) {} + }; + + #include "rapidjson/reader.h" + \endcode + + \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse + */ +#ifndef RAPIDJSON_PARSE_ERROR_NORETURN +#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \ + SetParseError(parseErrorCode, offset); \ + RAPIDJSON_MULTILINEMACRO_END +#endif + +/*! \def RAPIDJSON_PARSE_ERROR + \ingroup RAPIDJSON_ERRORS + \brief (Internal) macro to indicate and handle a parse error. + \param parseErrorCode \ref rapidjson::ParseErrorCode of the error + \param offset position of the error in JSON input (\c size_t) + + Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing. + + \see RAPIDJSON_PARSE_ERROR_NORETURN + \hideinitializer + */ +#ifndef RAPIDJSON_PARSE_ERROR +#define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \ + RAPIDJSON_MULTILINEMACRO_BEGIN \ + RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \ + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \ + RAPIDJSON_MULTILINEMACRO_END +#endif + +#include "error/error.h" // ParseErrorCode, ParseResult + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// ParseFlag + +/*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS + \ingroup RAPIDJSON_CONFIG + \brief User-defined kParseDefaultFlags definition. + + User can define this as any \c ParseFlag combinations. +*/ +#ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS +#define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags +#endif + +//! Combination of parseFlags +/*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream + */ +enum ParseFlag { + kParseNoFlags = 0, //!< No flags are set. + kParseInsituFlag = 1, //!< In-situ(destructive) parsing. + kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings. + kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing. + kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error. + kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower). + kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments. + kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings. + kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays. + kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles. + kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS +}; + +/////////////////////////////////////////////////////////////////////////////// +// Handler + +/*! \class rapidjson::Handler + \brief Concept for receiving events from GenericReader upon parsing. + The functions return true if no error occurs. If they return false, + the event publisher should terminate the process. +\code +concept Handler { + typename Ch; + + bool Null(); + bool Bool(bool b); + bool Int(int i); + bool Uint(unsigned i); + bool Int64(int64_t i); + bool Uint64(uint64_t i); + bool Double(double d); + /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) + bool RawNumber(const Ch* str, SizeType length, bool copy); + bool String(const Ch* str, SizeType length, bool copy); + bool StartObject(); + bool Key(const Ch* str, SizeType length, bool copy); + bool EndObject(SizeType memberCount); + bool StartArray(); + bool EndArray(SizeType elementCount); +}; +\endcode +*/ +/////////////////////////////////////////////////////////////////////////////// +// BaseReaderHandler + +//! Default implementation of Handler. +/*! This can be used as base class of any reader handler. + \note implements Handler concept +*/ +template, typename Derived = void> +struct BaseReaderHandler { + typedef typename Encoding::Ch Ch; + + typedef typename internal::SelectIf, BaseReaderHandler, Derived>::Type Override; + + bool Default() { return true; } + bool Null() { return static_cast(*this).Default(); } + bool Bool(bool) { return static_cast(*this).Default(); } + bool Int(int) { return static_cast(*this).Default(); } + bool Uint(unsigned) { return static_cast(*this).Default(); } + bool Int64(int64_t) { return static_cast(*this).Default(); } + bool Uint64(uint64_t) { return static_cast(*this).Default(); } + bool Double(double) { return static_cast(*this).Default(); } + /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length) + bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast(*this).String(str, len, copy); } + bool String(const Ch*, SizeType, bool) { return static_cast(*this).Default(); } + bool StartObject() { return static_cast(*this).Default(); } + bool Key(const Ch* str, SizeType len, bool copy) { return static_cast(*this).String(str, len, copy); } + bool EndObject(SizeType) { return static_cast(*this).Default(); } + bool StartArray() { return static_cast(*this).Default(); } + bool EndArray(SizeType) { return static_cast(*this).Default(); } +}; + +/////////////////////////////////////////////////////////////////////////////// +// StreamLocalCopy + +namespace internal { + +template::copyOptimization> +class StreamLocalCopy; + +//! Do copy optimization. +template +class StreamLocalCopy { +public: + StreamLocalCopy(Stream& original) : s(original), original_(original) {} + ~StreamLocalCopy() { original_ = s; } + + Stream s; + +private: + StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; + + Stream& original_; +}; + +//! Keep reference. +template +class StreamLocalCopy { +public: + StreamLocalCopy(Stream& original) : s(original) {} + + Stream& s; + +private: + StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */; +}; + +} // namespace internal + +/////////////////////////////////////////////////////////////////////////////// +// SkipWhitespace + +//! Skip the JSON white spaces in a stream. +/*! \param is A input stream for skipping white spaces. + \note This function has SSE2/SSE4.2 specialization. +*/ +template +void SkipWhitespace(InputStream& is) { + internal::StreamLocalCopy copy(is); + InputStream& s(copy.s); + + typename InputStream::Ch c; + while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t') + s.Take(); +} + +inline const char* SkipWhitespace(const char* p, const char* end) { + while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) + ++p; + return p; +} + +#ifdef RAPIDJSON_SSE42 +//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once. +inline const char *SkipWhitespace_SIMD(const char* p) { + // Fast return for single non-whitespace + if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') + ++p; + else + return p; + + // 16-byte align to the next boundary + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + while (p != nextAligned) + if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') + ++p; + else + return p; + + // The rest of string using SIMD + static const char whitespace[16] = " \n\r\t"; + const __m128i w = _mm_loadu_si128(reinterpret_cast(&whitespace[0])); + + for (;; p += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY)); + if (r != 0) { // some of characters is non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + _BitScanForward(&offset, r); + return p + offset; +#else + return p + __builtin_ffs(r) - 1; +#endif + } + } +} + +inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { + // Fast return for single non-whitespace + if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) + ++p; + else + return p; + + // The middle of string using SIMD + static const char whitespace[16] = " \n\r\t"; + const __m128i w = _mm_loadu_si128(reinterpret_cast(&whitespace[0])); + + for (; p <= end - 16; p += 16) { + const __m128i s = _mm_loadu_si128(reinterpret_cast(p)); + const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY)); + if (r != 0) { // some of characters is non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + _BitScanForward(&offset, r); + return p + offset; +#else + return p + __builtin_ffs(r) - 1; +#endif + } + } + + return SkipWhitespace(p, end); +} + +#elif defined(RAPIDJSON_SSE2) + +//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once. +inline const char *SkipWhitespace_SIMD(const char* p) { + // Fast return for single non-whitespace + if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') + ++p; + else + return p; + + // 16-byte align to the next boundary + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + while (p != nextAligned) + if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') + ++p; + else + return p; + + // The rest of string + #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } + static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; + #undef C16 + + const __m128i w0 = _mm_loadu_si128(reinterpret_cast(&whitespaces[0][0])); + const __m128i w1 = _mm_loadu_si128(reinterpret_cast(&whitespaces[1][0])); + const __m128i w2 = _mm_loadu_si128(reinterpret_cast(&whitespaces[2][0])); + const __m128i w3 = _mm_loadu_si128(reinterpret_cast(&whitespaces[3][0])); + + for (;; p += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + __m128i x = _mm_cmpeq_epi8(s, w0); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); + unsigned short r = static_cast(~_mm_movemask_epi8(x)); + if (r != 0) { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + _BitScanForward(&offset, r); + return p + offset; +#else + return p + __builtin_ffs(r) - 1; +#endif + } + } +} + +inline const char *SkipWhitespace_SIMD(const char* p, const char* end) { + // Fast return for single non-whitespace + if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')) + ++p; + else + return p; + + // The rest of string + #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c } + static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') }; + #undef C16 + + const __m128i w0 = _mm_loadu_si128(reinterpret_cast(&whitespaces[0][0])); + const __m128i w1 = _mm_loadu_si128(reinterpret_cast(&whitespaces[1][0])); + const __m128i w2 = _mm_loadu_si128(reinterpret_cast(&whitespaces[2][0])); + const __m128i w3 = _mm_loadu_si128(reinterpret_cast(&whitespaces[3][0])); + + for (; p <= end - 16; p += 16) { + const __m128i s = _mm_loadu_si128(reinterpret_cast(p)); + __m128i x = _mm_cmpeq_epi8(s, w0); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2)); + x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3)); + unsigned short r = static_cast(~_mm_movemask_epi8(x)); + if (r != 0) { // some of characters may be non-whitespace +#ifdef _MSC_VER // Find the index of first non-whitespace + unsigned long offset; + _BitScanForward(&offset, r); + return p + offset; +#else + return p + __builtin_ffs(r) - 1; +#endif + } + } + + return SkipWhitespace(p, end); +} + +#endif // RAPIDJSON_SSE2 + +#ifdef RAPIDJSON_SIMD +//! Template function specialization for InsituStringStream +template<> inline void SkipWhitespace(InsituStringStream& is) { + is.src_ = const_cast(SkipWhitespace_SIMD(is.src_)); +} + +//! Template function specialization for StringStream +template<> inline void SkipWhitespace(StringStream& is) { + is.src_ = SkipWhitespace_SIMD(is.src_); +} + +template<> inline void SkipWhitespace(EncodedInputStream, MemoryStream>& is) { + is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_); +} +#endif // RAPIDJSON_SIMD + +/////////////////////////////////////////////////////////////////////////////// +// GenericReader + +//! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator. +/*! GenericReader parses JSON text from a stream, and send events synchronously to an + object implementing Handler concept. + + It needs to allocate a stack for storing a single decoded string during + non-destructive parsing. + + For in-situ parsing, the decoded string is directly written to the source + text string, no temporary buffer is required. + + A GenericReader object can be reused for parsing multiple JSON text. + + \tparam SourceEncoding Encoding of the input stream. + \tparam TargetEncoding Encoding of the parse output. + \tparam StackAllocator Allocator type for stack. +*/ +template +class GenericReader { +public: + typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type + + //! Constructor. + /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing) + \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing) + */ + GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_() {} + + //! Parse JSON text. + /*! \tparam parseFlags Combination of \ref ParseFlag. + \tparam InputStream Type of input stream, implementing Stream concept. + \tparam Handler Type of handler, implementing Handler concept. + \param is Input stream to be parsed. + \param handler The handler to receive events. + \return Whether the parsing is successful. + */ + template + ParseResult Parse(InputStream& is, Handler& handler) { + if (parseFlags & kParseIterativeFlag) + return IterativeParse(is, handler); + + parseResult_.Clear(); + + ClearStackOnExit scope(*this); + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + + if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell()); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + } + else { + ParseValue(is, handler); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + + if (!(parseFlags & kParseStopWhenDoneFlag)) { + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + + if (RAPIDJSON_UNLIKELY(is.Peek() != '\0')) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell()); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + } + } + } + + return parseResult_; + } + + //! Parse JSON text (with \ref kParseDefaultFlags) + /*! \tparam InputStream Type of input stream, implementing Stream concept + \tparam Handler Type of handler, implementing Handler concept. + \param is Input stream to be parsed. + \param handler The handler to receive events. + \return Whether the parsing is successful. + */ + template + ParseResult Parse(InputStream& is, Handler& handler) { + return Parse(is, handler); + } + + //! Whether a parse error has occured in the last parsing. + bool HasParseError() const { return parseResult_.IsError(); } + + //! Get the \ref ParseErrorCode of last parsing. + ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); } + + //! Get the position of last parsing error in input, 0 otherwise. + size_t GetErrorOffset() const { return parseResult_.Offset(); } + +protected: + void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); } + +private: + // Prohibit copy constructor & assignment operator. + GenericReader(const GenericReader&); + GenericReader& operator=(const GenericReader&); + + void ClearStack() { stack_.Clear(); } + + // clear stack on any exit from ParseStream, e.g. due to exception + struct ClearStackOnExit { + explicit ClearStackOnExit(GenericReader& r) : r_(r) {} + ~ClearStackOnExit() { r_.ClearStack(); } + private: + GenericReader& r_; + ClearStackOnExit(const ClearStackOnExit&); + ClearStackOnExit& operator=(const ClearStackOnExit&); + }; + + template + void SkipWhitespaceAndComments(InputStream& is) { + SkipWhitespace(is); + + if (parseFlags & kParseCommentsFlag) { + while (RAPIDJSON_UNLIKELY(Consume(is, '/'))) { + if (Consume(is, '*')) { + while (true) { + if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) + RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); + else if (Consume(is, '*')) { + if (Consume(is, '/')) + break; + } + else + is.Take(); + } + } + else if (RAPIDJSON_LIKELY(Consume(is, '/'))) + while (is.Peek() != '\0' && is.Take() != '\n'); + else + RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell()); + + SkipWhitespace(is); + } + } + } + + // Parse object: { string : value, ... } + template + void ParseObject(InputStream& is, Handler& handler) { + RAPIDJSON_ASSERT(is.Peek() == '{'); + is.Take(); // Skip '{' + + if (RAPIDJSON_UNLIKELY(!handler.StartObject())) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + if (Consume(is, '}')) { + if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + return; + } + + for (SizeType memberCount = 0;;) { + if (RAPIDJSON_UNLIKELY(is.Peek() != '"')) + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); + + ParseString(is, handler, true); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + if (RAPIDJSON_UNLIKELY(!Consume(is, ':'))) + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + ParseValue(is, handler); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + ++memberCount; + + switch (is.Peek()) { + case ',': + is.Take(); + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + break; + case '}': + is.Take(); + if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + return; + default: + RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy + } + + if (parseFlags & kParseTrailingCommasFlag) { + if (is.Peek() == '}') { + if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + is.Take(); + return; + } + } + } + } + + // Parse array: [ value, ... ] + template + void ParseArray(InputStream& is, Handler& handler) { + RAPIDJSON_ASSERT(is.Peek() == '['); + is.Take(); // Skip '[' + + if (RAPIDJSON_UNLIKELY(!handler.StartArray())) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + if (Consume(is, ']')) { + if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + return; + } + + for (SizeType elementCount = 0;;) { + ParseValue(is, handler); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + ++elementCount; + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + + if (Consume(is, ',')) { + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + } + else if (Consume(is, ']')) { + if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + return; + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); + + if (parseFlags & kParseTrailingCommasFlag) { + if (is.Peek() == ']') { + if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + is.Take(); + return; + } + } + } + } + + template + void ParseNull(InputStream& is, Handler& handler) { + RAPIDJSON_ASSERT(is.Peek() == 'n'); + is.Take(); + + if (RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) { + if (RAPIDJSON_UNLIKELY(!handler.Null())) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); + } + + template + void ParseTrue(InputStream& is, Handler& handler) { + RAPIDJSON_ASSERT(is.Peek() == 't'); + is.Take(); + + if (RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) { + if (RAPIDJSON_UNLIKELY(!handler.Bool(true))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); + } + + template + void ParseFalse(InputStream& is, Handler& handler) { + RAPIDJSON_ASSERT(is.Peek() == 'f'); + is.Take(); + + if (RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) { + if (RAPIDJSON_UNLIKELY(!handler.Bool(false))) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell()); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); + } + + template + RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) { + if (RAPIDJSON_LIKELY(is.Peek() == expect)) { + is.Take(); + return true; + } + else + return false; + } + + // Helper function to parse four hexidecimal digits in \uXXXX in ParseString(). + template + unsigned ParseHex4(InputStream& is, size_t escapeOffset) { + unsigned codepoint = 0; + for (int i = 0; i < 4; i++) { + Ch c = is.Peek(); + codepoint <<= 4; + codepoint += static_cast(c); + if (c >= '0' && c <= '9') + codepoint -= '0'; + else if (c >= 'A' && c <= 'F') + codepoint -= 'A' - 10; + else if (c >= 'a' && c <= 'f') + codepoint -= 'a' - 10; + else { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0); + } + is.Take(); + } + return codepoint; + } + + template + class StackStream { + public: + typedef CharType Ch; + + StackStream(internal::Stack& stack) : stack_(stack), length_(0) {} + RAPIDJSON_FORCEINLINE void Put(Ch c) { + *stack_.template Push() = c; + ++length_; + } + + RAPIDJSON_FORCEINLINE void* Push(SizeType count) { + length_ += count; + return stack_.template Push(count); + } + + size_t Length() const { return length_; } + + Ch* Pop() { + return stack_.template Pop(length_); + } + + private: + StackStream(const StackStream&); + StackStream& operator=(const StackStream&); + + internal::Stack& stack_; + SizeType length_; + }; + + // Parse string and generate String event. Different code paths for kParseInsituFlag. + template + void ParseString(InputStream& is, Handler& handler, bool isKey = false) { + internal::StreamLocalCopy copy(is); + InputStream& s(copy.s); + + RAPIDJSON_ASSERT(s.Peek() == '\"'); + s.Take(); // Skip '\"' + + bool success = false; + if (parseFlags & kParseInsituFlag) { + typename InputStream::Ch *head = s.PutBegin(); + ParseStringToStream(s, s); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + size_t length = s.PutEnd(head) - 1; + RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); + const typename TargetEncoding::Ch* const str = reinterpret_cast(head); + success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false)); + } + else { + StackStream stackStream(stack_); + ParseStringToStream(s, stackStream); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + SizeType length = static_cast(stackStream.Length()) - 1; + const typename TargetEncoding::Ch* const str = stackStream.Pop(); + success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true)); + } + if (RAPIDJSON_UNLIKELY(!success)) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell()); + } + + // Parse string to an output is + // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation. + template + RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) { +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + static const char escape[256] = { + Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/', + Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, + 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0, + 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 + }; +#undef Z16 +//!@endcond + + for (;;) { + // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation. + if (!(parseFlags & kParseValidateEncodingFlag)) + ScanCopyUnescapedString(is, os); + + Ch c = is.Peek(); + if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape + size_t escapeOffset = is.Tell(); // For invalid escaping, report the inital '\\' as error offset + is.Take(); + Ch e = is.Peek(); + if ((sizeof(Ch) == 1 || unsigned(e) < 256) && RAPIDJSON_LIKELY(escape[static_cast(e)])) { + is.Take(); + os.Put(static_cast(escape[static_cast(e)])); + } + else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode + is.Take(); + unsigned codepoint = ParseHex4(is, escapeOffset); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + if (RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDBFF)) { + // Handle UTF-16 surrogate pair + if (RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u'))) + RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); + unsigned codepoint2 = ParseHex4(is, escapeOffset); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; + if (RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)) + RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset); + codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000; + } + TEncoding::Encode(os, codepoint); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset); + } + else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote + is.Take(); + os.Put('\0'); // null-terminate the string + return; + } + else if (RAPIDJSON_UNLIKELY(static_cast(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF + if (c == '\0') + RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell()); + else + RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell()); + } + else { + size_t offset = is.Tell(); + if (RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ? + !Transcoder::Validate(is, os) : + !Transcoder::Transcode(is, os)))) + RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset); + } + } + } + + template + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) { + // Do nothing for generic version + } + +#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) + // StringStream -> StackStream + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream& os) { + const char* p = is.src_; + + // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + while (p != nextAligned) + if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { + is.src_ = p; + return; + } + else + os.Put(*p++); + + // The rest of string using SIMD + static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; + static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; + static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; + const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); + const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); + const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); + + for (;; p += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + const __m128i t1 = _mm_cmpeq_epi8(s, dq); + const __m128i t2 = _mm_cmpeq_epi8(s, bs); + const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 + const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); + unsigned short r = static_cast(_mm_movemask_epi8(x)); + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + SizeType length; + #ifdef _MSC_VER // Find the index of first escaped + unsigned long offset; + _BitScanForward(&offset, r); + length = offset; + #else + length = static_cast(__builtin_ffs(r) - 1); + #endif + char* q = reinterpret_cast(os.Push(length)); + for (size_t i = 0; i < length; i++) + q[i] = p[i]; + + p += length; + break; + } + _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s); + } + + is.src_ = p; + } + + // InsituStringStream -> InsituStringStream + static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) { + RAPIDJSON_ASSERT(&is == &os); + (void)os; + + if (is.src_ == is.dst_) { + SkipUnescapedString(is); + return; + } + + char* p = is.src_; + char *q = is.dst_; + + // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + while (p != nextAligned) + if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { + is.src_ = p; + is.dst_ = q; + return; + } + else + *q++ = *p++; + + // The rest of string using SIMD + static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; + static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; + static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; + const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); + const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); + const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); + + for (;; p += 16, q += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + const __m128i t1 = _mm_cmpeq_epi8(s, dq); + const __m128i t2 = _mm_cmpeq_epi8(s, bs); + const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 + const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); + unsigned short r = static_cast(_mm_movemask_epi8(x)); + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + size_t length; +#ifdef _MSC_VER // Find the index of first escaped + unsigned long offset; + _BitScanForward(&offset, r); + length = offset; +#else + length = static_cast(__builtin_ffs(r) - 1); +#endif + for (const char* pend = p + length; p != pend; ) + *q++ = *p++; + break; + } + _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s); + } + + is.src_ = p; + is.dst_ = q; + } + + // When read/write pointers are the same for insitu stream, just skip unescaped characters + static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) { + RAPIDJSON_ASSERT(is.src_ == is.dst_); + char* p = is.src_; + + // Scan one by one until alignment (unaligned load may cross page boundary and cause crash) + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + for (; p != nextAligned; p++) + if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast(*p) < 0x20)) { + is.src_ = is.dst_ = p; + return; + } + + // The rest of string using SIMD + static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; + static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; + static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; + const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); + const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); + const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); + + for (;; p += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + const __m128i t1 = _mm_cmpeq_epi8(s, dq); + const __m128i t2 = _mm_cmpeq_epi8(s, bs); + const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 + const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); + unsigned short r = static_cast(_mm_movemask_epi8(x)); + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + size_t length; +#ifdef _MSC_VER // Find the index of first escaped + unsigned long offset; + _BitScanForward(&offset, r); + length = offset; +#else + length = static_cast(__builtin_ffs(r) - 1); +#endif + p += length; + break; + } + } + + is.src_ = is.dst_ = p; + } +#endif + + template + class NumberStream; + + template + class NumberStream { + public: + typedef typename InputStream::Ch Ch; + + NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; } + ~NumberStream() {} + + RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); } + RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); } + RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); } + RAPIDJSON_FORCEINLINE void Push(char) {} + + size_t Tell() { return is.Tell(); } + size_t Length() { return 0; } + const char* Pop() { return 0; } + + protected: + NumberStream& operator=(const NumberStream&); + + InputStream& is; + }; + + template + class NumberStream : public NumberStream { + typedef NumberStream Base; + public: + NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is), stackStream(reader.stack_) {} + ~NumberStream() {} + + RAPIDJSON_FORCEINLINE Ch TakePush() { + stackStream.Put(static_cast(Base::is.Peek())); + return Base::is.Take(); + } + + RAPIDJSON_FORCEINLINE void Push(char c) { + stackStream.Put(c); + } + + size_t Length() { return stackStream.Length(); } + + const char* Pop() { + stackStream.Put('\0'); + return stackStream.Pop(); + } + + private: + StackStream stackStream; + }; + + template + class NumberStream : public NumberStream { + typedef NumberStream Base; + public: + NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {} + ~NumberStream() {} + + RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); } + }; + + template + void ParseNumber(InputStream& is, Handler& handler) { + internal::StreamLocalCopy copy(is); + NumberStream s(*this, copy.s); + + size_t startOffset = s.Tell(); + double d = 0.0; + bool useNanOrInf = false; + + // Parse minus + bool minus = Consume(s, '-'); + + // Parse int: zero / ( digit1-9 *DIGIT ) + unsigned i = 0; + uint64_t i64 = 0; + bool use64bit = false; + int significandDigit = 0; + if (RAPIDJSON_UNLIKELY(s.Peek() == '0')) { + i = 0; + s.TakePush(); + } + else if (RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) { + i = static_cast(s.TakePush() - '0'); + + if (minus) + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648 + if (RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) { + i64 = i; + use64bit = true; + break; + } + } + i = i * 10 + static_cast(s.TakePush() - '0'); + significandDigit++; + } + else + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295 + if (RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) { + i64 = i; + use64bit = true; + break; + } + } + i = i * 10 + static_cast(s.TakePush() - '0'); + significandDigit++; + } + } + // Parse NaN or Infinity here + else if ((parseFlags & kParseNanAndInfFlag) && RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) { + useNanOrInf = true; + if (RAPIDJSON_LIKELY(Consume(s, 'N') && Consume(s, 'a') && Consume(s, 'N'))) { + d = std::numeric_limits::quiet_NaN(); + } + else if (RAPIDJSON_LIKELY(Consume(s, 'I') && Consume(s, 'n') && Consume(s, 'f'))) { + d = (minus ? -std::numeric_limits::infinity() : std::numeric_limits::infinity()); + if (RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n') + && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y')))) + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell()); + + // Parse 64bit int + bool useDouble = false; + if (use64bit) { + if (minus) + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808 + if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) { + d = static_cast(i64); + useDouble = true; + break; + } + i64 = i64 * 10 + static_cast(s.TakePush() - '0'); + significandDigit++; + } + else + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615 + if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) { + d = static_cast(i64); + useDouble = true; + break; + } + i64 = i64 * 10 + static_cast(s.TakePush() - '0'); + significandDigit++; + } + } + + // Force double for big integer + if (useDouble) { + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (RAPIDJSON_UNLIKELY(d >= 1.7976931348623157e307)) // DBL_MAX / 10.0 + RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); + d = d * 10 + (s.TakePush() - '0'); + } + } + + // Parse frac = decimal-point 1*DIGIT + int expFrac = 0; + size_t decimalPosition; + if (Consume(s, '.')) { + decimalPosition = s.Length(); + + if (RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9'))) + RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell()); + + if (!useDouble) { +#if RAPIDJSON_64BIT + // Use i64 to store significand in 64-bit architecture + if (!use64bit) + i64 = i; + + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path + break; + else { + i64 = i64 * 10 + static_cast(s.TakePush() - '0'); + --expFrac; + if (i64 != 0) + significandDigit++; + } + } + + d = static_cast(i64); +#else + // Use double to store significand in 32-bit architecture + d = static_cast(use64bit ? i64 : i); +#endif + useDouble = true; + } + + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + if (significandDigit < 17) { + d = d * 10.0 + (s.TakePush() - '0'); + --expFrac; + if (RAPIDJSON_LIKELY(d > 0.0)) + significandDigit++; + } + else + s.TakePush(); + } + } + else + decimalPosition = s.Length(); // decimal position at the end of integer. + + // Parse exp = e [ minus / plus ] 1*DIGIT + int exp = 0; + if (Consume(s, 'e') || Consume(s, 'E')) { + if (!useDouble) { + d = static_cast(use64bit ? i64 : i); + useDouble = true; + } + + bool expMinus = false; + if (Consume(s, '+')) + ; + else if (Consume(s, '-')) + expMinus = true; + + if (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + exp = static_cast(s.Take() - '0'); + if (expMinus) { + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + exp = exp * 10 + static_cast(s.Take() - '0'); + if (exp >= 214748364) { // Issue #313: prevent overflow exponent + while (RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent + s.Take(); + } + } + } + else { // positive exp + int maxExp = 308 - expFrac; + while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) { + exp = exp * 10 + static_cast(s.Take() - '0'); + if (RAPIDJSON_UNLIKELY(exp > maxExp)) + RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset); + } + } + } + else + RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell()); + + if (expMinus) + exp = -exp; + } + + // Finish parsing, call event according to the type of number. + bool cont = true; + + if (parseFlags & kParseNumbersAsStringsFlag) { + if (parseFlags & kParseInsituFlag) { + s.Pop(); // Pop stack no matter if it will be used or not. + typename InputStream::Ch* head = is.PutBegin(); + const size_t length = s.Tell() - startOffset; + RAPIDJSON_ASSERT(length <= 0xFFFFFFFF); + // unable to insert the \0 character here, it will erase the comma after this number + const typename TargetEncoding::Ch* const str = reinterpret_cast(head); + cont = handler.RawNumber(str, SizeType(length), false); + } + else { + SizeType numCharsToCopy = static_cast(s.Length()); + StringStream srcStream(s.Pop()); + StackStream dstStream(stack_); + while (numCharsToCopy--) { + Transcoder, TargetEncoding>::Transcode(srcStream, dstStream); + } + dstStream.Put('\0'); + const typename TargetEncoding::Ch* str = dstStream.Pop(); + const SizeType length = static_cast(dstStream.Length()) - 1; + cont = handler.RawNumber(str, SizeType(length), true); + } + } + else { + size_t length = s.Length(); + const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not. + + if (useDouble) { + int p = exp + expFrac; + if (parseFlags & kParseFullPrecisionFlag) + d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp); + else + d = internal::StrtodNormalPrecision(d, p); + + cont = handler.Double(minus ? -d : d); + } + else if (useNanOrInf) { + cont = handler.Double(d); + } + else { + if (use64bit) { + if (minus) + cont = handler.Int64(static_cast(~i64 + 1)); + else + cont = handler.Uint64(i64); + } + else { + if (minus) + cont = handler.Int(static_cast(~i + 1)); + else + cont = handler.Uint(i); + } + } + } + if (RAPIDJSON_UNLIKELY(!cont)) + RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset); + } + + // Parse any JSON value + template + void ParseValue(InputStream& is, Handler& handler) { + switch (is.Peek()) { + case 'n': ParseNull (is, handler); break; + case 't': ParseTrue (is, handler); break; + case 'f': ParseFalse (is, handler); break; + case '"': ParseString(is, handler); break; + case '{': ParseObject(is, handler); break; + case '[': ParseArray (is, handler); break; + default : + ParseNumber(is, handler); + break; + + } + } + + // Iterative Parsing + + // States + enum IterativeParsingState { + IterativeParsingStartState = 0, + IterativeParsingFinishState, + IterativeParsingErrorState, + + // Object states + IterativeParsingObjectInitialState, + IterativeParsingMemberKeyState, + IterativeParsingKeyValueDelimiterState, + IterativeParsingMemberValueState, + IterativeParsingMemberDelimiterState, + IterativeParsingObjectFinishState, + + // Array states + IterativeParsingArrayInitialState, + IterativeParsingElementState, + IterativeParsingElementDelimiterState, + IterativeParsingArrayFinishState, + + // Single value state + IterativeParsingValueState + }; + + enum { cIterativeParsingStateCount = IterativeParsingValueState + 1 }; + + // Tokens + enum Token { + LeftBracketToken = 0, + RightBracketToken, + + LeftCurlyBracketToken, + RightCurlyBracketToken, + + CommaToken, + ColonToken, + + StringToken, + FalseToken, + TrueToken, + NullToken, + NumberToken, + + kTokenCount + }; + + RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) { + +//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN +#define N NumberToken +#define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N + // Maps from ASCII to Token + static const unsigned char tokenMap[256] = { + N16, // 00~0F + N16, // 10~1F + N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F + N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F + N16, // 40~4F + N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F + N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F + N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F + N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF + }; +#undef N +#undef N16 +//!@endcond + + if (sizeof(Ch) == 1 || static_cast(c) < 256) + return static_cast(tokenMap[static_cast(c)]); + else + return NumberToken; + } + + RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) { + // current state x one lookahead token -> new state + static const char G[cIterativeParsingStateCount][kTokenCount] = { + // Start + { + IterativeParsingArrayInitialState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingValueState, // String + IterativeParsingValueState, // False + IterativeParsingValueState, // True + IterativeParsingValueState, // Null + IterativeParsingValueState // Number + }, + // Finish(sink state) + { + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState + }, + // Error(sink state) + { + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState + }, + // ObjectInitial + { + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberKeyState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number + }, + // MemberKey + { + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingKeyValueDelimiterState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number + }, + // KeyValueDelimiter + { + IterativeParsingArrayInitialState, // Left bracket(push MemberValue state) + IterativeParsingErrorState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberValueState, // String + IterativeParsingMemberValueState, // False + IterativeParsingMemberValueState, // True + IterativeParsingMemberValueState, // Null + IterativeParsingMemberValueState // Number + }, + // MemberValue + { + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingMemberDelimiterState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number + }, + // MemberDelimiter + { + IterativeParsingErrorState, // Left bracket + IterativeParsingErrorState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingObjectFinishState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingMemberKeyState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number + }, + // ObjectFinish(sink state) + { + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState + }, + // ArrayInitial + { + IterativeParsingArrayInitialState, // Left bracket(push Element state) + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket(push Element state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingElementState, // String + IterativeParsingElementState, // False + IterativeParsingElementState, // True + IterativeParsingElementState, // Null + IterativeParsingElementState // Number + }, + // Element + { + IterativeParsingErrorState, // Left bracket + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingErrorState, // Left curly bracket + IterativeParsingErrorState, // Right curly bracket + IterativeParsingElementDelimiterState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingErrorState, // String + IterativeParsingErrorState, // False + IterativeParsingErrorState, // True + IterativeParsingErrorState, // Null + IterativeParsingErrorState // Number + }, + // ElementDelimiter + { + IterativeParsingArrayInitialState, // Left bracket(push Element state) + IterativeParsingArrayFinishState, // Right bracket + IterativeParsingObjectInitialState, // Left curly bracket(push Element state) + IterativeParsingErrorState, // Right curly bracket + IterativeParsingErrorState, // Comma + IterativeParsingErrorState, // Colon + IterativeParsingElementState, // String + IterativeParsingElementState, // False + IterativeParsingElementState, // True + IterativeParsingElementState, // Null + IterativeParsingElementState // Number + }, + // ArrayFinish(sink state) + { + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState + }, + // Single Value (sink state) + { + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, + IterativeParsingErrorState + } + }; // End of G + + return static_cast(G[state][token]); + } + + // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit(). + // May return a new state on state pop. + template + RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) { + (void)token; + + switch (dst) { + case IterativeParsingErrorState: + return dst; + + case IterativeParsingObjectInitialState: + case IterativeParsingArrayInitialState: + { + // Push the state(Element or MemeberValue) if we are nested in another array or value of member. + // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop. + IterativeParsingState n = src; + if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState) + n = IterativeParsingElementState; + else if (src == IterativeParsingKeyValueDelimiterState) + n = IterativeParsingMemberValueState; + // Push current state. + *stack_.template Push(1) = n; + // Initialize and push the member/element count. + *stack_.template Push(1) = 0; + // Call handler + bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray(); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } + else { + is.Take(); + return dst; + } + } + + case IterativeParsingMemberKeyState: + ParseString(is, handler, true); + if (HasParseError()) + return IterativeParsingErrorState; + else + return dst; + + case IterativeParsingKeyValueDelimiterState: + RAPIDJSON_ASSERT(token == ColonToken); + is.Take(); + return dst; + + case IterativeParsingMemberValueState: + // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return dst; + + case IterativeParsingElementState: + // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return dst; + + case IterativeParsingMemberDelimiterState: + case IterativeParsingElementDelimiterState: + is.Take(); + // Update member/element count. + *stack_.template Top() = *stack_.template Top() + 1; + return dst; + + case IterativeParsingObjectFinishState: + { + // Transit from delimiter is only allowed when trailing commas are enabled + if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell()); + return IterativeParsingErrorState; + } + // Get member count. + SizeType c = *stack_.template Pop(1); + // If the object is not empty, count the last member. + if (src == IterativeParsingMemberValueState) + ++c; + // Restore the state. + IterativeParsingState n = static_cast(*stack_.template Pop(1)); + // Transit to Finish state if this is the topmost scope. + if (n == IterativeParsingStartState) + n = IterativeParsingFinishState; + // Call handler + bool hr = handler.EndObject(c); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } + else { + is.Take(); + return n; + } + } + + case IterativeParsingArrayFinishState: + { + // Transit from delimiter is only allowed when trailing commas are enabled + if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell()); + return IterativeParsingErrorState; + } + // Get element count. + SizeType c = *stack_.template Pop(1); + // If the array is not empty, count the last element. + if (src == IterativeParsingElementState) + ++c; + // Restore the state. + IterativeParsingState n = static_cast(*stack_.template Pop(1)); + // Transit to Finish state if this is the topmost scope. + if (n == IterativeParsingStartState) + n = IterativeParsingFinishState; + // Call handler + bool hr = handler.EndArray(c); + // On handler short circuits the parsing. + if (!hr) { + RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell()); + return IterativeParsingErrorState; + } + else { + is.Take(); + return n; + } + } + + default: + // This branch is for IterativeParsingValueState actually. + // Use `default:` rather than + // `case IterativeParsingValueState:` is for code coverage. + + // The IterativeParsingStartState is not enumerated in this switch-case. + // It is impossible for that case. And it can be caught by following assertion. + + // The IterativeParsingFinishState is not enumerated in this switch-case either. + // It is a "derivative" state which cannot triggered from Predict() directly. + // Therefore it cannot happen here. And it can be caught by following assertion. + RAPIDJSON_ASSERT(dst == IterativeParsingValueState); + + // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state. + ParseValue(is, handler); + if (HasParseError()) { + return IterativeParsingErrorState; + } + return IterativeParsingFinishState; + } + } + + template + void HandleError(IterativeParsingState src, InputStream& is) { + if (HasParseError()) { + // Error flag has been set. + return; + } + + switch (src) { + case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return; + case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return; + case IterativeParsingObjectInitialState: + case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return; + case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return; + case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return; + case IterativeParsingKeyValueDelimiterState: + case IterativeParsingArrayInitialState: + case IterativeParsingElementDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return; + default: RAPIDJSON_ASSERT(src == IterativeParsingElementState); RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return; + } + } + + template + ParseResult IterativeParse(InputStream& is, Handler& handler) { + parseResult_.Clear(); + ClearStackOnExit scope(*this); + IterativeParsingState state = IterativeParsingStartState; + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + while (is.Peek() != '\0') { + Token t = Tokenize(is.Peek()); + IterativeParsingState n = Predict(state, t); + IterativeParsingState d = Transit(state, t, n, is, handler); + + if (d == IterativeParsingErrorState) { + HandleError(state, is); + break; + } + + state = d; + + // Do not further consume streams if a root JSON has been parsed. + if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState) + break; + + SkipWhitespaceAndComments(is); + RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_); + } + + // Handle the end of file. + if (state != IterativeParsingFinishState) + HandleError(state, is); + + return parseResult_; + } + + static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string. + internal::Stack stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing. + ParseResult parseResult_; +}; // class GenericReader + +//! Reader with UTF8 encoding and default allocator. +typedef GenericReader, UTF8<> > Reader; + +RAPIDJSON_NAMESPACE_END + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_READER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/schema.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/schema.h new file mode 100644 index 0000000000..b182aa27f0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/schema.h @@ -0,0 +1,2006 @@ +// Tencent is pleased to support the open source community by making RapidJSON available-> +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip-> All rights reserved-> +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License-> You may obtain a copy of the License at +// +// http://opensource->org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied-> See the License for the +// specific language governing permissions and limitations under the License-> + +#ifndef RAPIDJSON_SCHEMA_H_ +#define RAPIDJSON_SCHEMA_H_ + +#include "document.h" +#include "pointer.h" +#include // abs, floor + +#if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX) +#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1 +#else +#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0 +#endif + +#if !RAPIDJSON_SCHEMA_USE_INTERNALREGEX && !defined(RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800)) +#define RAPIDJSON_SCHEMA_USE_STDREGEX 1 +#else +#define RAPIDJSON_SCHEMA_USE_STDREGEX 0 +#endif + +#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX +#include "internal/regex.h" +#elif RAPIDJSON_SCHEMA_USE_STDREGEX +#include +#endif + +#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX || RAPIDJSON_SCHEMA_USE_STDREGEX +#define RAPIDJSON_SCHEMA_HAS_REGEX 1 +#else +#define RAPIDJSON_SCHEMA_HAS_REGEX 0 +#endif + +#ifndef RAPIDJSON_SCHEMA_VERBOSE +#define RAPIDJSON_SCHEMA_VERBOSE 0 +#endif + +#if RAPIDJSON_SCHEMA_VERBOSE +#include "stringbuffer.h" +#endif + +RAPIDJSON_DIAG_PUSH + +#if defined(__GNUC__) +RAPIDJSON_DIAG_OFF(effc++) +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_OFF(weak-vtables) +RAPIDJSON_DIAG_OFF(exit-time-destructors) +RAPIDJSON_DIAG_OFF(c++98-compat-pedantic) +RAPIDJSON_DIAG_OFF(variadic-macros) +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// Verbose Utilities + +#if RAPIDJSON_SCHEMA_VERBOSE + +namespace internal { + +inline void PrintInvalidKeyword(const char* keyword) { + printf("Fail keyword: %s\n", keyword); +} + +inline void PrintInvalidKeyword(const wchar_t* keyword) { + wprintf(L"Fail keyword: %ls\n", keyword); +} + +inline void PrintInvalidDocument(const char* document) { + printf("Fail document: %s\n\n", document); +} + +inline void PrintInvalidDocument(const wchar_t* document) { + wprintf(L"Fail document: %ls\n\n", document); +} + +inline void PrintValidatorPointers(unsigned depth, const char* s, const char* d) { + printf("S: %*s%s\nD: %*s%s\n\n", depth * 4, " ", s, depth * 4, " ", d); +} + +inline void PrintValidatorPointers(unsigned depth, const wchar_t* s, const wchar_t* d) { + wprintf(L"S: %*ls%ls\nD: %*ls%ls\n\n", depth * 4, L" ", s, depth * 4, L" ", d); +} + +} // namespace internal + +#endif // RAPIDJSON_SCHEMA_VERBOSE + +/////////////////////////////////////////////////////////////////////////////// +// RAPIDJSON_INVALID_KEYWORD_RETURN + +#if RAPIDJSON_SCHEMA_VERBOSE +#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) internal::PrintInvalidKeyword(keyword) +#else +#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) +#endif + +#define RAPIDJSON_INVALID_KEYWORD_RETURN(keyword)\ +RAPIDJSON_MULTILINEMACRO_BEGIN\ + context.invalidKeyword = keyword.GetString();\ + RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString());\ + return false;\ +RAPIDJSON_MULTILINEMACRO_END + +/////////////////////////////////////////////////////////////////////////////// +// Forward declarations + +template +class GenericSchemaDocument; + +namespace internal { + +template +class Schema; + +/////////////////////////////////////////////////////////////////////////////// +// ISchemaValidator + +class ISchemaValidator { +public: + virtual ~ISchemaValidator() {} + virtual bool IsValid() const = 0; +}; + +/////////////////////////////////////////////////////////////////////////////// +// ISchemaStateFactory + +template +class ISchemaStateFactory { +public: + virtual ~ISchemaStateFactory() {} + virtual ISchemaValidator* CreateSchemaValidator(const SchemaType&) = 0; + virtual void DestroySchemaValidator(ISchemaValidator* validator) = 0; + virtual void* CreateHasher() = 0; + virtual uint64_t GetHashCode(void* hasher) = 0; + virtual void DestroryHasher(void* hasher) = 0; + virtual void* MallocState(size_t size) = 0; + virtual void FreeState(void* p) = 0; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Hasher + +// For comparison of compound value +template +class Hasher { +public: + typedef typename Encoding::Ch Ch; + + Hasher(Allocator* allocator = 0, size_t stackCapacity = kDefaultSize) : stack_(allocator, stackCapacity) {} + + bool Null() { return WriteType(kNullType); } + bool Bool(bool b) { return WriteType(b ? kTrueType : kFalseType); } + bool Int(int i) { Number n; n.u.i = i; n.d = static_cast(i); return WriteNumber(n); } + bool Uint(unsigned u) { Number n; n.u.u = u; n.d = static_cast(u); return WriteNumber(n); } + bool Int64(int64_t i) { Number n; n.u.i = i; n.d = static_cast(i); return WriteNumber(n); } + bool Uint64(uint64_t u) { Number n; n.u.u = u; n.d = static_cast(u); return WriteNumber(n); } + bool Double(double d) { + Number n; + if (d < 0) n.u.i = static_cast(d); + else n.u.u = static_cast(d); + n.d = d; + return WriteNumber(n); + } + + bool RawNumber(const Ch* str, SizeType len, bool) { + WriteBuffer(kNumberType, str, len * sizeof(Ch)); + return true; + } + + bool String(const Ch* str, SizeType len, bool) { + WriteBuffer(kStringType, str, len * sizeof(Ch)); + return true; + } + + bool StartObject() { return true; } + bool Key(const Ch* str, SizeType len, bool copy) { return String(str, len, copy); } + bool EndObject(SizeType memberCount) { + uint64_t h = Hash(0, kObjectType); + uint64_t* kv = stack_.template Pop(memberCount * 2); + for (SizeType i = 0; i < memberCount; i++) + h ^= Hash(kv[i * 2], kv[i * 2 + 1]); // Use xor to achieve member order insensitive + *stack_.template Push() = h; + return true; + } + + bool StartArray() { return true; } + bool EndArray(SizeType elementCount) { + uint64_t h = Hash(0, kArrayType); + uint64_t* e = stack_.template Pop(elementCount); + for (SizeType i = 0; i < elementCount; i++) + h = Hash(h, e[i]); // Use hash to achieve element order sensitive + *stack_.template Push() = h; + return true; + } + + bool IsValid() const { return stack_.GetSize() == sizeof(uint64_t); } + + uint64_t GetHashCode() const { + RAPIDJSON_ASSERT(IsValid()); + return *stack_.template Top(); + } + +private: + static const size_t kDefaultSize = 256; + struct Number { + union U { + uint64_t u; + int64_t i; + }u; + double d; + }; + + bool WriteType(Type type) { return WriteBuffer(type, 0, 0); } + + bool WriteNumber(const Number& n) { return WriteBuffer(kNumberType, &n, sizeof(n)); } + + bool WriteBuffer(Type type, const void* data, size_t len) { + // FNV-1a from http://isthe.com/chongo/tech/comp/fnv/ + uint64_t h = Hash(RAPIDJSON_UINT64_C2(0x84222325, 0xcbf29ce4), type); + const unsigned char* d = static_cast(data); + for (size_t i = 0; i < len; i++) + h = Hash(h, d[i]); + *stack_.template Push() = h; + return true; + } + + static uint64_t Hash(uint64_t h, uint64_t d) { + static const uint64_t kPrime = RAPIDJSON_UINT64_C2(0x00000100, 0x000001b3); + h ^= d; + h *= kPrime; + return h; + } + + Stack stack_; +}; + +/////////////////////////////////////////////////////////////////////////////// +// SchemaValidationContext + +template +struct SchemaValidationContext { + typedef Schema SchemaType; + typedef ISchemaStateFactory SchemaValidatorFactoryType; + typedef typename SchemaType::ValueType ValueType; + typedef typename ValueType::Ch Ch; + + enum PatternValidatorType { + kPatternValidatorOnly, + kPatternValidatorWithProperty, + kPatternValidatorWithAdditionalProperty + }; + + SchemaValidationContext(SchemaValidatorFactoryType& f, const SchemaType* s) : + factory(f), + schema(s), + valueSchema(), + invalidKeyword(), + hasher(), + arrayElementHashCodes(), + validators(), + validatorCount(), + patternPropertiesValidators(), + patternPropertiesValidatorCount(), + patternPropertiesSchemas(), + patternPropertiesSchemaCount(), + valuePatternValidatorType(kPatternValidatorOnly), + propertyExist(), + inArray(false), + valueUniqueness(false), + arrayUniqueness(false) + { + } + + ~SchemaValidationContext() { + if (hasher) + factory.DestroryHasher(hasher); + if (validators) { + for (SizeType i = 0; i < validatorCount; i++) + factory.DestroySchemaValidator(validators[i]); + factory.FreeState(validators); + } + if (patternPropertiesValidators) { + for (SizeType i = 0; i < patternPropertiesValidatorCount; i++) + factory.DestroySchemaValidator(patternPropertiesValidators[i]); + factory.FreeState(patternPropertiesValidators); + } + if (patternPropertiesSchemas) + factory.FreeState(patternPropertiesSchemas); + if (propertyExist) + factory.FreeState(propertyExist); + } + + SchemaValidatorFactoryType& factory; + const SchemaType* schema; + const SchemaType* valueSchema; + const Ch* invalidKeyword; + void* hasher; // Only validator access + void* arrayElementHashCodes; // Only validator access this + ISchemaValidator** validators; + SizeType validatorCount; + ISchemaValidator** patternPropertiesValidators; + SizeType patternPropertiesValidatorCount; + const SchemaType** patternPropertiesSchemas; + SizeType patternPropertiesSchemaCount; + PatternValidatorType valuePatternValidatorType; + PatternValidatorType objectPatternValidatorType; + SizeType arrayElementIndex; + bool* propertyExist; + bool inArray; + bool valueUniqueness; + bool arrayUniqueness; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Schema + +template +class Schema { +public: + typedef typename SchemaDocumentType::ValueType ValueType; + typedef typename SchemaDocumentType::AllocatorType AllocatorType; + typedef typename SchemaDocumentType::PointerType PointerType; + typedef typename ValueType::EncodingType EncodingType; + typedef typename EncodingType::Ch Ch; + typedef SchemaValidationContext Context; + typedef Schema SchemaType; + typedef GenericValue SValue; + friend class GenericSchemaDocument; + + Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) : + allocator_(allocator), + enum_(), + enumCount_(), + not_(), + type_((1 << kTotalSchemaType) - 1), // typeless + validatorCount_(), + properties_(), + additionalPropertiesSchema_(), + patternProperties_(), + patternPropertyCount_(), + propertyCount_(), + minProperties_(), + maxProperties_(SizeType(~0)), + additionalProperties_(true), + hasDependencies_(), + hasRequired_(), + hasSchemaDependencies_(), + additionalItemsSchema_(), + itemsList_(), + itemsTuple_(), + itemsTupleCount_(), + minItems_(), + maxItems_(SizeType(~0)), + additionalItems_(true), + uniqueItems_(false), + pattern_(), + minLength_(0), + maxLength_(~SizeType(0)), + exclusiveMinimum_(false), + exclusiveMaximum_(false) + { + typedef typename SchemaDocumentType::ValueType ValueType; + typedef typename ValueType::ConstValueIterator ConstValueIterator; + typedef typename ValueType::ConstMemberIterator ConstMemberIterator; + + if (!value.IsObject()) + return; + + if (const ValueType* v = GetMember(value, GetTypeString())) { + type_ = 0; + if (v->IsString()) + AddType(*v); + else if (v->IsArray()) + for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) + AddType(*itr); + } + + if (const ValueType* v = GetMember(value, GetEnumString())) + if (v->IsArray() && v->Size() > 0) { + enum_ = static_cast(allocator_->Malloc(sizeof(uint64_t) * v->Size())); + for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) { + typedef Hasher > EnumHasherType; + char buffer[256 + 24]; + MemoryPoolAllocator<> hasherAllocator(buffer, sizeof(buffer)); + EnumHasherType h(&hasherAllocator, 256); + itr->Accept(h); + enum_[enumCount_++] = h.GetHashCode(); + } + } + + if (schemaDocument) { + AssignIfExist(allOf_, *schemaDocument, p, value, GetAllOfString(), document); + AssignIfExist(anyOf_, *schemaDocument, p, value, GetAnyOfString(), document); + AssignIfExist(oneOf_, *schemaDocument, p, value, GetOneOfString(), document); + } + + if (const ValueType* v = GetMember(value, GetNotString())) { + schemaDocument->CreateSchema(¬_, p.Append(GetNotString(), allocator_), *v, document); + notValidatorIndex_ = validatorCount_; + validatorCount_++; + } + + // Object + + const ValueType* properties = GetMember(value, GetPropertiesString()); + const ValueType* required = GetMember(value, GetRequiredString()); + const ValueType* dependencies = GetMember(value, GetDependenciesString()); + { + // Gather properties from properties/required/dependencies + SValue allProperties(kArrayType); + + if (properties && properties->IsObject()) + for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) + AddUniqueElement(allProperties, itr->name); + + if (required && required->IsArray()) + for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr) + if (itr->IsString()) + AddUniqueElement(allProperties, *itr); + + if (dependencies && dependencies->IsObject()) + for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) { + AddUniqueElement(allProperties, itr->name); + if (itr->value.IsArray()) + for (ConstValueIterator i = itr->value.Begin(); i != itr->value.End(); ++i) + if (i->IsString()) + AddUniqueElement(allProperties, *i); + } + + if (allProperties.Size() > 0) { + propertyCount_ = allProperties.Size(); + properties_ = static_cast(allocator_->Malloc(sizeof(Property) * propertyCount_)); + for (SizeType i = 0; i < propertyCount_; i++) { + new (&properties_[i]) Property(); + properties_[i].name = allProperties[i]; + properties_[i].schema = GetTypeless(); + } + } + } + + if (properties && properties->IsObject()) { + PointerType q = p.Append(GetPropertiesString(), allocator_); + for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) { + SizeType index; + if (FindPropertyIndex(itr->name, &index)) + schemaDocument->CreateSchema(&properties_[index].schema, q.Append(itr->name, allocator_), itr->value, document); + } + } + + if (const ValueType* v = GetMember(value, GetPatternPropertiesString())) { + PointerType q = p.Append(GetPatternPropertiesString(), allocator_); + patternProperties_ = static_cast(allocator_->Malloc(sizeof(PatternProperty) * v->MemberCount())); + patternPropertyCount_ = 0; + + for (ConstMemberIterator itr = v->MemberBegin(); itr != v->MemberEnd(); ++itr) { + new (&patternProperties_[patternPropertyCount_]) PatternProperty(); + patternProperties_[patternPropertyCount_].pattern = CreatePattern(itr->name); + schemaDocument->CreateSchema(&patternProperties_[patternPropertyCount_].schema, q.Append(itr->name, allocator_), itr->value, document); + patternPropertyCount_++; + } + } + + if (required && required->IsArray()) + for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr) + if (itr->IsString()) { + SizeType index; + if (FindPropertyIndex(*itr, &index)) { + properties_[index].required = true; + hasRequired_ = true; + } + } + + if (dependencies && dependencies->IsObject()) { + PointerType q = p.Append(GetDependenciesString(), allocator_); + hasDependencies_ = true; + for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) { + SizeType sourceIndex; + if (FindPropertyIndex(itr->name, &sourceIndex)) { + if (itr->value.IsArray()) { + properties_[sourceIndex].dependencies = static_cast(allocator_->Malloc(sizeof(bool) * propertyCount_)); + std::memset(properties_[sourceIndex].dependencies, 0, sizeof(bool)* propertyCount_); + for (ConstValueIterator targetItr = itr->value.Begin(); targetItr != itr->value.End(); ++targetItr) { + SizeType targetIndex; + if (FindPropertyIndex(*targetItr, &targetIndex)) + properties_[sourceIndex].dependencies[targetIndex] = true; + } + } + else if (itr->value.IsObject()) { + hasSchemaDependencies_ = true; + schemaDocument->CreateSchema(&properties_[sourceIndex].dependenciesSchema, q.Append(itr->name, allocator_), itr->value, document); + properties_[sourceIndex].dependenciesValidatorIndex = validatorCount_; + validatorCount_++; + } + } + } + } + + if (const ValueType* v = GetMember(value, GetAdditionalPropertiesString())) { + if (v->IsBool()) + additionalProperties_ = v->GetBool(); + else if (v->IsObject()) + schemaDocument->CreateSchema(&additionalPropertiesSchema_, p.Append(GetAdditionalPropertiesString(), allocator_), *v, document); + } + + AssignIfExist(minProperties_, value, GetMinPropertiesString()); + AssignIfExist(maxProperties_, value, GetMaxPropertiesString()); + + // Array + if (const ValueType* v = GetMember(value, GetItemsString())) { + PointerType q = p.Append(GetItemsString(), allocator_); + if (v->IsObject()) // List validation + schemaDocument->CreateSchema(&itemsList_, q, *v, document); + else if (v->IsArray()) { // Tuple validation + itemsTuple_ = static_cast(allocator_->Malloc(sizeof(const Schema*) * v->Size())); + SizeType index = 0; + for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr, index++) + schemaDocument->CreateSchema(&itemsTuple_[itemsTupleCount_++], q.Append(index, allocator_), *itr, document); + } + } + + AssignIfExist(minItems_, value, GetMinItemsString()); + AssignIfExist(maxItems_, value, GetMaxItemsString()); + + if (const ValueType* v = GetMember(value, GetAdditionalItemsString())) { + if (v->IsBool()) + additionalItems_ = v->GetBool(); + else if (v->IsObject()) + schemaDocument->CreateSchema(&additionalItemsSchema_, p.Append(GetAdditionalItemsString(), allocator_), *v, document); + } + + AssignIfExist(uniqueItems_, value, GetUniqueItemsString()); + + // String + AssignIfExist(minLength_, value, GetMinLengthString()); + AssignIfExist(maxLength_, value, GetMaxLengthString()); + + if (const ValueType* v = GetMember(value, GetPatternString())) + pattern_ = CreatePattern(*v); + + // Number + if (const ValueType* v = GetMember(value, GetMinimumString())) + if (v->IsNumber()) + minimum_.CopyFrom(*v, *allocator_); + + if (const ValueType* v = GetMember(value, GetMaximumString())) + if (v->IsNumber()) + maximum_.CopyFrom(*v, *allocator_); + + AssignIfExist(exclusiveMinimum_, value, GetExclusiveMinimumString()); + AssignIfExist(exclusiveMaximum_, value, GetExclusiveMaximumString()); + + if (const ValueType* v = GetMember(value, GetMultipleOfString())) + if (v->IsNumber() && v->GetDouble() > 0.0) + multipleOf_.CopyFrom(*v, *allocator_); + } + + ~Schema() { + if (allocator_) { + allocator_->Free(enum_); + } + if (properties_) { + for (SizeType i = 0; i < propertyCount_; i++) + properties_[i].~Property(); + AllocatorType::Free(properties_); + } + if (patternProperties_) { + for (SizeType i = 0; i < patternPropertyCount_; i++) + patternProperties_[i].~PatternProperty(); + AllocatorType::Free(patternProperties_); + } + AllocatorType::Free(itemsTuple_); +#if RAPIDJSON_SCHEMA_HAS_REGEX + if (pattern_) { + pattern_->~RegexType(); + allocator_->Free(pattern_); + } +#endif + } + + bool BeginValue(Context& context) const { + if (context.inArray) { + if (uniqueItems_) + context.valueUniqueness = true; + + if (itemsList_) + context.valueSchema = itemsList_; + else if (itemsTuple_) { + if (context.arrayElementIndex < itemsTupleCount_) + context.valueSchema = itemsTuple_[context.arrayElementIndex]; + else if (additionalItemsSchema_) + context.valueSchema = additionalItemsSchema_; + else if (additionalItems_) + context.valueSchema = GetTypeless(); + else + RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString()); + } + else + context.valueSchema = GetTypeless(); + + context.arrayElementIndex++; + } + return true; + } + + RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const { + if (context.patternPropertiesValidatorCount > 0) { + bool otherValid = false; + SizeType count = context.patternPropertiesValidatorCount; + if (context.objectPatternValidatorType != Context::kPatternValidatorOnly) + otherValid = context.patternPropertiesValidators[--count]->IsValid(); + + bool patternValid = true; + for (SizeType i = 0; i < count; i++) + if (!context.patternPropertiesValidators[i]->IsValid()) { + patternValid = false; + break; + } + + if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) { + if (!patternValid) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } + else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) { + if (!patternValid || !otherValid) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } + else if (!patternValid && !otherValid) // kPatternValidatorWithAdditionalProperty) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString()); + } + + if (enum_) { + const uint64_t h = context.factory.GetHashCode(context.hasher); + for (SizeType i = 0; i < enumCount_; i++) + if (enum_[i] == h) + goto foundEnum; + RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString()); + foundEnum:; + } + + if (allOf_.schemas) + for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++) + if (!context.validators[i]->IsValid()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString()); + + if (anyOf_.schemas) { + for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++) + if (context.validators[i]->IsValid()) + goto foundAny; + RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString()); + foundAny:; + } + + if (oneOf_.schemas) { + bool oneValid = false; + for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++) + if (context.validators[i]->IsValid()) { + if (oneValid) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); + else + oneValid = true; + } + if (!oneValid) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString()); + } + + if (not_ && context.validators[notValidatorIndex_]->IsValid()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString()); + + return true; + } + + bool Null(Context& context) const { + if (!(type_ & (1 << kNullSchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + return CreateParallelValidator(context); + } + + bool Bool(Context& context, bool) const { + if (!(type_ & (1 << kBooleanSchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + return CreateParallelValidator(context); + } + + bool Int(Context& context, int i) const { + if (!CheckInt(context, i)) + return false; + return CreateParallelValidator(context); + } + + bool Uint(Context& context, unsigned u) const { + if (!CheckUint(context, u)) + return false; + return CreateParallelValidator(context); + } + + bool Int64(Context& context, int64_t i) const { + if (!CheckInt(context, i)) + return false; + return CreateParallelValidator(context); + } + + bool Uint64(Context& context, uint64_t u) const { + if (!CheckUint(context, u)) + return false; + return CreateParallelValidator(context); + } + + bool Double(Context& context, double d) const { + if (!(type_ & (1 << kNumberSchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d)) + return false; + + if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d)) + return false; + + if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d)) + return false; + + return CreateParallelValidator(context); + } + + bool String(Context& context, const Ch* str, SizeType length, bool) const { + if (!(type_ & (1 << kStringSchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + if (minLength_ != 0 || maxLength_ != SizeType(~0)) { + SizeType count; + if (internal::CountStringCodePoint(str, length, &count)) { + if (count < minLength_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString()); + if (count > maxLength_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString()); + } + } + + if (pattern_ && !IsPatternMatch(pattern_, str, length)) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString()); + + return CreateParallelValidator(context); + } + + bool StartObject(Context& context) const { + if (!(type_ & (1 << kObjectSchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + if (hasDependencies_ || hasRequired_) { + context.propertyExist = static_cast(context.factory.MallocState(sizeof(bool) * propertyCount_)); + std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_); + } + + if (patternProperties_) { // pre-allocate schema array + SizeType count = patternPropertyCount_ + 1; // extra for valuePatternValidatorType + context.patternPropertiesSchemas = static_cast(context.factory.MallocState(sizeof(const SchemaType*) * count)); + context.patternPropertiesSchemaCount = 0; + std::memset(context.patternPropertiesSchemas, 0, sizeof(SchemaType*) * count); + } + + return CreateParallelValidator(context); + } + + bool Key(Context& context, const Ch* str, SizeType len, bool) const { + if (patternProperties_) { + context.patternPropertiesSchemaCount = 0; + for (SizeType i = 0; i < patternPropertyCount_; i++) + if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) + context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema; + } + + SizeType index; + if (FindPropertyIndex(ValueType(str, len).Move(), &index)) { + if (context.patternPropertiesSchemaCount > 0) { + context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema; + context.valueSchema = GetTypeless(); + context.valuePatternValidatorType = Context::kPatternValidatorWithProperty; + } + else + context.valueSchema = properties_[index].schema; + + if (context.propertyExist) + context.propertyExist[index] = true; + + return true; + } + + if (additionalPropertiesSchema_) { + if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) { + context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_; + context.valueSchema = GetTypeless(); + context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty; + } + else + context.valueSchema = additionalPropertiesSchema_; + return true; + } + else if (additionalProperties_) { + context.valueSchema = GetTypeless(); + return true; + } + + if (context.patternPropertiesSchemaCount == 0) // patternProperties are not additional properties + RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString()); + + return true; + } + + bool EndObject(Context& context, SizeType memberCount) const { + if (hasRequired_) + for (SizeType index = 0; index < propertyCount_; index++) + if (properties_[index].required) + if (!context.propertyExist[index]) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString()); + + if (memberCount < minProperties_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString()); + + if (memberCount > maxProperties_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString()); + + if (hasDependencies_) { + for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++) + if (context.propertyExist[sourceIndex]) { + if (properties_[sourceIndex].dependencies) { + for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++) + if (properties_[sourceIndex].dependencies[targetIndex] && !context.propertyExist[targetIndex]) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); + } + else if (properties_[sourceIndex].dependenciesSchema) + if (!context.validators[properties_[sourceIndex].dependenciesValidatorIndex]->IsValid()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString()); + } + } + + return true; + } + + bool StartArray(Context& context) const { + if (!(type_ & (1 << kArraySchemaType))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + context.arrayElementIndex = 0; + context.inArray = true; + + return CreateParallelValidator(context); + } + + bool EndArray(Context& context, SizeType elementCount) const { + context.inArray = false; + + if (elementCount < minItems_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString()); + + if (elementCount > maxItems_) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString()); + + return true; + } + + // Generate functions for string literal according to Ch +#define RAPIDJSON_STRING_(name, ...) \ + static const ValueType& Get##name##String() {\ + static const Ch s[] = { __VA_ARGS__, '\0' };\ + static const ValueType v(s, sizeof(s) / sizeof(Ch) - 1);\ + return v;\ + } + + RAPIDJSON_STRING_(Null, 'n', 'u', 'l', 'l') + RAPIDJSON_STRING_(Boolean, 'b', 'o', 'o', 'l', 'e', 'a', 'n') + RAPIDJSON_STRING_(Object, 'o', 'b', 'j', 'e', 'c', 't') + RAPIDJSON_STRING_(Array, 'a', 'r', 'r', 'a', 'y') + RAPIDJSON_STRING_(String, 's', 't', 'r', 'i', 'n', 'g') + RAPIDJSON_STRING_(Number, 'n', 'u', 'm', 'b', 'e', 'r') + RAPIDJSON_STRING_(Integer, 'i', 'n', 't', 'e', 'g', 'e', 'r') + RAPIDJSON_STRING_(Type, 't', 'y', 'p', 'e') + RAPIDJSON_STRING_(Enum, 'e', 'n', 'u', 'm') + RAPIDJSON_STRING_(AllOf, 'a', 'l', 'l', 'O', 'f') + RAPIDJSON_STRING_(AnyOf, 'a', 'n', 'y', 'O', 'f') + RAPIDJSON_STRING_(OneOf, 'o', 'n', 'e', 'O', 'f') + RAPIDJSON_STRING_(Not, 'n', 'o', 't') + RAPIDJSON_STRING_(Properties, 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') + RAPIDJSON_STRING_(Required, 'r', 'e', 'q', 'u', 'i', 'r', 'e', 'd') + RAPIDJSON_STRING_(Dependencies, 'd', 'e', 'p', 'e', 'n', 'd', 'e', 'n', 'c', 'i', 'e', 's') + RAPIDJSON_STRING_(PatternProperties, 'p', 'a', 't', 't', 'e', 'r', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') + RAPIDJSON_STRING_(AdditionalProperties, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') + RAPIDJSON_STRING_(MinProperties, 'm', 'i', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') + RAPIDJSON_STRING_(MaxProperties, 'm', 'a', 'x', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's') + RAPIDJSON_STRING_(Items, 'i', 't', 'e', 'm', 's') + RAPIDJSON_STRING_(MinItems, 'm', 'i', 'n', 'I', 't', 'e', 'm', 's') + RAPIDJSON_STRING_(MaxItems, 'm', 'a', 'x', 'I', 't', 'e', 'm', 's') + RAPIDJSON_STRING_(AdditionalItems, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'I', 't', 'e', 'm', 's') + RAPIDJSON_STRING_(UniqueItems, 'u', 'n', 'i', 'q', 'u', 'e', 'I', 't', 'e', 'm', 's') + RAPIDJSON_STRING_(MinLength, 'm', 'i', 'n', 'L', 'e', 'n', 'g', 't', 'h') + RAPIDJSON_STRING_(MaxLength, 'm', 'a', 'x', 'L', 'e', 'n', 'g', 't', 'h') + RAPIDJSON_STRING_(Pattern, 'p', 'a', 't', 't', 'e', 'r', 'n') + RAPIDJSON_STRING_(Minimum, 'm', 'i', 'n', 'i', 'm', 'u', 'm') + RAPIDJSON_STRING_(Maximum, 'm', 'a', 'x', 'i', 'm', 'u', 'm') + RAPIDJSON_STRING_(ExclusiveMinimum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'i', 'n', 'i', 'm', 'u', 'm') + RAPIDJSON_STRING_(ExclusiveMaximum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'a', 'x', 'i', 'm', 'u', 'm') + RAPIDJSON_STRING_(MultipleOf, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 'O', 'f') + +#undef RAPIDJSON_STRING_ + +private: + enum SchemaValueType { + kNullSchemaType, + kBooleanSchemaType, + kObjectSchemaType, + kArraySchemaType, + kStringSchemaType, + kNumberSchemaType, + kIntegerSchemaType, + kTotalSchemaType + }; + +#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX + typedef internal::GenericRegex RegexType; +#elif RAPIDJSON_SCHEMA_USE_STDREGEX + typedef std::basic_regex RegexType; +#else + typedef char RegexType; +#endif + + struct SchemaArray { + SchemaArray() : schemas(), count() {} + ~SchemaArray() { AllocatorType::Free(schemas); } + const SchemaType** schemas; + SizeType begin; // begin index of context.validators + SizeType count; + }; + + static const SchemaType* GetTypeless() { + static SchemaType typeless(0, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0); + return &typeless; + } + + template + void AddUniqueElement(V1& a, const V2& v) { + for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) + if (*itr == v) + return; + V1 c(v, *allocator_); + a.PushBack(c, *allocator_); + } + + static const ValueType* GetMember(const ValueType& value, const ValueType& name) { + typename ValueType::ConstMemberIterator itr = value.FindMember(name); + return itr != value.MemberEnd() ? &(itr->value) : 0; + } + + static void AssignIfExist(bool& out, const ValueType& value, const ValueType& name) { + if (const ValueType* v = GetMember(value, name)) + if (v->IsBool()) + out = v->GetBool(); + } + + static void AssignIfExist(SizeType& out, const ValueType& value, const ValueType& name) { + if (const ValueType* v = GetMember(value, name)) + if (v->IsUint64() && v->GetUint64() <= SizeType(~0)) + out = static_cast(v->GetUint64()); + } + + void AssignIfExist(SchemaArray& out, SchemaDocumentType& schemaDocument, const PointerType& p, const ValueType& value, const ValueType& name, const ValueType& document) { + if (const ValueType* v = GetMember(value, name)) { + if (v->IsArray() && v->Size() > 0) { + PointerType q = p.Append(name, allocator_); + out.count = v->Size(); + out.schemas = static_cast(allocator_->Malloc(out.count * sizeof(const Schema*))); + memset(out.schemas, 0, sizeof(Schema*)* out.count); + for (SizeType i = 0; i < out.count; i++) + schemaDocument.CreateSchema(&out.schemas[i], q.Append(i, allocator_), (*v)[i], document); + out.begin = validatorCount_; + validatorCount_ += out.count; + } + } + } + +#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX + template + RegexType* CreatePattern(const ValueType& value) { + if (value.IsString()) { + RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString()); + if (!r->IsValid()) { + r->~RegexType(); + AllocatorType::Free(r); + r = 0; + } + return r; + } + return 0; + } + + static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) { + return pattern->Search(str); + } +#elif RAPIDJSON_SCHEMA_USE_STDREGEX + template + RegexType* CreatePattern(const ValueType& value) { + if (value.IsString()) + try { + return new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript); + } + catch (const std::regex_error&) { + } + return 0; + } + + static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType length) { + std::match_results r; + return std::regex_search(str, str + length, r, *pattern); + } +#else + template + RegexType* CreatePattern(const ValueType&) { return 0; } + + static bool IsPatternMatch(const RegexType*, const Ch *, SizeType) { return true; } +#endif // RAPIDJSON_SCHEMA_USE_STDREGEX + + void AddType(const ValueType& type) { + if (type == GetNullString() ) type_ |= 1 << kNullSchemaType; + else if (type == GetBooleanString()) type_ |= 1 << kBooleanSchemaType; + else if (type == GetObjectString() ) type_ |= 1 << kObjectSchemaType; + else if (type == GetArrayString() ) type_ |= 1 << kArraySchemaType; + else if (type == GetStringString() ) type_ |= 1 << kStringSchemaType; + else if (type == GetIntegerString()) type_ |= 1 << kIntegerSchemaType; + else if (type == GetNumberString() ) type_ |= (1 << kNumberSchemaType) | (1 << kIntegerSchemaType); + } + + bool CreateParallelValidator(Context& context) const { + if (enum_ || context.arrayUniqueness) + context.hasher = context.factory.CreateHasher(); + + if (validatorCount_) { + RAPIDJSON_ASSERT(context.validators == 0); + context.validators = static_cast(context.factory.MallocState(sizeof(ISchemaValidator*) * validatorCount_)); + context.validatorCount = validatorCount_; + + if (allOf_.schemas) + CreateSchemaValidators(context, allOf_); + + if (anyOf_.schemas) + CreateSchemaValidators(context, anyOf_); + + if (oneOf_.schemas) + CreateSchemaValidators(context, oneOf_); + + if (not_) + context.validators[notValidatorIndex_] = context.factory.CreateSchemaValidator(*not_); + + if (hasSchemaDependencies_) { + for (SizeType i = 0; i < propertyCount_; i++) + if (properties_[i].dependenciesSchema) + context.validators[properties_[i].dependenciesValidatorIndex] = context.factory.CreateSchemaValidator(*properties_[i].dependenciesSchema); + } + } + + return true; + } + + void CreateSchemaValidators(Context& context, const SchemaArray& schemas) const { + for (SizeType i = 0; i < schemas.count; i++) + context.validators[schemas.begin + i] = context.factory.CreateSchemaValidator(*schemas.schemas[i]); + } + + // O(n) + bool FindPropertyIndex(const ValueType& name, SizeType* outIndex) const { + SizeType len = name.GetStringLength(); + const Ch* str = name.GetString(); + for (SizeType index = 0; index < propertyCount_; index++) + if (properties_[index].name.GetStringLength() == len && + (std::memcmp(properties_[index].name.GetString(), str, sizeof(Ch) * len) == 0)) + { + *outIndex = index; + return true; + } + return false; + } + + bool CheckInt(Context& context, int64_t i) const { + if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + if (!minimum_.IsNull()) { + if (minimum_.IsInt64()) { + if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + } + else if (minimum_.IsUint64()) { + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64() + } + else if (!CheckDoubleMinimum(context, static_cast(i))) + return false; + } + + if (!maximum_.IsNull()) { + if (maximum_.IsInt64()) { + if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + } + else if (maximum_.IsUint64()) + /* do nothing */; // i <= max(int64_t) < maximum_.GetUint64() + else if (!CheckDoubleMaximum(context, static_cast(i))) + return false; + } + + if (!multipleOf_.IsNull()) { + if (multipleOf_.IsUint64()) { + if (static_cast(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + } + else if (!CheckDoubleMultipleOf(context, static_cast(i))) + return false; + } + + return true; + } + + bool CheckUint(Context& context, uint64_t i) const { + if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType)))) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString()); + + if (!minimum_.IsNull()) { + if (minimum_.IsUint64()) { + if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + } + else if (minimum_.IsInt64()) + /* do nothing */; // i >= 0 > minimum.Getint64() + else if (!CheckDoubleMinimum(context, static_cast(i))) + return false; + } + + if (!maximum_.IsNull()) { + if (maximum_.IsUint64()) { + if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + } + else if (maximum_.IsInt64()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_ + else if (!CheckDoubleMaximum(context, static_cast(i))) + return false; + } + + if (!multipleOf_.IsNull()) { + if (multipleOf_.IsUint64()) { + if (i % multipleOf_.GetUint64() != 0) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + } + else if (!CheckDoubleMultipleOf(context, static_cast(i))) + return false; + } + + return true; + } + + bool CheckDoubleMinimum(Context& context, double d) const { + if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); + return true; + } + + bool CheckDoubleMaximum(Context& context, double d) const { + if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble()) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); + return true; + } + + bool CheckDoubleMultipleOf(Context& context, double d) const { + double a = std::abs(d), b = std::abs(multipleOf_.GetDouble()); + double q = std::floor(a / b); + double r = a - q * b; + if (r > 0.0) + RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString()); + return true; + } + + struct Property { + Property() : schema(), dependenciesSchema(), dependenciesValidatorIndex(), dependencies(), required(false) {} + ~Property() { AllocatorType::Free(dependencies); } + SValue name; + const SchemaType* schema; + const SchemaType* dependenciesSchema; + SizeType dependenciesValidatorIndex; + bool* dependencies; + bool required; + }; + + struct PatternProperty { + PatternProperty() : schema(), pattern() {} + ~PatternProperty() { + if (pattern) { + pattern->~RegexType(); + AllocatorType::Free(pattern); + } + } + const SchemaType* schema; + RegexType* pattern; + }; + + AllocatorType* allocator_; + uint64_t* enum_; + SizeType enumCount_; + SchemaArray allOf_; + SchemaArray anyOf_; + SchemaArray oneOf_; + const SchemaType* not_; + unsigned type_; // bitmask of kSchemaType + SizeType validatorCount_; + SizeType notValidatorIndex_; + + Property* properties_; + const SchemaType* additionalPropertiesSchema_; + PatternProperty* patternProperties_; + SizeType patternPropertyCount_; + SizeType propertyCount_; + SizeType minProperties_; + SizeType maxProperties_; + bool additionalProperties_; + bool hasDependencies_; + bool hasRequired_; + bool hasSchemaDependencies_; + + const SchemaType* additionalItemsSchema_; + const SchemaType* itemsList_; + const SchemaType** itemsTuple_; + SizeType itemsTupleCount_; + SizeType minItems_; + SizeType maxItems_; + bool additionalItems_; + bool uniqueItems_; + + RegexType* pattern_; + SizeType minLength_; + SizeType maxLength_; + + SValue minimum_; + SValue maximum_; + SValue multipleOf_; + bool exclusiveMinimum_; + bool exclusiveMaximum_; +}; + +template +struct TokenHelper { + RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) { + *documentStack.template Push() = '/'; + char buffer[21]; + size_t length = static_cast((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer); + for (size_t i = 0; i < length; i++) + *documentStack.template Push() = buffer[i]; + } +}; + +// Partial specialized version for char to prevent buffer copying. +template +struct TokenHelper { + RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) { + if (sizeof(SizeType) == 4) { + char *buffer = documentStack.template Push(1 + 10); // '/' + uint + *buffer++ = '/'; + const char* end = internal::u32toa(index, buffer); + documentStack.template Pop(static_cast(10 - (end - buffer))); + } + else { + char *buffer = documentStack.template Push(1 + 20); // '/' + uint64 + *buffer++ = '/'; + const char* end = internal::u64toa(index, buffer); + documentStack.template Pop(static_cast(20 - (end - buffer))); + } + } +}; + +} // namespace internal + +/////////////////////////////////////////////////////////////////////////////// +// IGenericRemoteSchemaDocumentProvider + +template +class IGenericRemoteSchemaDocumentProvider { +public: + typedef typename SchemaDocumentType::Ch Ch; + + virtual ~IGenericRemoteSchemaDocumentProvider() {} + virtual const SchemaDocumentType* GetRemoteDocument(const Ch* uri, SizeType length) = 0; +}; + +/////////////////////////////////////////////////////////////////////////////// +// GenericSchemaDocument + +//! JSON schema document. +/*! + A JSON schema document is a compiled version of a JSON schema. + It is basically a tree of internal::Schema. + + \note This is an immutable class (i.e. its instance cannot be modified after construction). + \tparam ValueT Type of JSON value (e.g. \c Value ), which also determine the encoding. + \tparam Allocator Allocator type for allocating memory of this document. +*/ +template +class GenericSchemaDocument { +public: + typedef ValueT ValueType; + typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProviderType; + typedef Allocator AllocatorType; + typedef typename ValueType::EncodingType EncodingType; + typedef typename EncodingType::Ch Ch; + typedef internal::Schema SchemaType; + typedef GenericPointer PointerType; + friend class internal::Schema; + template + friend class GenericSchemaValidator; + + //! Constructor. + /*! + Compile a JSON document into schema document. + + \param document A JSON document as source. + \param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null. + \param allocator An optional allocator instance for allocating memory. Can be null. + */ + explicit GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) : + remoteProvider_(remoteProvider), + allocator_(allocator), + ownAllocator_(), + root_(), + schemaMap_(allocator, kInitialSchemaMapSize), + schemaRef_(allocator, kInitialSchemaRefSize) + { + if (!allocator_) + ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator()); + + // Generate root schema, it will call CreateSchema() to create sub-schemas, + // And call AddRefSchema() if there are $ref. + CreateSchemaRecursive(&root_, PointerType(), document, document); + + // Resolve $ref + while (!schemaRef_.Empty()) { + SchemaRefEntry* refEntry = schemaRef_.template Pop(1); + if (const SchemaType* s = GetSchema(refEntry->target)) { + if (refEntry->schema) + *refEntry->schema = s; + + // Create entry in map if not exist + if (!GetSchema(refEntry->source)) { + new (schemaMap_.template Push()) SchemaEntry(refEntry->source, const_cast(s), false, allocator_); + } + } + refEntry->~SchemaRefEntry(); + } + + RAPIDJSON_ASSERT(root_ != 0); + + schemaRef_.ShrinkToFit(); // Deallocate all memory for ref + } + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + //! Move constructor in C++11 + GenericSchemaDocument(GenericSchemaDocument&& rhs) RAPIDJSON_NOEXCEPT : + remoteProvider_(rhs.remoteProvider_), + allocator_(rhs.allocator_), + ownAllocator_(rhs.ownAllocator_), + root_(rhs.root_), + schemaMap_(std::move(rhs.schemaMap_)), + schemaRef_(std::move(rhs.schemaRef_)) + { + rhs.remoteProvider_ = 0; + rhs.allocator_ = 0; + rhs.ownAllocator_ = 0; + } +#endif + + //! Destructor + ~GenericSchemaDocument() { + while (!schemaMap_.Empty()) + schemaMap_.template Pop(1)->~SchemaEntry(); + + RAPIDJSON_DELETE(ownAllocator_); + } + + //! Get the root schema. + const SchemaType& GetRoot() const { return *root_; } + +private: + //! Prohibit copying + GenericSchemaDocument(const GenericSchemaDocument&); + //! Prohibit assignment + GenericSchemaDocument& operator=(const GenericSchemaDocument&); + + struct SchemaRefEntry { + SchemaRefEntry(const PointerType& s, const PointerType& t, const SchemaType** outSchema, Allocator *allocator) : source(s, allocator), target(t, allocator), schema(outSchema) {} + PointerType source; + PointerType target; + const SchemaType** schema; + }; + + struct SchemaEntry { + SchemaEntry(const PointerType& p, SchemaType* s, bool o, Allocator* allocator) : pointer(p, allocator), schema(s), owned(o) {} + ~SchemaEntry() { + if (owned) { + schema->~SchemaType(); + Allocator::Free(schema); + } + } + PointerType pointer; + SchemaType* schema; + bool owned; + }; + + void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) { + if (schema) + *schema = SchemaType::GetTypeless(); + + if (v.GetType() == kObjectType) { + const SchemaType* s = GetSchema(pointer); + if (!s) + CreateSchema(schema, pointer, v, document); + + for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) + CreateSchemaRecursive(0, pointer.Append(itr->name, allocator_), itr->value, document); + } + else if (v.GetType() == kArrayType) + for (SizeType i = 0; i < v.Size(); i++) + CreateSchemaRecursive(0, pointer.Append(i, allocator_), v[i], document); + } + + void CreateSchema(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) { + RAPIDJSON_ASSERT(pointer.IsValid()); + if (v.IsObject()) { + if (!HandleRefSchema(pointer, schema, v, document)) { + SchemaType* s = new (allocator_->Malloc(sizeof(SchemaType))) SchemaType(this, pointer, v, document, allocator_); + new (schemaMap_.template Push()) SchemaEntry(pointer, s, true, allocator_); + if (schema) + *schema = s; + } + } + } + + bool HandleRefSchema(const PointerType& source, const SchemaType** schema, const ValueType& v, const ValueType& document) { + static const Ch kRefString[] = { '$', 'r', 'e', 'f', '\0' }; + static const ValueType kRefValue(kRefString, 4); + + typename ValueType::ConstMemberIterator itr = v.FindMember(kRefValue); + if (itr == v.MemberEnd()) + return false; + + if (itr->value.IsString()) { + SizeType len = itr->value.GetStringLength(); + if (len > 0) { + const Ch* s = itr->value.GetString(); + SizeType i = 0; + while (i < len && s[i] != '#') // Find the first # + i++; + + if (i > 0) { // Remote reference, resolve immediately + if (remoteProvider_) { + if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i - 1)) { + PointerType pointer(&s[i], len - i, allocator_); + if (pointer.IsValid()) { + if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) { + if (schema) + *schema = sc; + return true; + } + } + } + } + } + else if (s[i] == '#') { // Local reference, defer resolution + PointerType pointer(&s[i], len - i, allocator_); + if (pointer.IsValid()) { + if (const ValueType* nv = pointer.Get(document)) + if (HandleRefSchema(source, schema, *nv, document)) + return true; + + new (schemaRef_.template Push()) SchemaRefEntry(source, pointer, schema, allocator_); + return true; + } + } + } + } + return false; + } + + const SchemaType* GetSchema(const PointerType& pointer) const { + for (const SchemaEntry* target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) + if (pointer == target->pointer) + return target->schema; + return 0; + } + + PointerType GetPointer(const SchemaType* schema) const { + for (const SchemaEntry* target = schemaMap_.template Bottom(); target != schemaMap_.template End(); ++target) + if (schema == target->schema) + return target->pointer; + return PointerType(); + } + + static const size_t kInitialSchemaMapSize = 64; + static const size_t kInitialSchemaRefSize = 64; + + IRemoteSchemaDocumentProviderType* remoteProvider_; + Allocator *allocator_; + Allocator *ownAllocator_; + const SchemaType* root_; //!< Root schema. + internal::Stack schemaMap_; // Stores created Pointer -> Schemas + internal::Stack schemaRef_; // Stores Pointer from $ref and schema which holds the $ref +}; + +//! GenericSchemaDocument using Value type. +typedef GenericSchemaDocument SchemaDocument; +//! IGenericRemoteSchemaDocumentProvider using SchemaDocument. +typedef IGenericRemoteSchemaDocumentProvider IRemoteSchemaDocumentProvider; + +/////////////////////////////////////////////////////////////////////////////// +// GenericSchemaValidator + +//! JSON Schema Validator. +/*! + A SAX style JSON schema validator. + It uses a \c GenericSchemaDocument to validate SAX events. + It delegates the incoming SAX events to an output handler. + The default output handler does nothing. + It can be reused multiple times by calling \c Reset(). + + \tparam SchemaDocumentType Type of schema document. + \tparam OutputHandler Type of output handler. Default handler does nothing. + \tparam StateAllocator Allocator for storing the internal validation states. +*/ +template < + typename SchemaDocumentType, + typename OutputHandler = BaseReaderHandler, + typename StateAllocator = CrtAllocator> +class GenericSchemaValidator : + public internal::ISchemaStateFactory, + public internal::ISchemaValidator +{ +public: + typedef typename SchemaDocumentType::SchemaType SchemaType; + typedef typename SchemaDocumentType::PointerType PointerType; + typedef typename SchemaType::EncodingType EncodingType; + typedef typename EncodingType::Ch Ch; + + //! Constructor without output handler. + /*! + \param schemaDocument The schema document to conform to. + \param allocator Optional allocator for storing internal validation states. + \param schemaStackCapacity Optional initial capacity of schema path stack. + \param documentStackCapacity Optional initial capacity of document path stack. + */ + GenericSchemaValidator( + const SchemaDocumentType& schemaDocument, + StateAllocator* allocator = 0, + size_t schemaStackCapacity = kDefaultSchemaStackCapacity, + size_t documentStackCapacity = kDefaultDocumentStackCapacity) + : + schemaDocument_(&schemaDocument), + root_(schemaDocument.GetRoot()), + outputHandler_(GetNullHandler()), + stateAllocator_(allocator), + ownStateAllocator_(0), + schemaStack_(allocator, schemaStackCapacity), + documentStack_(allocator, documentStackCapacity), + valid_(true) +#if RAPIDJSON_SCHEMA_VERBOSE + , depth_(0) +#endif + { + } + + //! Constructor with output handler. + /*! + \param schemaDocument The schema document to conform to. + \param allocator Optional allocator for storing internal validation states. + \param schemaStackCapacity Optional initial capacity of schema path stack. + \param documentStackCapacity Optional initial capacity of document path stack. + */ + GenericSchemaValidator( + const SchemaDocumentType& schemaDocument, + OutputHandler& outputHandler, + StateAllocator* allocator = 0, + size_t schemaStackCapacity = kDefaultSchemaStackCapacity, + size_t documentStackCapacity = kDefaultDocumentStackCapacity) + : + schemaDocument_(&schemaDocument), + root_(schemaDocument.GetRoot()), + outputHandler_(outputHandler), + stateAllocator_(allocator), + ownStateAllocator_(0), + schemaStack_(allocator, schemaStackCapacity), + documentStack_(allocator, documentStackCapacity), + valid_(true) +#if RAPIDJSON_SCHEMA_VERBOSE + , depth_(0) +#endif + { + } + + //! Destructor. + ~GenericSchemaValidator() { + Reset(); + RAPIDJSON_DELETE(ownStateAllocator_); + } + + //! Reset the internal states. + void Reset() { + while (!schemaStack_.Empty()) + PopSchema(); + documentStack_.Clear(); + valid_ = true; + } + + //! Checks whether the current state is valid. + // Implementation of ISchemaValidator + virtual bool IsValid() const { return valid_; } + + //! Gets the JSON pointer pointed to the invalid schema. + PointerType GetInvalidSchemaPointer() const { + return schemaStack_.Empty() ? PointerType() : schemaDocument_->GetPointer(&CurrentSchema()); + } + + //! Gets the keyword of invalid schema. + const Ch* GetInvalidSchemaKeyword() const { + return schemaStack_.Empty() ? 0 : CurrentContext().invalidKeyword; + } + + //! Gets the JSON pointer pointed to the invalid value. + PointerType GetInvalidDocumentPointer() const { + return documentStack_.Empty() ? PointerType() : PointerType(documentStack_.template Bottom(), documentStack_.GetSize() / sizeof(Ch)); + } + +#if RAPIDJSON_SCHEMA_VERBOSE +#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \ +RAPIDJSON_MULTILINEMACRO_BEGIN\ + *documentStack_.template Push() = '\0';\ + documentStack_.template Pop(1);\ + internal::PrintInvalidDocument(documentStack_.template Bottom());\ +RAPIDJSON_MULTILINEMACRO_END +#else +#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() +#endif + +#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1)\ + if (!valid_) return false; \ + if (!BeginValue() || !CurrentSchema().method arg1) {\ + RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_();\ + return valid_ = false;\ + } + +#define RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2)\ + for (Context* context = schemaStack_.template Bottom(); context != schemaStack_.template End(); context++) {\ + if (context->hasher)\ + static_cast(context->hasher)->method arg2;\ + if (context->validators)\ + for (SizeType i_ = 0; i_ < context->validatorCount; i_++)\ + static_cast(context->validators[i_])->method arg2;\ + if (context->patternPropertiesValidators)\ + for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; i_++)\ + static_cast(context->patternPropertiesValidators[i_])->method arg2;\ + } + +#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\ + return valid_ = EndValue() && outputHandler_.method arg2 + +#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \ + RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\ + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\ + RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2) + + bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext() ), ( )); } + bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); } + bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); } + bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); } + bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); } + bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); } + bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); } + bool RawNumber(const Ch* str, SizeType length, bool copy) + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } + bool String(const Ch* str, SizeType length, bool copy) + { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); } + + bool StartObject() { + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext())); + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ()); + return valid_ = outputHandler_.StartObject(); + } + + bool Key(const Ch* str, SizeType len, bool copy) { + if (!valid_) return false; + AppendToken(str, len); + if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false; + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy)); + return valid_ = outputHandler_.Key(str, len, copy); + } + + bool EndObject(SizeType memberCount) { + if (!valid_) return false; + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount)); + if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false; + RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount)); + } + + bool StartArray() { + RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext())); + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ()); + return valid_ = outputHandler_.StartArray(); + } + + bool EndArray(SizeType elementCount) { + if (!valid_) return false; + RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount)); + if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false; + RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount)); + } + +#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_ +#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_ +#undef RAPIDJSON_SCHEMA_HANDLE_PARALLEL_ +#undef RAPIDJSON_SCHEMA_HANDLE_VALUE_ + + // Implementation of ISchemaStateFactory + virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) { + return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root, +#if RAPIDJSON_SCHEMA_VERBOSE + depth_ + 1, +#endif + &GetStateAllocator()); + } + + virtual void DestroySchemaValidator(ISchemaValidator* validator) { + GenericSchemaValidator* v = static_cast(validator); + v->~GenericSchemaValidator(); + StateAllocator::Free(v); + } + + virtual void* CreateHasher() { + return new (GetStateAllocator().Malloc(sizeof(HasherType))) HasherType(&GetStateAllocator()); + } + + virtual uint64_t GetHashCode(void* hasher) { + return static_cast(hasher)->GetHashCode(); + } + + virtual void DestroryHasher(void* hasher) { + HasherType* h = static_cast(hasher); + h->~HasherType(); + StateAllocator::Free(h); + } + + virtual void* MallocState(size_t size) { + return GetStateAllocator().Malloc(size); + } + + virtual void FreeState(void* p) { + return StateAllocator::Free(p); + } + +private: + typedef typename SchemaType::Context Context; + typedef GenericValue, StateAllocator> HashCodeArray; + typedef internal::Hasher HasherType; + + GenericSchemaValidator( + const SchemaDocumentType& schemaDocument, + const SchemaType& root, +#if RAPIDJSON_SCHEMA_VERBOSE + unsigned depth, +#endif + StateAllocator* allocator = 0, + size_t schemaStackCapacity = kDefaultSchemaStackCapacity, + size_t documentStackCapacity = kDefaultDocumentStackCapacity) + : + schemaDocument_(&schemaDocument), + root_(root), + outputHandler_(GetNullHandler()), + stateAllocator_(allocator), + ownStateAllocator_(0), + schemaStack_(allocator, schemaStackCapacity), + documentStack_(allocator, documentStackCapacity), + valid_(true) +#if RAPIDJSON_SCHEMA_VERBOSE + , depth_(depth) +#endif + { + } + + StateAllocator& GetStateAllocator() { + if (!stateAllocator_) + stateAllocator_ = ownStateAllocator_ = RAPIDJSON_NEW(StateAllocator()); + return *stateAllocator_; + } + + bool BeginValue() { + if (schemaStack_.Empty()) + PushSchema(root_); + else { + if (CurrentContext().inArray) + internal::TokenHelper, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex); + + if (!CurrentSchema().BeginValue(CurrentContext())) + return false; + + SizeType count = CurrentContext().patternPropertiesSchemaCount; + const SchemaType** sa = CurrentContext().patternPropertiesSchemas; + typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType; + bool valueUniqueness = CurrentContext().valueUniqueness; + if (CurrentContext().valueSchema) + PushSchema(*CurrentContext().valueSchema); + + if (count > 0) { + CurrentContext().objectPatternValidatorType = patternValidatorType; + ISchemaValidator**& va = CurrentContext().patternPropertiesValidators; + SizeType& validatorCount = CurrentContext().patternPropertiesValidatorCount; + va = static_cast(MallocState(sizeof(ISchemaValidator*) * count)); + for (SizeType i = 0; i < count; i++) + va[validatorCount++] = CreateSchemaValidator(*sa[i]); + } + + CurrentContext().arrayUniqueness = valueUniqueness; + } + return true; + } + + bool EndValue() { + if (!CurrentSchema().EndValue(CurrentContext())) + return false; + +#if RAPIDJSON_SCHEMA_VERBOSE + GenericStringBuffer sb; + schemaDocument_->GetPointer(&CurrentSchema()).Stringify(sb); + + *documentStack_.template Push() = '\0'; + documentStack_.template Pop(1); + internal::PrintValidatorPointers(depth_, sb.GetString(), documentStack_.template Bottom()); +#endif + + uint64_t h = CurrentContext().arrayUniqueness ? static_cast(CurrentContext().hasher)->GetHashCode() : 0; + + PopSchema(); + + if (!schemaStack_.Empty()) { + Context& context = CurrentContext(); + if (context.valueUniqueness) { + HashCodeArray* a = static_cast(context.arrayElementHashCodes); + if (!a) + CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType); + for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr) + if (itr->GetUint64() == h) + RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString()); + a->PushBack(h, GetStateAllocator()); + } + } + + // Remove the last token of document pointer + while (!documentStack_.Empty() && *documentStack_.template Pop(1) != '/') + ; + + return true; + } + + void AppendToken(const Ch* str, SizeType len) { + documentStack_.template Reserve(1 + len * 2); // worst case all characters are escaped as two characters + *documentStack_.template PushUnsafe() = '/'; + for (SizeType i = 0; i < len; i++) { + if (str[i] == '~') { + *documentStack_.template PushUnsafe() = '~'; + *documentStack_.template PushUnsafe() = '0'; + } + else if (str[i] == '/') { + *documentStack_.template PushUnsafe() = '~'; + *documentStack_.template PushUnsafe() = '1'; + } + else + *documentStack_.template PushUnsafe() = str[i]; + } + } + + RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push()) Context(*this, &schema); } + + RAPIDJSON_FORCEINLINE void PopSchema() { + Context* c = schemaStack_.template Pop(1); + if (HashCodeArray* a = static_cast(c->arrayElementHashCodes)) { + a->~HashCodeArray(); + StateAllocator::Free(a); + } + c->~Context(); + } + + const SchemaType& CurrentSchema() const { return *schemaStack_.template Top()->schema; } + Context& CurrentContext() { return *schemaStack_.template Top(); } + const Context& CurrentContext() const { return *schemaStack_.template Top(); } + + static OutputHandler& GetNullHandler() { + static OutputHandler nullHandler; + return nullHandler; + } + + static const size_t kDefaultSchemaStackCapacity = 1024; + static const size_t kDefaultDocumentStackCapacity = 256; + const SchemaDocumentType* schemaDocument_; + const SchemaType& root_; + OutputHandler& outputHandler_; + StateAllocator* stateAllocator_; + StateAllocator* ownStateAllocator_; + internal::Stack schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *) + internal::Stack documentStack_; //!< stack to store the current path of validating document (Ch) + bool valid_; +#if RAPIDJSON_SCHEMA_VERBOSE + unsigned depth_; +#endif +}; + +typedef GenericSchemaValidator SchemaValidator; + +/////////////////////////////////////////////////////////////////////////////// +// SchemaValidatingReader + +//! A helper class for parsing with validation. +/*! + This helper class is a functor, designed as a parameter of \ref GenericDocument::Populate(). + + \tparam parseFlags Combination of \ref ParseFlag. + \tparam InputStream Type of input stream, implementing Stream concept. + \tparam SourceEncoding Encoding of the input stream. + \tparam SchemaDocumentType Type of schema document. + \tparam StackAllocator Allocator type for stack. +*/ +template < + unsigned parseFlags, + typename InputStream, + typename SourceEncoding, + typename SchemaDocumentType = SchemaDocument, + typename StackAllocator = CrtAllocator> +class SchemaValidatingReader { +public: + typedef typename SchemaDocumentType::PointerType PointerType; + typedef typename InputStream::Ch Ch; + + //! Constructor + /*! + \param is Input stream. + \param sd Schema document. + */ + SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), isValid_(true) {} + + template + bool operator()(Handler& handler) { + GenericReader reader; + GenericSchemaValidator validator(sd_, handler); + parseResult_ = reader.template Parse(is_, validator); + + isValid_ = validator.IsValid(); + if (isValid_) { + invalidSchemaPointer_ = PointerType(); + invalidSchemaKeyword_ = 0; + invalidDocumentPointer_ = PointerType(); + } + else { + invalidSchemaPointer_ = validator.GetInvalidSchemaPointer(); + invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword(); + invalidDocumentPointer_ = validator.GetInvalidDocumentPointer(); + } + + return parseResult_; + } + + const ParseResult& GetParseResult() const { return parseResult_; } + bool IsValid() const { return isValid_; } + const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; } + const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; } + const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; } + +private: + InputStream& is_; + const SchemaDocumentType& sd_; + + ParseResult parseResult_; + PointerType invalidSchemaPointer_; + const Ch* invalidSchemaKeyword_; + PointerType invalidDocumentPointer_; + bool isValid_; +}; + +RAPIDJSON_NAMESPACE_END +RAPIDJSON_DIAG_POP + +#endif // RAPIDJSON_SCHEMA_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/stream.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/stream.h new file mode 100644 index 0000000000..fef82c252f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/stream.h @@ -0,0 +1,179 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "rapidjson.h" + +#ifndef RAPIDJSON_STREAM_H_ +#define RAPIDJSON_STREAM_H_ + +#include "encodings.h" + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// Stream + +/*! \class rapidjson::Stream + \brief Concept for reading and writing characters. + + For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd(). + + For write-only stream, only need to implement Put() and Flush(). + +\code +concept Stream { + typename Ch; //!< Character type of the stream. + + //! Read the current character from stream without moving the read cursor. + Ch Peek() const; + + //! Read the current character from stream and moving the read cursor to next character. + Ch Take(); + + //! Get the current read cursor. + //! \return Number of characters read from start. + size_t Tell(); + + //! Begin writing operation at the current read pointer. + //! \return The begin writer pointer. + Ch* PutBegin(); + + //! Write a character. + void Put(Ch c); + + //! Flush the buffer. + void Flush(); + + //! End the writing operation. + //! \param begin The begin write pointer returned by PutBegin(). + //! \return Number of characters written. + size_t PutEnd(Ch* begin); +} +\endcode +*/ + +//! Provides additional information for stream. +/*! + By using traits pattern, this type provides a default configuration for stream. + For custom stream, this type can be specialized for other configuration. + See TEST(Reader, CustomStringStream) in readertest.cpp for example. +*/ +template +struct StreamTraits { + //! Whether to make local copy of stream for optimization during parsing. + /*! + By default, for safety, streams do not use local copy optimization. + Stream that can be copied fast should specialize this, like StreamTraits. + */ + enum { copyOptimization = 0 }; +}; + +//! Reserve n characters for writing to a stream. +template +inline void PutReserve(Stream& stream, size_t count) { + (void)stream; + (void)count; +} + +//! Write character to a stream, presuming buffer is reserved. +template +inline void PutUnsafe(Stream& stream, typename Stream::Ch c) { + stream.Put(c); +} + +//! Put N copies of a character to a stream. +template +inline void PutN(Stream& stream, Ch c, size_t n) { + PutReserve(stream, n); + for (size_t i = 0; i < n; i++) + PutUnsafe(stream, c); +} + +/////////////////////////////////////////////////////////////////////////////// +// StringStream + +//! Read-only string stream. +/*! \note implements Stream concept +*/ +template +struct GenericStringStream { + typedef typename Encoding::Ch Ch; + + GenericStringStream(const Ch *src) : src_(src), head_(src) {} + + Ch Peek() const { return *src_; } + Ch Take() { return *src_++; } + size_t Tell() const { return static_cast(src_ - head_); } + + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + + const Ch* src_; //!< Current read position. + const Ch* head_; //!< Original head of the string. +}; + +template +struct StreamTraits > { + enum { copyOptimization = 1 }; +}; + +//! String stream with UTF8 encoding. +typedef GenericStringStream > StringStream; + +/////////////////////////////////////////////////////////////////////////////// +// InsituStringStream + +//! A read-write string stream. +/*! This string stream is particularly designed for in-situ parsing. + \note implements Stream concept +*/ +template +struct GenericInsituStringStream { + typedef typename Encoding::Ch Ch; + + GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {} + + // Read + Ch Peek() { return *src_; } + Ch Take() { return *src_++; } + size_t Tell() { return static_cast(src_ - head_); } + + // Write + void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; } + + Ch* PutBegin() { return dst_ = src_; } + size_t PutEnd(Ch* begin) { return static_cast(dst_ - begin); } + void Flush() {} + + Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; } + void Pop(size_t count) { dst_ -= count; } + + Ch* src_; + Ch* dst_; + Ch* head_; +}; + +template +struct StreamTraits > { + enum { copyOptimization = 1 }; +}; + +//! Insitu string stream with UTF8 encoding. +typedef GenericInsituStringStream > InsituStringStream; + +RAPIDJSON_NAMESPACE_END + +#endif // RAPIDJSON_STREAM_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/stringbuffer.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/stringbuffer.h new file mode 100644 index 0000000000..78f34d2098 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/stringbuffer.h @@ -0,0 +1,117 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_STRINGBUFFER_H_ +#define RAPIDJSON_STRINGBUFFER_H_ + +#include "stream.h" +#include "internal/stack.h" + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS +#include // std::move +#endif + +#include "internal/stack.h" + +#if defined(__clang__) +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +//! Represents an in-memory output stream. +/*! + \tparam Encoding Encoding of the stream. + \tparam Allocator type for allocating memory buffer. + \note implements Stream concept +*/ +template +class GenericStringBuffer { +public: + typedef typename Encoding::Ch Ch; + + GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {} + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {} + GenericStringBuffer& operator=(GenericStringBuffer&& rhs) { + if (&rhs != this) + stack_ = std::move(rhs.stack_); + return *this; + } +#endif + + void Put(Ch c) { *stack_.template Push() = c; } + void PutUnsafe(Ch c) { *stack_.template PushUnsafe() = c; } + void Flush() {} + + void Clear() { stack_.Clear(); } + void ShrinkToFit() { + // Push and pop a null terminator. This is safe. + *stack_.template Push() = '\0'; + stack_.ShrinkToFit(); + stack_.template Pop(1); + } + + void Reserve(size_t count) { stack_.template Reserve(count); } + Ch* Push(size_t count) { return stack_.template Push(count); } + Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe(count); } + void Pop(size_t count) { stack_.template Pop(count); } + + const Ch* GetString() const { + // Push and pop a null terminator. This is safe. + *stack_.template Push() = '\0'; + stack_.template Pop(1); + + return stack_.template Bottom(); + } + + size_t GetSize() const { return stack_.GetSize(); } + + static const size_t kDefaultCapacity = 256; + mutable internal::Stack stack_; + +private: + // Prohibit copy constructor & assignment operator. + GenericStringBuffer(const GenericStringBuffer&); + GenericStringBuffer& operator=(const GenericStringBuffer&); +}; + +//! String buffer with UTF8 encoding +typedef GenericStringBuffer > StringBuffer; + +template +inline void PutReserve(GenericStringBuffer& stream, size_t count) { + stream.Reserve(count); +} + +template +inline void PutUnsafe(GenericStringBuffer& stream, typename Encoding::Ch c) { + stream.PutUnsafe(c); +} + +//! Implement specialized version of PutN() with memset() for better performance. +template<> +inline void PutN(GenericStringBuffer >& stream, char c, size_t n) { + std::memset(stream.stack_.Push(n), c, n * sizeof(c)); +} + +RAPIDJSON_NAMESPACE_END + +#if defined(__clang__) +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_STRINGBUFFER_H_ diff --git a/thirdparty/rapidjson-1.1.0/include/rapidjson/writer.h b/thirdparty/rapidjson-1.1.0/include/rapidjson/writer.h new file mode 100644 index 0000000000..94f22dd5fc --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include/rapidjson/writer.h @@ -0,0 +1,610 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef RAPIDJSON_WRITER_H_ +#define RAPIDJSON_WRITER_H_ + +#include "stream.h" +#include "internal/stack.h" +#include "internal/strfunc.h" +#include "internal/dtoa.h" +#include "internal/itoa.h" +#include "stringbuffer.h" +#include // placement new + +#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER) +#include +#pragma intrinsic(_BitScanForward) +#endif +#ifdef RAPIDJSON_SSE42 +#include +#elif defined(RAPIDJSON_SSE2) +#include +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(padded) +RAPIDJSON_DIAG_OFF(unreachable-code) +#endif + +RAPIDJSON_NAMESPACE_BEGIN + +/////////////////////////////////////////////////////////////////////////////// +// WriteFlag + +/*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS + \ingroup RAPIDJSON_CONFIG + \brief User-defined kWriteDefaultFlags definition. + + User can define this as any \c WriteFlag combinations. +*/ +#ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS +#define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags +#endif + +//! Combination of writeFlags +enum WriteFlag { + kWriteNoFlags = 0, //!< No flags are set. + kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings. + kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN. + kWriteDefaultFlags = RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining RAPIDJSON_WRITE_DEFAULT_FLAGS +}; + +//! JSON writer +/*! Writer implements the concept Handler. + It generates JSON text by events to an output os. + + User may programmatically calls the functions of a writer to generate JSON text. + + On the other side, a writer can also be passed to objects that generates events, + + for example Reader::Parse() and Document::Accept(). + + \tparam OutputStream Type of output stream. + \tparam SourceEncoding Encoding of source string. + \tparam TargetEncoding Encoding of output stream. + \tparam StackAllocator Type of allocator for allocating memory of stack. + \note implements Handler concept +*/ +template, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags> +class Writer { +public: + typedef typename SourceEncoding::Ch Ch; + + static const int kDefaultMaxDecimalPlaces = 324; + + //! Constructor + /*! \param os Output stream. + \param stackAllocator User supplied allocator. If it is null, it will create a private one. + \param levelDepth Initial capacity of stack. + */ + explicit + Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) : + os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} + + explicit + Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) : + os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {} + + //! Reset the writer with a new stream. + /*! + This function reset the writer with a new stream and default settings, + in order to make a Writer object reusable for output multiple JSONs. + + \param os New output stream. + \code + Writer writer(os1); + writer.StartObject(); + // ... + writer.EndObject(); + + writer.Reset(os2); + writer.StartObject(); + // ... + writer.EndObject(); + \endcode + */ + void Reset(OutputStream& os) { + os_ = &os; + hasRoot_ = false; + level_stack_.Clear(); + } + + //! Checks whether the output is a complete JSON. + /*! + A complete JSON has a complete root object or array. + */ + bool IsComplete() const { + return hasRoot_ && level_stack_.Empty(); + } + + int GetMaxDecimalPlaces() const { + return maxDecimalPlaces_; + } + + //! Sets the maximum number of decimal places for double output. + /*! + This setting truncates the output with specified number of decimal places. + + For example, + + \code + writer.SetMaxDecimalPlaces(3); + writer.StartArray(); + writer.Double(0.12345); // "0.123" + writer.Double(0.0001); // "0.0" + writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not truncate significand for positive exponent) + writer.Double(1.23e-4); // "0.0" (do truncate significand for negative exponent) + writer.EndArray(); + \endcode + + The default setting does not truncate any decimal places. You can restore to this setting by calling + \code + writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces); + \endcode + */ + void SetMaxDecimalPlaces(int maxDecimalPlaces) { + maxDecimalPlaces_ = maxDecimalPlaces; + } + + /*!@name Implementation of Handler + \see Handler + */ + //@{ + + bool Null() { Prefix(kNullType); return EndValue(WriteNull()); } + bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); } + bool Int(int i) { Prefix(kNumberType); return EndValue(WriteInt(i)); } + bool Uint(unsigned u) { Prefix(kNumberType); return EndValue(WriteUint(u)); } + bool Int64(int64_t i64) { Prefix(kNumberType); return EndValue(WriteInt64(i64)); } + bool Uint64(uint64_t u64) { Prefix(kNumberType); return EndValue(WriteUint64(u64)); } + + //! Writes the given \c double value to the stream + /*! + \param d The value to be written. + \return Whether it is succeed. + */ + bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); } + + bool RawNumber(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + Prefix(kNumberType); + return EndValue(WriteString(str, length)); + } + + bool String(const Ch* str, SizeType length, bool copy = false) { + (void)copy; + Prefix(kStringType); + return EndValue(WriteString(str, length)); + } + +#if RAPIDJSON_HAS_STDSTRING + bool String(const std::basic_string& str) { + return String(str.data(), SizeType(str.size())); + } +#endif + + bool StartObject() { + Prefix(kObjectType); + new (level_stack_.template Push()) Level(false); + return WriteStartObject(); + } + + bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); } + + bool EndObject(SizeType memberCount = 0) { + (void)memberCount; + RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); + RAPIDJSON_ASSERT(!level_stack_.template Top()->inArray); + level_stack_.template Pop(1); + return EndValue(WriteEndObject()); + } + + bool StartArray() { + Prefix(kArrayType); + new (level_stack_.template Push()) Level(true); + return WriteStartArray(); + } + + bool EndArray(SizeType elementCount = 0) { + (void)elementCount; + RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); + RAPIDJSON_ASSERT(level_stack_.template Top()->inArray); + level_stack_.template Pop(1); + return EndValue(WriteEndArray()); + } + //@} + + /*! @name Convenience extensions */ + //@{ + + //! Simpler but slower overload. + bool String(const Ch* str) { return String(str, internal::StrLen(str)); } + bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); } + + //@} + + //! Write a raw JSON value. + /*! + For user to write a stringified JSON as a value. + + \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range. + \param length Length of the json. + \param type Type of the root of json. + */ + bool RawValue(const Ch* json, size_t length, Type type) { Prefix(type); return EndValue(WriteRawValue(json, length)); } + +protected: + //! Information for each nested level + struct Level { + Level(bool inArray_) : valueCount(0), inArray(inArray_) {} + size_t valueCount; //!< number of values in this level + bool inArray; //!< true if in array, otherwise in object + }; + + static const size_t kDefaultLevelDepth = 32; + + bool WriteNull() { + PutReserve(*os_, 4); + PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true; + } + + bool WriteBool(bool b) { + if (b) { + PutReserve(*os_, 4); + PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e'); + } + else { + PutReserve(*os_, 5); + PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e'); + } + return true; + } + + bool WriteInt(int i) { + char buffer[11]; + const char* end = internal::i32toa(i, buffer); + PutReserve(*os_, static_cast(end - buffer)); + for (const char* p = buffer; p != end; ++p) + PutUnsafe(*os_, static_cast(*p)); + return true; + } + + bool WriteUint(unsigned u) { + char buffer[10]; + const char* end = internal::u32toa(u, buffer); + PutReserve(*os_, static_cast(end - buffer)); + for (const char* p = buffer; p != end; ++p) + PutUnsafe(*os_, static_cast(*p)); + return true; + } + + bool WriteInt64(int64_t i64) { + char buffer[21]; + const char* end = internal::i64toa(i64, buffer); + PutReserve(*os_, static_cast(end - buffer)); + for (const char* p = buffer; p != end; ++p) + PutUnsafe(*os_, static_cast(*p)); + return true; + } + + bool WriteUint64(uint64_t u64) { + char buffer[20]; + char* end = internal::u64toa(u64, buffer); + PutReserve(*os_, static_cast(end - buffer)); + for (char* p = buffer; p != end; ++p) + PutUnsafe(*os_, static_cast(*p)); + return true; + } + + bool WriteDouble(double d) { + if (internal::Double(d).IsNanOrInf()) { + if (!(writeFlags & kWriteNanAndInfFlag)) + return false; + if (internal::Double(d).IsNan()) { + PutReserve(*os_, 3); + PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); + return true; + } + if (internal::Double(d).Sign()) { + PutReserve(*os_, 9); + PutUnsafe(*os_, '-'); + } + else + PutReserve(*os_, 8); + PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); + PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); + return true; + } + + char buffer[25]; + char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); + PutReserve(*os_, static_cast(end - buffer)); + for (char* p = buffer; p != end; ++p) + PutUnsafe(*os_, static_cast(*p)); + return true; + } + + bool WriteString(const Ch* str, SizeType length) { + static const typename TargetEncoding::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + static const char escape[256] = { +#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + //0 1 2 3 4 5 6 7 8 9 A B C D E F + 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00 + 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10 + 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 + Z16, Z16, // 30~4F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50 + Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF +#undef Z16 + }; + + if (TargetEncoding::supportUnicode) + PutReserve(*os_, 2 + length * 6); // "\uxxxx..." + else + PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..." + + PutUnsafe(*os_, '\"'); + GenericStringStream is(str); + while (ScanWriteUnescapedString(is, length)) { + const Ch c = is.Peek(); + if (!TargetEncoding::supportUnicode && static_cast(c) >= 0x80) { + // Unicode escaping + unsigned codepoint; + if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint))) + return false; + PutUnsafe(*os_, '\\'); + PutUnsafe(*os_, 'u'); + if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) { + PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]); + PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]); + PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]); + PutUnsafe(*os_, hexDigits[(codepoint ) & 15]); + } + else { + RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF); + // Surrogate pair + unsigned s = codepoint - 0x010000; + unsigned lead = (s >> 10) + 0xD800; + unsigned trail = (s & 0x3FF) + 0xDC00; + PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]); + PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]); + PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]); + PutUnsafe(*os_, hexDigits[(lead ) & 15]); + PutUnsafe(*os_, '\\'); + PutUnsafe(*os_, 'u'); + PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]); + PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]); + PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]); + PutUnsafe(*os_, hexDigits[(trail ) & 15]); + } + } + else if ((sizeof(Ch) == 1 || static_cast(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast(c)])) { + is.Take(); + PutUnsafe(*os_, '\\'); + PutUnsafe(*os_, static_cast(escape[static_cast(c)])); + if (escape[static_cast(c)] == 'u') { + PutUnsafe(*os_, '0'); + PutUnsafe(*os_, '0'); + PutUnsafe(*os_, hexDigits[static_cast(c) >> 4]); + PutUnsafe(*os_, hexDigits[static_cast(c) & 0xF]); + } + } + else if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ? + Transcoder::Validate(is, *os_) : + Transcoder::TranscodeUnsafe(is, *os_)))) + return false; + } + PutUnsafe(*os_, '\"'); + return true; + } + + bool ScanWriteUnescapedString(GenericStringStream& is, size_t length) { + return RAPIDJSON_LIKELY(is.Tell() < length); + } + + bool WriteStartObject() { os_->Put('{'); return true; } + bool WriteEndObject() { os_->Put('}'); return true; } + bool WriteStartArray() { os_->Put('['); return true; } + bool WriteEndArray() { os_->Put(']'); return true; } + + bool WriteRawValue(const Ch* json, size_t length) { + PutReserve(*os_, length); + for (size_t i = 0; i < length; i++) { + RAPIDJSON_ASSERT(json[i] != '\0'); + PutUnsafe(*os_, json[i]); + } + return true; + } + + void Prefix(Type type) { + (void)type; + if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root + Level* level = level_stack_.template Top(); + if (level->valueCount > 0) { + if (level->inArray) + os_->Put(','); // add comma if it is not the first element in array + else // in object + os_->Put((level->valueCount % 2 == 0) ? ',' : ':'); + } + if (!level->inArray && level->valueCount % 2 == 0) + RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name + level->valueCount++; + } + else { + RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root. + hasRoot_ = true; + } + } + + // Flush the value if it is the top level one. + bool EndValue(bool ret) { + if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text + os_->Flush(); + return ret; + } + + OutputStream* os_; + internal::Stack level_stack_; + int maxDecimalPlaces_; + bool hasRoot_; + +private: + // Prohibit copy constructor & assignment operator. + Writer(const Writer&); + Writer& operator=(const Writer&); +}; + +// Full specialization for StringStream to prevent memory copying + +template<> +inline bool Writer::WriteInt(int i) { + char *buffer = os_->Push(11); + const char* end = internal::i32toa(i, buffer); + os_->Pop(static_cast(11 - (end - buffer))); + return true; +} + +template<> +inline bool Writer::WriteUint(unsigned u) { + char *buffer = os_->Push(10); + const char* end = internal::u32toa(u, buffer); + os_->Pop(static_cast(10 - (end - buffer))); + return true; +} + +template<> +inline bool Writer::WriteInt64(int64_t i64) { + char *buffer = os_->Push(21); + const char* end = internal::i64toa(i64, buffer); + os_->Pop(static_cast(21 - (end - buffer))); + return true; +} + +template<> +inline bool Writer::WriteUint64(uint64_t u) { + char *buffer = os_->Push(20); + const char* end = internal::u64toa(u, buffer); + os_->Pop(static_cast(20 - (end - buffer))); + return true; +} + +template<> +inline bool Writer::WriteDouble(double d) { + if (internal::Double(d).IsNanOrInf()) { + // Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag). + if (!(kWriteDefaultFlags & kWriteNanAndInfFlag)) + return false; + if (internal::Double(d).IsNan()) { + PutReserve(*os_, 3); + PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N'); + return true; + } + if (internal::Double(d).Sign()) { + PutReserve(*os_, 9); + PutUnsafe(*os_, '-'); + } + else + PutReserve(*os_, 8); + PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f'); + PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y'); + return true; + } + + char *buffer = os_->Push(25); + char* end = internal::dtoa(d, buffer, maxDecimalPlaces_); + os_->Pop(static_cast(25 - (end - buffer))); + return true; +} + +#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) +template<> +inline bool Writer::ScanWriteUnescapedString(StringStream& is, size_t length) { + if (length < 16) + return RAPIDJSON_LIKELY(is.Tell() < length); + + if (!RAPIDJSON_LIKELY(is.Tell() < length)) + return false; + + const char* p = is.src_; + const char* end = is.head_ + length; + const char* nextAligned = reinterpret_cast((reinterpret_cast(p) + 15) & static_cast(~15)); + const char* endAligned = reinterpret_cast(reinterpret_cast(end) & static_cast(~15)); + if (nextAligned > end) + return true; + + while (p != nextAligned) + if (*p < 0x20 || *p == '\"' || *p == '\\') { + is.src_ = p; + return RAPIDJSON_LIKELY(is.Tell() < length); + } + else + os_->PutUnsafe(*p++); + + // The rest of string using SIMD + static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' }; + static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; + static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 }; + const __m128i dq = _mm_loadu_si128(reinterpret_cast(&dquote[0])); + const __m128i bs = _mm_loadu_si128(reinterpret_cast(&bslash[0])); + const __m128i sp = _mm_loadu_si128(reinterpret_cast(&space[0])); + + for (; p != endAligned; p += 16) { + const __m128i s = _mm_load_si128(reinterpret_cast(p)); + const __m128i t1 = _mm_cmpeq_epi8(s, dq); + const __m128i t2 = _mm_cmpeq_epi8(s, bs); + const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19 + const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3); + unsigned short r = static_cast(_mm_movemask_epi8(x)); + if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped + SizeType len; +#ifdef _MSC_VER // Find the index of first escaped + unsigned long offset; + _BitScanForward(&offset, r); + len = offset; +#else + len = static_cast(__builtin_ffs(r) - 1); +#endif + char* q = reinterpret_cast(os_->PushUnsafe(len)); + for (size_t i = 0; i < len; i++) + q[i] = p[i]; + + p += len; + break; + } + _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s); + } + + is.src_ = p; + return RAPIDJSON_LIKELY(is.Tell() < length); +} +#endif // defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) + +RAPIDJSON_NAMESPACE_END + +#ifdef _MSC_VER +RAPIDJSON_DIAG_POP +#endif + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif + +#endif // RAPIDJSON_RAPIDJSON_H_ diff --git a/thirdparty/rapidjson-1.1.0/include_dirs.js b/thirdparty/rapidjson-1.1.0/include_dirs.js new file mode 100644 index 0000000000..b373e85f5a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/include_dirs.js @@ -0,0 +1,2 @@ +var path = require('path'); +console.log(path.join(path.relative('.', __dirname), 'include')); diff --git a/thirdparty/rapidjson-1.1.0/library.json b/thirdparty/rapidjson-1.1.0/library.json new file mode 100644 index 0000000000..47fd352ac7 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/library.json @@ -0,0 +1,12 @@ +{ + "name": "RapidJSON", + "keywords": "json, sax, dom, parser, generator", + "description": "A fast JSON parser/generator for C++ with both SAX/DOM style API", + "include": "include", + "examples": "example/*/*.cpp", + "repository": + { + "type": "git", + "url": "https://github.com/miloyip/rapidjson" + } +} diff --git a/thirdparty/rapidjson-1.1.0/license.txt b/thirdparty/rapidjson-1.1.0/license.txt new file mode 100644 index 0000000000..7ccc161c84 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/license.txt @@ -0,0 +1,57 @@ +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Open Source Software Licensed Under the JSON License: +-------------------------------------------------------------------- + +json.org +Copyright (c) 2002 JSON.org +All Rights Reserved. + +JSON_checker +Copyright (c) 2002 JSON.org +All Rights Reserved. + + +Terms of the JSON License: +--------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/thirdparty/rapidjson-1.1.0/package.json b/thirdparty/rapidjson-1.1.0/package.json new file mode 100644 index 0000000000..cc6087a5ca --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/package.json @@ -0,0 +1,24 @@ +{ + "name": "rapidjson", + "version": "1.0.4", + "description": "![](doc/logo/rapidjson.png)", + "main": "include_dirs.js", + "directories": { + "doc": "doc", + "example": "example", + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/miloyip/rapidjson.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/miloyip/rapidjson/issues" + }, + "homepage": "https://github.com/miloyip/rapidjson#readme" +} diff --git a/thirdparty/rapidjson-1.1.0/rapidjson.autopkg b/thirdparty/rapidjson-1.1.0/rapidjson.autopkg new file mode 100644 index 0000000000..70eb0d8a00 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/rapidjson.autopkg @@ -0,0 +1,75 @@ +nuget { + //Usage: Write-NuGetPackage rapidjson.autopkg -defines:MYVERSION=1.1.0 + //Be sure you are running Powershell 3.0 and have the CoApp powershell extensions installed properly. + nuspec { + id = rapidjson; + version : ${MYVERSION}; + title: "rapidjson"; + authors: {"https://github.com/miloyip/rapidjson/releases/tag/v1.1.0"}; + owners: {"@lsantos (github)"}; + licenseUrl: "https://github.com/miloyip/rapidjson/blob/master/license.txt"; + projectUrl: "https://github.com/miloyip/rapidjson/"; + iconUrl: "https://cdn1.iconfinder.com/data/icons/fatcow/32x32/json.png"; + requireLicenseAcceptance:false; + summary: @"A fast JSON parser/generator for C++ with both SAX/DOM style API"; + + // if you need to span several lines you can prefix a string with an @ symbol (exactly like c# does). + description: @"Rapidjson is an attempt to create the fastest JSON parser and generator. + + - Small but complete. Supports both SAX and DOM style API. SAX parser only a few hundred lines of code. + - Fast. In the order of magnitude of strlen(). Optionally supports SSE2/SSE4.2 for acceleration. + - Self-contained. Minimal dependency on standard libraries. No BOOST, not even STL. + - Compact. Each JSON value is 16 or 20 bytes for 32 or 64-bit machines respectively (excluding text string storage). With the custom memory allocator, parser allocates memory compactly during parsing. + - Full RFC4627 compliance. Supports UTF-8, UTF-16 and UTF-32. + - Support both in-situ parsing (directly decode strings into the source JSON text) and non-destructive parsing (decode strings into new buffers). + - Parse number to int/unsigned/int64_t/uint64_t/double depending on input + - Support custom memory allocation. Also, the default memory pool allocator can also be supplied with a user buffer (such as a buffer allocated on user's heap or - programme stack) to minimize allocation. + + As the name implies, rapidjson is inspired by rapidxml."; + + releaseNotes: @" +Added + Add Value::XXXMember(...) overloads for std::string (#335) + +Fixed + Include rapidjson.h for all internal/error headers. + Parsing some numbers incorrectly in full-precision mode (kFullPrecisionParseFlag) (#342) + Fix alignment of 64bit platforms (#328) + Fix MemoryPoolAllocator::Clear() to clear user-buffer (0691502) + +Changed + CMakeLists for include as a thirdparty in projects (#334, #337) + Change Document::ParseStream() to use stack allocator for Reader (ffbe386)"; + + copyright: "Copyright 2015"; + tags: { native, coapp, JSON, nativepackage }; + language: en-US; + }; + + dependencies { + packages : { + //TODO: Add dependecies here in [pkg.name]/[version] form per newline + //zlib/[1.2.8], + }; + } + + // the files that go into the content folders + files { + #defines { + SDK_ROOT = .\; + } + + // grab all the files in the include folder + // the folder that contains all the .h files will + // automatically get added to the Includes path. + nestedinclude += { + #destination = ${d_include}rapidjson; + "${SDK_ROOT}include\rapidjson\**\*.h" + }; + }; + + targets { + // We're trying to be standard about these sorts of thing. (Will help with config.h later :D) + //Defines += HAS_EQCORE; + }; +} \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/readme.md b/thirdparty/rapidjson-1.1.0/readme.md new file mode 100644 index 0000000000..4a1d64d0ad --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/readme.md @@ -0,0 +1,160 @@ +![](doc/logo/rapidjson.png) + +![](https://img.shields.io/badge/release-v1.1.0-blue.png) + +## A fast JSON parser/generator for C++ with both SAX/DOM style API + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +* [RapidJSON GitHub](https://github.com/miloyip/rapidjson/) +* RapidJSON Documentation + * [English](http://rapidjson.org/) + * [简体中文](http://rapidjson.org/zh-cn/) + * [GitBook](https://www.gitbook.com/book/miloyip/rapidjson/) with downloadable PDF/EPUB/MOBI, without API reference. + +## Build status + +| [Linux][lin-link] | [Windows][win-link] | [Coveralls][cov-link] | +| :---------------: | :-----------------: | :-------------------: | +| ![lin-badge] | ![win-badge] | ![cov-badge] | + +[lin-badge]: https://travis-ci.org/miloyip/rapidjson.png?branch=master "Travis build status" +[lin-link]: https://travis-ci.org/miloyip/rapidjson "Travis build status" +[win-badge]: https://ci.appveyor.com/api/projects/status/u658dcuwxo14a8m9/branch/master "AppVeyor build status" +[win-link]: https://ci.appveyor.com/project/miloyip/rapidjson/branch/master "AppVeyor build status" +[cov-badge]: https://coveralls.io/repos/miloyip/rapidjson/badge.png?branch=master +[cov-link]: https://coveralls.io/r/miloyip/rapidjson?branch=master + +## Introduction + +RapidJSON is a JSON parser and generator for C++. It was inspired by [RapidXml](http://rapidxml.sourceforge.net/). + +* RapidJSON is **small** but **complete**. It supports both SAX and DOM style API. The SAX parser is only a half thousand lines of code. + +* RapidJSON is **fast**. Its performance can be comparable to `strlen()`. It also optionally supports SSE2/SSE4.2 for acceleration. + +* RapidJSON is **self-contained** and **header-only**. It does not depend on external libraries such as BOOST. It even does not depend on STL. + +* RapidJSON is **memory-friendly**. Each JSON value occupies exactly 16 bytes for most 32/64-bit machines (excluding text string). By default it uses a fast memory allocator, and the parser allocates memory compactly during parsing. + +* RapidJSON is **Unicode-friendly**. It supports UTF-8, UTF-16, UTF-32 (LE & BE), and their detection, validation and transcoding internally. For example, you can read a UTF-8 file and let RapidJSON transcode the JSON strings into UTF-16 in the DOM. It also supports surrogates and "\u0000" (null character). + +More features can be read [here](doc/features.md). + +JSON(JavaScript Object Notation) is a light-weight data exchange format. RapidJSON should be in fully compliance with RFC7159/ECMA-404, with optional support of relaxed syntax. More information about JSON can be obtained at +* [Introducing JSON](http://json.org/) +* [RFC7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://www.ietf.org/rfc/rfc7159.txt) +* [Standard ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/standards/Ecma-404.htm) + +## Highlights in v1.1 (2016-8-25) + +* Added [JSON Pointer](doc/pointer.md) +* Added [JSON Schema](doc/schema.md) +* Added [relaxed JSON syntax](doc/dom.md) (comment, trailing comma, NaN/Infinity) +* Iterating array/object with [C++11 Range-based for loop](doc/tutorial.md) +* Reduce memory overhead of each `Value` from 24 bytes to 16 bytes in x86-64 architecture. + +For other changes please refer to [change log](CHANGELOG.md). + +## Compatibility + +RapidJSON is cross-platform. Some platform/compiler combinations which have been tested are shown as follows. +* Visual C++ 2008/2010/2013 on Windows (32/64-bit) +* GNU C++ 3.8.x on Cygwin +* Clang 3.4 on Mac OS X (32/64-bit) and iOS +* Clang 3.4 on Android NDK + +Users can build and run the unit tests on their platform/compiler. + +## Installation + +RapidJSON is a header-only C++ library. Just copy the `include/rapidjson` folder to system or project's include path. + +RapidJSON uses following software as its dependencies: +* [CMake](https://cmake.org/) as a general build tool +* (optional)[Doxygen](http://www.doxygen.org) to build documentation +* (optional)[googletest](https://github.com/google/googletest) for unit and performance testing + +To generate user documentation and run tests please proceed with the steps below: + +1. Execute `git submodule update --init` to get the files of thirdparty submodules (google test). +2. Create directory called `build` in rapidjson source directory. +3. Change to `build` directory and run `cmake ..` command to configure your build. Windows users can do the same with cmake-gui application. +4. On Windows, build the solution found in the build directory. On Linux, run `make` from the build directory. + +On successfull build you will find compiled test and example binaries in `bin` +directory. The generated documentation will be available in `doc/html` +directory of the build tree. To run tests after finished build please run `make +test` or `ctest` from your build tree. You can get detailed output using `ctest +-V` command. + +It is possible to install library system-wide by running `make install` command +from the build tree with administrative privileges. This will install all files +according to system preferences. Once RapidJSON is installed, it is possible +to use it from other CMake projects by adding `find_package(RapidJSON)` line to +your CMakeLists.txt. + +## Usage at a glance + +This simple example parses a JSON string into a document (DOM), make a simple modification of the DOM, and finally stringify the DOM to a JSON string. + +~~~~~~~~~~cpp +// rapidjson/example/simpledom/simpledom.cpp` +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; + +int main() { + // 1. Parse a JSON string into DOM. + const char* json = "{\"project\":\"rapidjson\",\"stars\":10}"; + Document d; + d.Parse(json); + + // 2. Modify it by DOM. + Value& s = d["stars"]; + s.SetInt(s.GetInt() + 1); + + // 3. Stringify the DOM + StringBuffer buffer; + Writer writer(buffer); + d.Accept(writer); + + // Output {"project":"rapidjson","stars":11} + std::cout << buffer.GetString() << std::endl; + return 0; +} +~~~~~~~~~~ + +Note that this example did not handle potential errors. + +The following diagram shows the process. + +![simpledom](doc/diagram/simpledom.png) + +More [examples](https://github.com/miloyip/rapidjson/tree/master/example) are available: + +* DOM API + * [tutorial](https://github.com/miloyip/rapidjson/blob/master/example/tutorial/tutorial.cpp): Basic usage of DOM API. + +* SAX API + * [simplereader](https://github.com/miloyip/rapidjson/blob/master/example/simplereader/simplereader.cpp): Dumps all SAX events while parsing a JSON by `Reader`. + * [condense](https://github.com/miloyip/rapidjson/blob/master/example/condense/condense.cpp): A command line tool to rewrite a JSON, with all whitespaces removed. + * [pretty](https://github.com/miloyip/rapidjson/blob/master/example/pretty/pretty.cpp): A command line tool to rewrite a JSON with indents and newlines by `PrettyWriter`. + * [capitalize](https://github.com/miloyip/rapidjson/blob/master/example/capitalize/capitalize.cpp): A command line tool to capitalize strings in JSON. + * [messagereader](https://github.com/miloyip/rapidjson/blob/master/example/messagereader/messagereader.cpp): Parse a JSON message with SAX API. + * [serialize](https://github.com/miloyip/rapidjson/blob/master/example/serialize/serialize.cpp): Serialize a C++ object into JSON with SAX API. + * [jsonx](https://github.com/miloyip/rapidjson/blob/master/example/jsonx/jsonx.cpp): Implements a `JsonxWriter` which stringify SAX events into [JSONx](https://www-01.ibm.com/support/knowledgecenter/SS9H2Y_7.1.0/com.ibm.dp.doc/json_jsonx.html) (a kind of XML) format. The example is a command line tool which converts input JSON into JSONx format. + +* Schema + * [schemavalidator](https://github.com/miloyip/rapidjson/blob/master/example/schemavalidator/schemavalidator.cpp) : A command line tool to validate a JSON with a JSON schema. + +* Advanced + * [prettyauto](https://github.com/miloyip/rapidjson/blob/master/example/prettyauto/prettyauto.cpp): A modified version of [pretty](https://github.com/miloyip/rapidjson/blob/master/example/pretty/pretty.cpp) to automatically handle JSON with any UTF encodings. + * [parsebyparts](https://github.com/miloyip/rapidjson/blob/master/example/parsebyparts/parsebyparts.cpp): Implements an `AsyncDocumentParser` which can parse JSON in parts, using C++11 thread. + * [filterkey](https://github.com/miloyip/rapidjson/blob/master/example/filterkey/filterkey.cpp): A command line tool to remove all values with user-specified key. + * [filterkeydom](https://github.com/miloyip/rapidjson/blob/master/example/filterkeydom/filterkeydom.cpp): Same tool as above, but it demonstrates how to use a generator to populate a `Document`. diff --git a/thirdparty/rapidjson-1.1.0/readme.zh-cn.md b/thirdparty/rapidjson-1.1.0/readme.zh-cn.md new file mode 100644 index 0000000000..74d267c983 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/readme.zh-cn.md @@ -0,0 +1,152 @@ +![](doc/logo/rapidjson.png) + +![](https://img.shields.io/badge/release-v1.1.0-blue.png) + +## 高效的 C++ JSON 解析/生成器,提供 SAX 及 DOM 风格 API + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +* [RapidJSON GitHub](https://github.com/miloyip/rapidjson/) +* RapidJSON 文档 + * [English](http://rapidjson.org/) + * [简体中文](http://rapidjson.org/zh-cn/) + * [GitBook](https://www.gitbook.com/book/miloyip/rapidjson/) 可下载 PDF/EPUB/MOBI,但不含 API 参考手册。 + +## Build 状态 + +| [Linux][lin-link] | [Windows][win-link] | [Coveralls][cov-link] | +| :---------------: | :-----------------: | :-------------------: | +| ![lin-badge] | ![win-badge] | ![cov-badge] | + +[lin-badge]: https://travis-ci.org/miloyip/rapidjson.png?branch=master "Travis build status" +[lin-link]: https://travis-ci.org/miloyip/rapidjson "Travis build status" +[win-badge]: https://ci.appveyor.com/api/projects/status/u658dcuwxo14a8m9/branch/master "AppVeyor build status" +[win-link]: https://ci.appveyor.com/project/miloyip/rapidjson/branch/master "AppVeyor build status" +[cov-badge]: https://coveralls.io/repos/miloyip/rapidjson/badge.png?branch=master +[cov-link]: https://coveralls.io/r/miloyip/rapidjson?branch=master + +## 简介 + +RapidJSON 是一个 C++ 的 JSON 解析器及生成器。它的灵感来自 [RapidXml](http://rapidxml.sourceforge.net/)。 + +* RapidJSON 小而全。它同时支持 SAX 和 DOM 风格的 API。SAX 解析器只有约 500 行代码。 + +* RapidJSON 快。它的性能可与 `strlen()` 相比。可支持 SSE2/SSE4.2 加速。 + +* RapidJSON 独立。它不依赖于 BOOST 等外部库。它甚至不依赖于 STL。 + +* RapidJSON 对内存友好。在大部分 32/64 位机器上,每个 JSON 值只占 16 字节(除字符串外)。它预设使用一个快速的内存分配器,令分析器可以紧凑地分配内存。 + +* RapidJSON 对 Unicode 友好。它支持 UTF-8、UTF-16、UTF-32 (大端序/小端序),并内部支持这些编码的检测、校验及转码。例如,RapidJSON 可以在分析一个 UTF-8 文件至 DOM 时,把当中的 JSON 字符串转码至 UTF-16。它也支持代理对(surrogate pair)及 `"\u0000"`(空字符)。 + +在 [这里](doc/features.zh-cn.md) 可读取更多特点。 + +JSON(JavaScript Object Notation)是一个轻量的数据交换格式。RapidJSON 应该完全遵从 RFC7159/ECMA-404,并支持可选的放宽语法。 关于 JSON 的更多信息可参考: +* [Introducing JSON](http://json.org/) +* [RFC7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://www.ietf.org/rfc/rfc7159.txt) +* [Standard ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/standards/Ecma-404.htm) + +## v1.1 中的亮点 (2016-8-25) + +* 加入 [JSON Pointer](doc/pointer.zh-cn.md) 功能,可更简单地访问及更改 DOM。 +* 加入 [JSON Schema](doc/schema.zh-cn.md) 功能,可在解析或生成 JSON 时进行校验。 +* 加入 [放宽的 JSON 语法](doc/dom.zh-cn.md) (注释、尾随逗号、NaN/Infinity) +* 使用 [C++11 范围 for 循环](doc/tutorial.zh-cn.md) 去遍历 array 和 object。 +* 在 x86-64 架构下,缩减每个 `Value` 的内存开销从 24 字节至 16 字节。 + +其他改动请参考 [change log](CHANGELOG.md). + +## 兼容性 + +RapidJSON 是跨平台的。以下是一些曾测试的平台/编译器组合: +* Visual C++ 2008/2010/2013 在 Windows (32/64-bit) +* GNU C++ 3.8.x 在 Cygwin +* Clang 3.4 在 Mac OS X (32/64-bit) 及 iOS +* Clang 3.4 在 Android NDK + +用户也可以在他们的平台上生成及执行单元测试。 + +## 安装 + +RapidJSON 是只有头文件的 C++ 库。只需把 `include/rapidjson` 目录复制至系统或项目的 include 目录中。 + +RapidJSON 依赖于以下软件: +* [CMake](http://www.cmake.org) 作为通用生成工具 +* (optional)[Doxygen](http://www.doxygen.org) 用于生成文档 +* (optional)[googletest](https://code.google.com/p/googletest/) 用于单元及性能测试 + +生成测试及例子的步骤: + +1. 执行 `git submodule update --init` 去获取 thirdparty submodules (google test)。 +2. 在 rapidjson 目渌下,建立一个 `build` 目录。 +3. 在 `build` 目录下执行 `cmake ..` 命令以设置生成。Windows 用户可使用 cmake-gui 应用程序。 +4. 在 Windows 下,编译生成在 build 目录中的 solution。在 Linux 下,于 build 目录运行 `make`。 + +成功生成后,你会在 `bin` 的目录下找到编译后的测试及例子可执行文件。而生成的文档将位于 build 下的 `doc/html` 目录。要执行测试,请在 build 下执行 `make test` 或 `ctest`。使用 `ctest -V` 命令可获取详细的输出。 + +我们也可以把程序库安装至全系统中,只要在具管理權限下从 build 目录执行 `make install` 命令。这样会按系统的偏好设置安装所有文件。当安装 RapidJSON 后,其他的 CMake 项目需要使用它时,可以通过在 `CMakeLists.txt` 加入一句 `find_package(RapidJSON)`。 + +## 用法一览 + +此简单例子解析一个 JSON 字符串至一个 document (DOM),对 DOM 作出简单修改,最终把 DOM 转换(stringify)至 JSON 字符串。 + +~~~~~~~~~~cpp +// rapidjson/example/simpledom/simpledom.cpp` +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; + +int main() { + // 1. 把 JSON 解析至 DOM。 + const char* json = "{\"project\":\"rapidjson\",\"stars\":10}"; + Document d; + d.Parse(json); + + // 2. 利用 DOM 作出修改。 + Value& s = d["stars"]; + s.SetInt(s.GetInt() + 1); + + // 3. 把 DOM 转换(stringify)成 JSON。 + StringBuffer buffer; + Writer writer(buffer); + d.Accept(writer); + + // Output {"project":"rapidjson","stars":11} + std::cout << buffer.GetString() << std::endl; + return 0; +} +~~~~~~~~~~ + +注意此例子并没有处理潜在错误。 + +下图展示执行过程。 + +![simpledom](doc/diagram/simpledom.png) + +还有许多 [例子](https://github.com/miloyip/rapidjson/tree/master/example) 可供参考: + +* DOM API + * [tutorial](https://github.com/miloyip/rapidjson/blob/master/example/tutorial/tutorial.cpp): DOM API 的基本使用方法。 + +* SAX API + * [simplereader](https://github.com/miloyip/rapidjson/blob/master/example/simplereader/simplereader.cpp): 使用 `Reader` 解析 JSON 时,打印所有 SAX 事件。 + * [condense](https://github.com/miloyip/rapidjson/blob/master/example/condense/condense.cpp): 移除 JSON 中所有空白符的命令行工具。 + * [pretty](https://github.com/miloyip/rapidjson/blob/master/example/pretty/pretty.cpp): 为 JSON 加入缩进与换行的命令行工具,当中使用了 `PrettyWriter`。 + * [capitalize](https://github.com/miloyip/rapidjson/blob/master/example/capitalize/capitalize.cpp): 把 JSON 中所有字符串改为大写的命令行工具。 + * [messagereader](https://github.com/miloyip/rapidjson/blob/master/example/messagereader/messagereader.cpp): 使用 SAX API 去解析一个 JSON 报文。 + * [serialize](https://github.com/miloyip/rapidjson/blob/master/example/serialize/serialize.cpp): 使用 SAX API 去序列化 C++ 对象,生成 JSON。 + * [jsonx](https://github.com/miloyip/rapidjson/blob/master/example/jsonx/jsonx.cpp): 实现了一个 `JsonxWriter`,它能把 SAX 事件写成 [JSONx](https://www-01.ibm.com/support/knowledgecenter/SS9H2Y_7.1.0/com.ibm.dp.doc/json_jsonx.html)(一种 XML)格式。这个例子是把 JSON 输入转换成 JSONx 格式的命令行工具。 + +* Schema API + * [schemavalidator](https://github.com/miloyip/rapidjson/blob/master/example/schemavalidator/schemavalidator.cpp): 使用 JSON Schema 去校验 JSON 的命令行工具。 + +* 进阶 + * [prettyauto](https://github.com/miloyip/rapidjson/blob/master/example/prettyauto/prettyauto.cpp): [pretty](https://github.com/miloyip/rapidjson/blob/master/example/pretty/pretty.cpp) 的修改版本,可自动处理任何 UTF 编码的 JSON。 + * [parsebyparts](https://github.com/miloyip/rapidjson/blob/master/example/parsebyparts/parsebyparts.cpp): 这例子中的 `AsyncDocumentParser` 类使用 C++ 线程来逐段解析 JSON。 + * [filterkey](https://github.com/miloyip/rapidjson/blob/master/example/filterkey/filterkey.cpp): 移取使用者指定的键值的命令行工具。 + * [filterkeydom](https://github.com/miloyip/rapidjson/blob/master/example/filterkey/filterkey.cpp): 如上的工具,但展示如何使用生成器(generator)去填充一个 `Document`。 \ No newline at end of file diff --git a/thirdparty/rapidjson-1.1.0/test/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/test/CMakeLists.txt new file mode 100644 index 0000000000..11c1b04c7d --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/CMakeLists.txt @@ -0,0 +1,20 @@ +find_package(GTestSrc) + +IF(GTESTSRC_FOUND) + enable_testing() + + if (WIN32 AND (NOT CYGWIN) AND (NOT MINGW)) + set(gtest_disable_pthreads ON) + set(gtest_force_shared_crt ON) + endif() + + add_subdirectory(${GTEST_SOURCE_DIR} ${CMAKE_BINARY_DIR}/googletest) + include_directories(SYSTEM ${GTEST_INCLUDE_DIR}) + + set(TEST_LIBRARIES gtest gtest_main) + + add_custom_target(tests ALL) + add_subdirectory(perftest) + add_subdirectory(unittest) + +ENDIF(GTESTSRC_FOUND) diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/test/perftest/CMakeLists.txt new file mode 100644 index 0000000000..c33aae469a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/CMakeLists.txt @@ -0,0 +1,26 @@ +set(PERFTEST_SOURCES + misctest.cpp + perftest.cpp + platformtest.cpp + rapidjsontest.cpp + schematest.cpp) + +add_executable(perftest ${PERFTEST_SOURCES}) +target_link_libraries(perftest ${TEST_LIBRARIES}) + +add_dependencies(tests perftest) + +find_program(CCACHE_FOUND ccache) +if(CCACHE_FOUND) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) + if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments -fcolor-diagnostics") + endif() +endif(CCACHE_FOUND) + +IF(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug")) +add_test(NAME perftest + COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/perftest + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) +ENDIF() diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/misctest.cpp b/thirdparty/rapidjson-1.1.0/test/perftest/misctest.cpp new file mode 100644 index 0000000000..aac8477842 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/misctest.cpp @@ -0,0 +1,974 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "perftest.h" + +#if TEST_MISC + +#define __STDC_FORMAT_MACROS +#include "rapidjson/stringbuffer.h" + +#define protected public +#include "rapidjson/writer.h" +#undef private + +class Misc : public PerfTest { +}; + +// Copyright (c) 2008-2010 Bjoern Hoehrmann +// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. + +#define UTF8_ACCEPT 0 +#define UTF8_REJECT 12 + +static const unsigned char utf8d[] = { + // The first part of the table maps bytes to character classes that + // to reduce the size of the transition table and create bitmasks. + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, + + // The second part is a transition table that maps a combination + // of a state of the automaton and a character class to a state. + 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, + 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, + 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, + 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, + 12,36,12,12,12,12,12,12,12,12,12,12, +}; + +static unsigned inline decode(unsigned* state, unsigned* codep, unsigned byte) { + unsigned type = utf8d[byte]; + + *codep = (*state != UTF8_ACCEPT) ? + (byte & 0x3fu) | (*codep << 6) : + (0xff >> type) & (byte); + + *state = utf8d[256 + *state + type]; + return *state; +} + +static bool IsUTF8(unsigned char* s) { + unsigned codepoint, state = 0; + + while (*s) + decode(&state, &codepoint, *s++); + + return state == UTF8_ACCEPT; +} + +TEST_F(Misc, Hoehrmann_IsUTF8) { + for (size_t i = 0; i < kTrialCount; i++) { + EXPECT_TRUE(IsUTF8((unsigned char*)json_)); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// CountDecimalDigit: Count number of decimal places + +inline unsigned CountDecimalDigit_naive(unsigned n) { + unsigned count = 1; + while (n >= 10) { + n /= 10; + count++; + } + return count; +} + +inline unsigned CountDecimalDigit_enroll4(unsigned n) { + unsigned count = 1; + while (n >= 10000) { + n /= 10000u; + count += 4; + } + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + return count + 3; +} + +inline unsigned CountDecimalDigit64_enroll4(uint64_t n) { + unsigned count = 1; + while (n >= 10000) { + n /= 10000u; + count += 4; + } + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + return count + 3; +} + +inline unsigned CountDecimalDigit_fast(unsigned n) { + static const uint32_t powers_of_10[] = { + 0, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000 + }; + +#if defined(_M_IX86) || defined(_M_X64) + unsigned long i = 0; + _BitScanReverse(&i, n | 1); + uint32_t t = (i + 1) * 1233 >> 12; +#elif defined(__GNUC__) + uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12; +#else +#error +#endif + return t - (n < powers_of_10[t]) + 1; +} + +inline unsigned CountDecimalDigit64_fast(uint64_t n) { + static const uint64_t powers_of_10[] = { + 0, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000, + 10000000000, + 100000000000, + 1000000000000, + 10000000000000, + 100000000000000, + 1000000000000000, + 10000000000000000, + 100000000000000000, + 1000000000000000000, + 10000000000000000000U + }; + +#if defined(_M_IX86) + uint64_t m = n | 1; + unsigned long i = 0; + if (_BitScanReverse(&i, m >> 32)) + i += 32; + else + _BitScanReverse(&i, m & 0xFFFFFFFF); + uint32_t t = (i + 1) * 1233 >> 12; +#elif defined(_M_X64) + unsigned long i = 0; + _BitScanReverse64(&i, n | 1); + uint32_t t = (i + 1) * 1233 >> 12; +#elif defined(__GNUC__) + uint32_t t = (64 - __builtin_clzll(n | 1)) * 1233 >> 12; +#else +#error +#endif + + return t - (n < powers_of_10[t]) + 1; +} + +#if 0 +// Exhaustive, very slow +TEST_F(Misc, CountDecimalDigit_Verify) { + unsigned i = 0; + do { + if (i % (65536 * 256) == 0) + printf("%u\n", i); + ASSERT_EQ(CountDecimalDigit_enroll4(i), CountDecimalDigit_fast(i)); + i++; + } while (i != 0); +} + +static const unsigned kDigits10Trial = 1000000000u; +TEST_F(Misc, CountDecimalDigit_naive) { + unsigned sum = 0; + for (unsigned i = 0; i < kDigits10Trial; i++) + sum += CountDecimalDigit_naive(i); + printf("%u\n", sum); +} + +TEST_F(Misc, CountDecimalDigit_enroll4) { + unsigned sum = 0; + for (unsigned i = 0; i < kDigits10Trial; i++) + sum += CountDecimalDigit_enroll4(i); + printf("%u\n", sum); +} + +TEST_F(Misc, CountDecimalDigit_fast) { + unsigned sum = 0; + for (unsigned i = 0; i < kDigits10Trial; i++) + sum += CountDecimalDigit_fast(i); + printf("%u\n", sum); +} +#endif + +TEST_F(Misc, CountDecimalDigit64_VerifyFast) { + uint64_t i = 1, j; + do { + //printf("%" PRIu64 "\n", i); + ASSERT_EQ(CountDecimalDigit64_enroll4(i), CountDecimalDigit64_fast(i)); + j = i; + i *= 3; + } while (j < i); +} + +//////////////////////////////////////////////////////////////////////////////// +// integer-to-string conversion + +// https://gist.github.com/anonymous/7179097 +static const int randval[] ={ + 936116, 369532, 453755, -72860, 209713, 268347, 435278, -360266, -416287, -182064, + -644712, 944969, 640463, -366588, 471577, -69401, -744294, -505829, 923883, 831785, + -601136, -636767, -437054, 591718, 100758, 231907, -719038, 973540, -605220, 506659, + -871653, 462533, 764843, -919138, 404305, -630931, -288711, -751454, -173726, -718208, + 432689, -281157, 360737, 659827, 19174, -376450, 769984, -858198, 439127, 734703, + -683426, 7, 386135, 186997, -643900, -744422, -604708, -629545, 42313, -933592, + -635566, 182308, 439024, -367219, -73924, -516649, 421935, -470515, 413507, -78952, + -427917, -561158, 737176, 94538, 572322, 405217, 709266, -357278, -908099, -425447, + 601119, 750712, -862285, -177869, 900102, 384877, 157859, -641680, 503738, -702558, + 278225, 463290, 268378, -212840, 580090, 347346, -473985, -950968, -114547, -839893, + -738032, -789424, 409540, 493495, 432099, 119755, 905004, -174834, 338266, 234298, + 74641, -965136, -754593, 685273, 466924, 920560, 385062, 796402, -67229, 994864, + 376974, 299869, -647540, -128724, 469890, -163167, -547803, -743363, 486463, -621028, + 612288, 27459, -514224, 126342, -66612, 803409, -777155, -336453, -284002, 472451, + 342390, -163630, 908356, -456147, -825607, 268092, -974715, 287227, 227890, -524101, + 616370, -782456, 922098, -624001, -813690, 171605, -192962, 796151, 707183, -95696, + -23163, -721260, 508892, 430715, 791331, 482048, -996102, 863274, 275406, -8279, + -556239, -902076, 268647, -818565, 260069, -798232, -172924, -566311, -806503, -885992, + 813969, -78468, 956632, 304288, 494867, -508784, 381751, 151264, 762953, 76352, + 594902, 375424, 271700, -743062, 390176, 924237, 772574, 676610, 435752, -153847, + 3959, -971937, -294181, -538049, -344620, -170136, 19120, -703157, 868152, -657961, + -818631, 219015, -872729, -940001, -956570, 880727, -345910, 942913, -942271, -788115, + 225294, 701108, -517736, -416071, 281940, 488730, 942698, 711494, 838382, -892302, + -533028, 103052, 528823, 901515, 949577, 159364, 718227, -241814, -733661, -462928, + -495829, 165170, 513580, -629188, -509571, -459083, 198437, 77198, -644612, 811276, + -422298, -860842, -52584, 920369, 686424, -530667, -243476, 49763, 345866, -411960, + -114863, 470810, -302860, 683007, -509080, 2, -174981, -772163, -48697, 447770, + -268246, 213268, 269215, 78810, -236340, -639140, -864323, 505113, -986569, -325215, + 541859, 163070, -819998, -645161, -583336, 573414, 696417, -132375, 3, -294501, + 320435, 682591, 840008, 351740, 426951, 609354, 898154, -943254, 227321, -859793, + -727993, 44137, -497965, -782239, 14955, -746080, -243366, 9837, -233083, 606507, + -995864, -615287, -994307, 602715, 770771, -315040, 610860, 446102, -307120, 710728, + -590392, -230474, -762625, -637525, 134963, -202700, -766902, -985541, 218163, 682009, + 926051, 525156, -61195, 403211, -810098, 245539, -431733, 179998, -806533, 745943, + 447597, 131973, -187130, 826019, 286107, -937230, -577419, 20254, 681802, -340500, + 323080, 266283, -667617, 309656, 416386, 611863, 759991, -534257, 523112, -634892, + -169913, -204905, -909867, -882185, -944908, 741811, -717675, 967007, -317396, 407230, + -412805, 792905, 994873, 744793, -456797, 713493, 355232, 116900, -945199, 880539, + 342505, -580824, -262273, 982968, -349497, -735488, 311767, -455191, 570918, 389734, + -958386, 10262, -99267, 155481, 304210, 204724, 704367, -144893, -233664, -671441, + 896849, 408613, 762236, 322697, 981321, 688476, 13663, -970704, -379507, 896412, + 977084, 348869, 875948, 341348, 318710, 512081, 6163, 669044, 833295, 811883, + 708756, -802534, -536057, 608413, -389625, -694603, 541106, -110037, 720322, -540581, + 645420, 32980, 62442, 510157, -981870, -87093, -325960, -500494, -718291, -67889, + 991501, 374804, 769026, -978869, 294747, 714623, 413327, -199164, 671368, 804789, + -362507, 798196, -170790, -568895, -869379, 62020, -316693, -837793, 644994, -39341, + -417504, -243068, -957756, 99072, 622234, -739992, 225668, 8863, -505910, 82483, + -559244, 241572, 1315, -36175, -54990, 376813, -11, 162647, -688204, -486163, + -54934, -197470, 744223, -762707, 732540, 996618, 351561, -445933, -898491, 486531, + 456151, 15276, 290186, -817110, -52995, 313046, -452533, -96267, 94470, -500176, + -818026, -398071, -810548, -143325, -819741, 1338, -897676, -101577, -855445, 37309, + 285742, 953804, -777927, -926962, -811217, -936744, -952245, -802300, -490188, -964953, + -552279, 329142, -570048, -505756, 682898, -381089, -14352, 175138, 152390, -582268, + -485137, 717035, 805329, 239572, -730409, 209643, -184403, -385864, 675086, 819648, + 629058, -527109, -488666, -171981, 532788, 552441, 174666, 984921, 766514, 758787, + 716309, 338801, -978004, -412163, 876079, -734212, 789557, -160491, -522719, 56644, + -991, -286038, -53983, 663740, 809812, 919889, -717502, -137704, 220511, 184396, + -825740, -588447, 430870, 124309, 135956, 558662, -307087, -788055, -451328, 812260, + 931601, 324347, -482989, -117858, -278861, 189068, -172774, 929057, 293787, 198161, + -342386, -47173, 906555, -759955, -12779, 777604, -97869, 899320, 927486, -25284, + -848550, 259450, -485856, -17820, 88, 171400, 235492, -326783, -340793, 886886, + 112428, -246280, 5979, 648444, -114982, 991013, -56489, -9497, 419706, 632820, + -341664, 393926, -848977, -22538, 257307, 773731, -905319, 491153, 734883, -868212, + -951053, 644458, -580758, 764735, 584316, 297077, 28852, -397710, -953669, 201772, + 879050, -198237, -588468, 448102, -116837, 770007, -231812, 642906, -582166, -885828, + 9, 305082, -996577, 303559, 75008, -772956, -447960, 599825, -295552, 870739, + -386278, -950300, 485359, -457081, 629461, -850276, 550496, -451755, -620841, -11766, + -950137, 832337, 28711, -273398, -507197, 91921, -271360, -705991, -753220, -388968, + 967945, 340434, -320883, -662793, -554617, -574568, 477946, -6148, -129519, 689217, + 920020, -656315, -974523, -212525, 80921, -612532, 645096, 545655, 655713, -591631, + -307385, -816688, -618823, -113713, 526430, 673063, 735916, -809095, -850417, 639004, + 432281, -388185, 270708, 860146, -39902, -786157, -258180, -246169, -966720, -264957, + 548072, -306010, -57367, -635665, 933824, 70553, -989936, -488741, 72411, -452509, + 529831, 956277, 449019, -577850, -360986, -803418, 48833, 296073, 203430, 609591, + 715483, 470964, 658106, -718254, -96424, 790163, 334739, 181070, -373578, 5, + -435088, 329841, 330939, -256602, 394355, 912412, 231910, 927278, -661933, 788539, + -769664, -893274, -96856, 298205, 901043, -608122, -527430, 183618, -553963, -35246, + -393924, 948832, -483198, 594501, 35460, -407007, 93494, -336881, -634072, 984205, + -812161, 944664, -31062, 753872, 823933, -69566, 50445, 290147, 85134, 34706, + 551902, 405202, -991246, -84642, 154341, 316432, -695101, -651588, -5030, 137564, + -294665, 332541, 528307, -90572, -344923, 523766, -758498, -968047, 339028, 494578, + 593129, -725773, 31834, -718406, -208638, 159665, -2043, 673344, -442767, 75816, + 755442, 769257, -158730, -410272, 691688, 589550, -878398, -184121, 460679, 346312, + 294163, -544602, 653308, 254167, -276979, 52073, -892684, 887653, -41222, 983065, + -68258, -408799, -99069, -674069, -863635, -32890, 622757, -743862, 40872, -4837, + -967228, 522370, -903951, -818669, 524459, 514702, 925801, 20007, -299229, 579348, + 626021, 430089, 348139, -562692, -607728, -130606, -928451, -424793, -458647, -448892, + -312230, 143337, 109746, 880042, -339658, -785614, 938995, 540916, 118429, 661351, + -402967, 404729, -40918, -976535, 743230, 713110, 440182, -381314, -499252, 74613, + 193652, 912717, 491323, 583633, 324691, 459397, 281253, 195540, -2764, -888651, + 892449, 132663, -478373, -430002, -314551, 527826, 247165, 557966, 554778, 481531, + -946634, 431685, -769059, -348371, 174046, 184597, -354867, 584422, 227390, -850397, + -542924, -849093, -737769, 325359, 736314, 269101, 767940, 674809, 81413, -447458, + 445076, 189072, 906218, 502688, -718476, -863827, -731381, 100660, 623249, 710008, + 572060, 922203, 685740, 55096, 263394, -243695, -353910, -516788, 388471, 455165, + 844103, -643772, 363976, 268875, -899450, 104470, 104029, -238874, -274659, 732969, + -676443, 953291, -916289, -861849, -242344, 958083, -479593, -970395, 799831, 277841, + -243236, -283462, -201510, 166263, -259105, -575706, 878926, 891064, 895297, 655262, + -34807, -809833, -89281, 342585, 554920, 1, 902141, -333425, 139703, 852318, + -618438, 329498, -932596, -692836, -513372, 733656, -523411, 85779, 500478, -682697, + -502836, 138776, 156341, -420037, -557964, -556378, 710993, -50383, -877159, 916334, + 132996, 583516, -603392, -111615, -12288, -780214, 476780, 123327, 137607, 519956, + 745837, 17358, -158581, -53490 +}; +static const size_t randvalCount = sizeof(randval) / sizeof(randval[0]); +static const size_t kItoaTrialCount = 10000; + +static const char digits[201] = +"0001020304050607080910111213141516171819" +"2021222324252627282930313233343536373839" +"4041424344454647484950515253545556575859" +"6061626364656667686970717273747576777879" +"8081828384858687888990919293949596979899"; + +// Prevent code being optimized out +//#define OUTPUT_LENGTH(length) printf("", length) +#define OUTPUT_LENGTH(length) printf("%u\n", (unsigned)length) + +template +class Writer1 { +public: + Writer1() : os_() {} + Writer1(OutputStream& os) : os_(&os) {} + + void Reset(OutputStream& os) { + os_ = &os; + } + + bool WriteInt(int i) { + if (i < 0) { + os_->Put('-'); + i = -i; + } + return WriteUint((unsigned)i); + } + + bool WriteUint(unsigned u) { + char buffer[10]; + char *p = buffer; + do { + *p++ = char(u % 10) + '0'; + u /= 10; + } while (u > 0); + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + + bool WriteInt64(int64_t i64) { + if (i64 < 0) { + os_->Put('-'); + i64 = -i64; + } + WriteUint64((uint64_t)i64); + return true; + } + + bool WriteUint64(uint64_t u64) { + char buffer[20]; + char *p = buffer; + do { + *p++ = char(u64 % 10) + '0'; + u64 /= 10; + } while (u64 > 0); + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + +private: + OutputStream* os_; +}; + +template<> +bool Writer1::WriteUint(unsigned u) { + char buffer[10]; + char* p = buffer; + do { + *p++ = char(u % 10) + '0'; + u /= 10; + } while (u > 0); + + char* d = os_->Push(p - buffer); + do { + --p; + *d++ = *p; + } while (p != buffer); + return true; +} + +// Using digits LUT to reduce divsion/modulo +template +class Writer2 { +public: + Writer2() : os_() {} + Writer2(OutputStream& os) : os_(&os) {} + + void Reset(OutputStream& os) { + os_ = &os; + } + + bool WriteInt(int i) { + if (i < 0) { + os_->Put('-'); + i = -i; + } + return WriteUint((unsigned)i); + } + + bool WriteUint(unsigned u) { + char buffer[10]; + char* p = buffer; + while (u >= 100) { + const unsigned i = (u % 100) << 1; + u /= 100; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + if (u < 10) + *p++ = char(u) + '0'; + else { + const unsigned i = u << 1; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + + bool WriteInt64(int64_t i64) { + if (i64 < 0) { + os_->Put('-'); + i64 = -i64; + } + WriteUint64((uint64_t)i64); + return true; + } + + bool WriteUint64(uint64_t u64) { + char buffer[20]; + char* p = buffer; + while (u64 >= 100) { + const unsigned i = static_cast(u64 % 100) << 1; + u64 /= 100; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + if (u64 < 10) + *p++ = char(u64) + '0'; + else { + const unsigned i = static_cast(u64) << 1; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + +private: + OutputStream* os_; +}; + +// First pass to count digits +template +class Writer3 { +public: + Writer3() : os_() {} + Writer3(OutputStream& os) : os_(&os) {} + + void Reset(OutputStream& os) { + os_ = &os; + } + + bool WriteInt(int i) { + if (i < 0) { + os_->Put('-'); + i = -i; + } + return WriteUint((unsigned)i); + } + + bool WriteUint(unsigned u) { + char buffer[10]; + char *p = buffer; + do { + *p++ = char(u % 10) + '0'; + u /= 10; + } while (u > 0); + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + + bool WriteInt64(int64_t i64) { + if (i64 < 0) { + os_->Put('-'); + i64 = -i64; + } + WriteUint64((uint64_t)i64); + return true; + } + + bool WriteUint64(uint64_t u64) { + char buffer[20]; + char *p = buffer; + do { + *p++ = char(u64 % 10) + '0'; + u64 /= 10; + } while (u64 > 0); + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + +private: + void WriteUintReverse(char* d, unsigned u) { + do { + *--d = char(u % 10) + '0'; + u /= 10; + } while (u > 0); + } + + void WriteUint64Reverse(char* d, uint64_t u) { + do { + *--d = char(u % 10) + '0'; + u /= 10; + } while (u > 0); + } + + OutputStream* os_; +}; + +template<> +inline bool Writer3::WriteUint(unsigned u) { + unsigned digit = CountDecimalDigit_fast(u); + WriteUintReverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer3::WriteUint(unsigned u) { + unsigned digit = CountDecimalDigit_fast(u); + WriteUintReverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer3::WriteUint64(uint64_t u) { + unsigned digit = CountDecimalDigit64_fast(u); + WriteUint64Reverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer3::WriteUint64(uint64_t u) { + unsigned digit = CountDecimalDigit64_fast(u); + WriteUint64Reverse(os_->Push(digit) + digit, u); + return true; +} + +// Using digits LUT to reduce divsion/modulo, two passes +template +class Writer4 { +public: + Writer4() : os_() {} + Writer4(OutputStream& os) : os_(&os) {} + + void Reset(OutputStream& os) { + os_ = &os; + } + + bool WriteInt(int i) { + if (i < 0) { + os_->Put('-'); + i = -i; + } + return WriteUint((unsigned)i); + } + + bool WriteUint(unsigned u) { + char buffer[10]; + char* p = buffer; + while (u >= 100) { + const unsigned i = (u % 100) << 1; + u /= 100; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + if (u < 10) + *p++ = char(u) + '0'; + else { + const unsigned i = u << 1; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + + bool WriteInt64(int64_t i64) { + if (i64 < 0) { + os_->Put('-'); + i64 = -i64; + } + WriteUint64((uint64_t)i64); + return true; + } + + bool WriteUint64(uint64_t u64) { + char buffer[20]; + char* p = buffer; + while (u64 >= 100) { + const unsigned i = static_cast(u64 % 100) << 1; + u64 /= 100; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + if (u64 < 10) + *p++ = char(u64) + '0'; + else { + const unsigned i = static_cast(u64) << 1; + *p++ = digits[i + 1]; + *p++ = digits[i]; + } + + do { + --p; + os_->Put(*p); + } while (p != buffer); + return true; + } + +private: + void WriteUintReverse(char* d, unsigned u) { + while (u >= 100) { + const unsigned i = (u % 100) << 1; + u /= 100; + *--d = digits[i + 1]; + *--d = digits[i]; + } + if (u < 10) { + *--d = char(u) + '0'; + } + else { + const unsigned i = u << 1; + *--d = digits[i + 1]; + *--d = digits[i]; + } + } + + void WriteUint64Reverse(char* d, uint64_t u) { + while (u >= 100) { + const unsigned i = (u % 100) << 1; + u /= 100; + *--d = digits[i + 1]; + *--d = digits[i]; + } + if (u < 10) { + *--d = char(u) + '0'; + } + else { + const unsigned i = u << 1; + *--d = digits[i + 1]; + *--d = digits[i]; + } + } + + OutputStream* os_; +}; + +template<> +inline bool Writer4::WriteUint(unsigned u) { + unsigned digit = CountDecimalDigit_fast(u); + WriteUintReverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer4::WriteUint(unsigned u) { + unsigned digit = CountDecimalDigit_fast(u); + WriteUintReverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer4::WriteUint64(uint64_t u) { + unsigned digit = CountDecimalDigit64_fast(u); + WriteUint64Reverse(os_->Push(digit) + digit, u); + return true; +} + +template<> +inline bool Writer4::WriteUint64(uint64_t u) { + unsigned digit = CountDecimalDigit64_fast(u); + WriteUint64Reverse(os_->Push(digit) + digit, u); + return true; +} + +template +void itoa_Writer_StringBufferVerify() { + rapidjson::StringBuffer sb; + Writer writer(sb); + for (size_t j = 0; j < randvalCount; j++) { + char buffer[32]; + sprintf(buffer, "%d", randval[j]); + writer.WriteInt(randval[j]); + ASSERT_STREQ(buffer, sb.GetString()); + sb.Clear(); + } +} + +template +void itoa_Writer_InsituStringStreamVerify() { + Writer writer; + for (size_t j = 0; j < randvalCount; j++) { + char buffer[32]; + sprintf(buffer, "%d", randval[j]); + char buffer2[32]; + rapidjson::InsituStringStream ss(buffer2); + writer.Reset(ss); + char* begin = ss.PutBegin(); + writer.WriteInt(randval[j]); + ss.Put('\0'); + ss.PutEnd(begin); + ASSERT_STREQ(buffer, buffer2); + } +} + +template +void itoa_Writer_StringBuffer() { + size_t length = 0; + + rapidjson::StringBuffer sb; + Writer writer(sb); + + for (size_t i = 0; i < kItoaTrialCount; i++) { + for (size_t j = 0; j < randvalCount; j++) { + writer.WriteInt(randval[j]); + length += sb.GetSize(); + sb.Clear(); + } + } + OUTPUT_LENGTH(length); +} + +template +void itoa_Writer_InsituStringStream() { + size_t length = 0; + + char buffer[32]; + Writer writer; + for (size_t i = 0; i < kItoaTrialCount; i++) { + for (size_t j = 0; j < randvalCount; j++) { + rapidjson::InsituStringStream ss(buffer); + writer.Reset(ss); + char* begin = ss.PutBegin(); + writer.WriteInt(randval[j]); + length += ss.PutEnd(begin); + } + } + OUTPUT_LENGTH(length); +}; + +template +void itoa64_Writer_StringBufferVerify() { + rapidjson::StringBuffer sb; + Writer writer(sb); + for (size_t j = 0; j < randvalCount; j++) { + char buffer[32]; + int64_t x = randval[j] * randval[j]; + sprintf(buffer, "%" PRIi64, x); + writer.WriteInt64(x); + ASSERT_STREQ(buffer, sb.GetString()); + sb.Clear(); + } +} + +template +void itoa64_Writer_InsituStringStreamVerify() { + Writer writer; + for (size_t j = 0; j < randvalCount; j++) { + char buffer[32]; + int64_t x = randval[j] * randval[j]; + sprintf(buffer, "%" PRIi64, x); + char buffer2[32]; + rapidjson::InsituStringStream ss(buffer2); + writer.Reset(ss); + char* begin = ss.PutBegin(); + writer.WriteInt64(x); + ss.Put('\0'); + ss.PutEnd(begin); + ASSERT_STREQ(buffer, buffer2); + } +} + +template +void itoa64_Writer_StringBuffer() { + size_t length = 0; + + rapidjson::StringBuffer sb; + Writer writer(sb); + + for (size_t i = 0; i < kItoaTrialCount; i++) { + for (size_t j = 0; j < randvalCount; j++) { + writer.WriteInt64(randval[j] * randval[j]); + length += sb.GetSize(); + sb.Clear(); + } + } + OUTPUT_LENGTH(length); +} + +template +void itoa64_Writer_InsituStringStream() { + size_t length = 0; + + char buffer[32]; + Writer writer; + for (size_t i = 0; i < kItoaTrialCount; i++) { + for (size_t j = 0; j < randvalCount; j++) { + rapidjson::InsituStringStream ss(buffer); + writer.Reset(ss); + char* begin = ss.PutBegin(); + writer.WriteInt64(randval[j] * randval[j]); + length += ss.PutEnd(begin); + } + } + OUTPUT_LENGTH(length); +}; + +// Full specialization for InsituStringStream to prevent memory copying +// (normally we will not use InsituStringStream for writing, just for testing) + +namespace rapidjson { + +template<> +bool rapidjson::Writer::WriteInt(int i) { + char *buffer = os_->Push(11); + const char* end = internal::i32toa(i, buffer); + os_->Pop(11 - (end - buffer)); + return true; +} + +template<> +bool Writer::WriteUint(unsigned u) { + char *buffer = os_->Push(10); + const char* end = internal::u32toa(u, buffer); + os_->Pop(10 - (end - buffer)); + return true; +} + +template<> +bool Writer::WriteInt64(int64_t i64) { + char *buffer = os_->Push(21); + const char* end = internal::i64toa(i64, buffer); + os_->Pop(21 - (end - buffer)); + return true; +} + +template<> +bool Writer::WriteUint64(uint64_t u) { + char *buffer = os_->Push(20); + const char* end = internal::u64toa(u, buffer); + os_->Pop(20 - (end - buffer)); + return true; +} + +} // namespace rapidjson + +TEST_F(Misc, itoa_Writer_StringBufferVerify) { itoa_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa_Writer1_StringBufferVerify) { itoa_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa_Writer2_StringBufferVerify) { itoa_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa_Writer3_StringBufferVerify) { itoa_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa_Writer4_StringBufferVerify) { itoa_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa_Writer_InsituStringStreamVerify) { itoa_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa_Writer1_InsituStringStreamVerify) { itoa_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa_Writer2_InsituStringStreamVerify) { itoa_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa_Writer3_InsituStringStreamVerify) { itoa_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa_Writer4_InsituStringStreamVerify) { itoa_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa_Writer_StringBuffer) { itoa_Writer_StringBuffer >(); } +TEST_F(Misc, itoa_Writer1_StringBuffer) { itoa_Writer_StringBuffer >(); } +TEST_F(Misc, itoa_Writer2_StringBuffer) { itoa_Writer_StringBuffer >(); } +TEST_F(Misc, itoa_Writer3_StringBuffer) { itoa_Writer_StringBuffer >(); } +TEST_F(Misc, itoa_Writer4_StringBuffer) { itoa_Writer_StringBuffer >(); } +TEST_F(Misc, itoa_Writer_InsituStringStream) { itoa_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa_Writer1_InsituStringStream) { itoa_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa_Writer2_InsituStringStream) { itoa_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa_Writer3_InsituStringStream) { itoa_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa_Writer4_InsituStringStream) { itoa_Writer_InsituStringStream >(); } + +TEST_F(Misc, itoa64_Writer_StringBufferVerify) { itoa64_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa64_Writer1_StringBufferVerify) { itoa64_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa64_Writer2_StringBufferVerify) { itoa64_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa64_Writer3_StringBufferVerify) { itoa64_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa64_Writer4_StringBufferVerify) { itoa64_Writer_StringBufferVerify >(); } +TEST_F(Misc, itoa64_Writer_InsituStringStreamVerify) { itoa64_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa64_Writer1_InsituStringStreamVerify) { itoa64_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa64_Writer2_InsituStringStreamVerify) { itoa64_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa64_Writer3_InsituStringStreamVerify) { itoa64_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa64_Writer4_InsituStringStreamVerify) { itoa64_Writer_InsituStringStreamVerify >(); } +TEST_F(Misc, itoa64_Writer_StringBuffer) { itoa64_Writer_StringBuffer >(); } +TEST_F(Misc, itoa64_Writer1_StringBuffer) { itoa64_Writer_StringBuffer >(); } +TEST_F(Misc, itoa64_Writer2_StringBuffer) { itoa64_Writer_StringBuffer >(); } +TEST_F(Misc, itoa64_Writer3_StringBuffer) { itoa64_Writer_StringBuffer >(); } +TEST_F(Misc, itoa64_Writer4_StringBuffer) { itoa64_Writer_StringBuffer >(); } +TEST_F(Misc, itoa64_Writer_InsituStringStream) { itoa64_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa64_Writer1_InsituStringStream) { itoa64_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa64_Writer2_InsituStringStream) { itoa64_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa64_Writer3_InsituStringStream) { itoa64_Writer_InsituStringStream >(); } +TEST_F(Misc, itoa64_Writer4_InsituStringStream) { itoa64_Writer_InsituStringStream >(); } + +#endif // TEST_MISC diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/perftest.cpp b/thirdparty/rapidjson-1.1.0/test/perftest/perftest.cpp new file mode 100644 index 0000000000..4e79f1f518 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/perftest.cpp @@ -0,0 +1,24 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "perftest.h" + +int main(int argc, char **argv) { +#if _MSC_VER + _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); + //void *testWhetherMemoryLeakDetectionWorks = malloc(1); +#endif + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/perftest.h b/thirdparty/rapidjson-1.1.0/test/perftest/perftest.h new file mode 100644 index 0000000000..b098e41472 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/perftest.h @@ -0,0 +1,182 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef PERFTEST_H_ +#define PERFTEST_H_ + +#define TEST_RAPIDJSON 1 +#define TEST_PLATFORM 0 +#define TEST_MISC 0 + +#define TEST_VERSION_CODE(x,y,z) \ + (((x)*100000) + ((y)*100) + (z)) + +// __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler. +// We use -march=native with gmake to enable -msse2 and -msse4.2, if supported. +#if defined(__SSE4_2__) +# define RAPIDJSON_SSE42 +#elif defined(__SSE2__) +# define RAPIDJSON_SSE2 +#endif + +#define RAPIDJSON_HAS_STDSTRING 1 + +//////////////////////////////////////////////////////////////////////////////// +// Google Test + +#ifdef __cplusplus + +// gtest indirectly included inttypes.h, without __STDC_CONSTANT_MACROS. +#ifndef __STDC_CONSTANT_MACROS +# define __STDC_CONSTANT_MACROS 1 // required by C++ standard +#endif + +#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)) +#if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#pragma GCC diagnostic push +#endif +#pragma GCC diagnostic ignored "-Weffc++" +#endif + +#include "gtest/gtest.h" + +#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#pragma GCC diagnostic pop +#endif + +#ifdef _MSC_VER +#define _CRTDBG_MAP_ALLOC +#include +#pragma warning(disable : 4996) // 'function': was declared deprecated +#endif + +//! Base class for all performance tests +class PerfTest : public ::testing::Test { +public: + PerfTest() : filename_(), json_(), length_(), whitespace_(), whitespace_length_() {} + + virtual void SetUp() { + { + const char *paths[] = { + "data/sample.json", + "bin/data/sample.json", + "../bin/data/sample.json", + "../../bin/data/sample.json", + "../../../bin/data/sample.json" + }; + + FILE *fp = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + fp = fopen(filename_ = paths[i], "rb"); + if (fp) + break; + } + ASSERT_TRUE(fp != 0); + + fseek(fp, 0, SEEK_END); + length_ = (size_t)ftell(fp); + fseek(fp, 0, SEEK_SET); + json_ = (char*)malloc(length_ + 1); + ASSERT_EQ(length_, fread(json_, 1, length_, fp)); + json_[length_] = '\0'; + fclose(fp); + } + + // whitespace test + { + whitespace_length_ = 1024 * 1024; + whitespace_ = (char *)malloc(whitespace_length_ + 4); + char *p = whitespace_; + for (size_t i = 0; i < whitespace_length_; i += 4) { + *p++ = ' '; + *p++ = '\n'; + *p++ = '\r'; + *p++ = '\t'; + } + *p++ = '['; + *p++ = '0'; + *p++ = ']'; + *p++ = '\0'; + } + + // types test + { + const char *typespaths[] = { + "data/types", + "bin/types", + "../bin/types", + "../../bin/types/", + "../../../bin/types" + }; + + const char* typesfilenames[] = { + "booleans.json", + "floats.json", + "guids.json", + "integers.json", + "mixed.json", + "nulls.json", + "paragraphs.json" + }; + + for (size_t j = 0; j < sizeof(typesfilenames) / sizeof(typesfilenames[0]); j++) { + types_[j] = 0; + for (size_t i = 0; i < sizeof(typespaths) / sizeof(typespaths[0]); i++) { + char filename[256]; + sprintf(filename, "%s/%s", typespaths[i], typesfilenames[j]); + if (FILE* fp = fopen(filename, "rb")) { + fseek(fp, 0, SEEK_END); + typesLength_[j] = (size_t)ftell(fp); + fseek(fp, 0, SEEK_SET); + types_[j] = (char*)malloc(typesLength_[j] + 1); + ASSERT_EQ(typesLength_[j], fread(types_[j], 1, typesLength_[j], fp)); + types_[j][typesLength_[j]] = '\0'; + fclose(fp); + break; + } + } + } + } + } + + virtual void TearDown() { + free(json_); + free(whitespace_); + json_ = 0; + whitespace_ = 0; + for (size_t i = 0; i < 7; i++) { + free(types_[i]); + types_[i] = 0; + } + } + +private: + PerfTest(const PerfTest&); + PerfTest& operator=(const PerfTest&); + +protected: + const char* filename_; + char *json_; + size_t length_; + char *whitespace_; + size_t whitespace_length_; + char *types_[7]; + size_t typesLength_[7]; + + static const size_t kTrialCount = 1000; +}; + +#endif // __cplusplus + +#endif // PERFTEST_H_ diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/platformtest.cpp b/thirdparty/rapidjson-1.1.0/test/perftest/platformtest.cpp new file mode 100644 index 0000000000..bb905ca73b --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/platformtest.cpp @@ -0,0 +1,166 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "perftest.h" + +// This file is for giving the performance characteristics of the platform (compiler/OS/CPU). + +#if TEST_PLATFORM + +#include +#include + +// Windows +#ifdef _WIN32 +#include +#endif + +// UNIX +#if defined(unix) || defined(__unix__) || defined(__unix) +#include +#ifdef _POSIX_MAPPED_FILES +#include +#endif +#endif + +class Platform : public PerfTest { +public: + virtual void SetUp() { + PerfTest::SetUp(); + + // temp buffer for testing + temp_ = (char *)malloc(length_ + 1); + memcpy(temp_, json_, length_); + checkSum_ = CheckSum(); + } + + char CheckSum() { + char c = 0; + for (size_t i = 0; i < length_; ++i) + c += temp_[i]; + return c; + } + + virtual void TearDown() { + PerfTest::TearDown(); + free(temp_); + } + +protected: + char *temp_; + char checkSum_; +}; + +TEST_F(Platform, CheckSum) { + for (int i = 0; i < kTrialCount; i++) + EXPECT_EQ(checkSum_, CheckSum()); +} + +TEST_F(Platform, strlen) { + for (int i = 0; i < kTrialCount; i++) { + size_t l = strlen(json_); + EXPECT_EQ(length_, l); + } +} + +TEST_F(Platform, memcmp) { + for (int i = 0; i < kTrialCount; i++) { + EXPECT_EQ(0, memcmp(temp_, json_, length_)); + } +} + +TEST_F(Platform, pow) { + double sum = 0; + for (int i = 0; i < kTrialCount * kTrialCount; i++) + sum += pow(10.0, i & 255); + EXPECT_GT(sum, 0.0); +} + +TEST_F(Platform, Whitespace_strlen) { + for (int i = 0; i < kTrialCount; i++) { + size_t l = strlen(whitespace_); + EXPECT_GT(l, whitespace_length_); + } +} + +TEST_F(Platform, Whitespace_strspn) { + for (int i = 0; i < kTrialCount; i++) { + size_t l = strspn(whitespace_, " \n\r\t"); + EXPECT_EQ(whitespace_length_, l); + } +} + +TEST_F(Platform, fread) { + for (int i = 0; i < kTrialCount; i++) { + FILE *fp = fopen(filename_, "rb"); + ASSERT_EQ(length_, fread(temp_, 1, length_, fp)); + EXPECT_EQ(checkSum_, CheckSum()); + fclose(fp); + } +} + +#ifdef _MSC_VER +TEST_F(Platform, read) { + for (int i = 0; i < kTrialCount; i++) { + int fd = _open(filename_, _O_BINARY | _O_RDONLY); + ASSERT_NE(-1, fd); + ASSERT_EQ(length_, _read(fd, temp_, length_)); + EXPECT_EQ(checkSum_, CheckSum()); + _close(fd); + } +} +#else +TEST_F(Platform, read) { + for (int i = 0; i < kTrialCount; i++) { + int fd = open(filename_, O_RDONLY); + ASSERT_NE(-1, fd); + ASSERT_EQ(length_, read(fd, temp_, length_)); + EXPECT_EQ(checkSum_, CheckSum()); + close(fd); + } +} +#endif + +#ifdef _WIN32 +TEST_F(Platform, MapViewOfFile) { + for (int i = 0; i < kTrialCount; i++) { + HANDLE file = CreateFile(filename_, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + ASSERT_NE(INVALID_HANDLE_VALUE, file); + HANDLE mapObject = CreateFileMapping(file, NULL, PAGE_READONLY, 0, length_, NULL); + ASSERT_NE(INVALID_HANDLE_VALUE, mapObject); + void *p = MapViewOfFile(mapObject, FILE_MAP_READ, 0, 0, length_); + ASSERT_TRUE(p != NULL); + EXPECT_EQ(checkSum_, CheckSum()); + ASSERT_TRUE(UnmapViewOfFile(p) == TRUE); + ASSERT_TRUE(CloseHandle(mapObject) == TRUE); + ASSERT_TRUE(CloseHandle(file) == TRUE); + } +} +#endif + +#ifdef _POSIX_MAPPED_FILES +TEST_F(Platform, mmap) { + for (int i = 0; i < kTrialCount; i++) { + int fd = open(filename_, O_RDONLY); + ASSERT_NE(-1, fd); + void *p = mmap(NULL, length_, PROT_READ, MAP_PRIVATE, fd, 0); + ASSERT_TRUE(p != NULL); + EXPECT_EQ(checkSum_, CheckSum()); + munmap(p, length_); + close(fd); + } +} +#endif + +#endif // TEST_PLATFORM diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/rapidjsontest.cpp b/thirdparty/rapidjson-1.1.0/test/perftest/rapidjsontest.cpp new file mode 100644 index 0000000000..675db3182a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/rapidjsontest.cpp @@ -0,0 +1,441 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "perftest.h" + +#if TEST_RAPIDJSON + +#include "rapidjson/rapidjson.h" +#include "rapidjson/document.h" +#include "rapidjson/prettywriter.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/memorystream.h" + +#ifdef RAPIDJSON_SSE2 +#define SIMD_SUFFIX(name) name##_SSE2 +#elif defined(RAPIDJSON_SSE42) +#define SIMD_SUFFIX(name) name##_SSE42 +#else +#define SIMD_SUFFIX(name) name +#endif + +using namespace rapidjson; + +class RapidJson : public PerfTest { +public: + RapidJson() : temp_(), doc_() {} + + virtual void SetUp() { + PerfTest::SetUp(); + + // temp buffer for insitu parsing. + temp_ = (char *)malloc(length_ + 1); + + // Parse as a document + EXPECT_FALSE(doc_.Parse(json_).HasParseError()); + + for (size_t i = 0; i < 7; i++) + EXPECT_FALSE(typesDoc_[i].Parse(types_[i]).HasParseError()); + } + + virtual void TearDown() { + PerfTest::TearDown(); + free(temp_); + } + +private: + RapidJson(const RapidJson&); + RapidJson& operator=(const RapidJson&); + +protected: + char *temp_; + Document doc_; + Document typesDoc_[7]; +}; + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + InsituStringStream s(temp_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_ValidateEncoding)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + InsituStringStream s(temp_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringStream s(json_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +#define TEST_TYPED(index, Name)\ +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_##Name)) {\ + for (size_t i = 0; i < kTrialCount * 10; i++) {\ + StringStream s(types_[index]);\ + BaseReaderHandler<> h;\ + Reader reader;\ + EXPECT_TRUE(reader.Parse(s, h));\ + }\ +}\ +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_##Name)) {\ + for (size_t i = 0; i < kTrialCount * 10; i++) {\ + memcpy(temp_, types_[index], typesLength_[index] + 1);\ + InsituStringStream s(temp_);\ + BaseReaderHandler<> h;\ + Reader reader;\ + EXPECT_TRUE(reader.Parse(s, h));\ + }\ +} + +TEST_TYPED(0, Booleans) +TEST_TYPED(1, Floats) +TEST_TYPED(2, Guids) +TEST_TYPED(3, Integers) +TEST_TYPED(4, Mixed) +TEST_TYPED(5, Nulls) +TEST_TYPED(6, Paragraphs) + +#undef TEST_TYPED + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FullPrecision)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringStream s(json_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterative_DummyHandler)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringStream s(json_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativeInsitu_DummyHandler)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + InsituStringStream s(temp_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringStream s(json_); + BaseReaderHandler<> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseInsitu_MemoryPoolAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + Document doc; + doc.ParseInsitu(temp_); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseIterativeInsitu_MemoryPoolAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + Document doc; + doc.ParseInsitu(temp_); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_MemoryPoolAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + Document doc; + doc.Parse(json_); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseLength_MemoryPoolAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + Document doc; + doc.Parse(json_, length_); + ASSERT_TRUE(doc.IsObject()); + } +} + +#if RAPIDJSON_HAS_STDSTRING +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseStdString_MemoryPoolAllocator)) { + const std::string s(json_, length_); + for (size_t i = 0; i < kTrialCount; i++) { + Document doc; + doc.Parse(s); + ASSERT_TRUE(doc.IsObject()); + } +} +#endif + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseIterative_MemoryPoolAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + Document doc; + doc.Parse(json_); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParse_CrtAllocator)) { + for (size_t i = 0; i < kTrialCount; i++) { + memcpy(temp_, json_, length_ + 1); + GenericDocument, CrtAllocator> doc; + doc.Parse(temp_); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseEncodedInputStream_MemoryStream)) { + for (size_t i = 0; i < kTrialCount; i++) { + MemoryStream ms(json_, length_); + EncodedInputStream, MemoryStream> is(ms); + Document doc; + doc.ParseStream<0, UTF8<> >(is); + ASSERT_TRUE(doc.IsObject()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(DocumentParseAutoUTFInputStream_MemoryStream)) { + for (size_t i = 0; i < kTrialCount; i++) { + MemoryStream ms(json_, length_); + AutoUTFInputStream is(ms); + Document doc; + doc.ParseStream<0, AutoUTF >(is); + ASSERT_TRUE(doc.IsObject()); + } +} + +template +size_t Traverse(const T& value) { + size_t count = 1; + switch(value.GetType()) { + case kObjectType: + for (typename T::ConstMemberIterator itr = value.MemberBegin(); itr != value.MemberEnd(); ++itr) { + count++; // name + count += Traverse(itr->value); + } + break; + + case kArrayType: + for (typename T::ConstValueIterator itr = value.Begin(); itr != value.End(); ++itr) + count += Traverse(*itr); + break; + + default: + // Do nothing. + break; + } + return count; +} + +TEST_F(RapidJson, DocumentTraverse) { + for (size_t i = 0; i < kTrialCount; i++) { + size_t count = Traverse(doc_); + EXPECT_EQ(4339u, count); + //if (i == 0) + // std::cout << count << std::endl; + } +} + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +struct ValueCounter : public BaseReaderHandler<> { + ValueCounter() : count_(1) {} // root + + bool EndObject(SizeType memberCount) { count_ += memberCount * 2; return true; } + bool EndArray(SizeType elementCount) { count_ += elementCount; return true; } + + SizeType count_; +}; + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif + +TEST_F(RapidJson, DocumentAccept) { + for (size_t i = 0; i < kTrialCount; i++) { + ValueCounter counter; + doc_.Accept(counter); + EXPECT_EQ(4339u, counter.count_); + } +} + +struct NullStream { + typedef char Ch; + + NullStream() /*: length_(0)*/ {} + void Put(Ch) { /*++length_;*/ } + void Flush() {} + //size_t length_; +}; + +TEST_F(RapidJson, Writer_NullStream) { + for (size_t i = 0; i < kTrialCount; i++) { + NullStream s; + Writer writer(s); + doc_.Accept(writer); + //if (i == 0) + // std::cout << s.length_ << std::endl; + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(Writer_StringBuffer)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringBuffer s(0, 1024 * 1024); + Writer writer(s); + doc_.Accept(writer); + const char* str = s.GetString(); + (void)str; + //if (i == 0) + // std::cout << strlen(str) << std::endl; + } +} + +#define TEST_TYPED(index, Name)\ +TEST_F(RapidJson, SIMD_SUFFIX(Writer_StringBuffer_##Name)) {\ + for (size_t i = 0; i < kTrialCount * 10; i++) {\ + StringBuffer s(0, 1024 * 1024);\ + Writer writer(s);\ + typesDoc_[index].Accept(writer);\ + const char* str = s.GetString();\ + (void)str;\ + }\ +} + +TEST_TYPED(0, Booleans) +TEST_TYPED(1, Floats) +TEST_TYPED(2, Guids) +TEST_TYPED(3, Integers) +TEST_TYPED(4, Mixed) +TEST_TYPED(5, Nulls) +TEST_TYPED(6, Paragraphs) + +#undef TEST_TYPED + +TEST_F(RapidJson, SIMD_SUFFIX(PrettyWriter_StringBuffer)) { + for (size_t i = 0; i < kTrialCount; i++) { + StringBuffer s(0, 2048 * 1024); + PrettyWriter writer(s); + writer.SetIndent(' ', 1); + doc_.Accept(writer); + const char* str = s.GetString(); + (void)str; + //if (i == 0) + // std::cout << strlen(str) << std::endl; + } +} + +TEST_F(RapidJson, internal_Pow10) { + double sum = 0; + for (size_t i = 0; i < kTrialCount * kTrialCount; i++) + sum += internal::Pow10(int(i & 255)); + EXPECT_GT(sum, 0.0); +} + +TEST_F(RapidJson, SkipWhitespace_Basic) { + for (size_t i = 0; i < kTrialCount; i++) { + rapidjson::StringStream s(whitespace_); + while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t') + s.Take(); + ASSERT_EQ('[', s.Peek()); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(SkipWhitespace)) { + for (size_t i = 0; i < kTrialCount; i++) { + rapidjson::StringStream s(whitespace_); + rapidjson::SkipWhitespace(s); + ASSERT_EQ('[', s.Peek()); + } +} + +TEST_F(RapidJson, SkipWhitespace_strspn) { + for (size_t i = 0; i < kTrialCount; i++) { + const char* s = whitespace_ + std::strspn(whitespace_, " \t\r\n"); + ASSERT_EQ('[', *s); + } +} + +TEST_F(RapidJson, UTF8_Validate) { + NullStream os; + + for (size_t i = 0; i < kTrialCount; i++) { + StringStream is(json_); + bool result = true; + while (is.Peek() != '\0') + result &= UTF8<>::Validate(is, os); + EXPECT_TRUE(result); + } +} + +TEST_F(RapidJson, FileReadStream) { + for (size_t i = 0; i < kTrialCount; i++) { + FILE *fp = fopen(filename_, "rb"); + char buffer[65536]; + FileReadStream s(fp, buffer, sizeof(buffer)); + while (s.Take() != '\0') + ; + fclose(fp); + } +} + +TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) { + for (size_t i = 0; i < kTrialCount; i++) { + FILE *fp = fopen(filename_, "rb"); + char buffer[65536]; + FileReadStream s(fp, buffer, sizeof(buffer)); + BaseReaderHandler<> h; + Reader reader; + reader.Parse(s, h); + fclose(fp); + } +} + +TEST_F(RapidJson, StringBuffer) { + StringBuffer sb; + for (int i = 0; i < 32 * 1024 * 1024; i++) + sb.Put(i & 0x7f); +} + +#endif // TEST_RAPIDJSON diff --git a/thirdparty/rapidjson-1.1.0/test/perftest/schematest.cpp b/thirdparty/rapidjson-1.1.0/test/perftest/schematest.cpp new file mode 100644 index 0000000000..468f5fe6f6 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/perftest/schematest.cpp @@ -0,0 +1,216 @@ +#include "perftest.h" + +#if TEST_RAPIDJSON + +#include "rapidjson/schema.h" +#include +#include +#include + +#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0]) + +using namespace rapidjson; + +template +static char* ReadFile(const char* filename, Allocator& allocator) { + const char *paths[] = { + "", + "bin/", + "../bin/", + "../../bin/", + "../../../bin/" + }; + char buffer[1024]; + FILE *fp = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s%s", paths[i], filename); + fp = fopen(buffer, "rb"); + if (fp) + break; + } + + if (!fp) + return 0; + + fseek(fp, 0, SEEK_END); + size_t length = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + char* json = reinterpret_cast(allocator.Malloc(length + 1)); + size_t readLength = fread(json, 1, length, fp); + json[readLength] = '\0'; + fclose(fp); + return json; +} + +class Schema : public PerfTest { +public: + Schema() {} + + virtual void SetUp() { + PerfTest::SetUp(); + + const char* filenames[] = { + "additionalItems.json", + "additionalProperties.json", + "allOf.json", + "anyOf.json", + "default.json", + "definitions.json", + "dependencies.json", + "enum.json", + "items.json", + "maximum.json", + "maxItems.json", + "maxLength.json", + "maxProperties.json", + "minimum.json", + "minItems.json", + "minLength.json", + "minProperties.json", + "multipleOf.json", + "not.json", + "oneOf.json", + "pattern.json", + "patternProperties.json", + "properties.json", + "ref.json", + "refRemote.json", + "required.json", + "type.json", + "uniqueItems.json" + }; + + char jsonBuffer[65536]; + MemoryPoolAllocator<> jsonAllocator(jsonBuffer, sizeof(jsonBuffer)); + + for (size_t i = 0; i < ARRAY_SIZE(filenames); i++) { + char filename[FILENAME_MAX]; + sprintf(filename, "jsonschema/tests/draft4/%s", filenames[i]); + char* json = ReadFile(filename, jsonAllocator); + if (!json) { + printf("json test suite file %s not found", filename); + return; + } + + Document d; + d.Parse(json); + if (d.HasParseError()) { + printf("json test suite file %s has parse error", filename); + return; + } + + for (Value::ConstValueIterator schemaItr = d.Begin(); schemaItr != d.End(); ++schemaItr) { + std::string schemaDescription = (*schemaItr)["description"].GetString(); + if (IsExcludeTestSuite(schemaDescription)) + continue; + + TestSuite* ts = new TestSuite; + ts->schema = new SchemaDocument((*schemaItr)["schema"]); + + const Value& tests = (*schemaItr)["tests"]; + for (Value::ConstValueIterator testItr = tests.Begin(); testItr != tests.End(); ++testItr) { + if (IsExcludeTest(schemaDescription + ", " + (*testItr)["description"].GetString())) + continue; + + Document* d2 = new Document; + d2->CopyFrom((*testItr)["data"], d2->GetAllocator()); + ts->tests.push_back(d2); + } + testSuites.push_back(ts); + } + } + } + + virtual void TearDown() { + PerfTest::TearDown(); + for (TestSuiteList::const_iterator itr = testSuites.begin(); itr != testSuites.end(); ++itr) + delete *itr; + testSuites.clear(); + } + +private: + // Using the same exclusion in https://github.com/json-schema/JSON-Schema-Test-Suite + static bool IsExcludeTestSuite(const std::string& description) { + const char* excludeTestSuites[] = { + //lost failing these tests + "remote ref", + "remote ref, containing refs itself", + "fragment within remote ref", + "ref within remote ref", + "change resolution scope", + // these below were added to get jsck in the benchmarks) + "uniqueItems validation", + "valid definition", + "invalid definition" + }; + + for (size_t i = 0; i < ARRAY_SIZE(excludeTestSuites); i++) + if (excludeTestSuites[i] == description) + return true; + return false; + } + + // Using the same exclusion in https://github.com/json-schema/JSON-Schema-Test-Suite + static bool IsExcludeTest(const std::string& description) { + const char* excludeTests[] = { + //lots of validators fail these + "invalid definition, invalid definition schema", + "maxLength validation, two supplementary Unicode code points is long enough", + "minLength validation, one supplementary Unicode code point is not long enough", + //this is to get tv4 in the benchmarks + "heterogeneous enum validation, something else is invalid" + }; + + for (size_t i = 0; i < ARRAY_SIZE(excludeTests); i++) + if (excludeTests[i] == description) + return true; + return false; + } + + Schema(const Schema&); + Schema& operator=(const Schema&); + +protected: + typedef std::vector DocumentList; + + struct TestSuite { + TestSuite() : schema() {} + ~TestSuite() { + delete schema; + for (DocumentList::iterator itr = tests.begin(); itr != tests.end(); ++itr) + delete *itr; + } + SchemaDocument* schema; + DocumentList tests; + }; + + typedef std::vector TestSuiteList; + TestSuiteList testSuites; +}; + +TEST_F(Schema, TestSuite) { + char validatorBuffer[65536]; + MemoryPoolAllocator<> validatorAllocator(validatorBuffer, sizeof(validatorBuffer)); + + const int trialCount = 100000; + int testCount = 0; + clock_t start = clock(); + for (int i = 0; i < trialCount; i++) { + for (TestSuiteList::const_iterator itr = testSuites.begin(); itr != testSuites.end(); ++itr) { + const TestSuite& ts = **itr; + GenericSchemaValidator >, MemoryPoolAllocator<> > validator(*ts.schema, &validatorAllocator); + for (DocumentList::const_iterator testItr = ts.tests.begin(); testItr != ts.tests.end(); ++testItr) { + validator.Reset(); + (*testItr)->Accept(validator); + testCount++; + } + validatorAllocator.Clear(); + } + } + clock_t end = clock(); + double duration = double(end - start) / CLOCKS_PER_SEC; + printf("%d trials in %f s -> %f trials per sec\n", trialCount, duration, trialCount / duration); + printf("%d tests per trial\n", testCount / trialCount); +} + +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/CMakeLists.txt b/thirdparty/rapidjson-1.1.0/test/unittest/CMakeLists.txt new file mode 100644 index 0000000000..b3204d6c8d --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/CMakeLists.txt @@ -0,0 +1,92 @@ +include(CheckCXXCompilerFlag) + +set(UNITTEST_SOURCES + allocatorstest.cpp + bigintegertest.cpp + documenttest.cpp + dtoatest.cpp + encodedstreamtest.cpp + encodingstest.cpp + fwdtest.cpp + filestreamtest.cpp + itoatest.cpp + istreamwrappertest.cpp + jsoncheckertest.cpp + namespacetest.cpp + pointertest.cpp + prettywritertest.cpp + ostreamwrappertest.cpp + readertest.cpp + regextest.cpp + schematest.cpp + simdtest.cpp + strfunctest.cpp + stringbuffertest.cpp + strtodtest.cpp + unittest.cpp + valuetest.cpp + writertest.cpp) + +find_program(CCACHE_FOUND ccache) +if(CCACHE_FOUND) + set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) + set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) + if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments -fcolor-diagnostics") + endif() +endif(CCACHE_FOUND) + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wall -Wextra -Weffc++ -Wswitch-default -Wfloat-equal") +elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wall -Wextra -Weffc++ -Wswitch-default -Wfloat-equal -Wimplicit-fallthrough -Weverything") + # If the user is running a newer version of Clang that includes the + # -Wdouble-promotion, we will ignore that warning. + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 3.7) + CHECK_CXX_COMPILER_FLAG("-Wno-double-promotion" HAS_NO_DOUBLE_PROMOTION) + if (HAS_NO_DOUBLE_PROMOTION) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-double-promotion") + endif() + endif() +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + # Force to always compile with /W4 + if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") + string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") + endif() + + # Force to always compile with /WX + if(CMAKE_CXX_FLAGS MATCHES "/WX-") + string(REGEX REPLACE "/WX-" "/WX" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /WX") + endif() +endif() + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DRAPIDJSON_HAS_STDSTRING=1") + +add_library(namespacetest STATIC namespacetest.cpp) + +add_executable(unittest ${UNITTEST_SOURCES}) +target_link_libraries(unittest ${TEST_LIBRARIES} namespacetest) + +add_dependencies(tests unittest) + +add_test(NAME unittest + COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unittest + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) + +if(NOT MSVC) + # Not running SIMD.* unit test cases for Valgrind + add_test(NAME valgrind_unittest + COMMAND valgrind --leak-check=full --error-exitcode=1 ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/unittest --gtest_filter=-SIMD.* + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/bin) + + if(CMAKE_BUILD_TYPE STREQUAL "Debug") + add_test(NAME symbol_check + COMMAND sh -c "objdump -t -C libnamespacetest.a | grep rapidjson ; test $? -ne 0" + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + endif(CMAKE_BUILD_TYPE STREQUAL "Debug") + +endif(NOT MSVC) diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/allocatorstest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/allocatorstest.cpp new file mode 100644 index 0000000000..a5958de199 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/allocatorstest.cpp @@ -0,0 +1,102 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/allocators.h" + +using namespace rapidjson; + +template +void TestAllocator(Allocator& a) { + EXPECT_TRUE(a.Malloc(0) == 0); + + uint8_t* p = static_cast(a.Malloc(100)); + EXPECT_TRUE(p != 0); + for (size_t i = 0; i < 100; i++) + p[i] = static_cast(i); + + // Expand + uint8_t* q = static_cast(a.Realloc(p, 100, 200)); + EXPECT_TRUE(q != 0); + for (size_t i = 0; i < 100; i++) + EXPECT_EQ(i, q[i]); + for (size_t i = 100; i < 200; i++) + q[i] = static_cast(i); + + // Shrink + uint8_t *r = static_cast(a.Realloc(q, 200, 150)); + EXPECT_TRUE(r != 0); + for (size_t i = 0; i < 150; i++) + EXPECT_EQ(i, r[i]); + + Allocator::Free(r); + + // Realloc to zero size + EXPECT_TRUE(a.Realloc(a.Malloc(1), 1, 0) == 0); +} + +TEST(Allocator, CrtAllocator) { + CrtAllocator a; + TestAllocator(a); +} + +TEST(Allocator, MemoryPoolAllocator) { + MemoryPoolAllocator<> a; + TestAllocator(a); + + for (size_t i = 1; i < 1000; i++) { + EXPECT_TRUE(a.Malloc(i) != 0); + EXPECT_LE(a.Size(), a.Capacity()); + } +} + +TEST(Allocator, Alignment) { +#if RAPIDJSON_64BIT == 1 + EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000000), RAPIDJSON_ALIGN(0)); + for (uint64_t i = 1; i < 8; i++) { + EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008), RAPIDJSON_ALIGN(i)); + EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000010), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008) + i)); + EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000001, 0x00000000), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0xFFFFFFF8) + i)); + EXPECT_EQ(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF8), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0) + i)); + } +#else + EXPECT_EQ(0u, RAPIDJSON_ALIGN(0u)); + for (uint32_t i = 1; i < 4; i++) { + EXPECT_EQ(4u, RAPIDJSON_ALIGN(i)); + EXPECT_EQ(8u, RAPIDJSON_ALIGN(4u + i)); + EXPECT_EQ(0xFFFFFFF8u, RAPIDJSON_ALIGN(0xFFFFFFF4u + i)); + EXPECT_EQ(0xFFFFFFFCu, RAPIDJSON_ALIGN(0xFFFFFFF8u + i)); + } +#endif +} + +TEST(Allocator, Issue399) { + MemoryPoolAllocator<> a; + void* p = a.Malloc(100); + void* q = a.Realloc(p, 100, 200); + EXPECT_EQ(p, q); + + // exhuasive testing + for (size_t j = 1; j < 32; j++) { + a.Clear(); + a.Malloc(j); // some unaligned size + p = a.Malloc(1); + for (size_t i = 1; i < 1024; i++) { + q = a.Realloc(p, i, i + 1); + EXPECT_EQ(p, q); + p = q; + } + } +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/bigintegertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/bigintegertest.cpp new file mode 100644 index 0000000000..a68e144467 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/bigintegertest.cpp @@ -0,0 +1,133 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/internal/biginteger.h" + +using namespace rapidjson::internal; + +#define BIGINTEGER_LITERAL(s) BigInteger(s, sizeof(s) - 1) + +static const BigInteger kZero(0); +static const BigInteger kOne(1); +static const BigInteger kUint64Max = BIGINTEGER_LITERAL("18446744073709551615"); +static const BigInteger kTwo64 = BIGINTEGER_LITERAL("18446744073709551616"); + +TEST(BigInteger, Constructor) { + EXPECT_TRUE(kZero.IsZero()); + EXPECT_TRUE(kZero == kZero); + EXPECT_TRUE(kZero == BIGINTEGER_LITERAL("0")); + EXPECT_TRUE(kZero == BIGINTEGER_LITERAL("00")); + + const BigInteger a(123); + EXPECT_TRUE(a == a); + EXPECT_TRUE(a == BIGINTEGER_LITERAL("123")); + EXPECT_TRUE(a == BIGINTEGER_LITERAL("0123")); + + EXPECT_EQ(2u, kTwo64.GetCount()); + EXPECT_EQ(0u, kTwo64.GetDigit(0)); + EXPECT_EQ(1u, kTwo64.GetDigit(1)); +} + +TEST(BigInteger, AddUint64) { + BigInteger a = kZero; + a += 0u; + EXPECT_TRUE(kZero == a); + + a += 1u; + EXPECT_TRUE(kOne == a); + + a += 1u; + EXPECT_TRUE(BigInteger(2) == a); + + EXPECT_TRUE(BigInteger(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF)) == kUint64Max); + BigInteger b = kUint64Max; + b += 1u; + EXPECT_TRUE(kTwo64 == b); + b += RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF); + EXPECT_TRUE(BIGINTEGER_LITERAL("36893488147419103231") == b); +} + +TEST(BigInteger, MultiplyUint64) { + BigInteger a = kZero; + a *= static_cast (0); + EXPECT_TRUE(kZero == a); + a *= static_cast (123); + EXPECT_TRUE(kZero == a); + + BigInteger b = kOne; + b *= static_cast(1); + EXPECT_TRUE(kOne == b); + b *= static_cast(0); + EXPECT_TRUE(kZero == b); + + BigInteger c(123); + c *= static_cast(456u); + EXPECT_TRUE(BigInteger(123u * 456u) == c); + c *= RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF); + EXPECT_TRUE(BIGINTEGER_LITERAL("1034640981606221330982120") == c); + c *= RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF); + EXPECT_TRUE(BIGINTEGER_LITERAL("19085757395861596536664473018420572782123800") == c); +} + +TEST(BigInteger, MultiplyUint32) { + BigInteger a = kZero; + a *= static_cast (0); + EXPECT_TRUE(kZero == a); + a *= static_cast (123); + EXPECT_TRUE(kZero == a); + + BigInteger b = kOne; + b *= static_cast(1); + EXPECT_TRUE(kOne == b); + b *= static_cast(0); + EXPECT_TRUE(kZero == b); + + BigInteger c(123); + c *= static_cast(456u); + EXPECT_TRUE(BigInteger(123u * 456u) == c); + c *= 0xFFFFFFFFu; + EXPECT_TRUE(BIGINTEGER_LITERAL("240896125641960") == c); + c *= 0xFFFFFFFFu; + EXPECT_TRUE(BIGINTEGER_LITERAL("1034640981124429079698200") == c); +} + +TEST(BigInteger, LeftShift) { + BigInteger a = kZero; + a <<= 1; + EXPECT_TRUE(kZero == a); + a <<= 64; + EXPECT_TRUE(kZero == a); + + a = BigInteger(123); + a <<= 0; + EXPECT_TRUE(BigInteger(123) == a); + a <<= 1; + EXPECT_TRUE(BigInteger(246) == a); + a <<= 64; + EXPECT_TRUE(BIGINTEGER_LITERAL("4537899042132549697536") == a); + a <<= 99; + EXPECT_TRUE(BIGINTEGER_LITERAL("2876235222267216943024851750785644982682875244576768") == a); +} + +TEST(BigInteger, Compare) { + EXPECT_EQ(0, kZero.Compare(kZero)); + EXPECT_EQ(1, kOne.Compare(kZero)); + EXPECT_EQ(-1, kZero.Compare(kOne)); + EXPECT_EQ(0, kUint64Max.Compare(kUint64Max)); + EXPECT_EQ(0, kTwo64.Compare(kTwo64)); + EXPECT_EQ(-1, kUint64Max.Compare(kTwo64)); + EXPECT_EQ(1, kTwo64.Compare(kUint64Max)); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/documenttest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/documenttest.cpp new file mode 100644 index 0000000000..ecd4b79bc2 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/documenttest.cpp @@ -0,0 +1,652 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/stringbuffer.h" +#include +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +RAPIDJSON_DIAG_OFF(missing-variable-declarations) +#endif + +using namespace rapidjson; + +template +void ParseCheck(DocumentType& doc) { + typedef typename DocumentType::ValueType ValueType; + + EXPECT_FALSE(doc.HasParseError()); + if (doc.HasParseError()) + printf("Error: %d at %zu\n", static_cast(doc.GetParseError()), doc.GetErrorOffset()); + EXPECT_TRUE(static_cast(doc)); + + EXPECT_TRUE(doc.IsObject()); + + EXPECT_TRUE(doc.HasMember("hello")); + const ValueType& hello = doc["hello"]; + EXPECT_TRUE(hello.IsString()); + EXPECT_STREQ("world", hello.GetString()); + + EXPECT_TRUE(doc.HasMember("t")); + const ValueType& t = doc["t"]; + EXPECT_TRUE(t.IsTrue()); + + EXPECT_TRUE(doc.HasMember("f")); + const ValueType& f = doc["f"]; + EXPECT_TRUE(f.IsFalse()); + + EXPECT_TRUE(doc.HasMember("n")); + const ValueType& n = doc["n"]; + EXPECT_TRUE(n.IsNull()); + + EXPECT_TRUE(doc.HasMember("i")); + const ValueType& i = doc["i"]; + EXPECT_TRUE(i.IsNumber()); + EXPECT_EQ(123, i.GetInt()); + + EXPECT_TRUE(doc.HasMember("pi")); + const ValueType& pi = doc["pi"]; + EXPECT_TRUE(pi.IsNumber()); + EXPECT_DOUBLE_EQ(3.1416, pi.GetDouble()); + + EXPECT_TRUE(doc.HasMember("a")); + const ValueType& a = doc["a"]; + EXPECT_TRUE(a.IsArray()); + EXPECT_EQ(4u, a.Size()); + for (SizeType j = 0; j < 4; j++) + EXPECT_EQ(j + 1, a[j].GetUint()); +} + +template +void ParseTest() { + typedef GenericDocument, Allocator, StackAllocator> DocumentType; + DocumentType doc; + + const char* json = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + + doc.Parse(json); + ParseCheck(doc); + + doc.SetNull(); + StringStream s(json); + doc.template ParseStream<0>(s); + ParseCheck(doc); + + doc.SetNull(); + char *buffer = strdup(json); + doc.ParseInsitu(buffer); + ParseCheck(doc); + free(buffer); + + // Parse(const Ch*, size_t) + size_t length = strlen(json); + buffer = reinterpret_cast(malloc(length * 2)); + memcpy(buffer, json, length); + memset(buffer + length, 'X', length); +#if RAPIDJSON_HAS_STDSTRING + std::string s2(buffer, length); // backup buffer +#endif + doc.SetNull(); + doc.Parse(buffer, length); + free(buffer); + ParseCheck(doc); + +#if RAPIDJSON_HAS_STDSTRING + // Parse(std::string) + doc.SetNull(); + doc.Parse(s2); + ParseCheck(doc); +#endif +} + +TEST(Document, Parse) { + ParseTest, CrtAllocator>(); + ParseTest, MemoryPoolAllocator<> >(); + ParseTest >(); + ParseTest(); +} + +TEST(Document, UnchangedOnParseError) { + Document doc; + doc.SetArray().PushBack(0, doc.GetAllocator()); + + ParseResult err = doc.Parse("{]"); + EXPECT_TRUE(doc.HasParseError()); + EXPECT_EQ(err.Code(), doc.GetParseError()); + EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); + EXPECT_TRUE(doc.IsArray()); + EXPECT_EQ(doc.Size(), 1u); + + err = doc.Parse("{}"); + EXPECT_FALSE(doc.HasParseError()); + EXPECT_FALSE(err.IsError()); + EXPECT_EQ(err.Code(), doc.GetParseError()); + EXPECT_EQ(err.Offset(), doc.GetErrorOffset()); + EXPECT_TRUE(doc.IsObject()); + EXPECT_EQ(doc.MemberCount(), 0u); +} + +static FILE* OpenEncodedFile(const char* filename) { + const char *paths[] = { + "encodings", + "bin/encodings", + "../bin/encodings", + "../../bin/encodings", + "../../../bin/encodings" + }; + char buffer[1024]; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s/%s", paths[i], filename); + FILE *fp = fopen(buffer, "rb"); + if (fp) + return fp; + } + return 0; +} + +TEST(Document, Parse_Encoding) { + const char* json = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; + + typedef GenericDocument > DocumentType; + DocumentType doc; + + // Parse(const SourceEncoding::Ch*) + // doc.Parse >(json); + // EXPECT_FALSE(doc.HasParseError()); + // EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); + + // Parse(const SourceEncoding::Ch*, size_t) + size_t length = strlen(json); + char* buffer = reinterpret_cast(malloc(length * 2)); + memcpy(buffer, json, length); + memset(buffer + length, 'X', length); +#if RAPIDJSON_HAS_STDSTRING + std::string s2(buffer, length); // backup buffer +#endif + doc.SetNull(); + doc.Parse >(buffer, length); + free(buffer); + EXPECT_FALSE(doc.HasParseError()); + if (doc.HasParseError()) + printf("Error: %d at %zu\n", static_cast(doc.GetParseError()), doc.GetErrorOffset()); + EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); + +#if RAPIDJSON_HAS_STDSTRING + // Parse(std::string) + doc.SetNull(); + +#if defined(_MSC_VER) && _MSC_VER < 1800 + doc.Parse >(s2.c_str()); // VS2010 or below cannot handle templated function overloading. Use const char* instead. +#else + doc.Parse >(s2); +#endif + EXPECT_FALSE(doc.HasParseError()); + EXPECT_EQ(0, StrCmp(doc[L"hello"].GetString(), L"world")); +#endif +} + +TEST(Document, ParseStream_EncodedInputStream) { + // UTF8 -> UTF16 + FILE* fp = OpenEncodedFile("utf8.json"); + char buffer[256]; + FileReadStream bis(fp, buffer, sizeof(buffer)); + EncodedInputStream, FileReadStream> eis(bis); + + GenericDocument > d; + d.ParseStream<0, UTF8<> >(eis); + EXPECT_FALSE(d.HasParseError()); + + fclose(fp); + + wchar_t expected[] = L"I can eat glass and it doesn't hurt me."; + GenericValue >& v = d[L"en"]; + EXPECT_TRUE(v.IsString()); + EXPECT_EQ(sizeof(expected) / sizeof(wchar_t) - 1, v.GetStringLength()); + EXPECT_EQ(0, StrCmp(expected, v.GetString())); + + // UTF16 -> UTF8 in memory + StringBuffer bos; + typedef EncodedOutputStream, StringBuffer> OutputStream; + OutputStream eos(bos, false); // Not writing BOM + { + Writer, UTF8<> > writer(eos); + d.Accept(writer); + } + + // Condense the original file and compare. + fp = OpenEncodedFile("utf8.json"); + FileReadStream is(fp, buffer, sizeof(buffer)); + Reader reader; + StringBuffer bos2; + Writer writer2(bos2); + reader.Parse(is, writer2); + fclose(fp); + + EXPECT_EQ(bos.GetSize(), bos2.GetSize()); + EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); +} + +TEST(Document, ParseStream_AutoUTFInputStream) { + // Any -> UTF8 + FILE* fp = OpenEncodedFile("utf32be.json"); + char buffer[256]; + FileReadStream bis(fp, buffer, sizeof(buffer)); + AutoUTFInputStream eis(bis); + + Document d; + d.ParseStream<0, AutoUTF >(eis); + EXPECT_FALSE(d.HasParseError()); + + fclose(fp); + + char expected[] = "I can eat glass and it doesn't hurt me."; + Value& v = d["en"]; + EXPECT_TRUE(v.IsString()); + EXPECT_EQ(sizeof(expected) - 1, v.GetStringLength()); + EXPECT_EQ(0, StrCmp(expected, v.GetString())); + + // UTF8 -> UTF8 in memory + StringBuffer bos; + Writer writer(bos); + d.Accept(writer); + + // Condense the original file and compare. + fp = OpenEncodedFile("utf8.json"); + FileReadStream is(fp, buffer, sizeof(buffer)); + Reader reader; + StringBuffer bos2; + Writer writer2(bos2); + reader.Parse(is, writer2); + fclose(fp); + + EXPECT_EQ(bos.GetSize(), bos2.GetSize()); + EXPECT_EQ(0, memcmp(bos.GetString(), bos2.GetString(), bos2.GetSize())); +} + +TEST(Document, Swap) { + Document d1; + Document::AllocatorType& a = d1.GetAllocator(); + + d1.SetArray().PushBack(1, a).PushBack(2, a); + + Value o; + o.SetObject().AddMember("a", 1, a); + + // Swap between Document and Value + // d1.Swap(o); // doesn't compile + o.Swap(d1); + EXPECT_TRUE(d1.IsObject()); + EXPECT_TRUE(o.IsArray()); + + // Swap between Document and Document + Document d2; + d2.SetArray().PushBack(3, a); + d1.Swap(d2); + EXPECT_TRUE(d1.IsArray()); + EXPECT_TRUE(d2.IsObject()); + EXPECT_EQ(&d2.GetAllocator(), &a); + + // reset value + Value().Swap(d1); + EXPECT_TRUE(d1.IsNull()); + + // reset document, including allocator + Document().Swap(d2); + EXPECT_TRUE(d2.IsNull()); + EXPECT_NE(&d2.GetAllocator(), &a); + + // testing std::swap compatibility + d1.SetBool(true); + using std::swap; + swap(d1, d2); + EXPECT_TRUE(d1.IsNull()); + EXPECT_TRUE(d2.IsTrue()); + + swap(o, d2); + EXPECT_TRUE(o.IsTrue()); + EXPECT_TRUE(d2.IsArray()); +} + + +// This should be slow due to assignment in inner-loop. +struct OutputStringStream : public std::ostringstream { + typedef char Ch; + + virtual ~OutputStringStream(); + + void Put(char c) { + put(c); + } + void Flush() {} +}; + +OutputStringStream::~OutputStringStream() {} + +TEST(Document, AcceptWriter) { + Document doc; + doc.Parse(" { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "); + + OutputStringStream os; + Writer writer(os); + doc.Accept(writer); + + EXPECT_EQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3,4]}", os.str()); +} + +TEST(Document, UserBuffer) { + typedef GenericDocument, MemoryPoolAllocator<>, MemoryPoolAllocator<> > DocumentType; + char valueBuffer[4096]; + char parseBuffer[1024]; + MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer)); + MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer)); + DocumentType doc(&valueAllocator, sizeof(parseBuffer) / 2, &parseAllocator); + doc.Parse(" { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "); + EXPECT_FALSE(doc.HasParseError()); + EXPECT_LE(valueAllocator.Size(), sizeof(valueBuffer)); + EXPECT_LE(parseAllocator.Size(), sizeof(parseBuffer)); + + // Cover MemoryPoolAllocator::Capacity() + EXPECT_LE(valueAllocator.Size(), valueAllocator.Capacity()); + EXPECT_LE(parseAllocator.Size(), parseAllocator.Capacity()); +} + +// Issue 226: Value of string type should not point to NULL +TEST(Document, AssertAcceptInvalidNameType) { + Document doc; + doc.SetObject(); + doc.AddMember("a", 0, doc.GetAllocator()); + doc.FindMember("a")->name.SetNull(); // Change name to non-string type. + + OutputStringStream os; + Writer writer(os); + ASSERT_THROW(doc.Accept(writer), AssertException); +} + +// Issue 44: SetStringRaw doesn't work with wchar_t +TEST(Document, UTF16_Document) { + GenericDocument< UTF16<> > json; + json.Parse(L"[{\"created_at\":\"Wed Oct 30 17:13:20 +0000 2012\"}]"); + + ASSERT_TRUE(json.IsArray()); + GenericValue< UTF16<> >& v = json[0]; + ASSERT_TRUE(v.IsObject()); + + GenericValue< UTF16<> >& s = v[L"created_at"]; + ASSERT_TRUE(s.IsString()); + + EXPECT_EQ(0, memcmp(L"Wed Oct 30 17:13:20 +0000 2012", s.GetString(), (s.GetStringLength() + 1) * sizeof(wchar_t))); +} + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + +#if 0 // Many old compiler does not support these. Turn it off temporaily. + +#include + +TEST(Document, Traits) { + static_assert(std::is_constructible::value, ""); + static_assert(std::is_default_constructible::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_constructible::value, ""); +#endif + static_assert(std::is_move_constructible::value, ""); + + static_assert(!std::is_nothrow_constructible::value, ""); + static_assert(!std::is_nothrow_default_constructible::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_nothrow_copy_constructible::value, ""); + static_assert(std::is_nothrow_move_constructible::value, ""); +#endif + + static_assert(std::is_assignable::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_assignable::value, ""); +#endif + static_assert(std::is_move_assignable::value, ""); + +#ifndef _MSC_VER + static_assert(std::is_nothrow_assignable::value, ""); +#endif + static_assert(!std::is_nothrow_copy_assignable::value, ""); +#ifndef _MSC_VER + static_assert(std::is_nothrow_move_assignable::value, ""); +#endif + + static_assert( std::is_destructible::value, ""); +#ifndef _MSC_VER + static_assert(std::is_nothrow_destructible::value, ""); +#endif +} + +#endif + +template +struct DocumentMove: public ::testing::Test { +}; + +typedef ::testing::Types< CrtAllocator, MemoryPoolAllocator<> > MoveAllocatorTypes; +TYPED_TEST_CASE(DocumentMove, MoveAllocatorTypes); + +TYPED_TEST(DocumentMove, MoveConstructor) { + typedef TypeParam Allocator; + typedef GenericDocument, Allocator> D; + Allocator allocator; + + D a(&allocator); + a.Parse("[\"one\", \"two\", \"three\"]"); + EXPECT_FALSE(a.HasParseError()); + EXPECT_TRUE(a.IsArray()); + EXPECT_EQ(3u, a.Size()); + EXPECT_EQ(&a.GetAllocator(), &allocator); + + // Document b(a); // does not compile (!is_copy_constructible) + D b(std::move(a)); + EXPECT_TRUE(a.IsNull()); + EXPECT_TRUE(b.IsArray()); + EXPECT_EQ(3u, b.Size()); + EXPECT_THROW(a.GetAllocator(), AssertException); + EXPECT_EQ(&b.GetAllocator(), &allocator); + + b.Parse("{\"Foo\": \"Bar\", \"Baz\": 42}"); + EXPECT_FALSE(b.HasParseError()); + EXPECT_TRUE(b.IsObject()); + EXPECT_EQ(2u, b.MemberCount()); + + // Document c = a; // does not compile (!is_copy_constructible) + D c = std::move(b); + EXPECT_TRUE(b.IsNull()); + EXPECT_TRUE(c.IsObject()); + EXPECT_EQ(2u, c.MemberCount()); + EXPECT_THROW(b.GetAllocator(), AssertException); + EXPECT_EQ(&c.GetAllocator(), &allocator); +} + +TYPED_TEST(DocumentMove, MoveConstructorParseError) { + typedef TypeParam Allocator; + typedef GenericDocument, Allocator> D; + + ParseResult noError; + D a; + a.Parse("{ 4 = 4]"); + ParseResult error(a.GetParseError(), a.GetErrorOffset()); + EXPECT_TRUE(a.HasParseError()); + EXPECT_NE(error.Code(), noError.Code()); + EXPECT_NE(error.Offset(), noError.Offset()); + + D b(std::move(a)); + EXPECT_FALSE(a.HasParseError()); + EXPECT_TRUE(b.HasParseError()); + EXPECT_EQ(a.GetParseError(), noError.Code()); + EXPECT_EQ(b.GetParseError(), error.Code()); + EXPECT_EQ(a.GetErrorOffset(), noError.Offset()); + EXPECT_EQ(b.GetErrorOffset(), error.Offset()); + + D c(std::move(b)); + EXPECT_FALSE(b.HasParseError()); + EXPECT_TRUE(c.HasParseError()); + EXPECT_EQ(b.GetParseError(), noError.Code()); + EXPECT_EQ(c.GetParseError(), error.Code()); + EXPECT_EQ(b.GetErrorOffset(), noError.Offset()); + EXPECT_EQ(c.GetErrorOffset(), error.Offset()); +} + +// This test does not properly use parsing, just for testing. +// It must call ClearStack() explicitly to prevent memory leak. +// But here we cannot as ClearStack() is private. +#if 0 +TYPED_TEST(DocumentMove, MoveConstructorStack) { + typedef TypeParam Allocator; + typedef UTF8<> Encoding; + typedef GenericDocument Document; + + Document a; + size_t defaultCapacity = a.GetStackCapacity(); + + // Trick Document into getting GetStackCapacity() to return non-zero + typedef GenericReader Reader; + Reader reader(&a.GetAllocator()); + GenericStringStream is("[\"one\", \"two\", \"three\"]"); + reader.template Parse(is, a); + size_t capacity = a.GetStackCapacity(); + EXPECT_GT(capacity, 0u); + + Document b(std::move(a)); + EXPECT_EQ(a.GetStackCapacity(), defaultCapacity); + EXPECT_EQ(b.GetStackCapacity(), capacity); + + Document c = std::move(b); + EXPECT_EQ(b.GetStackCapacity(), defaultCapacity); + EXPECT_EQ(c.GetStackCapacity(), capacity); +} +#endif + +TYPED_TEST(DocumentMove, MoveAssignment) { + typedef TypeParam Allocator; + typedef GenericDocument, Allocator> D; + Allocator allocator; + + D a(&allocator); + a.Parse("[\"one\", \"two\", \"three\"]"); + EXPECT_FALSE(a.HasParseError()); + EXPECT_TRUE(a.IsArray()); + EXPECT_EQ(3u, a.Size()); + EXPECT_EQ(&a.GetAllocator(), &allocator); + + // Document b; b = a; // does not compile (!is_copy_assignable) + D b; + b = std::move(a); + EXPECT_TRUE(a.IsNull()); + EXPECT_TRUE(b.IsArray()); + EXPECT_EQ(3u, b.Size()); + EXPECT_THROW(a.GetAllocator(), AssertException); + EXPECT_EQ(&b.GetAllocator(), &allocator); + + b.Parse("{\"Foo\": \"Bar\", \"Baz\": 42}"); + EXPECT_FALSE(b.HasParseError()); + EXPECT_TRUE(b.IsObject()); + EXPECT_EQ(2u, b.MemberCount()); + + // Document c; c = a; // does not compile (see static_assert) + D c; + c = std::move(b); + EXPECT_TRUE(b.IsNull()); + EXPECT_TRUE(c.IsObject()); + EXPECT_EQ(2u, c.MemberCount()); + EXPECT_THROW(b.GetAllocator(), AssertException); + EXPECT_EQ(&c.GetAllocator(), &allocator); +} + +TYPED_TEST(DocumentMove, MoveAssignmentParseError) { + typedef TypeParam Allocator; + typedef GenericDocument, Allocator> D; + + ParseResult noError; + D a; + a.Parse("{ 4 = 4]"); + ParseResult error(a.GetParseError(), a.GetErrorOffset()); + EXPECT_TRUE(a.HasParseError()); + EXPECT_NE(error.Code(), noError.Code()); + EXPECT_NE(error.Offset(), noError.Offset()); + + D b; + b = std::move(a); + EXPECT_FALSE(a.HasParseError()); + EXPECT_TRUE(b.HasParseError()); + EXPECT_EQ(a.GetParseError(), noError.Code()); + EXPECT_EQ(b.GetParseError(), error.Code()); + EXPECT_EQ(a.GetErrorOffset(), noError.Offset()); + EXPECT_EQ(b.GetErrorOffset(), error.Offset()); + + D c; + c = std::move(b); + EXPECT_FALSE(b.HasParseError()); + EXPECT_TRUE(c.HasParseError()); + EXPECT_EQ(b.GetParseError(), noError.Code()); + EXPECT_EQ(c.GetParseError(), error.Code()); + EXPECT_EQ(b.GetErrorOffset(), noError.Offset()); + EXPECT_EQ(c.GetErrorOffset(), error.Offset()); +} + +// This test does not properly use parsing, just for testing. +// It must call ClearStack() explicitly to prevent memory leak. +// But here we cannot as ClearStack() is private. +#if 0 +TYPED_TEST(DocumentMove, MoveAssignmentStack) { + typedef TypeParam Allocator; + typedef UTF8<> Encoding; + typedef GenericDocument D; + + D a; + size_t defaultCapacity = a.GetStackCapacity(); + + // Trick Document into getting GetStackCapacity() to return non-zero + typedef GenericReader Reader; + Reader reader(&a.GetAllocator()); + GenericStringStream is("[\"one\", \"two\", \"three\"]"); + reader.template Parse(is, a); + size_t capacity = a.GetStackCapacity(); + EXPECT_GT(capacity, 0u); + + D b; + b = std::move(a); + EXPECT_EQ(a.GetStackCapacity(), defaultCapacity); + EXPECT_EQ(b.GetStackCapacity(), capacity); + + D c; + c = std::move(b); + EXPECT_EQ(b.GetStackCapacity(), defaultCapacity); + EXPECT_EQ(c.GetStackCapacity(), capacity); +} +#endif + +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + +// Issue 22: Memory corruption via operator= +// Fixed by making unimplemented assignment operator private. +//TEST(Document, Assignment) { +// Document d1; +// Document d2; +// d1 = d2; +//} + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/dtoatest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/dtoatest.cpp new file mode 100644 index 0000000000..afd76eb09a --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/dtoatest.cpp @@ -0,0 +1,98 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/internal/dtoa.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(type-limits) +#endif + +using namespace rapidjson::internal; + +TEST(dtoa, normal) { + char buffer[30]; + +#define TEST_DTOA(d, a)\ + *dtoa(d, buffer) = '\0';\ + EXPECT_STREQ(a, buffer) + + TEST_DTOA(0.0, "0.0"); + TEST_DTOA(-0.0, "-0.0"); + TEST_DTOA(1.0, "1.0"); + TEST_DTOA(-1.0, "-1.0"); + TEST_DTOA(1.2345, "1.2345"); + TEST_DTOA(1.2345678, "1.2345678"); + TEST_DTOA(0.123456789012, "0.123456789012"); + TEST_DTOA(1234567.8, "1234567.8"); + TEST_DTOA(-79.39773355813419, "-79.39773355813419"); + TEST_DTOA(0.000001, "0.000001"); + TEST_DTOA(0.0000001, "1e-7"); + TEST_DTOA(1e30, "1e30"); + TEST_DTOA(1.234567890123456e30, "1.234567890123456e30"); + TEST_DTOA(5e-324, "5e-324"); // Min subnormal positive double + TEST_DTOA(2.225073858507201e-308, "2.225073858507201e-308"); // Max subnormal positive double + TEST_DTOA(2.2250738585072014e-308, "2.2250738585072014e-308"); // Min normal positive double + TEST_DTOA(1.7976931348623157e308, "1.7976931348623157e308"); // Max double + +#undef TEST_DTOA +} + +TEST(dtoa, maxDecimalPlaces) { + char buffer[30]; + +#define TEST_DTOA(m, d, a)\ + *dtoa(d, buffer, m) = '\0';\ + EXPECT_STREQ(a, buffer) + + TEST_DTOA(3, 0.0, "0.0"); + TEST_DTOA(1, 0.0, "0.0"); + TEST_DTOA(3, -0.0, "-0.0"); + TEST_DTOA(3, 1.0, "1.0"); + TEST_DTOA(3, -1.0, "-1.0"); + TEST_DTOA(3, 1.2345, "1.234"); + TEST_DTOA(2, 1.2345, "1.23"); + TEST_DTOA(1, 1.2345, "1.2"); + TEST_DTOA(3, 1.2345678, "1.234"); + TEST_DTOA(3, 1.0001, "1.0"); + TEST_DTOA(2, 1.0001, "1.0"); + TEST_DTOA(1, 1.0001, "1.0"); + TEST_DTOA(3, 0.123456789012, "0.123"); + TEST_DTOA(2, 0.123456789012, "0.12"); + TEST_DTOA(1, 0.123456789012, "0.1"); + TEST_DTOA(4, 0.0001, "0.0001"); + TEST_DTOA(3, 0.0001, "0.0"); + TEST_DTOA(2, 0.0001, "0.0"); + TEST_DTOA(1, 0.0001, "0.0"); + TEST_DTOA(3, 1234567.8, "1234567.8"); + TEST_DTOA(3, 1e30, "1e30"); + TEST_DTOA(3, 5e-324, "0.0"); // Min subnormal positive double + TEST_DTOA(3, 2.225073858507201e-308, "0.0"); // Max subnormal positive double + TEST_DTOA(3, 2.2250738585072014e-308, "0.0"); // Min normal positive double + TEST_DTOA(3, 1.7976931348623157e308, "1.7976931348623157e308"); // Max double + TEST_DTOA(5, -0.14000000000000001, "-0.14"); + TEST_DTOA(4, -0.14000000000000001, "-0.14"); + TEST_DTOA(3, -0.14000000000000001, "-0.14"); + TEST_DTOA(3, -0.10000000000000001, "-0.1"); + TEST_DTOA(2, -0.10000000000000001, "-0.1"); + TEST_DTOA(1, -0.10000000000000001, "-0.1"); + +#undef TEST_DTOA +} + + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/encodedstreamtest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/encodedstreamtest.cpp new file mode 100644 index 0000000000..bc234d3ba7 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/encodedstreamtest.cpp @@ -0,0 +1,313 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/memorystream.h" +#include "rapidjson/memorybuffer.h" + +using namespace rapidjson; + +class EncodedStreamTest : public ::testing::Test { +public: + EncodedStreamTest() : json_(), length_() {} + virtual ~EncodedStreamTest(); + + virtual void SetUp() { + json_ = ReadFile("utf8.json", true, &length_); + } + + virtual void TearDown() { + free(json_); + json_ = 0; + } + +private: + EncodedStreamTest(const EncodedStreamTest&); + EncodedStreamTest& operator=(const EncodedStreamTest&); + +protected: + static FILE* Open(const char* filename) { + const char *paths[] = { + "encodings", + "bin/encodings", + "../bin/encodings", + "../../bin/encodings", + "../../../bin/encodings" + }; + char buffer[1024]; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s/%s", paths[i], filename); + FILE *fp = fopen(buffer, "rb"); + if (fp) + return fp; + } + return 0; + } + + static char *ReadFile(const char* filename, bool appendPath, size_t* outLength) { + FILE *fp = appendPath ? Open(filename) : fopen(filename, "rb"); + + if (!fp) { + *outLength = 0; + return 0; + } + + fseek(fp, 0, SEEK_END); + *outLength = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + char* buffer = static_cast(malloc(*outLength + 1)); + size_t readLength = fread(buffer, 1, *outLength, fp); + buffer[readLength] = '\0'; + fclose(fp); + return buffer; + } + + template + void TestEncodedInputStream(const char* filename) { + // Test FileReadStream + { + char buffer[16]; + FILE *fp = Open(filename); + ASSERT_TRUE(fp != 0); + FileReadStream fs(fp, buffer, sizeof(buffer)); + EncodedInputStream eis(fs); + StringStream s(json_); + + while (eis.Peek() != '\0') { + unsigned expected, actual; + EXPECT_TRUE(UTF8<>::Decode(s, &expected)); + EXPECT_TRUE(MemoryEncoding::Decode(eis, &actual)); + EXPECT_EQ(expected, actual); + } + EXPECT_EQ('\0', s.Peek()); + fclose(fp); + } + + // Test MemoryStream + { + size_t size; + char* data = ReadFile(filename, true, &size); + MemoryStream ms(data, size); + EncodedInputStream eis(ms); + StringStream s(json_); + + while (eis.Peek() != '\0') { + unsigned expected, actual; + EXPECT_TRUE(UTF8<>::Decode(s, &expected)); + EXPECT_TRUE(MemoryEncoding::Decode(eis, &actual)); + EXPECT_EQ(expected, actual); + } + EXPECT_EQ('\0', s.Peek()); + free(data); + EXPECT_EQ(size, eis.Tell()); + } + } + + void TestAutoUTFInputStream(const char *filename, bool expectHasBOM) { + // Test FileReadStream + { + char buffer[16]; + FILE *fp = Open(filename); + ASSERT_TRUE(fp != 0); + FileReadStream fs(fp, buffer, sizeof(buffer)); + AutoUTFInputStream eis(fs); + EXPECT_EQ(expectHasBOM, eis.HasBOM()); + StringStream s(json_); + while (eis.Peek() != '\0') { + unsigned expected, actual; + EXPECT_TRUE(UTF8<>::Decode(s, &expected)); + EXPECT_TRUE(AutoUTF::Decode(eis, &actual)); + EXPECT_EQ(expected, actual); + } + EXPECT_EQ('\0', s.Peek()); + fclose(fp); + } + + // Test MemoryStream + { + size_t size; + char* data = ReadFile(filename, true, &size); + MemoryStream ms(data, size); + AutoUTFInputStream eis(ms); + EXPECT_EQ(expectHasBOM, eis.HasBOM()); + StringStream s(json_); + + while (eis.Peek() != '\0') { + unsigned expected, actual; + EXPECT_TRUE(UTF8<>::Decode(s, &expected)); + EXPECT_TRUE(AutoUTF::Decode(eis, &actual)); + EXPECT_EQ(expected, actual); + } + EXPECT_EQ('\0', s.Peek()); + free(data); + EXPECT_EQ(size, eis.Tell()); + } + } + + template + void TestEncodedOutputStream(const char* expectedFilename, bool putBOM) { + // Test FileWriteStream + { + char filename[L_tmpnam]; + FILE* fp = TempFile(filename); + char buffer[16]; + FileWriteStream os(fp, buffer, sizeof(buffer)); + EncodedOutputStream eos(os, putBOM); + StringStream s(json_); + while (s.Peek() != '\0') { + bool success = Transcoder, MemoryEncoding>::Transcode(s, eos); + EXPECT_TRUE(success); + } + eos.Flush(); + fclose(fp); + EXPECT_TRUE(CompareFile(filename, expectedFilename)); + remove(filename); + } + + // Test MemoryBuffer + { + MemoryBuffer mb; + EncodedOutputStream eos(mb, putBOM); + StringStream s(json_); + while (s.Peek() != '\0') { + bool success = Transcoder, MemoryEncoding>::Transcode(s, eos); + EXPECT_TRUE(success); + } + eos.Flush(); + EXPECT_TRUE(CompareBufferFile(mb.GetBuffer(), mb.GetSize(), expectedFilename)); + } + } + + void TestAutoUTFOutputStream(UTFType type, bool putBOM, const char *expectedFilename) { + // Test FileWriteStream + { + char filename[L_tmpnam]; + FILE* fp = TempFile(filename); + + char buffer[16]; + FileWriteStream os(fp, buffer, sizeof(buffer)); + AutoUTFOutputStream eos(os, type, putBOM); + StringStream s(json_); + while (s.Peek() != '\0') { + bool success = Transcoder, AutoUTF >::Transcode(s, eos); + EXPECT_TRUE(success); + } + eos.Flush(); + fclose(fp); + EXPECT_TRUE(CompareFile(filename, expectedFilename)); + remove(filename); + } + + // Test MemoryBuffer + { + MemoryBuffer mb; + AutoUTFOutputStream eos(mb, type, putBOM); + StringStream s(json_); + while (s.Peek() != '\0') { + bool success = Transcoder, AutoUTF >::Transcode(s, eos); + EXPECT_TRUE(success); + } + eos.Flush(); + EXPECT_TRUE(CompareBufferFile(mb.GetBuffer(), mb.GetSize(), expectedFilename)); + } + } + + bool CompareFile(const char* filename, const char* expectedFilename) { + size_t actualLength, expectedLength; + char* actualBuffer = ReadFile(filename, false, &actualLength); + char* expectedBuffer = ReadFile(expectedFilename, true, &expectedLength); + bool ret = (expectedLength == actualLength) && memcmp(expectedBuffer, actualBuffer, actualLength) == 0; + free(actualBuffer); + free(expectedBuffer); + return ret; + } + + bool CompareBufferFile(const char* actualBuffer, size_t actualLength, const char* expectedFilename) { + size_t expectedLength; + char* expectedBuffer = ReadFile(expectedFilename, true, &expectedLength); + bool ret = (expectedLength == actualLength) && memcmp(expectedBuffer, actualBuffer, actualLength) == 0; + free(expectedBuffer); + return ret; + } + + char *json_; + size_t length_; +}; + +EncodedStreamTest::~EncodedStreamTest() {} + +TEST_F(EncodedStreamTest, EncodedInputStream) { + TestEncodedInputStream, UTF8<> >("utf8.json"); + TestEncodedInputStream, UTF8<> >("utf8bom.json"); + TestEncodedInputStream, UTF16<> >("utf16le.json"); + TestEncodedInputStream, UTF16<> >("utf16lebom.json"); + TestEncodedInputStream, UTF16<> >("utf16be.json"); + TestEncodedInputStream, UTF16<> >("utf16bebom.json"); + TestEncodedInputStream, UTF32<> >("utf32le.json"); + TestEncodedInputStream, UTF32<> >("utf32lebom.json"); + TestEncodedInputStream, UTF32<> >("utf32be.json"); + TestEncodedInputStream, UTF32<> >("utf32bebom.json"); +} + +TEST_F(EncodedStreamTest, AutoUTFInputStream) { + TestAutoUTFInputStream("utf8.json", false); + TestAutoUTFInputStream("utf8bom.json", true); + TestAutoUTFInputStream("utf16le.json", false); + TestAutoUTFInputStream("utf16lebom.json",true); + TestAutoUTFInputStream("utf16be.json", false); + TestAutoUTFInputStream("utf16bebom.json",true); + TestAutoUTFInputStream("utf32le.json", false); + TestAutoUTFInputStream("utf32lebom.json",true); + TestAutoUTFInputStream("utf32be.json", false); + TestAutoUTFInputStream("utf32bebom.json", true); + + { + // Auto detection fail, use user defined UTF type + const char json[] = "{ }"; + MemoryStream ms(json, sizeof(json)); + AutoUTFInputStream eis(ms, kUTF8); + EXPECT_FALSE(eis.HasBOM()); + EXPECT_EQ(kUTF8, eis.GetType()); + } +} + +TEST_F(EncodedStreamTest, EncodedOutputStream) { + TestEncodedOutputStream, UTF8<> >("utf8.json", false); + TestEncodedOutputStream, UTF8<> >("utf8bom.json", true); + TestEncodedOutputStream, UTF16<> >("utf16le.json", false); + TestEncodedOutputStream, UTF16<> >("utf16lebom.json",true); + TestEncodedOutputStream, UTF16<> >("utf16be.json", false); + TestEncodedOutputStream, UTF16<> >("utf16bebom.json",true); + TestEncodedOutputStream, UTF32<> >("utf32le.json", false); + TestEncodedOutputStream, UTF32<> >("utf32lebom.json",true); + TestEncodedOutputStream, UTF32<> >("utf32be.json", false); + TestEncodedOutputStream, UTF32<> >("utf32bebom.json",true); +} + +TEST_F(EncodedStreamTest, AutoUTFOutputStream) { + TestAutoUTFOutputStream(kUTF8, false, "utf8.json"); + TestAutoUTFOutputStream(kUTF8, true, "utf8bom.json"); + TestAutoUTFOutputStream(kUTF16LE, false, "utf16le.json"); + TestAutoUTFOutputStream(kUTF16LE, true, "utf16lebom.json"); + TestAutoUTFOutputStream(kUTF16BE, false, "utf16be.json"); + TestAutoUTFOutputStream(kUTF16BE, true, "utf16bebom.json"); + TestAutoUTFOutputStream(kUTF32LE, false, "utf32le.json"); + TestAutoUTFOutputStream(kUTF32LE, true, "utf32lebom.json"); + TestAutoUTFOutputStream(kUTF32BE, false, "utf32be.json"); + TestAutoUTFOutputStream(kUTF32BE, true, "utf32bebom.json"); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/encodingstest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/encodingstest.cpp new file mode 100644 index 0000000000..67b0391ed0 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/encodingstest.cpp @@ -0,0 +1,451 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/stringbuffer.h" + +using namespace rapidjson; + +// Verification of encoders/decoders with Hoehrmann's UTF8 decoder + +// http://www.unicode.org/Public/UNIDATA/Blocks.txt +static const unsigned kCodepointRanges[] = { + 0x0000, 0x007F, // Basic Latin + 0x0080, 0x00FF, // Latin-1 Supplement + 0x0100, 0x017F, // Latin Extended-A + 0x0180, 0x024F, // Latin Extended-B + 0x0250, 0x02AF, // IPA Extensions + 0x02B0, 0x02FF, // Spacing Modifier Letters + 0x0300, 0x036F, // Combining Diacritical Marks + 0x0370, 0x03FF, // Greek and Coptic + 0x0400, 0x04FF, // Cyrillic + 0x0500, 0x052F, // Cyrillic Supplement + 0x0530, 0x058F, // Armenian + 0x0590, 0x05FF, // Hebrew + 0x0600, 0x06FF, // Arabic + 0x0700, 0x074F, // Syriac + 0x0750, 0x077F, // Arabic Supplement + 0x0780, 0x07BF, // Thaana + 0x07C0, 0x07FF, // NKo + 0x0800, 0x083F, // Samaritan + 0x0840, 0x085F, // Mandaic + 0x0900, 0x097F, // Devanagari + 0x0980, 0x09FF, // Bengali + 0x0A00, 0x0A7F, // Gurmukhi + 0x0A80, 0x0AFF, // Gujarati + 0x0B00, 0x0B7F, // Oriya + 0x0B80, 0x0BFF, // Tamil + 0x0C00, 0x0C7F, // Telugu + 0x0C80, 0x0CFF, // Kannada + 0x0D00, 0x0D7F, // Malayalam + 0x0D80, 0x0DFF, // Sinhala + 0x0E00, 0x0E7F, // Thai + 0x0E80, 0x0EFF, // Lao + 0x0F00, 0x0FFF, // Tibetan + 0x1000, 0x109F, // Myanmar + 0x10A0, 0x10FF, // Georgian + 0x1100, 0x11FF, // Hangul Jamo + 0x1200, 0x137F, // Ethiopic + 0x1380, 0x139F, // Ethiopic Supplement + 0x13A0, 0x13FF, // Cherokee + 0x1400, 0x167F, // Unified Canadian Aboriginal Syllabics + 0x1680, 0x169F, // Ogham + 0x16A0, 0x16FF, // Runic + 0x1700, 0x171F, // Tagalog + 0x1720, 0x173F, // Hanunoo + 0x1740, 0x175F, // Buhid + 0x1760, 0x177F, // Tagbanwa + 0x1780, 0x17FF, // Khmer + 0x1800, 0x18AF, // Mongolian + 0x18B0, 0x18FF, // Unified Canadian Aboriginal Syllabics Extended + 0x1900, 0x194F, // Limbu + 0x1950, 0x197F, // Tai Le + 0x1980, 0x19DF, // New Tai Lue + 0x19E0, 0x19FF, // Khmer Symbols + 0x1A00, 0x1A1F, // Buginese + 0x1A20, 0x1AAF, // Tai Tham + 0x1B00, 0x1B7F, // Balinese + 0x1B80, 0x1BBF, // Sundanese + 0x1BC0, 0x1BFF, // Batak + 0x1C00, 0x1C4F, // Lepcha + 0x1C50, 0x1C7F, // Ol Chiki + 0x1CD0, 0x1CFF, // Vedic Extensions + 0x1D00, 0x1D7F, // Phonetic Extensions + 0x1D80, 0x1DBF, // Phonetic Extensions Supplement + 0x1DC0, 0x1DFF, // Combining Diacritical Marks Supplement + 0x1E00, 0x1EFF, // Latin Extended Additional + 0x1F00, 0x1FFF, // Greek Extended + 0x2000, 0x206F, // General Punctuation + 0x2070, 0x209F, // Superscripts and Subscripts + 0x20A0, 0x20CF, // Currency Symbols + 0x20D0, 0x20FF, // Combining Diacritical Marks for Symbols + 0x2100, 0x214F, // Letterlike Symbols + 0x2150, 0x218F, // Number Forms + 0x2190, 0x21FF, // Arrows + 0x2200, 0x22FF, // Mathematical Operators + 0x2300, 0x23FF, // Miscellaneous Technical + 0x2400, 0x243F, // Control Pictures + 0x2440, 0x245F, // Optical Character Recognition + 0x2460, 0x24FF, // Enclosed Alphanumerics + 0x2500, 0x257F, // Box Drawing + 0x2580, 0x259F, // Block Elements + 0x25A0, 0x25FF, // Geometric Shapes + 0x2600, 0x26FF, // Miscellaneous Symbols + 0x2700, 0x27BF, // Dingbats + 0x27C0, 0x27EF, // Miscellaneous Mathematical Symbols-A + 0x27F0, 0x27FF, // Supplemental Arrows-A + 0x2800, 0x28FF, // Braille Patterns + 0x2900, 0x297F, // Supplemental Arrows-B + 0x2980, 0x29FF, // Miscellaneous Mathematical Symbols-B + 0x2A00, 0x2AFF, // Supplemental Mathematical Operators + 0x2B00, 0x2BFF, // Miscellaneous Symbols and Arrows + 0x2C00, 0x2C5F, // Glagolitic + 0x2C60, 0x2C7F, // Latin Extended-C + 0x2C80, 0x2CFF, // Coptic + 0x2D00, 0x2D2F, // Georgian Supplement + 0x2D30, 0x2D7F, // Tifinagh + 0x2D80, 0x2DDF, // Ethiopic Extended + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0x2E00, 0x2E7F, // Supplemental Punctuation + 0x2E80, 0x2EFF, // CJK Radicals Supplement + 0x2F00, 0x2FDF, // Kangxi Radicals + 0x2FF0, 0x2FFF, // Ideographic Description Characters + 0x3000, 0x303F, // CJK Symbols and Punctuation + 0x3040, 0x309F, // Hiragana + 0x30A0, 0x30FF, // Katakana + 0x3100, 0x312F, // Bopomofo + 0x3130, 0x318F, // Hangul Compatibility Jamo + 0x3190, 0x319F, // Kanbun + 0x31A0, 0x31BF, // Bopomofo Extended + 0x31C0, 0x31EF, // CJK Strokes + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0x3200, 0x32FF, // Enclosed CJK Letters and Months + 0x3300, 0x33FF, // CJK Compatibility + 0x3400, 0x4DBF, // CJK Unified Ideographs Extension A + 0x4DC0, 0x4DFF, // Yijing Hexagram Symbols + 0x4E00, 0x9FFF, // CJK Unified Ideographs + 0xA000, 0xA48F, // Yi Syllables + 0xA490, 0xA4CF, // Yi Radicals + 0xA4D0, 0xA4FF, // Lisu + 0xA500, 0xA63F, // Vai + 0xA640, 0xA69F, // Cyrillic Extended-B + 0xA6A0, 0xA6FF, // Bamum + 0xA700, 0xA71F, // Modifier Tone Letters + 0xA720, 0xA7FF, // Latin Extended-D + 0xA800, 0xA82F, // Syloti Nagri + 0xA830, 0xA83F, // Common Indic Number Forms + 0xA840, 0xA87F, // Phags-pa + 0xA880, 0xA8DF, // Saurashtra + 0xA8E0, 0xA8FF, // Devanagari Extended + 0xA900, 0xA92F, // Kayah Li + 0xA930, 0xA95F, // Rejang + 0xA960, 0xA97F, // Hangul Jamo Extended-A + 0xA980, 0xA9DF, // Javanese + 0xAA00, 0xAA5F, // Cham + 0xAA60, 0xAA7F, // Myanmar Extended-A + 0xAA80, 0xAADF, // Tai Viet + 0xAB00, 0xAB2F, // Ethiopic Extended-A + 0xABC0, 0xABFF, // Meetei Mayek + 0xAC00, 0xD7AF, // Hangul Syllables + 0xD7B0, 0xD7FF, // Hangul Jamo Extended-B + //0xD800, 0xDB7F, // High Surrogates + //0xDB80, 0xDBFF, // High Private Use Surrogates + //0xDC00, 0xDFFF, // Low Surrogates + 0xE000, 0xF8FF, // Private Use Area + 0xF900, 0xFAFF, // CJK Compatibility Ideographs + 0xFB00, 0xFB4F, // Alphabetic Presentation Forms + 0xFB50, 0xFDFF, // Arabic Presentation Forms-A + 0xFE00, 0xFE0F, // Variation Selectors + 0xFE10, 0xFE1F, // Vertical Forms + 0xFE20, 0xFE2F, // Combining Half Marks + 0xFE30, 0xFE4F, // CJK Compatibility Forms + 0xFE50, 0xFE6F, // Small Form Variants + 0xFE70, 0xFEFF, // Arabic Presentation Forms-B + 0xFF00, 0xFFEF, // Halfwidth and Fullwidth Forms + 0xFFF0, 0xFFFF, // Specials + 0x10000, 0x1007F, // Linear B Syllabary + 0x10080, 0x100FF, // Linear B Ideograms + 0x10100, 0x1013F, // Aegean Numbers + 0x10140, 0x1018F, // Ancient Greek Numbers + 0x10190, 0x101CF, // Ancient Symbols + 0x101D0, 0x101FF, // Phaistos Disc + 0x10280, 0x1029F, // Lycian + 0x102A0, 0x102DF, // Carian + 0x10300, 0x1032F, // Old Italic + 0x10330, 0x1034F, // Gothic + 0x10380, 0x1039F, // Ugaritic + 0x103A0, 0x103DF, // Old Persian + 0x10400, 0x1044F, // Deseret + 0x10450, 0x1047F, // Shavian + 0x10480, 0x104AF, // Osmanya + 0x10800, 0x1083F, // Cypriot Syllabary + 0x10840, 0x1085F, // Imperial Aramaic + 0x10900, 0x1091F, // Phoenician + 0x10920, 0x1093F, // Lydian + 0x10A00, 0x10A5F, // Kharoshthi + 0x10A60, 0x10A7F, // Old South Arabian + 0x10B00, 0x10B3F, // Avestan + 0x10B40, 0x10B5F, // Inscriptional Parthian + 0x10B60, 0x10B7F, // Inscriptional Pahlavi + 0x10C00, 0x10C4F, // Old Turkic + 0x10E60, 0x10E7F, // Rumi Numeral Symbols + 0x11000, 0x1107F, // Brahmi + 0x11080, 0x110CF, // Kaithi + 0x12000, 0x123FF, // Cuneiform + 0x12400, 0x1247F, // Cuneiform Numbers and Punctuation + 0x13000, 0x1342F, // Egyptian Hieroglyphs + 0x16800, 0x16A3F, // Bamum Supplement + 0x1B000, 0x1B0FF, // Kana Supplement + 0x1D000, 0x1D0FF, // Byzantine Musical Symbols + 0x1D100, 0x1D1FF, // Musical Symbols + 0x1D200, 0x1D24F, // Ancient Greek Musical Notation + 0x1D300, 0x1D35F, // Tai Xuan Jing Symbols + 0x1D360, 0x1D37F, // Counting Rod Numerals + 0x1D400, 0x1D7FF, // Mathematical Alphanumeric Symbols + 0x1F000, 0x1F02F, // Mahjong Tiles + 0x1F030, 0x1F09F, // Domino Tiles + 0x1F0A0, 0x1F0FF, // Playing Cards + 0x1F100, 0x1F1FF, // Enclosed Alphanumeric Supplement + 0x1F200, 0x1F2FF, // Enclosed Ideographic Supplement + 0x1F300, 0x1F5FF, // Miscellaneous Symbols And Pictographs + 0x1F600, 0x1F64F, // Emoticons + 0x1F680, 0x1F6FF, // Transport And Map Symbols + 0x1F700, 0x1F77F, // Alchemical Symbols + 0x20000, 0x2A6DF, // CJK Unified Ideographs Extension B + 0x2A700, 0x2B73F, // CJK Unified Ideographs Extension C + 0x2B740, 0x2B81F, // CJK Unified Ideographs Extension D + 0x2F800, 0x2FA1F, // CJK Compatibility Ideographs Supplement + 0xE0000, 0xE007F, // Tags + 0xE0100, 0xE01EF, // Variation Selectors Supplement + 0xF0000, 0xFFFFF, // Supplementary Private Use Area-A + 0x100000, 0x10FFFF, // Supplementary Private Use Area-B + 0xFFFFFFFF +}; + +// Copyright (c) 2008-2010 Bjoern Hoehrmann +// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details. + +#define UTF8_ACCEPT 0u + +static const unsigned char utf8d[] = { + // The first part of the table maps bytes to character classes that + // to reduce the size of the transition table and create bitmasks. + 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, + 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, + 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, + 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, + 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, + 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, + 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, + 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, + + // The second part is a transition table that maps a combination + // of a state of the automaton and a character class to a state. + 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, + 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, + 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, + 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, + 12,36,12,12,12,12,12,12,12,12,12,12, +}; + +static unsigned inline decode(unsigned* state, unsigned* codep, unsigned byte) { + unsigned type = utf8d[byte]; + + *codep = (*state != UTF8_ACCEPT) ? + (byte & 0x3fu) | (*codep << 6) : + (0xff >> type) & (byte); + + *state = utf8d[256 + *state + type]; + return *state; +} + +//static bool IsUTF8(unsigned char* s) { +// unsigned codepoint, state = 0; +// +// while (*s) +// decode(&state, &codepoint, *s++); +// +// return state == UTF8_ACCEPT; +//} + +TEST(EncodingsTest, UTF8) { + StringBuffer os, os2; + for (const unsigned* range = kCodepointRanges; *range != 0xFFFFFFFF; range += 2) { + for (unsigned codepoint = range[0]; codepoint <= range[1]; ++codepoint) { + os.Clear(); + UTF8<>::Encode(os, codepoint); + const char* encodedStr = os.GetString(); + + // Decode with Hoehrmann + { + unsigned decodedCodepoint = 0; + unsigned state = 0; + + unsigned decodedCount = 0; + for (const char* s = encodedStr; *s; ++s) + if (!decode(&state, &decodedCodepoint, static_cast(*s))) { + EXPECT_EQ(codepoint, decodedCodepoint); + decodedCount++; + } + + if (*encodedStr) { // This decoder cannot handle U+0000 + EXPECT_EQ(1u, decodedCount); // Should only contain one code point + } + + EXPECT_EQ(UTF8_ACCEPT, state); + if (UTF8_ACCEPT != state) + std::cout << std::hex << codepoint << " " << decodedCodepoint << std::endl; + } + + // Decode + { + StringStream is(encodedStr); + unsigned decodedCodepoint; + bool result = UTF8<>::Decode(is, &decodedCodepoint); + EXPECT_TRUE(result); + EXPECT_EQ(codepoint, decodedCodepoint); + if (!result || codepoint != decodedCodepoint) + std::cout << std::hex << codepoint << " " << decodedCodepoint << std::endl; + } + + // Validate + { + StringStream is(encodedStr); + os2.Clear(); + bool result = UTF8<>::Validate(is, os2); + EXPECT_TRUE(result); + EXPECT_EQ(0, StrCmp(encodedStr, os2.GetString())); + } + } + } +} + +TEST(EncodingsTest, UTF16) { + GenericStringBuffer > os, os2; + GenericStringBuffer > utf8os; + for (const unsigned* range = kCodepointRanges; *range != 0xFFFFFFFF; range += 2) { + for (unsigned codepoint = range[0]; codepoint <= range[1]; ++codepoint) { + os.Clear(); + UTF16<>::Encode(os, codepoint); + const UTF16<>::Ch* encodedStr = os.GetString(); + + // Encode with Hoehrmann's code + if (codepoint != 0) // cannot handle U+0000 + { + // encode with UTF8<> first + utf8os.Clear(); + UTF8<>::Encode(utf8os, codepoint); + + // transcode from UTF8 to UTF16 with Hoehrmann's code + unsigned decodedCodepoint = 0; + unsigned state = 0; + UTF16<>::Ch buffer[3], *p = &buffer[0]; + for (const char* s = utf8os.GetString(); *s; ++s) { + if (!decode(&state, &decodedCodepoint, static_cast(*s))) + break; + } + + if (codepoint <= 0xFFFF) + *p++ = static_cast::Ch>(decodedCodepoint); + else { + // Encode code points above U+FFFF as surrogate pair. + *p++ = static_cast::Ch>(0xD7C0 + (decodedCodepoint >> 10)); + *p++ = static_cast::Ch>(0xDC00 + (decodedCodepoint & 0x3FF)); + } + *p++ = '\0'; + + EXPECT_EQ(0, StrCmp(buffer, encodedStr)); + } + + // Decode + { + GenericStringStream > is(encodedStr); + unsigned decodedCodepoint; + bool result = UTF16<>::Decode(is, &decodedCodepoint); + EXPECT_TRUE(result); + EXPECT_EQ(codepoint, decodedCodepoint); + if (!result || codepoint != decodedCodepoint) + std::cout << std::hex << codepoint << " " << decodedCodepoint << std::endl; + } + + // Validate + { + GenericStringStream > is(encodedStr); + os2.Clear(); + bool result = UTF16<>::Validate(is, os2); + EXPECT_TRUE(result); + EXPECT_EQ(0, StrCmp(encodedStr, os2.GetString())); + } + } + } +} + +TEST(EncodingsTest, UTF32) { + GenericStringBuffer > os, os2; + for (const unsigned* range = kCodepointRanges; *range != 0xFFFFFFFF; range += 2) { + for (unsigned codepoint = range[0]; codepoint <= range[1]; ++codepoint) { + os.Clear(); + UTF32<>::Encode(os, codepoint); + const UTF32<>::Ch* encodedStr = os.GetString(); + + // Decode + { + GenericStringStream > is(encodedStr); + unsigned decodedCodepoint; + bool result = UTF32<>::Decode(is, &decodedCodepoint); + EXPECT_TRUE(result); + EXPECT_EQ(codepoint, decodedCodepoint); + if (!result || codepoint != decodedCodepoint) + std::cout << std::hex << codepoint << " " << decodedCodepoint << std::endl; + } + + // Validate + { + GenericStringStream > is(encodedStr); + os2.Clear(); + bool result = UTF32<>::Validate(is, os2); + EXPECT_TRUE(result); + EXPECT_EQ(0, StrCmp(encodedStr, os2.GetString())); + } + } + } +} + +TEST(EncodingsTest, ASCII) { + StringBuffer os, os2; + for (unsigned codepoint = 0; codepoint < 128; codepoint++) { + os.Clear(); + ASCII<>::Encode(os, codepoint); + const ASCII<>::Ch* encodedStr = os.GetString(); + { + StringStream is(encodedStr); + unsigned decodedCodepoint; + bool result = ASCII<>::Decode(is, &decodedCodepoint); + if (!result || codepoint != decodedCodepoint) + std::cout << std::hex << codepoint << " " << decodedCodepoint << std::endl; + } + + // Validate + { + StringStream is(encodedStr); + os2.Clear(); + bool result = ASCII<>::Validate(is, os2); + EXPECT_TRUE(result); + EXPECT_EQ(0, StrCmp(encodedStr, os2.GetString())); + } + } +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/filestreamtest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/filestreamtest.cpp new file mode 100644 index 0000000000..a38133fa7f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/filestreamtest.cpp @@ -0,0 +1,112 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/encodedstream.h" + +using namespace rapidjson; + +class FileStreamTest : public ::testing::Test { +public: + FileStreamTest() : filename_(), json_(), length_() {} + virtual ~FileStreamTest(); + + virtual void SetUp() { + const char *paths[] = { + "data/sample.json", + "bin/data/sample.json", + "../bin/data/sample.json", + "../../bin/data/sample.json", + "../../../bin/data/sample.json" + }; + FILE* fp = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + fp = fopen(paths[i], "rb"); + if (fp) { + filename_ = paths[i]; + break; + } + } + ASSERT_TRUE(fp != 0); + + fseek(fp, 0, SEEK_END); + length_ = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + json_ = static_cast(malloc(length_ + 1)); + size_t readLength = fread(json_, 1, length_, fp); + json_[readLength] = '\0'; + fclose(fp); + } + + virtual void TearDown() { + free(json_); + json_ = 0; + } + +private: + FileStreamTest(const FileStreamTest&); + FileStreamTest& operator=(const FileStreamTest&); + +protected: + const char* filename_; + char *json_; + size_t length_; +}; + +FileStreamTest::~FileStreamTest() {} + +TEST_F(FileStreamTest, FileReadStream) { + FILE *fp = fopen(filename_, "rb"); + ASSERT_TRUE(fp != 0); + char buffer[65536]; + FileReadStream s(fp, buffer, sizeof(buffer)); + + for (size_t i = 0; i < length_; i++) { + EXPECT_EQ(json_[i], s.Peek()); + EXPECT_EQ(json_[i], s.Peek()); // 2nd time should be the same + EXPECT_EQ(json_[i], s.Take()); + } + + EXPECT_EQ(length_, s.Tell()); + EXPECT_EQ('\0', s.Peek()); + + fclose(fp); +} + +TEST_F(FileStreamTest, FileWriteStream) { + char filename[L_tmpnam]; + FILE* fp = TempFile(filename); + + char buffer[65536]; + FileWriteStream os(fp, buffer, sizeof(buffer)); + for (size_t i = 0; i < length_; i++) + os.Put(json_[i]); + os.Flush(); + fclose(fp); + + // Read it back to verify + fp = fopen(filename, "rb"); + FileReadStream is(fp, buffer, sizeof(buffer)); + + for (size_t i = 0; i < length_; i++) + EXPECT_EQ(json_[i], is.Take()); + + EXPECT_EQ(length_, is.Tell()); + fclose(fp); + + //std::cout << filename << std::endl; + remove(filename); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/fwdtest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/fwdtest.cpp new file mode 100644 index 0000000000..4f32684611 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/fwdtest.cpp @@ -0,0 +1,227 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +// Using forward declared types here. + +#include "rapidjson/fwd.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +using namespace rapidjson; + +struct Foo { + Foo(); + ~Foo(); + + // encodings.h + UTF8* utf8; + UTF16* utf16; + UTF16BE* utf16be; + UTF16LE* utf16le; + UTF32* utf32; + UTF32BE* utf32be; + UTF32LE* utf32le; + ASCII* ascii; + AutoUTF* autoutf; + Transcoder, UTF8 >* transcoder; + + // allocators.h + CrtAllocator* crtallocator; + MemoryPoolAllocator* memorypoolallocator; + + // stream.h + StringStream* stringstream; + InsituStringStream* insitustringstream; + + // stringbuffer.h + StringBuffer* stringbuffer; + + // // filereadstream.h + // FileReadStream* filereadstream; + + // // filewritestream.h + // FileWriteStream* filewritestream; + + // memorybuffer.h + MemoryBuffer* memorybuffer; + + // memorystream.h + MemoryStream* memorystream; + + // reader.h + BaseReaderHandler, void>* basereaderhandler; + Reader* reader; + + // writer.h + Writer, UTF8, CrtAllocator, 0>* writer; + + // prettywriter.h + PrettyWriter, UTF8, CrtAllocator, 0>* prettywriter; + + // document.h + Value* value; + Document* document; + + // pointer.h + Pointer* pointer; + + // schema.h + SchemaDocument* schemadocument; + SchemaValidator* schemavalidator; + + // char buffer[16]; +}; + +// Using type definitions here. + +#include "rapidjson/stringbuffer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/memorybuffer.h" +#include "rapidjson/memorystream.h" +#include "rapidjson/document.h" // -> reader.h +#include "rapidjson/writer.h" +#include "rapidjson/prettywriter.h" +#include "rapidjson/schema.h" // -> pointer.h + +Foo::Foo() : + // encodings.h + utf8(RAPIDJSON_NEW(UTF8<>)), + utf16(RAPIDJSON_NEW(UTF16<>)), + utf16be(RAPIDJSON_NEW(UTF16BE<>)), + utf16le(RAPIDJSON_NEW(UTF16LE<>)), + utf32(RAPIDJSON_NEW(UTF32<>)), + utf32be(RAPIDJSON_NEW(UTF32BE<>)), + utf32le(RAPIDJSON_NEW(UTF32LE<>)), + ascii(RAPIDJSON_NEW(ASCII<>)), + autoutf(RAPIDJSON_NEW(AutoUTF)), + transcoder(RAPIDJSON_NEW((Transcoder, UTF8<> >))), + + // allocators.h + crtallocator(RAPIDJSON_NEW(CrtAllocator)), + memorypoolallocator(RAPIDJSON_NEW(MemoryPoolAllocator<>)), + + // stream.h + stringstream(RAPIDJSON_NEW(StringStream(0))), + insitustringstream(RAPIDJSON_NEW(InsituStringStream(0))), + + // stringbuffer.h + stringbuffer(RAPIDJSON_NEW(StringBuffer)), + + // // filereadstream.h + // filereadstream(RAPIDJSON_NEW(FileReadStream(stdout, buffer, sizeof(buffer)))), + + // // filewritestream.h + // filewritestream(RAPIDJSON_NEW(FileWriteStream(stdout, buffer, sizeof(buffer)))), + + // memorybuffer.h + memorybuffer(RAPIDJSON_NEW(MemoryBuffer)), + + // memorystream.h + memorystream(RAPIDJSON_NEW(MemoryStream(0, 0))), + + // reader.h + basereaderhandler(RAPIDJSON_NEW((BaseReaderHandler, void>))), + reader(RAPIDJSON_NEW(Reader)), + + // writer.h + writer(RAPIDJSON_NEW((Writer))), + + // prettywriter.h + prettywriter(RAPIDJSON_NEW((PrettyWriter))), + + // document.h + value(RAPIDJSON_NEW(Value)), + document(RAPIDJSON_NEW(Document)), + + // pointer.h + pointer(RAPIDJSON_NEW(Pointer)), + + // schema.h + schemadocument(RAPIDJSON_NEW(SchemaDocument(*document))), + schemavalidator(RAPIDJSON_NEW(SchemaValidator(*schemadocument))) +{ + +} + +Foo::~Foo() { + // encodings.h + RAPIDJSON_DELETE(utf8); + RAPIDJSON_DELETE(utf16); + RAPIDJSON_DELETE(utf16be); + RAPIDJSON_DELETE(utf16le); + RAPIDJSON_DELETE(utf32); + RAPIDJSON_DELETE(utf32be); + RAPIDJSON_DELETE(utf32le); + RAPIDJSON_DELETE(ascii); + RAPIDJSON_DELETE(autoutf); + RAPIDJSON_DELETE(transcoder); + + // allocators.h + RAPIDJSON_DELETE(crtallocator); + RAPIDJSON_DELETE(memorypoolallocator); + + // stream.h + RAPIDJSON_DELETE(stringstream); + RAPIDJSON_DELETE(insitustringstream); + + // stringbuffer.h + RAPIDJSON_DELETE(stringbuffer); + + // // filereadstream.h + // RAPIDJSON_DELETE(filereadstream); + + // // filewritestream.h + // RAPIDJSON_DELETE(filewritestream); + + // memorybuffer.h + RAPIDJSON_DELETE(memorybuffer); + + // memorystream.h + RAPIDJSON_DELETE(memorystream); + + // reader.h + RAPIDJSON_DELETE(basereaderhandler); + RAPIDJSON_DELETE(reader); + + // writer.h + RAPIDJSON_DELETE(writer); + + // prettywriter.h + RAPIDJSON_DELETE(prettywriter); + + // document.h + RAPIDJSON_DELETE(value); + RAPIDJSON_DELETE(document); + + // pointer.h + RAPIDJSON_DELETE(pointer); + + // schema.h + RAPIDJSON_DELETE(schemadocument); + RAPIDJSON_DELETE(schemavalidator); +} + +TEST(Fwd, Fwd) { + Foo f; +} + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/istreamwrappertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/istreamwrappertest.cpp new file mode 100644 index 0000000000..9d6fbcff0d --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/istreamwrappertest.cpp @@ -0,0 +1,181 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/istreamwrapper.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/document.h" +#include +#include + +#ifdef _MSC_VER +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(4702) // unreachable code +#endif + +using namespace rapidjson; +using namespace std; + +template +static void TestStringStream() { + typedef typename StringStreamType::char_type Ch; + + { + StringStreamType iss; + BasicIStreamWrapper is(iss); + EXPECT_EQ(0, is.Tell()); + if (sizeof(Ch) == 1) { + EXPECT_EQ(0, is.Peek4()); + EXPECT_EQ(0, is.Tell()); + } + EXPECT_EQ(0, is.Peek()); + EXPECT_EQ(0, is.Take()); + EXPECT_EQ(0, is.Tell()); + } + + { + Ch s[] = { 'A', 'B', 'C', '\0' }; + StringStreamType iss(s); + BasicIStreamWrapper is(iss); + EXPECT_EQ(0, is.Tell()); + if (sizeof(Ch) == 1) { + EXPECT_EQ(0, is.Peek4()); // less than 4 bytes + } + for (int i = 0; i < 3; i++) { + EXPECT_EQ(static_cast(i), is.Tell()); + EXPECT_EQ('A' + i, is.Peek()); + EXPECT_EQ('A' + i, is.Peek()); + EXPECT_EQ('A' + i, is.Take()); + } + EXPECT_EQ(3, is.Tell()); + EXPECT_EQ(0, is.Peek()); + EXPECT_EQ(0, is.Take()); + } + + { + Ch s[] = { 'A', 'B', 'C', 'D', 'E', '\0' }; + StringStreamType iss(s); + BasicIStreamWrapper is(iss); + if (sizeof(Ch) == 1) { + const Ch* c = is.Peek4(); + for (int i = 0; i < 4; i++) + EXPECT_EQ('A' + i, c[i]); + EXPECT_EQ(0, is.Tell()); + } + for (int i = 0; i < 5; i++) { + EXPECT_EQ(static_cast(i), is.Tell()); + EXPECT_EQ('A' + i, is.Peek()); + EXPECT_EQ('A' + i, is.Peek()); + EXPECT_EQ('A' + i, is.Take()); + } + EXPECT_EQ(5, is.Tell()); + EXPECT_EQ(0, is.Peek()); + EXPECT_EQ(0, is.Take()); + } +} + +TEST(IStreamWrapper, istringstream) { + TestStringStream(); +} + +TEST(IStreamWrapper, stringstream) { + TestStringStream(); +} + +TEST(IStreamWrapper, wistringstream) { + TestStringStream(); +} + +TEST(IStreamWrapper, wstringstream) { + TestStringStream(); +} + +template +static bool Open(FileStreamType& fs, const char* filename) { + const char *paths[] = { + "encodings", + "bin/encodings", + "../bin/encodings", + "../../bin/encodings", + "../../../bin/encodings" + }; + char buffer[1024]; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s/%s", paths[i], filename); + fs.open(buffer, ios_base::in | ios_base::binary); + if (fs.is_open()) + return true; + } + return false; +} + +TEST(IStreamWrapper, ifstream) { + ifstream ifs; + ASSERT_TRUE(Open(ifs, "utf8bom.json")); + IStreamWrapper isw(ifs); + EncodedInputStream, IStreamWrapper> eis(isw); + Document d; + EXPECT_TRUE(!d.ParseStream(eis).HasParseError()); + EXPECT_TRUE(d.IsObject()); + EXPECT_EQ(5, d.MemberCount()); +} + +TEST(IStreamWrapper, fstream) { + fstream fs; + ASSERT_TRUE(Open(fs, "utf8bom.json")); + IStreamWrapper isw(fs); + EncodedInputStream, IStreamWrapper> eis(isw); + Document d; + EXPECT_TRUE(!d.ParseStream(eis).HasParseError()); + EXPECT_TRUE(d.IsObject()); + EXPECT_EQ(5, d.MemberCount()); +} + +// wifstream/wfstream only works on C++11 with codecvt_utf16 +// But many C++11 library still not have it. +#if 0 +#include + +TEST(IStreamWrapper, wifstream) { + wifstream ifs; + ASSERT_TRUE(Open(ifs, "utf16bebom.json")); + ifs.imbue(std::locale(ifs.getloc(), + new std::codecvt_utf16)); + WIStreamWrapper isw(ifs); + GenericDocument > d; + d.ParseStream, WIStreamWrapper>(isw); + EXPECT_TRUE(!d.HasParseError()); + EXPECT_TRUE(d.IsObject()); + EXPECT_EQ(5, d.MemberCount()); +} + +TEST(IStreamWrapper, wfstream) { + wfstream fs; + ASSERT_TRUE(Open(fs, "utf16bebom.json")); + fs.imbue(std::locale(fs.getloc(), + new std::codecvt_utf16)); + WIStreamWrapper isw(fs); + GenericDocument > d; + d.ParseStream, WIStreamWrapper>(isw); + EXPECT_TRUE(!d.HasParseError()); + EXPECT_TRUE(d.IsObject()); + EXPECT_EQ(5, d.MemberCount()); +} + +#endif + +#ifdef _MSC_VER +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/itoatest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/itoatest.cpp new file mode 100644 index 0000000000..b752a6a26e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/itoatest.cpp @@ -0,0 +1,160 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/internal/itoa.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(type-limits) +#endif + +using namespace rapidjson::internal; + +template +struct Traits { +}; + +template <> +struct Traits { + enum { kBufferSize = 11 }; + enum { kMaxDigit = 10 }; + static uint32_t Negate(uint32_t x) { return x; } +}; + +template <> +struct Traits { + enum { kBufferSize = 12 }; + enum { kMaxDigit = 10 }; + static int32_t Negate(int32_t x) { return -x; } +}; + +template <> +struct Traits { + enum { kBufferSize = 21 }; + enum { kMaxDigit = 20 }; + static uint64_t Negate(uint64_t x) { return x; } +}; + +template <> +struct Traits { + enum { kBufferSize = 22 }; + enum { kMaxDigit = 20 }; + static int64_t Negate(int64_t x) { return -x; } +}; + +template +static void VerifyValue(T value, void(*f)(T, char*), char* (*g)(T, char*)) { + char buffer1[Traits::kBufferSize]; + char buffer2[Traits::kBufferSize]; + + f(value, buffer1); + *g(value, buffer2) = '\0'; + + + EXPECT_STREQ(buffer1, buffer2); +} + +template +static void Verify(void(*f)(T, char*), char* (*g)(T, char*)) { + // Boundary cases + VerifyValue(0, f, g); + VerifyValue(std::numeric_limits::min(), f, g); + VerifyValue(std::numeric_limits::max(), f, g); + + // 2^n - 1, 2^n, 10^n - 1, 10^n until overflow + for (uint32_t power = 2; power <= 10; power += 8) { + T i = 1, last; + do { + VerifyValue(i - 1, f, g); + VerifyValue(i, f, g); + if (std::numeric_limits::min() < 0) { + VerifyValue(Traits::Negate(i), f, g); + VerifyValue(Traits::Negate(i + 1), f, g); + } + last = i; + if (i > static_cast(std::numeric_limits::max() / static_cast(power))) + break; + i *= power; + } while (last < i); + } +} + +static void u32toa_naive(uint32_t value, char* buffer) { + char temp[10]; + char *p = temp; + do { + *p++ = static_cast(char(value % 10) + '0'); + value /= 10; + } while (value > 0); + + do { + *buffer++ = *--p; + } while (p != temp); + + *buffer = '\0'; +} + +static void i32toa_naive(int32_t value, char* buffer) { + uint32_t u = static_cast(value); + if (value < 0) { + *buffer++ = '-'; + u = ~u + 1; + } + u32toa_naive(u, buffer); +} + +static void u64toa_naive(uint64_t value, char* buffer) { + char temp[20]; + char *p = temp; + do { + *p++ = static_cast(char(value % 10) + '0'); + value /= 10; + } while (value > 0); + + do { + *buffer++ = *--p; + } while (p != temp); + + *buffer = '\0'; +} + +static void i64toa_naive(int64_t value, char* buffer) { + uint64_t u = static_cast(value); + if (value < 0) { + *buffer++ = '-'; + u = ~u + 1; + } + u64toa_naive(u, buffer); +} + +TEST(itoa, u32toa) { + Verify(u32toa_naive, u32toa); +} + +TEST(itoa, i32toa) { + Verify(i32toa_naive, i32toa); +} + +TEST(itoa, u64toa) { + Verify(u64toa_naive, u64toa); +} + +TEST(itoa, i64toa) { + Verify(i64toa_naive, i64toa); +} + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/jsoncheckertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/jsoncheckertest.cpp new file mode 100644 index 0000000000..bea788d26e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/jsoncheckertest.cpp @@ -0,0 +1,99 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/document.h" + +using namespace rapidjson; + +static char* ReadFile(const char* filename, size_t& length) { + const char *paths[] = { + "jsonchecker", + "bin/jsonchecker", + "../bin/jsonchecker", + "../../bin/jsonchecker", + "../../../bin/jsonchecker" + }; + char buffer[1024]; + FILE *fp = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s/%s", paths[i], filename); + fp = fopen(buffer, "rb"); + if (fp) + break; + } + + if (!fp) + return 0; + + fseek(fp, 0, SEEK_END); + length = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + char* json = static_cast(malloc(length + 1)); + size_t readLength = fread(json, 1, length, fp); + json[readLength] = '\0'; + fclose(fp); + return json; +} + +TEST(JsonChecker, Reader) { + char filename[256]; + + // jsonchecker/failXX.json + for (int i = 1; i <= 33; i++) { + if (i == 1) // fail1.json is valid in rapidjson, which has no limitation on type of root element (RFC 7159). + continue; + if (i == 18) // fail18.json is valid in rapidjson, which has no limitation on depth of nesting. + continue; + + sprintf(filename, "fail%d.json", i); + size_t length; + char* json = ReadFile(filename, length); + if (!json) { + printf("jsonchecker file %s not found", filename); + ADD_FAILURE(); + continue; + } + + GenericDocument, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) + document.Parse(json); + EXPECT_TRUE(document.HasParseError()); + + document.Parse(json); + EXPECT_TRUE(document.HasParseError()); + + free(json); + } + + // passX.json + for (int i = 1; i <= 3; i++) { + sprintf(filename, "pass%d.json", i); + size_t length; + char* json = ReadFile(filename, length); + if (!json) { + printf("jsonchecker file %s not found", filename); + continue; + } + + GenericDocument, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) + document.Parse(json); + EXPECT_FALSE(document.HasParseError()); + + document.Parse(json); + EXPECT_FALSE(document.HasParseError()); + + free(json); + } +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/namespacetest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/namespacetest.cpp new file mode 100644 index 0000000000..1814724aec --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/namespacetest.cpp @@ -0,0 +1,70 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +// test another instantiation of RapidJSON in a different namespace + +#define RAPIDJSON_NAMESPACE my::rapid::json +#define RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapid { namespace json { +#define RAPIDJSON_NAMESPACE_END } } } + +// include lots of RapidJSON files + +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/filereadstream.h" +#include "rapidjson/filewritestream.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/stringbuffer.h" + +static const char json[] = "{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3,4]}"; + +TEST(NamespaceTest,Using) { + using namespace RAPIDJSON_NAMESPACE; + typedef GenericDocument, CrtAllocator> DocumentType; + DocumentType doc; + + doc.Parse(json); + EXPECT_TRUE(!doc.HasParseError()); +} + +TEST(NamespaceTest,Direct) { + typedef RAPIDJSON_NAMESPACE::Document Document; + typedef RAPIDJSON_NAMESPACE::Reader Reader; + typedef RAPIDJSON_NAMESPACE::StringStream StringStream; + typedef RAPIDJSON_NAMESPACE::StringBuffer StringBuffer; + typedef RAPIDJSON_NAMESPACE::Writer WriterType; + + StringStream s(json); + StringBuffer buffer; + WriterType writer(buffer); + buffer.ShrinkToFit(); + Reader reader; + reader.Parse(s, writer); + + EXPECT_STREQ(json, buffer.GetString()); + EXPECT_EQ(sizeof(json)-1, buffer.GetSize()); + EXPECT_TRUE(writer.IsComplete()); + + Document doc; + doc.Parse(buffer.GetString()); + EXPECT_TRUE(!doc.HasParseError()); + + buffer.Clear(); + writer.Reset(buffer); + doc.Accept(writer); + EXPECT_STREQ(json, buffer.GetString()); + EXPECT_TRUE(writer.IsComplete()); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/ostreamwrappertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/ostreamwrappertest.cpp new file mode 100644 index 0000000000..b1d1cd827f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/ostreamwrappertest.cpp @@ -0,0 +1,91 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/ostreamwrapper.h" +#include "rapidjson/encodedstream.h" +#include "rapidjson/document.h" +#include +#include + +using namespace rapidjson; +using namespace std; + +template +static void TestStringStream() { + typedef typename StringStreamType::char_type Ch; + + Ch s[] = { 'A', 'B', 'C', '\0' }; + StringStreamType oss(s); + BasicOStreamWrapper os(oss); + for (size_t i = 0; i < 3; i++) + os.Put(s[i]); + os.Flush(); + for (size_t i = 0; i < 3; i++) + EXPECT_EQ(s[i], oss.str()[i]); +} + +TEST(OStreamWrapper, ostringstream) { + TestStringStream(); +} + +TEST(OStreamWrapper, stringstream) { + TestStringStream(); +} + +TEST(OStreamWrapper, wostringstream) { + TestStringStream(); +} + +TEST(OStreamWrapper, wstringstream) { + TestStringStream(); +} + +TEST(OStreamWrapper, cout) { + OStreamWrapper os(cout); + const char* s = "Hello World!\n"; + while (*s) + os.Put(*s++); + os.Flush(); +} + +template +static void TestFileStream() { + char filename[L_tmpnam]; + FILE* fp = TempFile(filename); + fclose(fp); + + const char* s = "Hello World!\n"; + { + ofstream ofs(filename, ios::out | ios::binary); + BasicOStreamWrapper osw(ofs); + for (const char* p = s; *p; p++) + osw.Put(*p); + osw.Flush(); + } + + fp = fopen(filename, "r"); + for (const char* p = s; *p; p++) + EXPECT_EQ(*p, static_cast(fgetc(fp))); + fclose(fp); +} + +TEST(OStreamWrapper, ofstream) { + TestFileStream(); +} + +TEST(OStreamWrapper, fstream) { + TestFileStream(); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/pointertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/pointertest.cpp new file mode 100644 index 0000000000..dbddbedee2 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/pointertest.cpp @@ -0,0 +1,1524 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/pointer.h" +#include "rapidjson/stringbuffer.h" +#include + +using namespace rapidjson; + +static const char kJson[] = "{\n" +" \"foo\":[\"bar\", \"baz\"],\n" +" \"\" : 0,\n" +" \"a/b\" : 1,\n" +" \"c%d\" : 2,\n" +" \"e^f\" : 3,\n" +" \"g|h\" : 4,\n" +" \"i\\\\j\" : 5,\n" +" \"k\\\"l\" : 6,\n" +" \" \" : 7,\n" +" \"m~n\" : 8\n" +"}"; + +TEST(Pointer, DefaultConstructor) { + Pointer p; + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(0u, p.GetTokenCount()); +} + +TEST(Pointer, Parse) { + { + Pointer p(""); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(0u, p.GetTokenCount()); + } + + { + Pointer p("/"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(0u, p.GetTokens()[0].length); + EXPECT_STREQ("", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + { + Pointer p("/foo"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + #if RAPIDJSON_HAS_STDSTRING + { + Pointer p(std::string("/foo")); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + #endif + + { + Pointer p("/foo/0"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(2u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + EXPECT_EQ(1u, p.GetTokens()[1].length); + EXPECT_STREQ("0", p.GetTokens()[1].name); + EXPECT_EQ(0u, p.GetTokens()[1].index); + } + + { + // Unescape ~1 + Pointer p("/a~1b"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("a/b", p.GetTokens()[0].name); + } + + { + // Unescape ~0 + Pointer p("/m~0n"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("m~n", p.GetTokens()[0].name); + } + + { + // empty name + Pointer p("/"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(0u, p.GetTokens()[0].length); + EXPECT_STREQ("", p.GetTokens()[0].name); + } + + { + // empty and non-empty name + Pointer p("//a"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(2u, p.GetTokenCount()); + EXPECT_EQ(0u, p.GetTokens()[0].length); + EXPECT_STREQ("", p.GetTokens()[0].name); + EXPECT_EQ(1u, p.GetTokens()[1].length); + EXPECT_STREQ("a", p.GetTokens()[1].name); + } + + { + // Null characters + Pointer p("/\0\0", 3); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(2u, p.GetTokens()[0].length); + EXPECT_EQ('\0', p.GetTokens()[0].name[0]); + EXPECT_EQ('\0', p.GetTokens()[0].name[1]); + EXPECT_EQ('\0', p.GetTokens()[0].name[2]); + } + + { + // Valid index + Pointer p("/123"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("123", p.GetTokens()[0].name); + EXPECT_EQ(123u, p.GetTokens()[0].index); + } + + { + // Invalid index (with leading zero) + Pointer p("/01"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("01", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + if (sizeof(SizeType) == 4) { + // Invalid index (overflow) + Pointer p("/4294967296"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("4294967296", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + { + // kPointerParseErrorTokenMustBeginWithSolidus + Pointer p(" "); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorTokenMustBeginWithSolidus, p.GetParseErrorCode()); + EXPECT_EQ(0u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidEscape + Pointer p("/~"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidEscape + Pointer p("/~2"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } +} + +TEST(Pointer, Parse_URIFragment) { + { + Pointer p("#"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(0u, p.GetTokenCount()); + } + + { + Pointer p("#/foo"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + } + + { + Pointer p("#/foo/0"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(2u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + EXPECT_EQ(1u, p.GetTokens()[1].length); + EXPECT_STREQ("0", p.GetTokens()[1].name); + EXPECT_EQ(0u, p.GetTokens()[1].index); + } + + { + // Unescape ~1 + Pointer p("#/a~1b"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("a/b", p.GetTokens()[0].name); + } + + { + // Unescape ~0 + Pointer p("#/m~0n"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("m~n", p.GetTokens()[0].name); + } + + { + // empty name + Pointer p("#/"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(0u, p.GetTokens()[0].length); + EXPECT_STREQ("", p.GetTokens()[0].name); + } + + { + // empty and non-empty name + Pointer p("#//a"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(2u, p.GetTokenCount()); + EXPECT_EQ(0u, p.GetTokens()[0].length); + EXPECT_STREQ("", p.GetTokens()[0].name); + EXPECT_EQ(1u, p.GetTokens()[1].length); + EXPECT_STREQ("a", p.GetTokens()[1].name); + } + + { + // Null characters + Pointer p("#/%00%00"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(2u, p.GetTokens()[0].length); + EXPECT_EQ('\0', p.GetTokens()[0].name[0]); + EXPECT_EQ('\0', p.GetTokens()[0].name[1]); + EXPECT_EQ('\0', p.GetTokens()[0].name[2]); + } + + { + // Percentage Escapes + EXPECT_STREQ("c%d", Pointer("#/c%25d").GetTokens()[0].name); + EXPECT_STREQ("e^f", Pointer("#/e%5Ef").GetTokens()[0].name); + EXPECT_STREQ("g|h", Pointer("#/g%7Ch").GetTokens()[0].name); + EXPECT_STREQ("i\\j", Pointer("#/i%5Cj").GetTokens()[0].name); + EXPECT_STREQ("k\"l", Pointer("#/k%22l").GetTokens()[0].name); + EXPECT_STREQ(" ", Pointer("#/%20").GetTokens()[0].name); + } + + { + // Valid index + Pointer p("#/123"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("123", p.GetTokens()[0].name); + EXPECT_EQ(123u, p.GetTokens()[0].index); + } + + { + // Invalid index (with leading zero) + Pointer p("#/01"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("01", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + if (sizeof(SizeType) == 4) { + // Invalid index (overflow) + Pointer p("#/4294967296"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("4294967296", p.GetTokens()[0].name); + EXPECT_EQ(kPointerInvalidIndex, p.GetTokens()[0].index); + } + + { + // Decode UTF-8 perecent encoding to UTF-8 + Pointer p("#/%C2%A2"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_STREQ("\xC2\xA2", p.GetTokens()[0].name); + } + + { + // Decode UTF-8 perecent encoding to UTF-16 + GenericPointer > > p(L"#/%C2%A2"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(static_cast::Ch>(0x00A2), p.GetTokens()[0].name[0]); + EXPECT_EQ(1u, p.GetTokens()[0].length); + } + + { + // Decode UTF-8 perecent encoding to UTF-16 + GenericPointer > > p(L"#/%E2%82%AC"); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(1u, p.GetTokenCount()); + EXPECT_EQ(static_cast::Ch>(0x20AC), p.GetTokens()[0].name[0]); + EXPECT_EQ(1u, p.GetTokens()[0].length); + } + + { + // kPointerParseErrorTokenMustBeginWithSolidus + Pointer p("# "); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorTokenMustBeginWithSolidus, p.GetParseErrorCode()); + EXPECT_EQ(1u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidEscape + Pointer p("#/~"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); + EXPECT_EQ(3u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidEscape + Pointer p("#/~2"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidEscape, p.GetParseErrorCode()); + EXPECT_EQ(3u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidPercentEncoding + Pointer p("#/%"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidPercentEncoding (invalid hex) + Pointer p("#/%g0"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidPercentEncoding (invalid hex) + Pointer p("#/%0g"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorInvalidPercentEncoding (incomplete UTF-8 sequence) + Pointer p("#/%C2"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorInvalidPercentEncoding, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorCharacterMustPercentEncode + Pointer p("#/ "); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorCharacterMustPercentEncode, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } + + { + // kPointerParseErrorCharacterMustPercentEncode + Pointer p("#/\n"); + EXPECT_FALSE(p.IsValid()); + EXPECT_EQ(kPointerParseErrorCharacterMustPercentEncode, p.GetParseErrorCode()); + EXPECT_EQ(2u, p.GetParseErrorOffset()); + } +} + +TEST(Pointer, Stringify) { + // Test by roundtrip + const char* sources[] = { + "", + "/foo", + "/foo/0", + "/", + "/a~1b", + "/c%d", + "/e^f", + "/g|h", + "/i\\j", + "/k\"l", + "/ ", + "/m~0n", + "/\xC2\xA2", + "/\xE2\x82\xAC", + "/\xF0\x9D\x84\x9E" + }; + + for (size_t i = 0; i < sizeof(sources) / sizeof(sources[0]); i++) { + Pointer p(sources[i]); + StringBuffer s; + EXPECT_TRUE(p.Stringify(s)); + EXPECT_STREQ(sources[i], s.GetString()); + + // Stringify to URI fragment + StringBuffer s2; + EXPECT_TRUE(p.StringifyUriFragment(s2)); + Pointer p2(s2.GetString(), s2.GetSize()); + EXPECT_TRUE(p2.IsValid()); + EXPECT_TRUE(p == p2); + } + + { + // Strigify to URI fragment with an invalid UTF-8 sequence + Pointer p("/\xC2"); + StringBuffer s; + EXPECT_FALSE(p.StringifyUriFragment(s)); + } +} + +// Construct a Pointer with static tokens, no dynamic allocation involved. +#define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex } +#define INDEX(i) { #i, sizeof(#i) - 1, i } + +static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(0) }; // equivalent to "/foo/0" + +#undef NAME +#undef INDEX + +TEST(Pointer, ConstructorWithToken) { + Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); + EXPECT_TRUE(p.IsValid()); + EXPECT_EQ(2u, p.GetTokenCount()); + EXPECT_EQ(3u, p.GetTokens()[0].length); + EXPECT_STREQ("foo", p.GetTokens()[0].name); + EXPECT_EQ(1u, p.GetTokens()[1].length); + EXPECT_STREQ("0", p.GetTokens()[1].name); + EXPECT_EQ(0u, p.GetTokens()[1].index); +} + +TEST(Pointer, CopyConstructor) { + { + Pointer p("/foo/0"); + Pointer q(p); + EXPECT_TRUE(q.IsValid()); + EXPECT_EQ(2u, q.GetTokenCount()); + EXPECT_EQ(3u, q.GetTokens()[0].length); + EXPECT_STREQ("foo", q.GetTokens()[0].name); + EXPECT_EQ(1u, q.GetTokens()[1].length); + EXPECT_STREQ("0", q.GetTokens()[1].name); + EXPECT_EQ(0u, q.GetTokens()[1].index); + } + + // Static tokens + { + Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); + Pointer q(p); + EXPECT_TRUE(q.IsValid()); + EXPECT_EQ(2u, q.GetTokenCount()); + EXPECT_EQ(3u, q.GetTokens()[0].length); + EXPECT_STREQ("foo", q.GetTokens()[0].name); + EXPECT_EQ(1u, q.GetTokens()[1].length); + EXPECT_STREQ("0", q.GetTokens()[1].name); + EXPECT_EQ(0u, q.GetTokens()[1].index); + } +} + +TEST(Pointer, Assignment) { + { + Pointer p("/foo/0"); + Pointer q; + q = p; + EXPECT_TRUE(q.IsValid()); + EXPECT_EQ(2u, q.GetTokenCount()); + EXPECT_EQ(3u, q.GetTokens()[0].length); + EXPECT_STREQ("foo", q.GetTokens()[0].name); + EXPECT_EQ(1u, q.GetTokens()[1].length); + EXPECT_STREQ("0", q.GetTokens()[1].name); + EXPECT_EQ(0u, q.GetTokens()[1].index); + q = q; + EXPECT_TRUE(q.IsValid()); + EXPECT_EQ(2u, q.GetTokenCount()); + EXPECT_EQ(3u, q.GetTokens()[0].length); + EXPECT_STREQ("foo", q.GetTokens()[0].name); + EXPECT_EQ(1u, q.GetTokens()[1].length); + EXPECT_STREQ("0", q.GetTokens()[1].name); + EXPECT_EQ(0u, q.GetTokens()[1].index); + } + + // Static tokens + { + Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0])); + Pointer q; + q = p; + EXPECT_TRUE(q.IsValid()); + EXPECT_EQ(2u, q.GetTokenCount()); + EXPECT_EQ(3u, q.GetTokens()[0].length); + EXPECT_STREQ("foo", q.GetTokens()[0].name); + EXPECT_EQ(1u, q.GetTokens()[1].length); + EXPECT_STREQ("0", q.GetTokens()[1].name); + EXPECT_EQ(0u, q.GetTokens()[1].index); + } +} + +TEST(Pointer, Append) { + { + Pointer p; + Pointer q = p.Append("foo"); + EXPECT_TRUE(Pointer("/foo") == q); + q = q.Append(1234); + EXPECT_TRUE(Pointer("/foo/1234") == q); + q = q.Append(""); + EXPECT_TRUE(Pointer("/foo/1234/") == q); + } + + { + Pointer p; + Pointer q = p.Append(Value("foo").Move()); + EXPECT_TRUE(Pointer("/foo") == q); + q = q.Append(Value(1234).Move()); + EXPECT_TRUE(Pointer("/foo/1234") == q); + q = q.Append(Value(kStringType).Move()); + EXPECT_TRUE(Pointer("/foo/1234/") == q); + } + +#if RAPIDJSON_HAS_STDSTRING + { + Pointer p; + Pointer q = p.Append(std::string("foo")); + EXPECT_TRUE(Pointer("/foo") == q); + } +#endif +} + +TEST(Pointer, Equality) { + EXPECT_TRUE(Pointer("/foo/0") == Pointer("/foo/0")); + EXPECT_FALSE(Pointer("/foo/0") == Pointer("/foo/1")); + EXPECT_FALSE(Pointer("/foo/0") == Pointer("/foo/0/1")); + EXPECT_FALSE(Pointer("/foo/0") == Pointer("a")); + EXPECT_FALSE(Pointer("a") == Pointer("a")); // Invalid always not equal +} + +TEST(Pointer, Inequality) { + EXPECT_FALSE(Pointer("/foo/0") != Pointer("/foo/0")); + EXPECT_TRUE(Pointer("/foo/0") != Pointer("/foo/1")); + EXPECT_TRUE(Pointer("/foo/0") != Pointer("/foo/0/1")); + EXPECT_TRUE(Pointer("/foo/0") != Pointer("a")); + EXPECT_TRUE(Pointer("a") != Pointer("a")); // Invalid always not equal +} + +TEST(Pointer, Create) { + Document d; + { + Value* v = &Pointer("").Create(d, d.GetAllocator()); + EXPECT_EQ(&d, v); + } + { + Value* v = &Pointer("/foo").Create(d, d.GetAllocator()); + EXPECT_EQ(&d["foo"], v); + } + { + Value* v = &Pointer("/foo/0").Create(d, d.GetAllocator()); + EXPECT_EQ(&d["foo"][0], v); + } + { + Value* v = &Pointer("/foo/-").Create(d, d.GetAllocator()); + EXPECT_EQ(&d["foo"][1], v); + } + + { + Value* v = &Pointer("/foo/-/-").Create(d, d.GetAllocator()); + // "foo/-" is a newly created null value x. + // "foo/-/-" finds that x is not an array, it converts x to empty object + // and treats - as "-" member name + EXPECT_EQ(&d["foo"][2]["-"], v); + } + + { + // Document with no allocator + Value* v = &Pointer("/foo/-").Create(d); + EXPECT_EQ(&d["foo"][3], v); + } + + { + // Value (not document) must give allocator + Value* v = &Pointer("/-").Create(d["foo"], d.GetAllocator()); + EXPECT_EQ(&d["foo"][4], v); + } +} + +TEST(Pointer, Get) { + Document d; + d.Parse(kJson); + + EXPECT_EQ(&d, Pointer("").Get(d)); + EXPECT_EQ(&d["foo"], Pointer("/foo").Get(d)); + EXPECT_EQ(&d["foo"][0], Pointer("/foo/0").Get(d)); + EXPECT_EQ(&d[""], Pointer("/").Get(d)); + EXPECT_EQ(&d["a/b"], Pointer("/a~1b").Get(d)); + EXPECT_EQ(&d["c%d"], Pointer("/c%d").Get(d)); + EXPECT_EQ(&d["e^f"], Pointer("/e^f").Get(d)); + EXPECT_EQ(&d["g|h"], Pointer("/g|h").Get(d)); + EXPECT_EQ(&d["i\\j"], Pointer("/i\\j").Get(d)); + EXPECT_EQ(&d["k\"l"], Pointer("/k\"l").Get(d)); + EXPECT_EQ(&d[" "], Pointer("/ ").Get(d)); + EXPECT_EQ(&d["m~n"], Pointer("/m~0n").Get(d)); + EXPECT_TRUE(Pointer("/abc").Get(d) == 0); + size_t unresolvedTokenIndex; + EXPECT_TRUE(Pointer("/foo/2").Get(d, &unresolvedTokenIndex) == 0); // Out of boundary + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(Pointer("/foo/a").Get(d, &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(Pointer("/foo/0/0").Get(d, &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); + EXPECT_TRUE(Pointer("/foo/0/a").Get(d, &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); +} + +TEST(Pointer, GetWithDefault) { + Document d; + d.Parse(kJson); + + // Value version + Document::AllocatorType& a = d.GetAllocator(); + const Value v("qux"); + EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v, a)); + EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v, a)); + EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v, a)); + EXPECT_TRUE(Value("last") == Pointer("/foo/-").GetWithDefault(d, Value("last").Move(), a)); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, Value().Move(), a).IsNull()); + EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, "x", a).IsNull()); + + // Generic version + EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -1, a).GetInt()); + EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -2, a).GetInt()); + EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x87654321, a).GetUint()); + EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x12345678, a).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64, a).GetInt64()); + EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64 + 1, a).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64, a).GetUint64()); + EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64 - 1, a).GetUint64()); + + EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, true, a).IsTrue()); + EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, false, a).IsTrue()); + + EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, false, a).IsFalse()); + EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, true, a).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", Pointer("/foo/hello").GetWithDefault(d, "Hello", a).GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", Pointer("/foo/world").GetWithDefault(d, buffer, a).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", Pointer("/foo/C++").GetWithDefault(d, std::string("C++"), a).GetString()); +#endif +} + +TEST(Pointer, GetWithDefault_NoAllocator) { + Document d; + d.Parse(kJson); + + // Value version + const Value v("qux"); + EXPECT_TRUE(Value("bar") == Pointer("/foo/0").GetWithDefault(d, v)); + EXPECT_TRUE(Value("baz") == Pointer("/foo/1").GetWithDefault(d, v)); + EXPECT_TRUE(Value("qux") == Pointer("/foo/2").GetWithDefault(d, v)); + EXPECT_TRUE(Value("last") == Pointer("/foo/-").GetWithDefault(d, Value("last").Move())); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, Value().Move()).IsNull()); + EXPECT_TRUE(Pointer("/foo/null").GetWithDefault(d, "x").IsNull()); + + // Generic version + EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -1).GetInt()); + EXPECT_EQ(-1, Pointer("/foo/int").GetWithDefault(d, -2).GetInt()); + EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x87654321).GetUint()); + EXPECT_EQ(0x87654321, Pointer("/foo/uint").GetWithDefault(d, 0x12345678).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64).GetInt64()); + EXPECT_EQ(i64, Pointer("/foo/int64").GetWithDefault(d, i64 + 1).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64).GetUint64()); + EXPECT_EQ(u64, Pointer("/foo/uint64").GetWithDefault(d, u64 - 1).GetUint64()); + + EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, true).IsTrue()); + EXPECT_TRUE(Pointer("/foo/true").GetWithDefault(d, false).IsTrue()); + + EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, false).IsFalse()); + EXPECT_TRUE(Pointer("/foo/false").GetWithDefault(d, true).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", Pointer("/foo/hello").GetWithDefault(d, "Hello").GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", Pointer("/foo/world").GetWithDefault(d, buffer).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", Pointer("/foo/C++").GetWithDefault(d, std::string("C++")).GetString()); +#endif +} + +TEST(Pointer, Set) { + Document d; + d.Parse(kJson); + Document::AllocatorType& a = d.GetAllocator(); + + // Value version + Pointer("/foo/0").Set(d, Value(123).Move(), a); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + Pointer("/foo/-").Set(d, Value(456).Move(), a); + EXPECT_EQ(456, d["foo"][2].GetInt()); + + Pointer("/foo/null").Set(d, Value().Move(), a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], a); + Pointer("/clone").Set(d, foo, a); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + Pointer("/foo/int").Set(d, -1, a); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + Pointer("/foo/uint").Set(d, 0x87654321, a); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + Pointer("/foo/int64").Set(d, i64, a); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + Pointer("/foo/uint64").Set(d, u64, a); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + Pointer("/foo/true").Set(d, true, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + Pointer("/foo/false").Set(d, false, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + Pointer("/foo/hello").Set(d, "Hello", a); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + Pointer("/foo/world").Set(d, buffer, a); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + Pointer("/foo/c++").Set(d, std::string("C++"), a); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, Set_NoAllocator) { + Document d; + d.Parse(kJson); + + // Value version + Pointer("/foo/0").Set(d, Value(123).Move()); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + Pointer("/foo/-").Set(d, Value(456).Move()); + EXPECT_EQ(456, d["foo"][2].GetInt()); + + Pointer("/foo/null").Set(d, Value().Move()); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], d.GetAllocator()); + Pointer("/clone").Set(d, foo); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + Pointer("/foo/int").Set(d, -1); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + Pointer("/foo/uint").Set(d, 0x87654321); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + Pointer("/foo/int64").Set(d, i64); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + Pointer("/foo/uint64").Set(d, u64); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + Pointer("/foo/true").Set(d, true); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + Pointer("/foo/false").Set(d, false); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + Pointer("/foo/hello").Set(d, "Hello"); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + Pointer("/foo/world").Set(d, buffer); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + Pointer("/foo/c++").Set(d, std::string("C++")); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, Swap) { + Document d; + d.Parse(kJson); + Document::AllocatorType& a = d.GetAllocator(); + Pointer("/foo/0").Swap(d, *Pointer("/foo/1").Get(d), a); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_STREQ("bar", d["foo"][1].GetString()); +} + +TEST(Pointer, Swap_NoAllocator) { + Document d; + d.Parse(kJson); + Pointer("/foo/0").Swap(d, *Pointer("/foo/1").Get(d)); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_STREQ("bar", d["foo"][1].GetString()); +} + +TEST(Pointer, Erase) { + Document d; + d.Parse(kJson); + + EXPECT_FALSE(Pointer("").Erase(d)); + EXPECT_FALSE(Pointer("/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/nonexist/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/foo/nonexist/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/foo/0/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/foo/0/nonexist/nonexist").Erase(d)); + EXPECT_FALSE(Pointer("/foo/2/nonexist").Erase(d)); + EXPECT_TRUE(Pointer("/foo/0").Erase(d)); + EXPECT_EQ(1u, d["foo"].Size()); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_TRUE(Pointer("/foo/0").Erase(d)); + EXPECT_TRUE(d["foo"].Empty()); + EXPECT_TRUE(Pointer("/foo").Erase(d)); + EXPECT_TRUE(Pointer("/foo").Get(d) == 0); + + Pointer("/a/0/b/0").Create(d); + + EXPECT_TRUE(Pointer("/a/0/b/0").Get(d) != 0); + EXPECT_TRUE(Pointer("/a/0/b/0").Erase(d)); + EXPECT_TRUE(Pointer("/a/0/b/0").Get(d) == 0); + + EXPECT_TRUE(Pointer("/a/0/b").Get(d) != 0); + EXPECT_TRUE(Pointer("/a/0/b").Erase(d)); + EXPECT_TRUE(Pointer("/a/0/b").Get(d) == 0); + + EXPECT_TRUE(Pointer("/a/0").Get(d) != 0); + EXPECT_TRUE(Pointer("/a/0").Erase(d)); + EXPECT_TRUE(Pointer("/a/0").Get(d) == 0); + + EXPECT_TRUE(Pointer("/a").Get(d) != 0); + EXPECT_TRUE(Pointer("/a").Erase(d)); + EXPECT_TRUE(Pointer("/a").Get(d) == 0); +} + +TEST(Pointer, CreateValueByPointer) { + Document d; + Document::AllocatorType& a = d.GetAllocator(); + + { + Value& v = CreateValueByPointer(d, Pointer("/foo/0"), a); + EXPECT_EQ(&d["foo"][0], &v); + } + { + Value& v = CreateValueByPointer(d, "/foo/1", a); + EXPECT_EQ(&d["foo"][1], &v); + } +} + +TEST(Pointer, CreateValueByPointer_NoAllocator) { + Document d; + + { + Value& v = CreateValueByPointer(d, Pointer("/foo/0")); + EXPECT_EQ(&d["foo"][0], &v); + } + { + Value& v = CreateValueByPointer(d, "/foo/1"); + EXPECT_EQ(&d["foo"][1], &v); + } +} + +TEST(Pointer, GetValueByPointer) { + Document d; + d.Parse(kJson); + + EXPECT_EQ(&d["foo"][0], GetValueByPointer(d, Pointer("/foo/0"))); + EXPECT_EQ(&d["foo"][0], GetValueByPointer(d, "/foo/0")); + + size_t unresolvedTokenIndex; + EXPECT_TRUE(GetValueByPointer(d, "/foo/2", &unresolvedTokenIndex) == 0); // Out of boundary + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(d, "/foo/a", &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(d, "/foo/0/0", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(d, "/foo/0/a", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); + + // const version + const Value& v = d; + EXPECT_EQ(&d["foo"][0], GetValueByPointer(v, Pointer("/foo/0"))); + EXPECT_EQ(&d["foo"][0], GetValueByPointer(v, "/foo/0")); + + EXPECT_TRUE(GetValueByPointer(v, "/foo/2", &unresolvedTokenIndex) == 0); // Out of boundary + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(v, "/foo/a", &unresolvedTokenIndex) == 0); // "/foo" is an array, cannot query by "a" + EXPECT_EQ(1, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(v, "/foo/0/0", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); + EXPECT_TRUE(GetValueByPointer(v, "/foo/0/a", &unresolvedTokenIndex) == 0); // "/foo/0" is an string, cannot further query + EXPECT_EQ(2, unresolvedTokenIndex); + +} + +TEST(Pointer, GetValueByPointerWithDefault_Pointer) { + Document d; + d.Parse(kJson); + + Document::AllocatorType& a = d.GetAllocator(); + const Value v("qux"); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v, a)); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v, a)); + EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, Pointer("/foo/1"), v, a)); + EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, Pointer("/foo/2"), v, a)); + EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, Pointer("/foo/-"), Value("last").Move(), a)); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), Value().Move(), a).IsNull()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), "x", a).IsNull()); + + // Generic version + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -1, a).GetInt()); + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -2, a).GetInt()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x87654321, a).GetUint()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x12345678, a).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64, a).GetInt64()); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64 + 1, a).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64, a).GetUint64()); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64 - 1, a).GetUint64()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), true, a).IsTrue()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), false, a).IsTrue()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), false, a).IsFalse()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), true, a).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, Pointer("/foo/hello"), "Hello", a).GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", GetValueByPointerWithDefault(d, Pointer("/foo/world"), buffer, a).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, Pointer("/foo/world"))->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++"), a).GetString()); +#endif +} + +TEST(Pointer, GetValueByPointerWithDefault_String) { + Document d; + d.Parse(kJson); + + Document::AllocatorType& a = d.GetAllocator(); + const Value v("qux"); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v, a)); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v, a)); + EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, "/foo/1", v, a)); + EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, "/foo/2", v, a)); + EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, "/foo/-", Value("last").Move(), a)); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", Value().Move(), a).IsNull()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", "x", a).IsNull()); + + // Generic version + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -1, a).GetInt()); + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -2, a).GetInt()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x87654321, a).GetUint()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x12345678, a).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64, a).GetInt64()); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64 + 1, a).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64, a).GetUint64()); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64 - 1, a).GetUint64()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", true, a).IsTrue()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", false, a).IsTrue()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", false, a).IsFalse()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", true, a).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, "/foo/hello", "Hello", a).GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", GetValueByPointerWithDefault(d, "/foo/world", buffer, a).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, "/foo/C++", std::string("C++"), a).GetString()); +#endif +} + +TEST(Pointer, GetValueByPointerWithDefault_Pointer_NoAllocator) { + Document d; + d.Parse(kJson); + + const Value v("qux"); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v)); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, Pointer("/foo/0"), v)); + EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, Pointer("/foo/1"), v)); + EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, Pointer("/foo/2"), v)); + EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, Pointer("/foo/-"), Value("last").Move())); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), Value().Move()).IsNull()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/null"), "x").IsNull()); + + // Generic version + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -1).GetInt()); + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, Pointer("/foo/int"), -2).GetInt()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x87654321).GetUint()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, Pointer("/foo/uint"), 0x12345678).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64).GetInt64()); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, Pointer("/foo/int64"), i64 + 1).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64).GetUint64()); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, Pointer("/foo/uint64"), u64 - 1).GetUint64()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), true).IsTrue()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/true"), false).IsTrue()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), false).IsFalse()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, Pointer("/foo/false"), true).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, Pointer("/foo/hello"), "Hello").GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", GetValueByPointerWithDefault(d, Pointer("/foo/world"), buffer).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, Pointer("/foo/world"))->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++")).GetString()); +#endif +} + +TEST(Pointer, GetValueByPointerWithDefault_String_NoAllocator) { + Document d; + d.Parse(kJson); + + const Value v("qux"); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v)); + EXPECT_TRUE(Value("bar") == GetValueByPointerWithDefault(d, "/foo/0", v)); + EXPECT_TRUE(Value("baz") == GetValueByPointerWithDefault(d, "/foo/1", v)); + EXPECT_TRUE(Value("qux") == GetValueByPointerWithDefault(d, "/foo/2", v)); + EXPECT_TRUE(Value("last") == GetValueByPointerWithDefault(d, "/foo/-", Value("last").Move())); + EXPECT_STREQ("last", d["foo"][3].GetString()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", Value().Move()).IsNull()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/null", "x").IsNull()); + + // Generic version + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -1).GetInt()); + EXPECT_EQ(-1, GetValueByPointerWithDefault(d, "/foo/int", -2).GetInt()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x87654321).GetUint()); + EXPECT_EQ(0x87654321, GetValueByPointerWithDefault(d, "/foo/uint", 0x12345678).GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64).GetInt64()); + EXPECT_EQ(i64, GetValueByPointerWithDefault(d, "/foo/int64", i64 + 1).GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64).GetUint64()); + EXPECT_EQ(u64, GetValueByPointerWithDefault(d, "/foo/uint64", u64 - 1).GetUint64()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", true).IsTrue()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/true", false).IsTrue()); + + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", false).IsFalse()); + EXPECT_TRUE(GetValueByPointerWithDefault(d, "/foo/false", true).IsFalse()); + + // StringRef version + EXPECT_STREQ("Hello", GetValueByPointerWithDefault(d, "/foo/hello", "Hello").GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + EXPECT_STREQ("World", GetValueByPointerWithDefault(d, "/foo/world", buffer).GetString()); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("C++", GetValueByPointerWithDefault(d, Pointer("/foo/C++"), std::string("C++")).GetString()); +#endif +} + +TEST(Pointer, SetValueByPointer_Pointer) { + Document d; + d.Parse(kJson); + Document::AllocatorType& a = d.GetAllocator(); + + // Value version + SetValueByPointer(d, Pointer("/foo/0"), Value(123).Move(), a); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + SetValueByPointer(d, Pointer("/foo/null"), Value().Move(), a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], d.GetAllocator()); + SetValueByPointer(d, Pointer("/clone"), foo, a); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + SetValueByPointer(d, Pointer("/foo/int"), -1, a); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + SetValueByPointer(d, Pointer("/foo/uint"), 0x87654321, a); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + SetValueByPointer(d, Pointer("/foo/int64"), i64, a); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + SetValueByPointer(d, Pointer("/foo/uint64"), u64, a); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + SetValueByPointer(d, Pointer("/foo/true"), true, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + SetValueByPointer(d, Pointer("/foo/false"), false, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + SetValueByPointer(d, Pointer("/foo/hello"), "Hello", a); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + SetValueByPointer(d, Pointer("/foo/world"), buffer, a); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + SetValueByPointer(d, Pointer("/foo/c++"), std::string("C++"), a); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, SetValueByPointer_String) { + Document d; + d.Parse(kJson); + Document::AllocatorType& a = d.GetAllocator(); + + // Value version + SetValueByPointer(d, "/foo/0", Value(123).Move(), a); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + SetValueByPointer(d, "/foo/null", Value().Move(), a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], d.GetAllocator()); + SetValueByPointer(d, "/clone", foo, a); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + SetValueByPointer(d, "/foo/int", -1, a); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + SetValueByPointer(d, "/foo/uint", 0x87654321, a); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + SetValueByPointer(d, "/foo/int64", i64, a); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + SetValueByPointer(d, "/foo/uint64", u64, a); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + SetValueByPointer(d, "/foo/true", true, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + SetValueByPointer(d, "/foo/false", false, a); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + SetValueByPointer(d, "/foo/hello", "Hello", a); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + SetValueByPointer(d, "/foo/world", buffer, a); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + SetValueByPointer(d, "/foo/c++", std::string("C++"), a); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, SetValueByPointer_Pointer_NoAllocator) { + Document d; + d.Parse(kJson); + + // Value version + SetValueByPointer(d, Pointer("/foo/0"), Value(123).Move()); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + SetValueByPointer(d, Pointer("/foo/null"), Value().Move()); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], d.GetAllocator()); + SetValueByPointer(d, Pointer("/clone"), foo); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + SetValueByPointer(d, Pointer("/foo/int"), -1); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + SetValueByPointer(d, Pointer("/foo/uint"), 0x87654321); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + SetValueByPointer(d, Pointer("/foo/int64"), i64); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + SetValueByPointer(d, Pointer("/foo/uint64"), u64); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + SetValueByPointer(d, Pointer("/foo/true"), true); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + SetValueByPointer(d, Pointer("/foo/false"), false); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + SetValueByPointer(d, Pointer("/foo/hello"), "Hello"); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + SetValueByPointer(d, Pointer("/foo/world"), buffer); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + SetValueByPointer(d, Pointer("/foo/c++"), std::string("C++")); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, SetValueByPointer_String_NoAllocator) { + Document d; + d.Parse(kJson); + + // Value version + SetValueByPointer(d, "/foo/0", Value(123).Move()); + EXPECT_EQ(123, d["foo"][0].GetInt()); + + SetValueByPointer(d, "/foo/null", Value().Move()); + EXPECT_TRUE(GetValueByPointer(d, "/foo/null")->IsNull()); + + // Const Value version + const Value foo(d["foo"], d.GetAllocator()); + SetValueByPointer(d, "/clone", foo); + EXPECT_EQ(foo, *GetValueByPointer(d, "/clone")); + + // Generic version + SetValueByPointer(d, "/foo/int", -1); + EXPECT_EQ(-1, GetValueByPointer(d, "/foo/int")->GetInt()); + + SetValueByPointer(d, "/foo/uint", 0x87654321); + EXPECT_EQ(0x87654321, GetValueByPointer(d, "/foo/uint")->GetUint()); + + const int64_t i64 = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0)); + SetValueByPointer(d, "/foo/int64", i64); + EXPECT_EQ(i64, GetValueByPointer(d, "/foo/int64")->GetInt64()); + + const uint64_t u64 = RAPIDJSON_UINT64_C2(0xFFFFFFFFF, 0xFFFFFFFFF); + SetValueByPointer(d, "/foo/uint64", u64); + EXPECT_EQ(u64, GetValueByPointer(d, "/foo/uint64")->GetUint64()); + + SetValueByPointer(d, "/foo/true", true); + EXPECT_TRUE(GetValueByPointer(d, "/foo/true")->IsTrue()); + + SetValueByPointer(d, "/foo/false", false); + EXPECT_TRUE(GetValueByPointer(d, "/foo/false")->IsFalse()); + + // StringRef version + SetValueByPointer(d, "/foo/hello", "Hello"); + EXPECT_STREQ("Hello", GetValueByPointer(d, "/foo/hello")->GetString()); + + // Copy string version + { + char buffer[256]; + strcpy(buffer, "World"); + SetValueByPointer(d, "/foo/world", buffer); + memset(buffer, 0, sizeof(buffer)); + } + EXPECT_STREQ("World", GetValueByPointer(d, "/foo/world")->GetString()); + +#if RAPIDJSON_HAS_STDSTRING + SetValueByPointer(d, "/foo/c++", std::string("C++")); + EXPECT_STREQ("C++", GetValueByPointer(d, "/foo/c++")->GetString()); +#endif +} + +TEST(Pointer, SwapValueByPointer) { + Document d; + d.Parse(kJson); + Document::AllocatorType& a = d.GetAllocator(); + SwapValueByPointer(d, Pointer("/foo/0"), *GetValueByPointer(d, "/foo/1"), a); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_STREQ("bar", d["foo"][1].GetString()); + + SwapValueByPointer(d, "/foo/0", *GetValueByPointer(d, "/foo/1"), a); + EXPECT_STREQ("bar", d["foo"][0].GetString()); + EXPECT_STREQ("baz", d["foo"][1].GetString()); +} + +TEST(Pointer, SwapValueByPointer_NoAllocator) { + Document d; + d.Parse(kJson); + SwapValueByPointer(d, Pointer("/foo/0"), *GetValueByPointer(d, "/foo/1")); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_STREQ("bar", d["foo"][1].GetString()); + + SwapValueByPointer(d, "/foo/0", *GetValueByPointer(d, "/foo/1")); + EXPECT_STREQ("bar", d["foo"][0].GetString()); + EXPECT_STREQ("baz", d["foo"][1].GetString()); +} + +TEST(Pointer, EraseValueByPointer_Pointer) { + Document d; + d.Parse(kJson); + + EXPECT_FALSE(EraseValueByPointer(d, Pointer(""))); + EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); + EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo/0"))); + EXPECT_EQ(1u, d["foo"].Size()); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo/0"))); + EXPECT_TRUE(d["foo"].Empty()); + EXPECT_TRUE(EraseValueByPointer(d, Pointer("/foo"))); + EXPECT_TRUE(Pointer("/foo").Get(d) == 0); +} + +TEST(Pointer, EraseValueByPointer_String) { + Document d; + d.Parse(kJson); + + EXPECT_FALSE(EraseValueByPointer(d, "")); + EXPECT_FALSE(Pointer("/foo/nonexist").Erase(d)); + EXPECT_TRUE(EraseValueByPointer(d, "/foo/0")); + EXPECT_EQ(1u, d["foo"].Size()); + EXPECT_STREQ("baz", d["foo"][0].GetString()); + EXPECT_TRUE(EraseValueByPointer(d, "/foo/0")); + EXPECT_TRUE(d["foo"].Empty()); + EXPECT_TRUE(EraseValueByPointer(d, "/foo")); + EXPECT_TRUE(Pointer("/foo").Get(d) == 0); +} + +TEST(Pointer, Ambiguity) { + { + Document d; + d.Parse("{\"0\" : [123]}"); + EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); + Pointer("/0/a").Set(d, 456); // Change array [123] to object {456} + EXPECT_EQ(456, Pointer("/0/a").Get(d)->GetInt()); + } + + { + Document d; + EXPECT_FALSE(d.Parse("[{\"0\": 123}]").HasParseError()); + EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); + Pointer("/0/1").Set(d, 456); // 1 is treated as "1" to index object + EXPECT_EQ(123, Pointer("/0/0").Get(d)->GetInt()); + EXPECT_EQ(456, Pointer("/0/1").Get(d)->GetInt()); + } +} + +// https://github.com/miloyip/rapidjson/issues/483 +namespace myjson { + +class MyAllocator +{ +public: + static const bool kNeedFree = true; + void * Malloc(size_t _size) { return malloc(_size); } + void * Realloc(void *_org_p, size_t _org_size, size_t _new_size) { (void)_org_size; return realloc(_org_p, _new_size); } + static void Free(void *_p) { return free(_p); } +}; + +typedef rapidjson::GenericDocument< + rapidjson::UTF8<>, + rapidjson::MemoryPoolAllocator< MyAllocator >, + MyAllocator + > Document; + +typedef rapidjson::GenericPointer< + ::myjson::Document::ValueType, + MyAllocator + > Pointer; + +typedef ::myjson::Document::ValueType Value; + +} + +TEST(Pointer, Issue483) { + std::string mystr, path; + myjson::Document document; + myjson::Value value(rapidjson::kStringType); + value.SetString(mystr.c_str(), static_cast(mystr.length()), document.GetAllocator()); + myjson::Pointer(path.c_str()).Set(document, value, document.GetAllocator()); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/prettywritertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/prettywritertest.cpp new file mode 100644 index 0000000000..a372f7986f --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/prettywritertest.cpp @@ -0,0 +1,203 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/reader.h" +#include "rapidjson/prettywriter.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/filewritestream.h" + +using namespace rapidjson; + +static const char kJson[] = "{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3,-1],\"u64\":1234567890123456789,\"i64\":-1234567890123456789}"; +static const char kPrettyJson[] = +"{\n" +" \"hello\": \"world\",\n" +" \"t\": true,\n" +" \"f\": false,\n" +" \"n\": null,\n" +" \"i\": 123,\n" +" \"pi\": 3.1416,\n" +" \"a\": [\n" +" 1,\n" +" 2,\n" +" 3,\n" +" -1\n" +" ],\n" +" \"u64\": 1234567890123456789,\n" +" \"i64\": -1234567890123456789\n" +"}"; + +static const char kPrettyJson_FormatOptions_SLA[] = +"{\n" +" \"hello\": \"world\",\n" +" \"t\": true,\n" +" \"f\": false,\n" +" \"n\": null,\n" +" \"i\": 123,\n" +" \"pi\": 3.1416,\n" +" \"a\": [1, 2, 3, -1],\n" +" \"u64\": 1234567890123456789,\n" +" \"i64\": -1234567890123456789\n" +"}"; + +TEST(PrettyWriter, Basic) { + StringBuffer buffer; + PrettyWriter writer(buffer); + Reader reader; + StringStream s(kJson); + reader.Parse(s, writer); + EXPECT_STREQ(kPrettyJson, buffer.GetString()); +} + +TEST(PrettyWriter, FormatOptions) { + StringBuffer buffer; + PrettyWriter writer(buffer); + writer.SetFormatOptions(kFormatSingleLineArray); + Reader reader; + StringStream s(kJson); + reader.Parse(s, writer); + EXPECT_STREQ(kPrettyJson_FormatOptions_SLA, buffer.GetString()); +} + +TEST(PrettyWriter, SetIndent) { + StringBuffer buffer; + PrettyWriter writer(buffer); + writer.SetIndent('\t', 1); + Reader reader; + StringStream s(kJson); + reader.Parse(s, writer); + EXPECT_STREQ( + "{\n" + "\t\"hello\": \"world\",\n" + "\t\"t\": true,\n" + "\t\"f\": false,\n" + "\t\"n\": null,\n" + "\t\"i\": 123,\n" + "\t\"pi\": 3.1416,\n" + "\t\"a\": [\n" + "\t\t1,\n" + "\t\t2,\n" + "\t\t3,\n" + "\t\t-1\n" + "\t],\n" + "\t\"u64\": 1234567890123456789,\n" + "\t\"i64\": -1234567890123456789\n" + "}", + buffer.GetString()); +} + +TEST(PrettyWriter, String) { + StringBuffer buffer; + PrettyWriter writer(buffer); + EXPECT_TRUE(writer.StartArray()); + EXPECT_TRUE(writer.String("Hello\n")); + EXPECT_TRUE(writer.EndArray()); + EXPECT_STREQ("[\n \"Hello\\n\"\n]", buffer.GetString()); +} + +#if RAPIDJSON_HAS_STDSTRING +TEST(PrettyWriter, String_STDSTRING) { + StringBuffer buffer; + PrettyWriter writer(buffer); + EXPECT_TRUE(writer.StartArray()); + EXPECT_TRUE(writer.String(std::string("Hello\n"))); + EXPECT_TRUE(writer.EndArray()); + EXPECT_STREQ("[\n \"Hello\\n\"\n]", buffer.GetString()); +} +#endif + +#include + +class OStreamWrapper { +public: + typedef char Ch; + + OStreamWrapper(std::ostream& os) : os_(os) {} + + Ch Peek() const { assert(false); return '\0'; } + Ch Take() { assert(false); return '\0'; } + size_t Tell() const { return 0; } + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch c) { os_.put(c); } + void Flush() { os_.flush(); } + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + OStreamWrapper(const OStreamWrapper&); + OStreamWrapper& operator=(const OStreamWrapper&); + + std::ostream& os_; +}; + +// For covering PutN() generic version +TEST(PrettyWriter, OStreamWrapper) { + StringStream s(kJson); + + std::stringstream ss; + OStreamWrapper os(ss); + + PrettyWriter writer(os); + + Reader reader; + reader.Parse(s, writer); + + std::string actual = ss.str(); + EXPECT_STREQ(kPrettyJson, actual.c_str()); +} + +// For covering FileWriteStream::PutN() +TEST(PrettyWriter, FileWriteStream) { + char filename[L_tmpnam]; + FILE* fp = TempFile(filename); + char buffer[16]; + FileWriteStream os(fp, buffer, sizeof(buffer)); + PrettyWriter writer(os); + Reader reader; + StringStream s(kJson); + reader.Parse(s, writer); + fclose(fp); + + fp = fopen(filename, "rb"); + fseek(fp, 0, SEEK_END); + size_t size = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + char* json = static_cast(malloc(size + 1)); + size_t readLength = fread(json, 1, size, fp); + json[readLength] = '\0'; + fclose(fp); + remove(filename); + EXPECT_STREQ(kPrettyJson, json); + free(json); +} + +TEST(PrettyWriter, RawValue) { + StringBuffer buffer; + PrettyWriter writer(buffer); + writer.StartObject(); + writer.Key("a"); + writer.Int(1); + writer.Key("raw"); + const char json[] = "[\"Hello\\nWorld\", 123.456]"; + writer.RawValue(json, strlen(json), kArrayType); + writer.EndObject(); + EXPECT_TRUE(writer.IsComplete()); + EXPECT_STREQ( + "{\n" + " \"a\": 1,\n" + " \"raw\": [\"Hello\\nWorld\", 123.456]\n" // no indentation within raw value + "}", + buffer.GetString()); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/readertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/readertest.cpp new file mode 100644 index 0000000000..64a1f9c3cf --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/readertest.cpp @@ -0,0 +1,1844 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/reader.h" +#include "rapidjson/internal/dtoa.h" +#include "rapidjson/internal/itoa.h" +#include "rapidjson/memorystream.h" + +#include + +using namespace rapidjson; + +RAPIDJSON_DIAG_PUSH +#ifdef __GNUC__ +RAPIDJSON_DIAG_OFF(effc++) +RAPIDJSON_DIAG_OFF(float-equal) +RAPIDJSON_DIAG_OFF(missing-noreturn) +#if __GNUC__ >= 7 +RAPIDJSON_DIAG_OFF(dangling-else) +#endif +#endif // __GNUC__ + +#ifdef __clang__ +RAPIDJSON_DIAG_OFF(variadic-macros) +RAPIDJSON_DIAG_OFF(c++98-compat-pedantic) +#endif + +template +struct ParseBoolHandler : BaseReaderHandler, ParseBoolHandler > { + ParseBoolHandler() : step_(0) {} + bool Default() { ADD_FAILURE(); return false; } + // gcc 4.8.x generates warning in EXPECT_EQ(bool, bool) on this gtest version. + // Workaround with EXPECT_TRUE(). + bool Bool(bool b) { /*EXPECT_EQ(expect, b); */EXPECT_TRUE(expect == b); ++step_; return true; } + + unsigned step_; +}; + +TEST(Reader, ParseTrue) { + StringStream s("true"); + ParseBoolHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(1u, h.step_); +} + +TEST(Reader, ParseFalse) { + StringStream s("false"); + ParseBoolHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(1u, h.step_); +} + +struct ParseIntHandler : BaseReaderHandler, ParseIntHandler> { + ParseIntHandler() : step_(0), actual_() {} + bool Default() { ADD_FAILURE(); return false; } + bool Int(int i) { actual_ = i; step_++; return true; } + + unsigned step_; + int actual_; +}; + +struct ParseUintHandler : BaseReaderHandler, ParseUintHandler> { + ParseUintHandler() : step_(0), actual_() {} + bool Default() { ADD_FAILURE(); return false; } + bool Uint(unsigned i) { actual_ = i; step_++; return true; } + + unsigned step_; + unsigned actual_; +}; + +struct ParseInt64Handler : BaseReaderHandler, ParseInt64Handler> { + ParseInt64Handler() : step_(0), actual_() {} + bool Default() { ADD_FAILURE(); return false; } + bool Int64(int64_t i) { actual_ = i; step_++; return true; } + + unsigned step_; + int64_t actual_; +}; + +struct ParseUint64Handler : BaseReaderHandler, ParseUint64Handler> { + ParseUint64Handler() : step_(0), actual_() {} + bool Default() { ADD_FAILURE(); return false; } + bool Uint64(uint64_t i) { actual_ = i; step_++; return true; } + + unsigned step_; + uint64_t actual_; +}; + +struct ParseDoubleHandler : BaseReaderHandler, ParseDoubleHandler> { + ParseDoubleHandler() : step_(0), actual_() {} + bool Default() { ADD_FAILURE(); return false; } + bool Double(double d) { actual_ = d; step_++; return true; } + + unsigned step_; + double actual_; +}; + +TEST(Reader, ParseNumber_Integer) { +#define TEST_INTEGER(Handler, str, x) \ + { \ + StringStream s(str); \ + Handler h; \ + Reader reader; \ + reader.Parse(s, h); \ + EXPECT_EQ(1u, h.step_); \ + EXPECT_EQ(x, h.actual_); \ + } + + TEST_INTEGER(ParseUintHandler, "0", 0u); + TEST_INTEGER(ParseUintHandler, "123", 123u); + TEST_INTEGER(ParseUintHandler, "2147483648", 2147483648u); // 2^31 - 1 (cannot be stored in int) + TEST_INTEGER(ParseUintHandler, "4294967295", 4294967295u); + + TEST_INTEGER(ParseIntHandler, "-123", -123); + TEST_INTEGER(ParseIntHandler, "-2147483648", static_cast(0x80000000)); // -2^31 (min of int) + + TEST_INTEGER(ParseUint64Handler, "4294967296", RAPIDJSON_UINT64_C2(1, 0)); // 2^32 (max of unsigned + 1, force to use uint64_t) + TEST_INTEGER(ParseUint64Handler, "18446744073709551615", RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF)); // 2^64 - 1 (max of uint64_t) + + TEST_INTEGER(ParseInt64Handler, "-2147483649", static_cast(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x7FFFFFFF))); // -2^31 -1 (min of int - 1, force to use int64_t) + TEST_INTEGER(ParseInt64Handler, "-9223372036854775808", static_cast(RAPIDJSON_UINT64_C2(0x80000000, 0x00000000))); // -2^63 (min of int64_t) + + // Random test for uint32_t/int32_t + { + union { + uint32_t u; + int32_t i; + }u; + Random r; + + for (unsigned i = 0; i < 100000; i++) { + u.u = r(); + + char buffer[32]; + *internal::u32toa(u.u, buffer) = '\0'; + TEST_INTEGER(ParseUintHandler, buffer, u.u); + + if (u.i < 0) { + *internal::i32toa(u.i, buffer) = '\0'; + TEST_INTEGER(ParseIntHandler, buffer, u.i); + } + } + } + + // Random test for uint64_t/int64_t + { + union { + uint64_t u; + int64_t i; + }u; + Random r; + + for (unsigned i = 0; i < 100000; i++) { + u.u = uint64_t(r()) << 32; + u.u |= r(); + + char buffer[32]; + if (u.u > uint64_t(4294967295u)) { + *internal::u64toa(u.u, buffer) = '\0'; + TEST_INTEGER(ParseUint64Handler, buffer, u.u); + } + + if (u.i < -int64_t(2147483648u)) { + *internal::i64toa(u.i, buffer) = '\0'; + TEST_INTEGER(ParseInt64Handler, buffer, u.i); + } + } + } +#undef TEST_INTEGER +} + +template +static void TestParseDouble() { +#define TEST_DOUBLE(fullPrecision, str, x) \ + { \ + StringStream s(str); \ + ParseDoubleHandler h; \ + Reader reader; \ + ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code()); \ + EXPECT_EQ(1u, h.step_); \ + internal::Double e(x), a(h.actual_); \ + if (fullPrecision) { \ + EXPECT_EQ(e.Uint64Value(), a.Uint64Value()); \ + if (e.Uint64Value() != a.Uint64Value()) \ + printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", str, h.actual_, x); \ + } \ + else { \ + EXPECT_EQ(e.Sign(), a.Sign()); /* for 0.0 != -0.0 */ \ + EXPECT_DOUBLE_EQ(x, h.actual_); \ + } \ + } + + TEST_DOUBLE(fullPrecision, "0.0", 0.0); + TEST_DOUBLE(fullPrecision, "-0.0", -0.0); // For checking issue #289 + TEST_DOUBLE(fullPrecision, "1.0", 1.0); + TEST_DOUBLE(fullPrecision, "-1.0", -1.0); + TEST_DOUBLE(fullPrecision, "1.5", 1.5); + TEST_DOUBLE(fullPrecision, "-1.5", -1.5); + TEST_DOUBLE(fullPrecision, "3.1416", 3.1416); + TEST_DOUBLE(fullPrecision, "1E10", 1E10); + TEST_DOUBLE(fullPrecision, "1e10", 1e10); + TEST_DOUBLE(fullPrecision, "1E+10", 1E+10); + TEST_DOUBLE(fullPrecision, "1E-10", 1E-10); + TEST_DOUBLE(fullPrecision, "-1E10", -1E10); + TEST_DOUBLE(fullPrecision, "-1e10", -1e10); + TEST_DOUBLE(fullPrecision, "-1E+10", -1E+10); + TEST_DOUBLE(fullPrecision, "-1E-10", -1E-10); + TEST_DOUBLE(fullPrecision, "1.234E+10", 1.234E+10); + TEST_DOUBLE(fullPrecision, "1.234E-10", 1.234E-10); + TEST_DOUBLE(fullPrecision, "1.79769e+308", 1.79769e+308); + TEST_DOUBLE(fullPrecision, "2.22507e-308", 2.22507e-308); + TEST_DOUBLE(fullPrecision, "-1.79769e+308", -1.79769e+308); + TEST_DOUBLE(fullPrecision, "-2.22507e-308", -2.22507e-308); + TEST_DOUBLE(fullPrecision, "4.9406564584124654e-324", 4.9406564584124654e-324); // minimum denormal + TEST_DOUBLE(fullPrecision, "2.2250738585072009e-308", 2.2250738585072009e-308); // Max subnormal double + TEST_DOUBLE(fullPrecision, "2.2250738585072014e-308", 2.2250738585072014e-308); // Min normal positive double + TEST_DOUBLE(fullPrecision, "1.7976931348623157e+308", 1.7976931348623157e+308); // Max double + TEST_DOUBLE(fullPrecision, "1e-10000", 0.0); // must underflow + TEST_DOUBLE(fullPrecision, "18446744073709551616", 18446744073709551616.0); // 2^64 (max of uint64_t + 1, force to use double) + TEST_DOUBLE(fullPrecision, "-9223372036854775809", -9223372036854775809.0); // -2^63 - 1(min of int64_t + 1, force to use double) + TEST_DOUBLE(fullPrecision, "0.9868011474609375", 0.9868011474609375); // https://github.com/miloyip/rapidjson/issues/120 + TEST_DOUBLE(fullPrecision, "123e34", 123e34); // Fast Path Cases In Disguise + TEST_DOUBLE(fullPrecision, "45913141877270640000.0", 45913141877270640000.0); + TEST_DOUBLE(fullPrecision, "2.2250738585072011e-308", 2.2250738585072011e-308); // http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ + TEST_DOUBLE(fullPrecision, "1e-00011111111111", 0.0); // Issue #313 + TEST_DOUBLE(fullPrecision, "-1e-00011111111111", -0.0); + TEST_DOUBLE(fullPrecision, "1e-214748363", 0.0); // Maximum supported negative exponent + TEST_DOUBLE(fullPrecision, "1e-214748364", 0.0); + TEST_DOUBLE(fullPrecision, "1e-21474836311", 0.0); + TEST_DOUBLE(fullPrecision, "0.017976931348623157e+310", 1.7976931348623157e+308); // Max double in another form + + // Since + // abs((2^-1022 - 2^-1074) - 2.2250738585072012e-308) = 3.109754131239141401123495768877590405345064751974375599... �� 10^-324 + // abs((2^-1022) - 2.2250738585072012e-308) = 1.830902327173324040642192159804623318305533274168872044... �� 10 ^ -324 + // So 2.2250738585072012e-308 should round to 2^-1022 = 2.2250738585072014e-308 + TEST_DOUBLE(fullPrecision, "2.2250738585072012e-308", 2.2250738585072014e-308); // http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/ + + // More closer to normal/subnormal boundary + // boundary = 2^-1022 - 2^-1075 = 2.225073858507201136057409796709131975934819546351645648... �� 10^-308 + TEST_DOUBLE(fullPrecision, "2.22507385850720113605740979670913197593481954635164564e-308", 2.2250738585072009e-308); + TEST_DOUBLE(fullPrecision, "2.22507385850720113605740979670913197593481954635164565e-308", 2.2250738585072014e-308); + + // 1.0 is in (1.0 - 2^-54, 1.0 + 2^-53) + // 1.0 - 2^-54 = 0.999999999999999944488848768742172978818416595458984375 + TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984375", 1.0); // round to even + TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984374", 0.99999999999999989); // previous double + TEST_DOUBLE(fullPrecision, "0.999999999999999944488848768742172978818416595458984376", 1.0); // next double + // 1.0 + 2^-53 = 1.00000000000000011102230246251565404236316680908203125 + TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203125", 1.0); // round to even + TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203124", 1.0); // previous double + TEST_DOUBLE(fullPrecision, "1.00000000000000011102230246251565404236316680908203126", 1.00000000000000022); // next double + + // Numbers from https://github.com/floitsch/double-conversion/blob/master/test/cctest/test-strtod.cc + + TEST_DOUBLE(fullPrecision, "72057594037927928.0", 72057594037927928.0); + TEST_DOUBLE(fullPrecision, "72057594037927936.0", 72057594037927936.0); + TEST_DOUBLE(fullPrecision, "72057594037927932.0", 72057594037927936.0); + TEST_DOUBLE(fullPrecision, "7205759403792793199999e-5", 72057594037927928.0); + TEST_DOUBLE(fullPrecision, "7205759403792793200001e-5", 72057594037927936.0); + + TEST_DOUBLE(fullPrecision, "9223372036854774784.0", 9223372036854774784.0); + TEST_DOUBLE(fullPrecision, "9223372036854775808.0", 9223372036854775808.0); + TEST_DOUBLE(fullPrecision, "9223372036854775296.0", 9223372036854775808.0); + TEST_DOUBLE(fullPrecision, "922337203685477529599999e-5", 9223372036854774784.0); + TEST_DOUBLE(fullPrecision, "922337203685477529600001e-5", 9223372036854775808.0); + + TEST_DOUBLE(fullPrecision, "10141204801825834086073718800384", 10141204801825834086073718800384.0); + TEST_DOUBLE(fullPrecision, "10141204801825835211973625643008", 10141204801825835211973625643008.0); + TEST_DOUBLE(fullPrecision, "10141204801825834649023672221696", 10141204801825835211973625643008.0); + TEST_DOUBLE(fullPrecision, "1014120480182583464902367222169599999e-5", 10141204801825834086073718800384.0); + TEST_DOUBLE(fullPrecision, "1014120480182583464902367222169600001e-5", 10141204801825835211973625643008.0); + + TEST_DOUBLE(fullPrecision, "5708990770823838890407843763683279797179383808", 5708990770823838890407843763683279797179383808.0); + TEST_DOUBLE(fullPrecision, "5708990770823839524233143877797980545530986496", 5708990770823839524233143877797980545530986496.0); + TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185152", 5708990770823839524233143877797980545530986496.0); + TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185151999e-3", 5708990770823838890407843763683279797179383808.0); + TEST_DOUBLE(fullPrecision, "5708990770823839207320493820740630171355185152001e-3", 5708990770823839524233143877797980545530986496.0); + + { + char n1e308[310]; // '1' followed by 308 '0' + n1e308[0] = '1'; + for (int i = 1; i < 309; i++) + n1e308[i] = '0'; + n1e308[309] = '\0'; + TEST_DOUBLE(fullPrecision, n1e308, 1E308); + } + + // Cover trimming + TEST_DOUBLE(fullPrecision, +"2.22507385850720113605740979670913197593481954635164564802342610972482222202107694551652952390813508" +"7914149158913039621106870086438694594645527657207407820621743379988141063267329253552286881372149012" +"9811224514518898490572223072852551331557550159143974763979834118019993239625482890171070818506906306" +"6665599493827577257201576306269066333264756530000924588831643303777979186961204949739037782970490505" +"1080609940730262937128958950003583799967207254304360284078895771796150945516748243471030702609144621" +"5722898802581825451803257070188608721131280795122334262883686223215037756666225039825343359745688844" +"2390026549819838548794829220689472168983109969836584681402285424333066033985088644580400103493397042" +"7567186443383770486037861622771738545623065874679014086723327636718751234567890123456789012345678901" +"e-308", + 2.2250738585072014e-308); + + { + static const unsigned count = 100; // Tested with 1000000 locally + Random r; + Reader reader; // Reusing reader to prevent heap allocation + + // Exhaustively test different exponents with random significant + for (uint64_t exp = 0; exp < 2047; exp++) { + ; + for (unsigned i = 0; i < count; i++) { + // Need to call r() in two statements for cross-platform coherent sequence. + uint64_t u = (exp << 52) | uint64_t(r() & 0x000FFFFF) << 32; + u |= uint64_t(r()); + internal::Double d = internal::Double(u); + + char buffer[32]; + *internal::dtoa(d.Value(), buffer) = '\0'; + + StringStream s(buffer); + ParseDoubleHandler h; + ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code()); + EXPECT_EQ(1u, h.step_); + internal::Double a(h.actual_); + if (fullPrecision) { + EXPECT_EQ(d.Uint64Value(), a.Uint64Value()); + if (d.Uint64Value() != a.Uint64Value()) + printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", buffer, h.actual_, d.Value()); + } + else { + EXPECT_EQ(d.Sign(), a.Sign()); // for 0.0 != -0.0 + EXPECT_DOUBLE_EQ(d.Value(), h.actual_); + } + } + } + } + + // Issue #340 + TEST_DOUBLE(fullPrecision, "7.450580596923828e-9", 7.450580596923828e-9); + { + internal::Double d(1.0); + for (int i = 0; i < 324; i++) { + char buffer[32]; + *internal::dtoa(d.Value(), buffer) = '\0'; + + StringStream s(buffer); + ParseDoubleHandler h; + Reader reader; + ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code()); + EXPECT_EQ(1u, h.step_); + internal::Double a(h.actual_); + if (fullPrecision) { + EXPECT_EQ(d.Uint64Value(), a.Uint64Value()); + if (d.Uint64Value() != a.Uint64Value()) + printf(" String: %s\n Actual: %.17g\nExpected: %.17g\n", buffer, h.actual_, d.Value()); + } + else { + EXPECT_EQ(d.Sign(), a.Sign()); // for 0.0 != -0.0 + EXPECT_DOUBLE_EQ(d.Value(), h.actual_); + } + + + d = d.Value() * 0.5; + } + } +#undef TEST_DOUBLE +} + +TEST(Reader, ParseNumber_NormalPrecisionDouble) { + TestParseDouble(); +} + +TEST(Reader, ParseNumber_FullPrecisionDouble) { + TestParseDouble(); +} + +TEST(Reader, ParseNumber_NormalPrecisionError) { + static unsigned count = 1000000; + Random r; + + double ulpSum = 0.0; + double ulpMax = 0.0; + for (unsigned i = 0; i < count; i++) { + internal::Double e, a; + do { + // Need to call r() in two statements for cross-platform coherent sequence. + uint64_t u = uint64_t(r()) << 32; + u |= uint64_t(r()); + e = u; + } while (e.IsNan() || e.IsInf() || !e.IsNormal()); + + char buffer[32]; + *internal::dtoa(e.Value(), buffer) = '\0'; + + StringStream s(buffer); + ParseDoubleHandler h; + Reader reader; + ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code()); + EXPECT_EQ(1u, h.step_); + + a = h.actual_; + uint64_t bias1 = e.ToBias(); + uint64_t bias2 = a.ToBias(); + double ulp = static_cast(bias1 >= bias2 ? bias1 - bias2 : bias2 - bias1); + ulpMax = std::max(ulpMax, ulp); + ulpSum += ulp; + } + printf("ULP Average = %g, Max = %g \n", ulpSum / count, ulpMax); +} + +TEST(Reader, ParseNumber_Error) { +#define TEST_NUMBER_ERROR(errorCode, str, errorOffset, streamPos) \ + { \ + char buffer[1001]; \ + sprintf(buffer, "%s", str); \ + InsituStringStream s(buffer); \ + BaseReaderHandler<> h; \ + Reader reader; \ + EXPECT_FALSE(reader.Parse(s, h)); \ + EXPECT_EQ(errorCode, reader.GetParseErrorCode());\ + EXPECT_EQ(errorOffset, reader.GetErrorOffset());\ + EXPECT_EQ(streamPos, s.Tell());\ + } + + // Number too big to be stored in double. + { + char n1e309[311]; // '1' followed by 309 '0' + n1e309[0] = '1'; + for (int i = 1; i < 310; i++) + n1e309[i] = '0'; + n1e309[310] = '\0'; + TEST_NUMBER_ERROR(kParseErrorNumberTooBig, n1e309, 0, 309); + } + TEST_NUMBER_ERROR(kParseErrorNumberTooBig, "1e309", 0, 5); + + // Miss fraction part in number. + TEST_NUMBER_ERROR(kParseErrorNumberMissFraction, "1.", 2, 2); + TEST_NUMBER_ERROR(kParseErrorNumberMissFraction, "1.a", 2, 2); + + // Miss exponent in number. + TEST_NUMBER_ERROR(kParseErrorNumberMissExponent, "1e", 2, 2); + TEST_NUMBER_ERROR(kParseErrorNumberMissExponent, "1e_", 2, 2); + +#undef TEST_NUMBER_ERROR +} + +template +struct ParseStringHandler : BaseReaderHandler > { + ParseStringHandler() : str_(0), length_(0), copy_() {} + ~ParseStringHandler() { EXPECT_TRUE(str_ != 0); if (copy_) free(const_cast(str_)); } + + ParseStringHandler(const ParseStringHandler&); + ParseStringHandler& operator=(const ParseStringHandler&); + + bool Default() { ADD_FAILURE(); return false; } + bool String(const typename Encoding::Ch* str, size_t length, bool copy) { + EXPECT_EQ(0, str_); + if (copy) { + str_ = static_cast(malloc((length + 1) * sizeof(typename Encoding::Ch))); + memcpy(const_cast(str_), str, (length + 1) * sizeof(typename Encoding::Ch)); + } + else + str_ = str; + length_ = length; + copy_ = copy; + return true; + } + + const typename Encoding::Ch* str_; + size_t length_; + bool copy_; +}; + +TEST(Reader, ParseString) { +#define TEST_STRING(Encoding, e, x) \ + { \ + Encoding::Ch* buffer = StrDup(x); \ + GenericInsituStringStream is(buffer); \ + ParseStringHandler h; \ + GenericReader reader; \ + reader.Parse(is, h); \ + EXPECT_EQ(0, StrCmp(e, h.str_)); \ + EXPECT_EQ(StrLen(e), h.length_); \ + free(buffer); \ + GenericStringStream s(x); \ + ParseStringHandler h2; \ + GenericReader reader2; \ + reader2.Parse(s, h2); \ + EXPECT_EQ(0, StrCmp(e, h2.str_)); \ + EXPECT_EQ(StrLen(e), h2.length_); \ + } + + // String constant L"\xXX" can only specify character code in bytes, which is not endianness-neutral. + // And old compiler does not support u"" and U"" string literal. So here specify string literal by array of Ch. + // In addition, GCC 4.8 generates -Wnarrowing warnings when character code >= 128 are assigned to signed integer types. + // Therefore, utype is added for declaring unsigned array, and then cast it to Encoding::Ch. +#define ARRAY(...) { __VA_ARGS__ } +#define TEST_STRINGARRAY(Encoding, utype, array, x) \ + { \ + static const utype ue[] = array; \ + static const Encoding::Ch* e = reinterpret_cast(&ue[0]); \ + TEST_STRING(Encoding, e, x); \ + } + +#define TEST_STRINGARRAY2(Encoding, utype, earray, xarray) \ + { \ + static const utype ue[] = earray; \ + static const utype xe[] = xarray; \ + static const Encoding::Ch* e = reinterpret_cast(&ue[0]); \ + static const Encoding::Ch* x = reinterpret_cast(&xe[0]); \ + TEST_STRING(Encoding, e, x); \ + } + + TEST_STRING(UTF8<>, "", "\"\""); + TEST_STRING(UTF8<>, "Hello", "\"Hello\""); + TEST_STRING(UTF8<>, "Hello\nWorld", "\"Hello\\nWorld\""); + TEST_STRING(UTF8<>, "\"\\/\b\f\n\r\t", "\"\\\"\\\\/\\b\\f\\n\\r\\t\""); + TEST_STRING(UTF8<>, "\x24", "\"\\u0024\""); // Dollar sign U+0024 + TEST_STRING(UTF8<>, "\xC2\xA2", "\"\\u00A2\""); // Cents sign U+00A2 + TEST_STRING(UTF8<>, "\xE2\x82\xAC", "\"\\u20AC\""); // Euro sign U+20AC + TEST_STRING(UTF8<>, "\xF0\x9D\x84\x9E", "\"\\uD834\\uDD1E\""); // G clef sign U+1D11E + + // UTF16 + TEST_STRING(UTF16<>, L"", L"\"\""); + TEST_STRING(UTF16<>, L"Hello", L"\"Hello\""); + TEST_STRING(UTF16<>, L"Hello\nWorld", L"\"Hello\\nWorld\""); + TEST_STRING(UTF16<>, L"\"\\/\b\f\n\r\t", L"\"\\\"\\\\/\\b\\f\\n\\r\\t\""); + TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x0024, 0x0000), L"\"\\u0024\""); + TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x00A2, 0x0000), L"\"\\u00A2\""); // Cents sign U+00A2 + TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0x20AC, 0x0000), L"\"\\u20AC\""); // Euro sign U+20AC + TEST_STRINGARRAY(UTF16<>, wchar_t, ARRAY(0xD834, 0xDD1E, 0x0000), L"\"\\uD834\\uDD1E\""); // G clef sign U+1D11E + + // UTF32 + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('\0'), ARRAY('\"', '\"', '\0')); + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('H', 'e', 'l', 'l', 'o', '\0'), ARRAY('\"', 'H', 'e', 'l', 'l', 'o', '\"', '\0')); + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('H', 'e', 'l', 'l', 'o', '\n', 'W', 'o', 'r', 'l', 'd', '\0'), ARRAY('\"', 'H', 'e', 'l', 'l', 'o', '\\', 'n', 'W', 'o', 'r', 'l', 'd', '\"', '\0')); + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY('\"', '\\', '/', '\b', '\f', '\n', '\r', '\t', '\0'), ARRAY('\"', '\\', '\"', '\\', '\\', '/', '\\', 'b', '\\', 'f', '\\', 'n', '\\', 'r', '\\', 't', '\"', '\0')); + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x00024, 0x0000), ARRAY('\"', '\\', 'u', '0', '0', '2', '4', '\"', '\0')); + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x000A2, 0x0000), ARRAY('\"', '\\', 'u', '0', '0', 'A', '2', '\"', '\0')); // Cents sign U+00A2 + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x020AC, 0x0000), ARRAY('\"', '\\', 'u', '2', '0', 'A', 'C', '\"', '\0')); // Euro sign U+20AC + TEST_STRINGARRAY2(UTF32<>, unsigned, ARRAY(0x1D11E, 0x0000), ARRAY('\"', '\\', 'u', 'D', '8', '3', '4', '\\', 'u', 'D', 'D', '1', 'E', '\"', '\0')); // G clef sign U+1D11E + +#undef TEST_STRINGARRAY +#undef ARRAY +#undef TEST_STRING + + // Support of null character in string + { + StringStream s("\"Hello\\u0000World\""); + const char e[] = "Hello\0World"; + ParseStringHandler > h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(0, memcmp(e, h.str_, h.length_ + 1)); + EXPECT_EQ(11u, h.length_); + } +} + +TEST(Reader, ParseString_Transcoding) { + const char* x = "\"Hello\""; + const wchar_t* e = L"Hello"; + GenericStringStream > is(x); + GenericReader, UTF16<> > reader; + ParseStringHandler > h; + reader.Parse(is, h); + EXPECT_EQ(0, StrCmp::Ch>(e, h.str_)); + EXPECT_EQ(StrLen(e), h.length_); +} + +TEST(Reader, ParseString_TranscodingWithValidation) { + const char* x = "\"Hello\""; + const wchar_t* e = L"Hello"; + GenericStringStream > is(x); + GenericReader, UTF16<> > reader; + ParseStringHandler > h; + reader.Parse(is, h); + EXPECT_EQ(0, StrCmp::Ch>(e, h.str_)); + EXPECT_EQ(StrLen(e), h.length_); +} + +TEST(Reader, ParseString_NonDestructive) { + StringStream s("\"Hello\\nWorld\""); + ParseStringHandler > h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(0, StrCmp("Hello\nWorld", h.str_)); + EXPECT_EQ(11u, h.length_); +} + +template +ParseErrorCode TestString(const typename Encoding::Ch* str) { + GenericStringStream s(str); + BaseReaderHandler h; + GenericReader reader; + reader.template Parse(s, h); + return reader.GetParseErrorCode(); +} + +TEST(Reader, ParseString_Error) { +#define TEST_STRING_ERROR(errorCode, str, errorOffset, streamPos)\ +{\ + GenericStringStream > s(str);\ + BaseReaderHandler > h;\ + GenericReader , UTF8<> > reader;\ + reader.Parse(s, h);\ + EXPECT_EQ(errorCode, reader.GetParseErrorCode());\ + EXPECT_EQ(errorOffset, reader.GetErrorOffset());\ + EXPECT_EQ(streamPos, s.Tell());\ +} + +#define ARRAY(...) { __VA_ARGS__ } +#define TEST_STRINGENCODING_ERROR(Encoding, TargetEncoding, utype, array) \ + { \ + static const utype ue[] = array; \ + static const Encoding::Ch* e = reinterpret_cast(&ue[0]); \ + EXPECT_EQ(kParseErrorStringInvalidEncoding, TestString(e));\ + /* decode error */\ + GenericStringStream s(e);\ + BaseReaderHandler h;\ + GenericReader reader;\ + reader.Parse(s, h);\ + EXPECT_EQ(kParseErrorStringInvalidEncoding, reader.GetParseErrorCode());\ + } + + // Invalid escape character in string. + TEST_STRING_ERROR(kParseErrorStringEscapeInvalid, "[\"\\a\"]", 2, 3); + + // Incorrect hex digit after \\u escape in string. + TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uABCG\"]", 2, 7); + + // Quotation in \\u escape in string (Issue #288) + TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uaaa\"]", 2, 7); + TEST_STRING_ERROR(kParseErrorStringUnicodeEscapeInvalidHex, "[\"\\uD800\\uFFF\"]", 2, 13); + + // The surrogate pair in string is invalid. + TEST_STRING_ERROR(kParseErrorStringUnicodeSurrogateInvalid, "[\"\\uD800X\"]", 2, 8); + TEST_STRING_ERROR(kParseErrorStringUnicodeSurrogateInvalid, "[\"\\uD800\\uFFFF\"]", 2, 14); + + // Missing a closing quotation mark in string. + TEST_STRING_ERROR(kParseErrorStringMissQuotationMark, "[\"Test]", 7, 7); + + // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt + + // 3 Malformed sequences + + // 3.1 Unexpected continuation bytes + { + char e[] = { '[', '\"', 0, '\"', ']', '\0' }; + for (unsigned char c = 0x80u; c <= 0xBFu; c++) { + e[2] = static_cast(c); + ParseErrorCode error = TestString >(e); + EXPECT_EQ(kParseErrorStringInvalidEncoding, error); + if (error != kParseErrorStringInvalidEncoding) + std::cout << static_cast(c) << std::endl; + } + } + + // 3.2 Lonely start characters, 3.5 Impossible bytes + { + char e[] = { '[', '\"', 0, ' ', '\"', ']', '\0' }; + for (unsigned c = 0xC0u; c <= 0xFFu; c++) { + e[2] = static_cast(c); + int streamPos; + if (c <= 0xC1u) + streamPos = 3; // 0xC0 - 0xC1 + else if (c <= 0xDFu) + streamPos = 4; // 0xC2 - 0xDF + else if (c <= 0xEFu) + streamPos = 5; // 0xE0 - 0xEF + else if (c <= 0xF4u) + streamPos = 6; // 0xF0 - 0xF4 + else + streamPos = 3; // 0xF5 - 0xFF + TEST_STRING_ERROR(kParseErrorStringInvalidEncoding, e, 2, streamPos); + } + } + + // 4 Overlong sequences + + // 4.1 Examples of an overlong ASCII character + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC0u, 0xAFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x80u, 0xAFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x80u, 0x80u, 0xAFu, '\"', ']', '\0')); + + // 4.2 Maximum overlong sequences + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC1u, 0xBFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x9Fu, 0xBFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x8Fu, 0xBFu, 0xBFu, '\"', ']', '\0')); + + // 4.3 Overlong representation of the NUL character + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xC0u, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xE0u, 0x80u, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xF0u, 0x80u, 0x80u, 0x80u, '\"', ']', '\0')); + + // 5 Illegal code positions + + // 5.1 Single UTF-16 surrogates + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xA0u, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xADu, 0xBFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xAEu, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xAFu, 0xBFu, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xB0u, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xBEu, 0x80u, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF8<>, UTF16<>, unsigned char, ARRAY('[', '\"', 0xEDu, 0xBFu, 0xBFu, '\"', ']', '\0')); + + // Malform UTF-16 sequences + TEST_STRINGENCODING_ERROR(UTF16<>, UTF8<>, wchar_t, ARRAY('[', '\"', 0xDC00, 0xDC00, '\"', ']', '\0')); + TEST_STRINGENCODING_ERROR(UTF16<>, UTF8<>, wchar_t, ARRAY('[', '\"', 0xD800, 0xD800, '\"', ']', '\0')); + + // Malform UTF-32 sequence + TEST_STRINGENCODING_ERROR(UTF32<>, UTF8<>, unsigned, ARRAY('[', '\"', 0x110000, '\"', ']', '\0')); + + // Malform ASCII sequence + TEST_STRINGENCODING_ERROR(ASCII<>, UTF8<>, char, ARRAY('[', '\"', char(0x80u), '\"', ']', '\0')); + +#undef ARRAY +#undef TEST_STRINGARRAY_ERROR +} + +template +struct ParseArrayHandler : BaseReaderHandler, ParseArrayHandler > { + ParseArrayHandler() : step_(0) {} + + bool Default() { ADD_FAILURE(); return false; } + bool Uint(unsigned i) { EXPECT_EQ(step_, i); step_++; return true; } + bool StartArray() { EXPECT_EQ(0u, step_); step_++; return true; } + bool EndArray(SizeType) { step_++; return true; } + + unsigned step_; +}; + +TEST(Reader, ParseEmptyArray) { + char *json = StrDup("[ ] "); + InsituStringStream s(json); + ParseArrayHandler<0> h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(2u, h.step_); + free(json); +} + +TEST(Reader, ParseArray) { + char *json = StrDup("[1, 2, 3, 4]"); + InsituStringStream s(json); + ParseArrayHandler<4> h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(6u, h.step_); + free(json); +} + +TEST(Reader, ParseArray_Error) { +#define TEST_ARRAY_ERROR(errorCode, str, errorOffset) \ + { \ + int streamPos = errorOffset; \ + char buffer[1001]; \ + strncpy(buffer, str, 1000); \ + InsituStringStream s(buffer); \ + BaseReaderHandler<> h; \ + GenericReader, UTF8<>, CrtAllocator> reader; \ + EXPECT_FALSE(reader.Parse(s, h)); \ + EXPECT_EQ(errorCode, reader.GetParseErrorCode());\ + EXPECT_EQ(errorOffset, reader.GetErrorOffset());\ + EXPECT_EQ(streamPos, s.Tell());\ + } + + // Missing a comma or ']' after an array element. + TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1", 2); + TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1}", 2); + TEST_ARRAY_ERROR(kParseErrorArrayMissCommaOrSquareBracket, "[1 2]", 3); + + // Array cannot have a trailing comma (without kParseTrailingCommasFlag); + // a value must follow a comma + TEST_ARRAY_ERROR(kParseErrorValueInvalid, "[1,]", 3); + +#undef TEST_ARRAY_ERROR +} + +struct ParseObjectHandler : BaseReaderHandler, ParseObjectHandler> { + ParseObjectHandler() : step_(0) {} + + bool Default() { ADD_FAILURE(); return false; } + bool Null() { EXPECT_EQ(8u, step_); step_++; return true; } + bool Bool(bool b) { + switch(step_) { + case 4: EXPECT_TRUE(b); step_++; return true; + case 6: EXPECT_FALSE(b); step_++; return true; + default: ADD_FAILURE(); return false; + } + } + bool Int(int i) { + switch(step_) { + case 10: EXPECT_EQ(123, i); step_++; return true; + case 15: EXPECT_EQ(1, i); step_++; return true; + case 16: EXPECT_EQ(2, i); step_++; return true; + case 17: EXPECT_EQ(3, i); step_++; return true; + default: ADD_FAILURE(); return false; + } + } + bool Uint(unsigned i) { return Int(static_cast(i)); } + bool Double(double d) { EXPECT_EQ(12u, step_); EXPECT_DOUBLE_EQ(3.1416, d); step_++; return true; } + bool String(const char* str, size_t, bool) { + switch(step_) { + case 1: EXPECT_STREQ("hello", str); step_++; return true; + case 2: EXPECT_STREQ("world", str); step_++; return true; + case 3: EXPECT_STREQ("t", str); step_++; return true; + case 5: EXPECT_STREQ("f", str); step_++; return true; + case 7: EXPECT_STREQ("n", str); step_++; return true; + case 9: EXPECT_STREQ("i", str); step_++; return true; + case 11: EXPECT_STREQ("pi", str); step_++; return true; + case 13: EXPECT_STREQ("a", str); step_++; return true; + default: ADD_FAILURE(); return false; + } + } + bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; } + bool EndObject(SizeType memberCount) { EXPECT_EQ(19u, step_); EXPECT_EQ(7u, memberCount); step_++; return true; } + bool StartArray() { EXPECT_EQ(14u, step_); step_++; return true; } + bool EndArray(SizeType elementCount) { EXPECT_EQ(18u, step_); EXPECT_EQ(3u, elementCount); step_++; return true; } + + unsigned step_; +}; + +TEST(Reader, ParseObject) { + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "; + + // Insitu + { + char* json2 = StrDup(json); + InsituStringStream s(json2); + ParseObjectHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(20u, h.step_); + free(json2); + } + + // Normal + { + StringStream s(json); + ParseObjectHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(20u, h.step_); + } +} + +struct ParseEmptyObjectHandler : BaseReaderHandler, ParseEmptyObjectHandler> { + ParseEmptyObjectHandler() : step_(0) {} + + bool Default() { ADD_FAILURE(); return false; } + bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; } + bool EndObject(SizeType) { EXPECT_EQ(1u, step_); step_++; return true; } + + unsigned step_; +}; + +TEST(Reader, Parse_EmptyObject) { + StringStream s("{ } "); + ParseEmptyObjectHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(2u, h.step_); +} + +struct ParseMultipleRootHandler : BaseReaderHandler, ParseMultipleRootHandler> { + ParseMultipleRootHandler() : step_(0) {} + + bool Default() { ADD_FAILURE(); return false; } + bool StartObject() { EXPECT_EQ(0u, step_); step_++; return true; } + bool EndObject(SizeType) { EXPECT_EQ(1u, step_); step_++; return true; } + bool StartArray() { EXPECT_EQ(2u, step_); step_++; return true; } + bool EndArray(SizeType) { EXPECT_EQ(3u, step_); step_++; return true; } + + unsigned step_; +}; + +template +void TestMultipleRoot() { + StringStream s("{}[] a"); + ParseMultipleRootHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(2u, h.step_); + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(4u, h.step_); + EXPECT_EQ(' ', s.Take()); + EXPECT_EQ('a', s.Take()); +} + +TEST(Reader, Parse_MultipleRoot) { + TestMultipleRoot(); +} + +TEST(Reader, ParseIterative_MultipleRoot) { + TestMultipleRoot(); +} + +template +void TestInsituMultipleRoot() { + char* buffer = strdup("{}[] a"); + InsituStringStream s(buffer); + ParseMultipleRootHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(2u, h.step_); + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(4u, h.step_); + EXPECT_EQ(' ', s.Take()); + EXPECT_EQ('a', s.Take()); + free(buffer); +} + +TEST(Reader, ParseInsitu_MultipleRoot) { + TestInsituMultipleRoot(); +} + +TEST(Reader, ParseInsituIterative_MultipleRoot) { + TestInsituMultipleRoot(); +} + +#define TEST_ERROR(errorCode, str, errorOffset) \ + { \ + int streamPos = errorOffset; \ + char buffer[1001]; \ + strncpy(buffer, str, 1000); \ + InsituStringStream s(buffer); \ + BaseReaderHandler<> h; \ + Reader reader; \ + EXPECT_FALSE(reader.Parse(s, h)); \ + EXPECT_EQ(errorCode, reader.GetParseErrorCode());\ + EXPECT_EQ(errorOffset, reader.GetErrorOffset());\ + EXPECT_EQ(streamPos, s.Tell());\ + } + +TEST(Reader, ParseDocument_Error) { + // The document is empty. + TEST_ERROR(kParseErrorDocumentEmpty, "", 0); + TEST_ERROR(kParseErrorDocumentEmpty, " ", 1); + TEST_ERROR(kParseErrorDocumentEmpty, " \n", 2); + + // The document root must not follow by other values. + TEST_ERROR(kParseErrorDocumentRootNotSingular, "[] 0", 3); + TEST_ERROR(kParseErrorDocumentRootNotSingular, "{} 0", 3); + TEST_ERROR(kParseErrorDocumentRootNotSingular, "null []", 5); + TEST_ERROR(kParseErrorDocumentRootNotSingular, "0 {}", 2); +} + +TEST(Reader, ParseValue_Error) { + // Invalid value. + TEST_ERROR(kParseErrorValueInvalid, "nulL", 3); + TEST_ERROR(kParseErrorValueInvalid, "truE", 3); + TEST_ERROR(kParseErrorValueInvalid, "falsE", 4); + TEST_ERROR(kParseErrorValueInvalid, "a]", 0); + TEST_ERROR(kParseErrorValueInvalid, ".1", 0); +} + +TEST(Reader, ParseObject_Error) { + // Missing a name for object member. + TEST_ERROR(kParseErrorObjectMissName, "{1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{null:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{true:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{false:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{1:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{[]:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{{}:1}", 1); + TEST_ERROR(kParseErrorObjectMissName, "{xyz:1}", 1); + + // Missing a colon after a name of object member. + TEST_ERROR(kParseErrorObjectMissColon, "{\"a\" 1}", 5); + TEST_ERROR(kParseErrorObjectMissColon, "{\"a\",1}", 4); + + // Must be a comma or '}' after an object member + TEST_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, "{\"a\":1]", 6); + + // Object cannot have a trailing comma (without kParseTrailingCommasFlag); + // an object member name must follow a comma + TEST_ERROR(kParseErrorObjectMissName, "{\"a\":1,}", 7); + + // This tests that MemoryStream is checking the length in Peek(). + { + MemoryStream ms("{\"a\"", 1); + BaseReaderHandler<> h; + Reader reader; + EXPECT_FALSE(reader.Parse(ms, h)); + EXPECT_EQ(kParseErrorObjectMissName, reader.GetParseErrorCode()); + } +} + +#undef TEST_ERROR + +TEST(Reader, SkipWhitespace) { + StringStream ss(" A \t\tB\n \n\nC\r\r \rD \t\n\r E"); + const char* expected = "ABCDE"; + for (size_t i = 0; i < 5; i++) { + SkipWhitespace(ss); + EXPECT_EQ(expected[i], ss.Take()); + } +} + +// Test implementing a stream without copy stream optimization. +// Clone from GenericStringStream except that copy constructor is disabled. +template +class CustomStringStream { +public: + typedef typename Encoding::Ch Ch; + + CustomStringStream(const Ch *src) : src_(src), head_(src) {} + + Ch Peek() const { return *src_; } + Ch Take() { return *src_++; } + size_t Tell() const { return static_cast(src_ - head_); } + + Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; } + void Put(Ch) { RAPIDJSON_ASSERT(false); } + void Flush() { RAPIDJSON_ASSERT(false); } + size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; } + +private: + // Prohibit copy constructor & assignment operator. + CustomStringStream(const CustomStringStream&); + CustomStringStream& operator=(const CustomStringStream&); + + const Ch* src_; //!< Current read position. + const Ch* head_; //!< Original head of the string. +}; + +// If the following code is compiled, it should generate compilation error as predicted. +// Because CustomStringStream<> is not copyable via making copy constructor private. +#if 0 +namespace rapidjson { + +template +struct StreamTraits > { + enum { copyOptimization = 1 }; +}; + +} // namespace rapidjson +#endif + +TEST(Reader, CustomStringStream) { + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "; + CustomStringStream > s(json); + ParseObjectHandler h; + Reader reader; + reader.Parse(s, h); + EXPECT_EQ(20u, h.step_); +} + +#include + +class IStreamWrapper { +public: + typedef char Ch; + + IStreamWrapper(std::istream& is) : is_(is) {} + + Ch Peek() const { + int c = is_.peek(); + return c == std::char_traits::eof() ? '\0' : static_cast(c); + } + + Ch Take() { + int c = is_.get(); + return c == std::char_traits::eof() ? '\0' : static_cast(c); + } + + size_t Tell() const { return static_cast(is_.tellg()); } + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch) { assert(false); } + void Flush() { assert(false); } + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + IStreamWrapper(const IStreamWrapper&); + IStreamWrapper& operator=(const IStreamWrapper&); + + std::istream& is_; +}; + +TEST(Reader, Parse_IStreamWrapper_StringStream) { + const char* json = "[1,2,3,4]"; + + std::stringstream ss(json); + IStreamWrapper is(ss); + + Reader reader; + ParseArrayHandler<4> h; + reader.Parse(is, h); + EXPECT_FALSE(reader.HasParseError()); +} + +// Test iterative parsing. + +#define TESTERRORHANDLING(text, errorCode, offset)\ +{\ + int streamPos = offset; \ + StringStream json(text); \ + BaseReaderHandler<> handler; \ + Reader reader; \ + reader.Parse(json, handler); \ + EXPECT_TRUE(reader.HasParseError()); \ + EXPECT_EQ(errorCode, reader.GetParseErrorCode()); \ + EXPECT_EQ(offset, reader.GetErrorOffset()); \ + EXPECT_EQ(streamPos, json.Tell()); \ +} + +TEST(Reader, IterativeParsing_ErrorHandling) { + TESTERRORHANDLING("{\"a\": a}", kParseErrorValueInvalid, 6u); + + TESTERRORHANDLING("", kParseErrorDocumentEmpty, 0u); + TESTERRORHANDLING("{}{}", kParseErrorDocumentRootNotSingular, 2u); + + TESTERRORHANDLING("{1}", kParseErrorObjectMissName, 1u); + TESTERRORHANDLING("{\"a\", 1}", kParseErrorObjectMissColon, 4u); + TESTERRORHANDLING("{\"a\"}", kParseErrorObjectMissColon, 4u); + TESTERRORHANDLING("{\"a\": 1", kParseErrorObjectMissCommaOrCurlyBracket, 7u); + TESTERRORHANDLING("[1 2 3]", kParseErrorArrayMissCommaOrSquareBracket, 3u); + TESTERRORHANDLING("{\"a: 1", kParseErrorStringMissQuotationMark, 6u); + TESTERRORHANDLING("{\"a\":}", kParseErrorValueInvalid, 5u); + TESTERRORHANDLING("{\"a\":]", kParseErrorValueInvalid, 5u); + TESTERRORHANDLING("[1,2,}", kParseErrorValueInvalid, 5u); + TESTERRORHANDLING("[}]", kParseErrorValueInvalid, 1u); + TESTERRORHANDLING("[,]", kParseErrorValueInvalid, 1u); + TESTERRORHANDLING("[1,,]", kParseErrorValueInvalid, 3u); + + // Trailing commas are not allowed without kParseTrailingCommasFlag + TESTERRORHANDLING("{\"a\": 1,}", kParseErrorObjectMissName, 8u); + TESTERRORHANDLING("[1,2,3,]", kParseErrorValueInvalid, 7u); + + // Any JSON value can be a valid root element in RFC7159. + TESTERRORHANDLING("\"ab", kParseErrorStringMissQuotationMark, 3u); + TESTERRORHANDLING("truE", kParseErrorValueInvalid, 3u); + TESTERRORHANDLING("False", kParseErrorValueInvalid, 0u); + TESTERRORHANDLING("true, false", kParseErrorDocumentRootNotSingular, 4u); + TESTERRORHANDLING("false, false", kParseErrorDocumentRootNotSingular, 5u); + TESTERRORHANDLING("nulL", kParseErrorValueInvalid, 3u); + TESTERRORHANDLING("null , null", kParseErrorDocumentRootNotSingular, 5u); + TESTERRORHANDLING("1a", kParseErrorDocumentRootNotSingular, 1u); +} + +template > +struct IterativeParsingReaderHandler { + typedef typename Encoding::Ch Ch; + + const static int LOG_NULL = -1; + const static int LOG_BOOL = -2; + const static int LOG_INT = -3; + const static int LOG_UINT = -4; + const static int LOG_INT64 = -5; + const static int LOG_UINT64 = -6; + const static int LOG_DOUBLE = -7; + const static int LOG_STRING = -8; + const static int LOG_STARTOBJECT = -9; + const static int LOG_KEY = -10; + const static int LOG_ENDOBJECT = -11; + const static int LOG_STARTARRAY = -12; + const static int LOG_ENDARRAY = -13; + + const static size_t LogCapacity = 256; + int Logs[LogCapacity]; + size_t LogCount; + + IterativeParsingReaderHandler() : LogCount(0) { + } + + bool Null() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_NULL; return true; } + + bool Bool(bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_BOOL; return true; } + + bool Int(int) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT; return true; } + + bool Uint(unsigned) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT; return true; } + + bool Int64(int64_t) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_INT64; return true; } + + bool Uint64(uint64_t) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_UINT64; return true; } + + bool Double(double) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_DOUBLE; return true; } + + bool RawNumber(const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STRING; return true; } + + bool String(const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STRING; return true; } + + bool StartObject() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STARTOBJECT; return true; } + + bool Key (const Ch*, SizeType, bool) { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_KEY; return true; } + + bool EndObject(SizeType c) { + RAPIDJSON_ASSERT(LogCount < LogCapacity); + Logs[LogCount++] = LOG_ENDOBJECT; + Logs[LogCount++] = static_cast(c); + return true; + } + + bool StartArray() { RAPIDJSON_ASSERT(LogCount < LogCapacity); Logs[LogCount++] = LOG_STARTARRAY; return true; } + + bool EndArray(SizeType c) { + RAPIDJSON_ASSERT(LogCount < LogCapacity); + Logs[LogCount++] = LOG_ENDARRAY; + Logs[LogCount++] = static_cast(c); + return true; + } +}; + +TEST(Reader, IterativeParsing_General) { + { + StringStream is("[1, {\"k\": [1, 2]}, null, false, true, \"string\", 1.2]"); + Reader reader; + IterativeParsingReaderHandler<> handler; + + ParseResult r = reader.Parse(is, handler); + + EXPECT_FALSE(r.IsError()); + EXPECT_FALSE(reader.HasParseError()); + + int e[] = { + handler.LOG_STARTARRAY, + handler.LOG_INT, + handler.LOG_STARTOBJECT, + handler.LOG_KEY, + handler.LOG_STARTARRAY, + handler.LOG_INT, + handler.LOG_INT, + handler.LOG_ENDARRAY, 2, + handler.LOG_ENDOBJECT, 1, + handler.LOG_NULL, + handler.LOG_BOOL, + handler.LOG_BOOL, + handler.LOG_STRING, + handler.LOG_DOUBLE, + handler.LOG_ENDARRAY, 7 + }; + + EXPECT_EQ(sizeof(e) / sizeof(int), handler.LogCount); + + for (size_t i = 0; i < handler.LogCount; ++i) { + EXPECT_EQ(e[i], handler.Logs[i]) << "i = " << i; + } + } +} + +TEST(Reader, IterativeParsing_Count) { + { + StringStream is("[{}, {\"k\": 1}, [1], []]"); + Reader reader; + IterativeParsingReaderHandler<> handler; + + ParseResult r = reader.Parse(is, handler); + + EXPECT_FALSE(r.IsError()); + EXPECT_FALSE(reader.HasParseError()); + + int e[] = { + handler.LOG_STARTARRAY, + handler.LOG_STARTOBJECT, + handler.LOG_ENDOBJECT, 0, + handler.LOG_STARTOBJECT, + handler.LOG_KEY, + handler.LOG_INT, + handler.LOG_ENDOBJECT, 1, + handler.LOG_STARTARRAY, + handler.LOG_INT, + handler.LOG_ENDARRAY, 1, + handler.LOG_STARTARRAY, + handler.LOG_ENDARRAY, 0, + handler.LOG_ENDARRAY, 4 + }; + + EXPECT_EQ(sizeof(e) / sizeof(int), handler.LogCount); + + for (size_t i = 0; i < handler.LogCount; ++i) { + EXPECT_EQ(e[i], handler.Logs[i]) << "i = " << i; + } + } +} + +// Test iterative parsing on kParseErrorTermination. +struct HandlerTerminateAtStartObject : public IterativeParsingReaderHandler<> { + bool StartObject() { return false; } +}; + +struct HandlerTerminateAtStartArray : public IterativeParsingReaderHandler<> { + bool StartArray() { return false; } +}; + +struct HandlerTerminateAtEndObject : public IterativeParsingReaderHandler<> { + bool EndObject(SizeType) { return false; } +}; + +struct HandlerTerminateAtEndArray : public IterativeParsingReaderHandler<> { + bool EndArray(SizeType) { return false; } +}; + +TEST(Reader, IterativeParsing_ShortCircuit) { + { + HandlerTerminateAtStartObject handler; + Reader reader; + StringStream is("[1, {}]"); + + ParseResult r = reader.Parse(is, handler); + + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(4u, r.Offset()); + } + + { + HandlerTerminateAtStartArray handler; + Reader reader; + StringStream is("{\"a\": []}"); + + ParseResult r = reader.Parse(is, handler); + + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(6u, r.Offset()); + } + + { + HandlerTerminateAtEndObject handler; + Reader reader; + StringStream is("[1, {}]"); + + ParseResult r = reader.Parse(is, handler); + + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(5u, r.Offset()); + } + + { + HandlerTerminateAtEndArray handler; + Reader reader; + StringStream is("{\"a\": []}"); + + ParseResult r = reader.Parse(is, handler); + + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(7u, r.Offset()); + } +} + +// For covering BaseReaderHandler default functions +TEST(Reader, BaseReaderHandler_Default) { + BaseReaderHandler<> h; + Reader reader; + StringStream is("[null, true, -1, 1, -1234567890123456789, 1234567890123456789, 3.14, \"s\", { \"a\" : 1 }]"); + EXPECT_TRUE(reader.Parse(is, h)); +} + +template +struct TerminateHandler { + bool Null() { return e != 0; } + bool Bool(bool) { return e != 1; } + bool Int(int) { return e != 2; } + bool Uint(unsigned) { return e != 3; } + bool Int64(int64_t) { return e != 4; } + bool Uint64(uint64_t) { return e != 5; } + bool Double(double) { return e != 6; } + bool RawNumber(const char*, SizeType, bool) { return e != 7; } + bool String(const char*, SizeType, bool) { return e != 8; } + bool StartObject() { return e != 9; } + bool Key(const char*, SizeType, bool) { return e != 10; } + bool EndObject(SizeType) { return e != 11; } + bool StartArray() { return e != 12; } + bool EndArray(SizeType) { return e != 13; } +}; + +#define TEST_TERMINATION(e, json)\ +{\ + Reader reader;\ + TerminateHandler h;\ + StringStream is(json);\ + EXPECT_FALSE(reader.Parse(is, h));\ + EXPECT_EQ(kParseErrorTermination, reader.GetParseErrorCode());\ +} + +TEST(Reader, ParseTerminationByHandler) { + TEST_TERMINATION(0, "[null"); + TEST_TERMINATION(1, "[true"); + TEST_TERMINATION(1, "[false"); + TEST_TERMINATION(2, "[-1"); + TEST_TERMINATION(3, "[1"); + TEST_TERMINATION(4, "[-1234567890123456789"); + TEST_TERMINATION(5, "[1234567890123456789"); + TEST_TERMINATION(6, "[0.5]"); + // RawNumber() is never called + TEST_TERMINATION(8, "[\"a\""); + TEST_TERMINATION(9, "[{"); + TEST_TERMINATION(10, "[{\"a\""); + TEST_TERMINATION(11, "[{}"); + TEST_TERMINATION(11, "[{\"a\":1}"); // non-empty object + TEST_TERMINATION(12, "{\"a\":["); + TEST_TERMINATION(13, "{\"a\":[]"); + TEST_TERMINATION(13, "{\"a\":[1]"); // non-empty array +} + +TEST(Reader, ParseComments) { + const char* json = + "// Here is a one-line comment.\n" + "{// And here's another one\n" + " /*And here's an in-line one.*/\"hello\" : \"world\"," + " \"t\" :/* And one with '*' symbol*/true ," + "/* A multiline comment\n" + " goes here*/" + " \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3]" + "}/*And the last one to be sure */"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); +} + +TEST(Reader, ParseEmptyInlineComment) { + const char* json = "{/**/\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); +} + +TEST(Reader, ParseEmptyOnelineComment) { + const char* json = "{//\n\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); +} + +TEST(Reader, ParseMultipleCommentsInARow) { + const char* json = + "{/* first comment *//* second */\n" + "/* third */ /*fourth*/// last one\n" + "\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); +} + +TEST(Reader, InlineCommentsAreDisabledByDefault) { + { + const char* json = "{/* Inline comment. */\"hello\" : \"world\", \"t\" : true, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + } + + { + const char* json = + "{\"hello\" : /* Multiline comment starts here\n" + " continues here\n" + " and ends here */\"world\", \"t\" :true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + } +} + +TEST(Reader, OnelineCommentsAreDisabledByDefault) { + const char* json = "{// One-line comment\n\"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); +} + +TEST(Reader, EofAfterOneLineComment) { + const char* json = "{\"hello\" : \"world\" // EOF is here -->\0 \n}"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + EXPECT_EQ(kParseErrorObjectMissCommaOrCurlyBracket, reader.GetParseErrorCode()); +} + +TEST(Reader, IncompleteMultilineComment) { + const char* json = "{\"hello\" : \"world\" /* EOF is here -->\0 */}"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode()); +} + +TEST(Reader, IncompleteMultilineComment2) { + const char* json = "{\"hello\" : \"world\" /* *\0 */}"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode()); +} + +TEST(Reader, UnrecognizedComment) { + const char* json = "{\"hello\" : \"world\" /! }"; + + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_FALSE(reader.Parse(s, h)); + EXPECT_EQ(kParseErrorUnspecificSyntaxError, reader.GetParseErrorCode()); +} + +struct NumbersAsStringsHandler { + bool Null() { return true; } + bool Bool(bool) { return true; } + bool Int(int) { return true; } + bool Uint(unsigned) { return true; } + bool Int64(int64_t) { return true; } + bool Uint64(uint64_t) { return true; } + bool Double(double) { return true; } + // 'str' is not null-terminated + bool RawNumber(const char* str, SizeType length, bool) { + EXPECT_TRUE(str != 0); + EXPECT_TRUE(expected_len_ == length); + EXPECT_TRUE(strncmp(str, expected_, length) == 0); + return true; + } + bool String(const char*, SizeType, bool) { return true; } + bool StartObject() { return true; } + bool Key(const char*, SizeType, bool) { return true; } + bool EndObject(SizeType) { return true; } + bool StartArray() { return true; } + bool EndArray(SizeType) { return true; } + + NumbersAsStringsHandler(const char* expected) + : expected_(expected) + , expected_len_(strlen(expected)) {} + + const char* expected_; + size_t expected_len_; +}; + +TEST(Reader, NumbersAsStrings) { + { + const char* json = "{ \"pi\": 3.1416 } "; + StringStream s(json); + NumbersAsStringsHandler h("3.1416"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } + { + char* json = StrDup("{ \"pi\": 3.1416 } "); + InsituStringStream s(json); + NumbersAsStringsHandler h("3.1416"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + free(json); + } + { + const char* json = "{ \"gigabyte\": 1.0e9 } "; + StringStream s(json); + NumbersAsStringsHandler h("1.0e9"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } + { + char* json = StrDup("{ \"gigabyte\": 1.0e9 } "); + InsituStringStream s(json); + NumbersAsStringsHandler h("1.0e9"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + free(json); + } + { + const char* json = "{ \"pi\": 314.159e-2 } "; + StringStream s(json); + NumbersAsStringsHandler h("314.159e-2"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } + { + char* json = StrDup("{ \"gigabyte\": 314.159e-2 } "); + InsituStringStream s(json); + NumbersAsStringsHandler h("314.159e-2"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + free(json); + } + { + const char* json = "{ \"negative\": -1.54321 } "; + StringStream s(json); + NumbersAsStringsHandler h("-1.54321"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } + { + char* json = StrDup("{ \"negative\": -1.54321 } "); + InsituStringStream s(json); + NumbersAsStringsHandler h("-1.54321"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + free(json); + } + { + const char* json = "{ \"pi\": 314.159e-2 } "; + std::stringstream ss(json); + IStreamWrapper s(ss); + NumbersAsStringsHandler h("314.159e-2"); + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + } +} + +template +void TestTrailingCommas() { + { + StringStream s("[1,2,3,]"); + ParseArrayHandler<3> h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(5u, h.step_); + } + { + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false," + "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3],}"; + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); + } + { + // whitespace around trailing commas + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false," + "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3\n,\n]\n,\n} "; + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); + } + { + // comments around trailing commas + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null," + "\"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3/*test*/,/*test*/]/*test*/,/*test*/}"; + StringStream s(json); + ParseObjectHandler h; + Reader reader; + EXPECT_TRUE(reader.Parse(s, h)); + EXPECT_EQ(20u, h.step_); + } +} + +TEST(Reader, TrailingCommas) { + TestTrailingCommas(); +} + +TEST(Reader, TrailingCommasIterative) { + TestTrailingCommas(); +} + +template +void TestMultipleTrailingCommaErrors() { + // only a single trailing comma is allowed. + { + StringStream s("[1,2,3,,]"); + ParseArrayHandler<3> h; + Reader reader; + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorValueInvalid, r.Code()); + EXPECT_EQ(7u, r.Offset()); + } + { + const char* json = "{ \"hello\" : \"world\", \"t\" : true , \"f\" : false," + "\"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3,],,}"; + StringStream s(json); + ParseObjectHandler h; + Reader reader; + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorObjectMissName, r.Code()); + EXPECT_EQ(95u, r.Offset()); + } +} + +TEST(Reader, MultipleTrailingCommaErrors) { + TestMultipleTrailingCommaErrors(); +} + +TEST(Reader, MultipleTrailingCommaErrorsIterative) { + TestMultipleTrailingCommaErrors(); +} + +template +void TestEmptyExceptForCommaErrors() { + // not allowed even with trailing commas enabled; the + // trailing comma must follow a value. + { + StringStream s("[,]"); + ParseArrayHandler<3> h; + Reader reader; + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorValueInvalid, r.Code()); + EXPECT_EQ(1u, r.Offset()); + } + { + StringStream s("{,}"); + ParseObjectHandler h; + Reader reader; + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorObjectMissName, r.Code()); + EXPECT_EQ(1u, r.Offset()); + } +} + +TEST(Reader, EmptyExceptForCommaErrors) { + TestEmptyExceptForCommaErrors(); +} + +TEST(Reader, EmptyExceptForCommaErrorsIterative) { + TestEmptyExceptForCommaErrors(); +} + +template +void TestTrailingCommaHandlerTermination() { + { + HandlerTerminateAtEndArray h; + Reader reader; + StringStream s("[1,2,3,]"); + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(7u, r.Offset()); + } + { + HandlerTerminateAtEndObject h; + Reader reader; + StringStream s("{\"t\": true, \"f\": false,}"); + ParseResult r = reader.Parse(s, h); + EXPECT_TRUE(reader.HasParseError()); + EXPECT_EQ(kParseErrorTermination, r.Code()); + EXPECT_EQ(23u, r.Offset()); + } +} + +TEST(Reader, TrailingCommaHandlerTermination) { + TestTrailingCommaHandlerTermination(); +} + +TEST(Reader, TrailingCommaHandlerTerminationIterative) { + TestTrailingCommaHandlerTermination(); +} + +TEST(Reader, ParseNanAndInfinity) { +#define TEST_NAN_INF(str, x) \ + { \ + { \ + StringStream s(str); \ + ParseDoubleHandler h; \ + Reader reader; \ + ASSERT_EQ(kParseErrorNone, reader.Parse(s, h).Code()); \ + EXPECT_EQ(1u, h.step_); \ + internal::Double e(x), a(h.actual_); \ + EXPECT_EQ(e.IsNan(), a.IsNan()); \ + EXPECT_EQ(e.IsInf(), a.IsInf()); \ + if (!e.IsNan()) \ + EXPECT_EQ(e.Sign(), a.Sign()); \ + } \ + { \ + const char* json = "{ \"naninfdouble\": " str " } "; \ + StringStream s(json); \ + NumbersAsStringsHandler h(str); \ + Reader reader; \ + EXPECT_TRUE(reader.Parse(s, h)); \ + } \ + { \ + char* json = StrDup("{ \"naninfdouble\": " str " } "); \ + InsituStringStream s(json); \ + NumbersAsStringsHandler h(str); \ + Reader reader; \ + EXPECT_TRUE(reader.Parse(s, h)); \ + free(json); \ + } \ + } +#define TEST_NAN_INF_ERROR(errorCode, str, errorOffset) \ + { \ + int streamPos = errorOffset; \ + char buffer[1001]; \ + strncpy(buffer, str, 1000); \ + InsituStringStream s(buffer); \ + BaseReaderHandler<> h; \ + Reader reader; \ + EXPECT_FALSE(reader.Parse(s, h)); \ + EXPECT_EQ(errorCode, reader.GetParseErrorCode());\ + EXPECT_EQ(errorOffset, reader.GetErrorOffset());\ + EXPECT_EQ(streamPos, s.Tell());\ + } + + double nan = std::numeric_limits::quiet_NaN(); + double inf = std::numeric_limits::infinity(); + + TEST_NAN_INF("NaN", nan); + TEST_NAN_INF("-NaN", nan); + TEST_NAN_INF("Inf", inf); + TEST_NAN_INF("Infinity", inf); + TEST_NAN_INF("-Inf", -inf); + TEST_NAN_INF("-Infinity", -inf); + TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "nan", 1); + TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "-nan", 1); + TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "NAN", 1); + TEST_NAN_INF_ERROR(kParseErrorValueInvalid, "-Infinty", 6); + +#undef TEST_NAN_INF_ERROR +#undef TEST_NAN_INF +} + +RAPIDJSON_DIAG_POP diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/regextest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/regextest.cpp new file mode 100644 index 0000000000..4fb5b222e4 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/regextest.cpp @@ -0,0 +1,592 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/internal/regex.h" + +using namespace rapidjson::internal; + +TEST(Regex, Single) { + Regex re("a"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("b")); +} + +TEST(Regex, Concatenation) { + Regex re("abc"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abc")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ab")); + EXPECT_FALSE(re.Match("abcd")); +} + +TEST(Regex, Alternation1) { + Regex re("abab|abbb"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abab")); + EXPECT_TRUE(re.Match("abbb")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("ab")); + EXPECT_FALSE(re.Match("ababa")); + EXPECT_FALSE(re.Match("abb")); + EXPECT_FALSE(re.Match("abbbb")); +} + +TEST(Regex, Alternation2) { + Regex re("a|b|c"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("c")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("aa")); + EXPECT_FALSE(re.Match("ab")); +} + +TEST(Regex, Parenthesis1) { + Regex re("(ab)c"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abc")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ab")); + EXPECT_FALSE(re.Match("abcd")); +} + +TEST(Regex, Parenthesis2) { + Regex re("a(bc)"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abc")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ab")); + EXPECT_FALSE(re.Match("abcd")); +} + +TEST(Regex, Parenthesis3) { + Regex re("(a|b)(c|d)"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ac")); + EXPECT_TRUE(re.Match("ad")); + EXPECT_TRUE(re.Match("bc")); + EXPECT_TRUE(re.Match("bd")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("ab")); + EXPECT_FALSE(re.Match("cd")); +} + +TEST(Regex, ZeroOrOne1) { + Regex re("a?"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("")); + EXPECT_TRUE(re.Match("a")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, ZeroOrOne2) { + Regex re("a?b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("ab")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("aa")); + EXPECT_FALSE(re.Match("bb")); + EXPECT_FALSE(re.Match("ba")); +} + +TEST(Regex, ZeroOrOne3) { + Regex re("ab?"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("ab")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("aa")); + EXPECT_FALSE(re.Match("bb")); + EXPECT_FALSE(re.Match("ba")); +} + +TEST(Regex, ZeroOrOne4) { + Regex re("a?b?"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("")); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("ab")); + EXPECT_FALSE(re.Match("aa")); + EXPECT_FALSE(re.Match("bb")); + EXPECT_FALSE(re.Match("ba")); + EXPECT_FALSE(re.Match("abc")); +} + +TEST(Regex, ZeroOrOne5) { + Regex re("a(ab)?b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aabb")); + EXPECT_FALSE(re.Match("aab")); + EXPECT_FALSE(re.Match("abb")); +} + +TEST(Regex, ZeroOrMore1) { + Regex re("a*"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("")); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("aa")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ab")); +} + +TEST(Regex, ZeroOrMore2) { + Regex re("a*b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aab")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("bb")); +} + +TEST(Regex, ZeroOrMore3) { + Regex re("a*b*"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("")); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("aa")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("bb")); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aabb")); + EXPECT_FALSE(re.Match("ba")); +} + +TEST(Regex, ZeroOrMore4) { + Regex re("a(ab)*b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aabb")); + EXPECT_TRUE(re.Match("aababb")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, OneOrMore1) { + Regex re("a+"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("aa")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ab")); +} + +TEST(Regex, OneOrMore2) { + Regex re("a+b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aab")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("b")); +} + +TEST(Regex, OneOrMore3) { + Regex re("a+b+"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ab")); + EXPECT_TRUE(re.Match("aab")); + EXPECT_TRUE(re.Match("abb")); + EXPECT_TRUE(re.Match("aabb")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("ba")); +} + +TEST(Regex, OneOrMore4) { + Regex re("a(ab)+b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("aabb")); + EXPECT_TRUE(re.Match("aababb")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("ab")); +} + +TEST(Regex, QuantifierExact1) { + Regex re("ab{3}c"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbc")); + EXPECT_FALSE(re.Match("ac")); + EXPECT_FALSE(re.Match("abc")); + EXPECT_FALSE(re.Match("abbc")); + EXPECT_FALSE(re.Match("abbbbc")); +} + +TEST(Regex, QuantifierExact2) { + Regex re("a(bc){3}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abcbcbcd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abcd")); + EXPECT_FALSE(re.Match("abcbcd")); + EXPECT_FALSE(re.Match("abcbcbcbcd")); +} + +TEST(Regex, QuantifierExact3) { + Regex re("a(b|c){3}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbd")); + EXPECT_TRUE(re.Match("acccd")); + EXPECT_TRUE(re.Match("abcbd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abbd")); + EXPECT_FALSE(re.Match("accccd")); + EXPECT_FALSE(re.Match("abbbbd")); +} + +TEST(Regex, QuantifierMin1) { + Regex re("ab{3,}c"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbc")); + EXPECT_TRUE(re.Match("abbbbc")); + EXPECT_TRUE(re.Match("abbbbbc")); + EXPECT_FALSE(re.Match("ac")); + EXPECT_FALSE(re.Match("abc")); + EXPECT_FALSE(re.Match("abbc")); +} + +TEST(Regex, QuantifierMin2) { + Regex re("a(bc){3,}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abcbcbcd")); + EXPECT_TRUE(re.Match("abcbcbcbcd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abcd")); + EXPECT_FALSE(re.Match("abcbcd")); +} + +TEST(Regex, QuantifierMin3) { + Regex re("a(b|c){3,}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbd")); + EXPECT_TRUE(re.Match("acccd")); + EXPECT_TRUE(re.Match("abcbd")); + EXPECT_TRUE(re.Match("accccd")); + EXPECT_TRUE(re.Match("abbbbd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abbd")); +} + +TEST(Regex, QuantifierMinMax1) { + Regex re("ab{3,5}c"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbc")); + EXPECT_TRUE(re.Match("abbbbc")); + EXPECT_TRUE(re.Match("abbbbbc")); + EXPECT_FALSE(re.Match("ac")); + EXPECT_FALSE(re.Match("abc")); + EXPECT_FALSE(re.Match("abbc")); + EXPECT_FALSE(re.Match("abbbbbbc")); +} + +TEST(Regex, QuantifierMinMax2) { + Regex re("a(bc){3,5}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abcbcbcd")); + EXPECT_TRUE(re.Match("abcbcbcbcd")); + EXPECT_TRUE(re.Match("abcbcbcbcbcd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abcd")); + EXPECT_FALSE(re.Match("abcbcd")); + EXPECT_FALSE(re.Match("abcbcbcbcbcbcd")); +} + +TEST(Regex, QuantifierMinMax3) { + Regex re("a(b|c){3,5}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("abbbd")); + EXPECT_TRUE(re.Match("acccd")); + EXPECT_TRUE(re.Match("abcbd")); + EXPECT_TRUE(re.Match("accccd")); + EXPECT_TRUE(re.Match("abbbbd")); + EXPECT_TRUE(re.Match("acccccd")); + EXPECT_TRUE(re.Match("abbbbbd")); + EXPECT_FALSE(re.Match("ad")); + EXPECT_FALSE(re.Match("abbd")); + EXPECT_FALSE(re.Match("accccccd")); + EXPECT_FALSE(re.Match("abbbbbbd")); +} + +// Issue538 +TEST(Regex, QuantifierMinMax4) { + Regex re("a(b|c){0,3}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ad")); + EXPECT_TRUE(re.Match("abd")); + EXPECT_TRUE(re.Match("acd")); + EXPECT_TRUE(re.Match("abbd")); + EXPECT_TRUE(re.Match("accd")); + EXPECT_TRUE(re.Match("abcd")); + EXPECT_TRUE(re.Match("abbbd")); + EXPECT_TRUE(re.Match("acccd")); + EXPECT_FALSE(re.Match("abbbbd")); + EXPECT_FALSE(re.Match("add")); + EXPECT_FALSE(re.Match("accccd")); + EXPECT_FALSE(re.Match("abcbcd")); +} + +// Issue538 +TEST(Regex, QuantifierMinMax5) { + Regex re("a(b|c){0,}d"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("ad")); + EXPECT_TRUE(re.Match("abd")); + EXPECT_TRUE(re.Match("acd")); + EXPECT_TRUE(re.Match("abbd")); + EXPECT_TRUE(re.Match("accd")); + EXPECT_TRUE(re.Match("abcd")); + EXPECT_TRUE(re.Match("abbbd")); + EXPECT_TRUE(re.Match("acccd")); + EXPECT_TRUE(re.Match("abbbbd")); + EXPECT_TRUE(re.Match("accccd")); + EXPECT_TRUE(re.Match("abcbcd")); + EXPECT_FALSE(re.Match("add")); + EXPECT_FALSE(re.Match("aad")); +} + +#define EURO "\xE2\x82\xAC" // "\xE2\x82\xAC" is UTF-8 sequence of Euro sign U+20AC + +TEST(Regex, Unicode) { + Regex re("a" EURO "+b"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a" EURO "b")); + EXPECT_TRUE(re.Match("a" EURO EURO "b")); + EXPECT_FALSE(re.Match("a?b")); + EXPECT_FALSE(re.Match("a" EURO "\xAC" "b")); // unaware of UTF-8 will match +} + +TEST(Regex, AnyCharacter) { + Regex re("."); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match(EURO)); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, CharacterRange1) { + Regex re("[abc]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("c")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("`")); + EXPECT_FALSE(re.Match("d")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, CharacterRange2) { + Regex re("[^abc]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("`")); + EXPECT_TRUE(re.Match("d")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("c")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, CharacterRange3) { + Regex re("[a-c]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("b")); + EXPECT_TRUE(re.Match("c")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("`")); + EXPECT_FALSE(re.Match("d")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, CharacterRange4) { + Regex re("[^a-c]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("`")); + EXPECT_TRUE(re.Match("d")); + EXPECT_FALSE(re.Match("a")); + EXPECT_FALSE(re.Match("b")); + EXPECT_FALSE(re.Match("c")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("aa")); +} + +TEST(Regex, CharacterRange5) { + Regex re("[-]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("-")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("a")); +} + +TEST(Regex, CharacterRange6) { + Regex re("[a-]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("-")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("`")); + EXPECT_FALSE(re.Match("b")); +} + +TEST(Regex, CharacterRange7) { + Regex re("[-a]"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("a")); + EXPECT_TRUE(re.Match("-")); + EXPECT_FALSE(re.Match("")); + EXPECT_FALSE(re.Match("`")); + EXPECT_FALSE(re.Match("b")); +} + +TEST(Regex, CharacterRange8) { + Regex re("[a-zA-Z0-9]*"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("Milo")); + EXPECT_TRUE(re.Match("MT19937")); + EXPECT_TRUE(re.Match("43")); + EXPECT_FALSE(re.Match("a_b")); + EXPECT_FALSE(re.Match("!")); +} + +TEST(Regex, Search) { + Regex re("abc"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Search("abc")); + EXPECT_TRUE(re.Search("_abc")); + EXPECT_TRUE(re.Search("abc_")); + EXPECT_TRUE(re.Search("_abc_")); + EXPECT_TRUE(re.Search("__abc__")); + EXPECT_TRUE(re.Search("abcabc")); + EXPECT_FALSE(re.Search("a")); + EXPECT_FALSE(re.Search("ab")); + EXPECT_FALSE(re.Search("bc")); + EXPECT_FALSE(re.Search("cba")); +} + +TEST(Regex, Search_BeginAnchor) { + Regex re("^abc"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Search("abc")); + EXPECT_TRUE(re.Search("abc_")); + EXPECT_TRUE(re.Search("abcabc")); + EXPECT_FALSE(re.Search("_abc")); + EXPECT_FALSE(re.Search("_abc_")); + EXPECT_FALSE(re.Search("a")); + EXPECT_FALSE(re.Search("ab")); + EXPECT_FALSE(re.Search("bc")); + EXPECT_FALSE(re.Search("cba")); +} + +TEST(Regex, Search_EndAnchor) { + Regex re("abc$"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Search("abc")); + EXPECT_TRUE(re.Search("_abc")); + EXPECT_TRUE(re.Search("abcabc")); + EXPECT_FALSE(re.Search("abc_")); + EXPECT_FALSE(re.Search("_abc_")); + EXPECT_FALSE(re.Search("a")); + EXPECT_FALSE(re.Search("ab")); + EXPECT_FALSE(re.Search("bc")); + EXPECT_FALSE(re.Search("cba")); +} + +TEST(Regex, Search_BothAnchor) { + Regex re("^abc$"); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Search("abc")); + EXPECT_FALSE(re.Search("")); + EXPECT_FALSE(re.Search("a")); + EXPECT_FALSE(re.Search("b")); + EXPECT_FALSE(re.Search("ab")); + EXPECT_FALSE(re.Search("abcd")); +} + +TEST(Regex, Escape) { + const char* s = "\\^\\$\\|\\(\\)\\?\\*\\+\\.\\[\\]\\{\\}\\\\\\f\\n\\r\\t\\v[\\b][\\[][\\]]"; + Regex re(s); + ASSERT_TRUE(re.IsValid()); + EXPECT_TRUE(re.Match("^$|()?*+.[]{}\\\x0C\n\r\t\x0B\b[]")); + EXPECT_FALSE(re.Match(s)); // Not escaping +} + +TEST(Regex, Invalid) { +#define TEST_INVALID(s) \ + {\ + Regex re(s);\ + EXPECT_FALSE(re.IsValid());\ + } + + TEST_INVALID(""); + TEST_INVALID("a|"); + TEST_INVALID("()"); + TEST_INVALID(")"); + TEST_INVALID("(a))"); + TEST_INVALID("(a|)"); + TEST_INVALID("(a||b)"); + TEST_INVALID("(|b)"); + TEST_INVALID("?"); + TEST_INVALID("*"); + TEST_INVALID("+"); + TEST_INVALID("{"); + TEST_INVALID("{}"); + TEST_INVALID("a{a}"); + TEST_INVALID("a{0}"); + TEST_INVALID("a{-1}"); + TEST_INVALID("a{}"); + // TEST_INVALID("a{0,}"); // Support now + TEST_INVALID("a{,0}"); + TEST_INVALID("a{1,0}"); + TEST_INVALID("a{-1,0}"); + TEST_INVALID("a{-1,1}"); + TEST_INVALID("a{4294967296}"); // overflow of unsigned + TEST_INVALID("a{1a}"); + TEST_INVALID("["); + TEST_INVALID("[]"); + TEST_INVALID("[^]"); + TEST_INVALID("[\\a]"); + TEST_INVALID("\\a"); + +#undef TEST_INVALID +} + +TEST(Regex, Issue538) { + Regex re("^[0-9]+(\\\\.[0-9]+){0,2}"); + EXPECT_TRUE(re.IsValid()); +} + +TEST(Regex, Issue583) { + Regex re("[0-9]{99999}"); + ASSERT_TRUE(re.IsValid()); +} + +#undef EURO diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/schematest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/schematest.cpp new file mode 100644 index 0000000000..d75b1e593e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/schematest.cpp @@ -0,0 +1,1313 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/schema.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(variadic-macros) +#endif + +using namespace rapidjson; + +#define TEST_HASHER(json1, json2, expected) \ +{\ + Document d1, d2;\ + d1.Parse(json1);\ + ASSERT_FALSE(d1.HasParseError());\ + d2.Parse(json2);\ + ASSERT_FALSE(d2.HasParseError());\ + internal::Hasher h1, h2;\ + d1.Accept(h1);\ + d2.Accept(h2);\ + ASSERT_TRUE(h1.IsValid());\ + ASSERT_TRUE(h2.IsValid());\ + /*printf("%s: 0x%016llx\n%s: 0x%016llx\n\n", json1, h1.GetHashCode(), json2, h2.GetHashCode());*/\ + EXPECT_TRUE(expected == (h1.GetHashCode() == h2.GetHashCode()));\ +} + +TEST(SchemaValidator, Hasher) { + TEST_HASHER("null", "null", true); + + TEST_HASHER("true", "true", true); + TEST_HASHER("false", "false", true); + TEST_HASHER("true", "false", false); + TEST_HASHER("false", "true", false); + TEST_HASHER("true", "null", false); + TEST_HASHER("false", "null", false); + + TEST_HASHER("1", "1", true); + TEST_HASHER("2147483648", "2147483648", true); // 2^31 can only be fit in unsigned + TEST_HASHER("-2147483649", "-2147483649", true); // -2^31 - 1 can only be fit in int64_t + TEST_HASHER("2147483648", "2147483648", true); // 2^31 can only be fit in unsigned + TEST_HASHER("4294967296", "4294967296", true); // 2^32 can only be fit in int64_t + TEST_HASHER("9223372036854775808", "9223372036854775808", true); // 2^63 can only be fit in uint64_t + TEST_HASHER("1.5", "1.5", true); + TEST_HASHER("1", "1.0", true); + TEST_HASHER("1", "-1", false); + TEST_HASHER("0.0", "-0.0", false); + TEST_HASHER("1", "true", false); + TEST_HASHER("0", "false", false); + TEST_HASHER("0", "null", false); + + TEST_HASHER("\"\"", "\"\"", true); + TEST_HASHER("\"\"", "\"\\u0000\"", false); + TEST_HASHER("\"Hello\"", "\"Hello\"", true); + TEST_HASHER("\"Hello\"", "\"World\"", false); + TEST_HASHER("\"Hello\"", "null", false); + TEST_HASHER("\"Hello\\u0000\"", "\"Hello\"", false); + TEST_HASHER("\"\"", "null", false); + TEST_HASHER("\"\"", "true", false); + TEST_HASHER("\"\"", "false", false); + + TEST_HASHER("[]", "[ ]", true); + TEST_HASHER("[1, true, false]", "[1, true, false]", true); + TEST_HASHER("[1, true, false]", "[1, true]", false); + TEST_HASHER("[1, 2]", "[2, 1]", false); + TEST_HASHER("[[1], 2]", "[[1, 2]]", false); + TEST_HASHER("[1, 2]", "[1, [2]]", false); + TEST_HASHER("[]", "null", false); + TEST_HASHER("[]", "true", false); + TEST_HASHER("[]", "false", false); + TEST_HASHER("[]", "0", false); + TEST_HASHER("[]", "0.0", false); + TEST_HASHER("[]", "\"\"", false); + + TEST_HASHER("{}", "{ }", true); + TEST_HASHER("{\"a\":1}", "{\"a\":1}", true); + TEST_HASHER("{\"a\":1}", "{\"b\":1}", false); + TEST_HASHER("{\"a\":1}", "{\"a\":2}", false); + TEST_HASHER("{\"a\":1, \"b\":2}", "{\"b\":2, \"a\":1}", true); // Member order insensitive + TEST_HASHER("{}", "null", false); + TEST_HASHER("{}", "false", false); + TEST_HASHER("{}", "true", false); + TEST_HASHER("{}", "0", false); + TEST_HASHER("{}", "0.0", false); + TEST_HASHER("{}", "\"\"", false); +} + +// Test cases following http://spacetelescope.github.io/understanding-json-schema + +#define VALIDATE(schema, json, expected) \ +{\ + SchemaValidator validator(schema);\ + Document d;\ + /*printf("\n%s\n", json);*/\ + d.Parse(json);\ + EXPECT_FALSE(d.HasParseError());\ + EXPECT_TRUE(expected == d.Accept(validator));\ + EXPECT_TRUE(expected == validator.IsValid());\ + if ((expected) && !validator.IsValid()) {\ + StringBuffer sb;\ + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);\ + printf("Invalid schema: %s\n", sb.GetString());\ + printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());\ + sb.Clear();\ + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);\ + printf("Invalid document: %s\n", sb.GetString());\ + }\ +} + +#define INVALIDATE(schema, json, invalidSchemaPointer, invalidSchemaKeyword, invalidDocumentPointer) \ +{\ + SchemaValidator validator(schema);\ + Document d;\ + /*printf("\n%s\n", json);*/\ + d.Parse(json);\ + EXPECT_FALSE(d.HasParseError());\ + EXPECT_FALSE(d.Accept(validator));\ + EXPECT_FALSE(validator.IsValid());\ + if (validator.GetInvalidSchemaPointer() != Pointer(invalidSchemaPointer)) {\ + StringBuffer sb;\ + validator.GetInvalidSchemaPointer().Stringify(sb);\ + printf("GetInvalidSchemaPointer() Expected: %s Actual: %s\n", invalidSchemaPointer, sb.GetString());\ + ADD_FAILURE();\ + }\ + ASSERT_TRUE(validator.GetInvalidSchemaKeyword() != 0);\ + if (strcmp(validator.GetInvalidSchemaKeyword(), invalidSchemaKeyword) != 0) {\ + printf("GetInvalidSchemaKeyword() Expected: %s Actual %s\n", invalidSchemaKeyword, validator.GetInvalidSchemaKeyword());\ + ADD_FAILURE();\ + }\ + if (validator.GetInvalidDocumentPointer() != Pointer(invalidDocumentPointer)) {\ + StringBuffer sb;\ + validator.GetInvalidDocumentPointer().Stringify(sb);\ + printf("GetInvalidDocumentPointer() Expected: %s Actual: %s\n", invalidDocumentPointer, sb.GetString());\ + ADD_FAILURE();\ + }\ +} + +TEST(SchemaValidator, Typeless) { + Document sd; + sd.Parse("{}"); + SchemaDocument s(sd); + + VALIDATE(s, "42", true); + VALIDATE(s, "\"I'm a string\"", true); + VALIDATE(s, "{ \"an\": [ \"arbitrarily\", \"nested\" ], \"data\": \"structure\" }", true); +} + +TEST(SchemaValidator, MultiType) { + Document sd; + sd.Parse("{ \"type\": [\"number\", \"string\"] }"); + SchemaDocument s(sd); + + VALIDATE(s, "42", true); + VALIDATE(s, "\"Life, the universe, and everything\"", true); + INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", ""); +} + +TEST(SchemaValidator, Enum_Typed) { + Document sd; + sd.Parse("{ \"type\": \"string\", \"enum\" : [\"red\", \"amber\", \"green\"] }"); + SchemaDocument s(sd); + + VALIDATE(s, "\"red\"", true); + INVALIDATE(s, "\"blue\"", "", "enum", ""); +} + +TEST(SchemaValidator, Enum_Typless) { + Document sd; + sd.Parse("{ \"enum\": [\"red\", \"amber\", \"green\", null, 42] }"); + SchemaDocument s(sd); + + VALIDATE(s, "\"red\"", true); + VALIDATE(s, "null", true); + VALIDATE(s, "42", true); + INVALIDATE(s, "0", "", "enum", ""); +} + +TEST(SchemaValidator, Enum_InvalidType) { + Document sd; + sd.Parse("{ \"type\": \"string\", \"enum\": [\"red\", \"amber\", \"green\", null] }"); + SchemaDocument s(sd); + + VALIDATE(s, "\"red\"", true); + INVALIDATE(s, "null", "", "type", ""); +} + +TEST(SchemaValidator, AllOf) { + { + Document sd; + sd.Parse("{\"allOf\": [{ \"type\": \"string\" }, { \"type\": \"string\", \"maxLength\": 5 }]}"); + SchemaDocument s(sd); + + VALIDATE(s, "\"ok\"", true); + INVALIDATE(s, "\"too long\"", "", "allOf", ""); + } + { + Document sd; + sd.Parse("{\"allOf\": [{ \"type\": \"string\" }, { \"type\": \"number\" } ] }"); + SchemaDocument s(sd); + + VALIDATE(s, "\"No way\"", false); + INVALIDATE(s, "-1", "", "allOf", ""); + } +} + +TEST(SchemaValidator, AnyOf) { + Document sd; + sd.Parse("{\"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"number\" } ] }"); + SchemaDocument s(sd); + + VALIDATE(s, "\"Yes\"", true); + VALIDATE(s, "42", true); + INVALIDATE(s, "{ \"Not a\": \"string or number\" }", "", "anyOf", ""); +} + +TEST(SchemaValidator, OneOf) { + Document sd; + sd.Parse("{\"oneOf\": [{ \"type\": \"number\", \"multipleOf\": 5 }, { \"type\": \"number\", \"multipleOf\": 3 } ] }"); + SchemaDocument s(sd); + + VALIDATE(s, "10", true); + VALIDATE(s, "9", true); + INVALIDATE(s, "2", "", "oneOf", ""); + INVALIDATE(s, "15", "", "oneOf", ""); +} + +TEST(SchemaValidator, Not) { + Document sd; + sd.Parse("{\"not\":{ \"type\": \"string\"}}"); + SchemaDocument s(sd); + + VALIDATE(s, "42", true); + VALIDATE(s, "{ \"key\": \"value\" }", true); + INVALIDATE(s, "\"I am a string\"", "", "not", ""); +} + +TEST(SchemaValidator, Ref) { + Document sd; + sd.Parse( + "{" + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + "" + " \"definitions\": {" + " \"address\": {" + " \"type\": \"object\"," + " \"properties\": {" + " \"street_address\": { \"type\": \"string\" }," + " \"city\": { \"type\": \"string\" }," + " \"state\": { \"type\": \"string\" }" + " }," + " \"required\": [\"street_address\", \"city\", \"state\"]" + " }" + " }," + " \"type\": \"object\"," + " \"properties\": {" + " \"billing_address\": { \"$ref\": \"#/definitions/address\" }," + " \"shipping_address\": { \"$ref\": \"#/definitions/address\" }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"}, \"billing_address\": {\"street_address\": \"1st Street SE\", \"city\": \"Washington\", \"state\": \"DC\"} }", true); +} + +TEST(SchemaValidator, Ref_AllOf) { + Document sd; + sd.Parse( + "{" + " \"$schema\": \"http://json-schema.org/draft-04/schema#\"," + "" + " \"definitions\": {" + " \"address\": {" + " \"type\": \"object\"," + " \"properties\": {" + " \"street_address\": { \"type\": \"string\" }," + " \"city\": { \"type\": \"string\" }," + " \"state\": { \"type\": \"string\" }" + " }," + " \"required\": [\"street_address\", \"city\", \"state\"]" + " }" + " }," + " \"type\": \"object\"," + " \"properties\": {" + " \"billing_address\": { \"$ref\": \"#/definitions/address\" }," + " \"shipping_address\": {" + " \"allOf\": [" + " { \"$ref\": \"#/definitions/address\" }," + " { \"properties\":" + " { \"type\": { \"enum\": [ \"residential\", \"business\" ] } }," + " \"required\": [\"type\"]" + " }" + " ]" + " }" + " }" + "}"); + SchemaDocument s(sd); + + INVALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\"} }", "/properties/shipping_address", "allOf", "/shipping_address"); + VALIDATE(s, "{\"shipping_address\": {\"street_address\": \"1600 Pennsylvania Avenue NW\", \"city\": \"Washington\", \"state\": \"DC\", \"type\": \"business\"} }", true); +} + +TEST(SchemaValidator, String) { + Document sd; + sd.Parse("{\"type\":\"string\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "\"I'm a string\"", true); + INVALIDATE(s, "42", "", "type", ""); + INVALIDATE(s, "2147483648", "", "type", ""); // 2^31 can only be fit in unsigned + INVALIDATE(s, "-2147483649", "", "type", ""); // -2^31 - 1 can only be fit in int64_t + INVALIDATE(s, "4294967296", "", "type", ""); // 2^32 can only be fit in int64_t + INVALIDATE(s, "3.1415926", "", "type", ""); +} + +TEST(SchemaValidator, String_LengthRange) { + Document sd; + sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}"); + SchemaDocument s(sd); + + INVALIDATE(s, "\"A\"", "", "minLength", ""); + VALIDATE(s, "\"AB\"", true); + VALIDATE(s, "\"ABC\"", true); + INVALIDATE(s, "\"ABCD\"", "", "maxLength", ""); +} + +#if RAPIDJSON_SCHEMA_HAS_REGEX +TEST(SchemaValidator, String_Pattern) { + Document sd; + sd.Parse("{\"type\":\"string\",\"pattern\":\"^(\\\\([0-9]{3}\\\\))?[0-9]{3}-[0-9]{4}$\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "\"555-1212\"", true); + VALIDATE(s, "\"(888)555-1212\"", true); + INVALIDATE(s, "\"(888)555-1212 ext. 532\"", "", "pattern", ""); + INVALIDATE(s, "\"(800)FLOWERS\"", "", "pattern", ""); +} + +TEST(SchemaValidator, String_Pattern_Invalid) { + Document sd; + sd.Parse("{\"type\":\"string\",\"pattern\":\"a{0}\"}"); // TODO: report regex is invalid somehow + SchemaDocument s(sd); + + VALIDATE(s, "\"\"", true); + VALIDATE(s, "\"a\"", true); + VALIDATE(s, "\"aa\"", true); +} +#endif + +TEST(SchemaValidator, Integer) { + Document sd; + sd.Parse("{\"type\":\"integer\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "42", true); + VALIDATE(s, "-1", true); + VALIDATE(s, "2147483648", true); // 2^31 can only be fit in unsigned + VALIDATE(s, "-2147483649", true); // -2^31 - 1 can only be fit in int64_t + VALIDATE(s, "2147483648", true); // 2^31 can only be fit in unsigned + VALIDATE(s, "4294967296", true); // 2^32 can only be fit in int64_t + INVALIDATE(s, "3.1415926", "", "type", ""); + INVALIDATE(s, "\"42\"", "", "type", ""); +} + +TEST(SchemaValidator, Integer_Range) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-1", "", "minimum", ""); + VALIDATE(s, "0", true); + VALIDATE(s, "10", true); + VALIDATE(s, "99", true); + INVALIDATE(s, "100", "", "maximum", ""); + INVALIDATE(s, "101", "", "maximum", ""); +} + +TEST(SchemaValidator, Integer_Range64Boundary) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775807,\"maximum\":9223372036854775806}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + VALIDATE(s, "-9223372036854775807", true); + VALIDATE(s, "-2147483648", true); // int min + VALIDATE(s, "0", true); + VALIDATE(s, "2147483647", true); // int max + VALIDATE(s, "2147483648", true); // unsigned first + VALIDATE(s, "4294967295", true); // unsigned max + VALIDATE(s, "9223372036854775806", true); + INVALIDATE(s, "9223372036854775807", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); // uint64_t max +} + +TEST(SchemaValidator, Integer_RangeU64Boundary) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"minimum\":9223372036854775808,\"maximum\":18446744073709551614}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + INVALIDATE(s, "9223372036854775807", "", "minimum", ""); + INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min + INVALIDATE(s, "0", "", "minimum", ""); + INVALIDATE(s, "2147483647", "", "minimum", ""); // int max + INVALIDATE(s, "2147483648", "", "minimum", ""); // unsigned first + INVALIDATE(s, "4294967295", "", "minimum", ""); // unsigned max + VALIDATE(s, "9223372036854775808", true); + VALIDATE(s, "18446744073709551614", true); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); +} + +TEST(SchemaValidator, Integer_Range64BoundaryExclusive) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"minimum\":-9223372036854775808,\"maximum\":18446744073709551615,\"exclusiveMinimum\":true,\"exclusiveMaximum\":true}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + VALIDATE(s, "-9223372036854775807", true); + VALIDATE(s, "18446744073709551614", true); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); +} + +TEST(SchemaValidator, Integer_MultipleOf) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"multipleOf\":10}"); + SchemaDocument s(sd); + + VALIDATE(s, "0", true); + VALIDATE(s, "10", true); + VALIDATE(s, "-10", true); + VALIDATE(s, "20", true); + INVALIDATE(s, "23", "", "multipleOf", ""); + INVALIDATE(s, "-23", "", "multipleOf", ""); +} + +TEST(SchemaValidator, Integer_MultipleOf64Boundary) { + Document sd; + sd.Parse("{\"type\":\"integer\",\"multipleOf\":18446744073709551615}"); + SchemaDocument s(sd); + + VALIDATE(s, "0", true); + VALIDATE(s, "18446744073709551615", true); + INVALIDATE(s, "18446744073709551614", "", "multipleOf", ""); +} + +TEST(SchemaValidator, Number_Range) { + Document sd; + sd.Parse("{\"type\":\"number\",\"minimum\":0,\"maximum\":100,\"exclusiveMaximum\":true}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-1", "", "minimum", ""); + VALIDATE(s, "0", true); + VALIDATE(s, "0.1", true); + VALIDATE(s, "10", true); + VALIDATE(s, "99", true); + VALIDATE(s, "99.9", true); + INVALIDATE(s, "100", "", "maximum", ""); + INVALIDATE(s, "100.0", "", "maximum", ""); + INVALIDATE(s, "101.5", "", "maximum", ""); +} + +TEST(SchemaValidator, Number_RangeInt) { + Document sd; + sd.Parse("{\"type\":\"number\",\"minimum\":-100,\"maximum\":-1,\"exclusiveMaximum\":true}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-101", "", "minimum", ""); + INVALIDATE(s, "-100.1", "", "minimum", ""); + VALIDATE(s, "-100", true); + VALIDATE(s, "-2", true); + INVALIDATE(s, "-1", "", "maximum", ""); + INVALIDATE(s, "-0.9", "", "maximum", ""); + INVALIDATE(s, "0", "", "maximum", ""); + INVALIDATE(s, "2147483647", "", "maximum", ""); // int max + INVALIDATE(s, "2147483648", "", "maximum", ""); // unsigned first + INVALIDATE(s, "4294967295", "", "maximum", ""); // unsigned max + INVALIDATE(s, "9223372036854775808", "", "maximum", ""); + INVALIDATE(s, "18446744073709551614", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); +} + +TEST(SchemaValidator, Number_RangeDouble) { + Document sd; + sd.Parse("{\"type\":\"number\",\"minimum\":0.1,\"maximum\":100.1,\"exclusiveMaximum\":true}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min + INVALIDATE(s, "-1", "", "minimum", ""); + VALIDATE(s, "0.1", true); + VALIDATE(s, "10", true); + VALIDATE(s, "99", true); + VALIDATE(s, "100", true); + INVALIDATE(s, "101", "", "maximum", ""); + INVALIDATE(s, "101.5", "", "maximum", ""); + INVALIDATE(s, "18446744073709551614", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); + INVALIDATE(s, "2147483647", "", "maximum", ""); // int max + INVALIDATE(s, "2147483648", "", "maximum", ""); // unsigned first + INVALIDATE(s, "4294967295", "", "maximum", ""); // unsigned max + INVALIDATE(s, "9223372036854775808", "", "maximum", ""); + INVALIDATE(s, "18446744073709551614", "", "maximum", ""); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); +} + +TEST(SchemaValidator, Number_RangeDoubleU64Boundary) { + Document sd; + sd.Parse("{\"type\":\"number\",\"minimum\":9223372036854775808.0,\"maximum\":18446744073709550000.0}"); + SchemaDocument s(sd); + + INVALIDATE(s, "-9223372036854775808", "", "minimum", ""); + INVALIDATE(s, "-2147483648", "", "minimum", ""); // int min + INVALIDATE(s, "0", "", "minimum", ""); + INVALIDATE(s, "2147483647", "", "minimum", ""); // int max + INVALIDATE(s, "2147483648", "", "minimum", ""); // unsigned first + INVALIDATE(s, "4294967295", "", "minimum", ""); // unsigned max + VALIDATE(s, "9223372036854775808", true); + VALIDATE(s, "18446744073709540000", true); + INVALIDATE(s, "18446744073709551615", "", "maximum", ""); +} + +TEST(SchemaValidator, Number_MultipleOf) { + Document sd; + sd.Parse("{\"type\":\"number\",\"multipleOf\":10.0}"); + SchemaDocument s(sd); + + VALIDATE(s, "0", true); + VALIDATE(s, "10", true); + VALIDATE(s, "-10", true); + VALIDATE(s, "20", true); + INVALIDATE(s, "23", "", "multipleOf", ""); + INVALIDATE(s, "-2147483648", "", "multipleOf", ""); // int min + VALIDATE(s, "-2147483640", true); + INVALIDATE(s, "2147483647", "", "multipleOf", ""); // int max + INVALIDATE(s, "2147483648", "", "multipleOf", ""); // unsigned first + VALIDATE(s, "2147483650", true); + INVALIDATE(s, "4294967295", "", "multipleOf", ""); // unsigned max + VALIDATE(s, "4294967300", true); +} + +TEST(SchemaValidator, Number_MultipleOfOne) { + Document sd; + sd.Parse("{\"type\":\"number\",\"multipleOf\":1}"); + SchemaDocument s(sd); + + VALIDATE(s, "42", true); + VALIDATE(s, "42.0", true); + INVALIDATE(s, "3.1415926", "", "multipleOf", ""); +} + +TEST(SchemaValidator, Object) { + Document sd; + sd.Parse("{\"type\":\"object\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "{\"key\":\"value\",\"another_key\":\"another_value\"}", true); + VALIDATE(s, "{\"Sun\":1.9891e30,\"Jupiter\":1.8986e27,\"Saturn\":5.6846e26,\"Neptune\":10.243e25,\"Uranus\":8.6810e25,\"Earth\":5.9736e24,\"Venus\":4.8685e24,\"Mars\":6.4185e23,\"Mercury\":3.3022e23,\"Moon\":7.349e22,\"Pluto\":1.25e22}", true); + INVALIDATE(s, "[\"An\", \"array\", \"not\", \"an\", \"object\"]", "", "type", ""); + INVALIDATE(s, "\"Not an object\"", "", "type", ""); +} + +TEST(SchemaValidator, Object_Properties) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\" : {" + " \"number\": { \"type\": \"number\" }," + " \"street_name\" : { \"type\": \"string\" }," + " \"street_type\" : { \"type\": \"string\", \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"] }" + " }" + "}"); + + SchemaDocument s(sd); + + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); + INVALIDATE(s, "{ \"number\": \"1600\", \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", "/properties/number", "type", "/number"); + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\" }", true); + VALIDATE(s, "{}", true); + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true); +} + +TEST(SchemaValidator, Object_AdditionalPropertiesBoolean) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\" : {" + " \"number\": { \"type\": \"number\" }," + " \"street_name\" : { \"type\": \"string\" }," + " \"street_type\" : { \"type\": \"string\"," + " \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"]" + " }" + " }," + " \"additionalProperties\": false" + "}"); + + SchemaDocument s(sd); + + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); + INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", "", "additionalProperties", "/direction"); +} + +TEST(SchemaValidator, Object_AdditionalPropertiesObject) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\" : {" + " \"number\": { \"type\": \"number\" }," + " \"street_name\" : { \"type\": \"string\" }," + " \"street_type\" : { \"type\": \"string\"," + " \"enum\" : [\"Street\", \"Avenue\", \"Boulevard\"]" + " }" + " }," + " \"additionalProperties\": { \"type\": \"string\" }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\" }", true); + VALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"direction\": \"NW\" }", true); + INVALIDATE(s, "{ \"number\": 1600, \"street_name\": \"Pennsylvania\", \"street_type\": \"Avenue\", \"office_number\": 201 }", "/additionalProperties", "type", "/office_number"); +} + +TEST(SchemaValidator, Object_Required) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\" : {" + " \"name\": { \"type\": \"string\" }," + " \"email\" : { \"type\": \"string\" }," + " \"address\" : { \"type\": \"string\" }," + " \"telephone\" : { \"type\": \"string\" }" + " }," + " \"required\":[\"name\", \"email\"]" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\" }", true); + VALIDATE(s, "{ \"name\": \"William Shakespeare\", \"email\" : \"bill@stratford-upon-avon.co.uk\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\", \"authorship\" : \"in question\"}", true); + INVALIDATE(s, "{ \"name\": \"William Shakespeare\", \"address\" : \"Henley Street, Stratford-upon-Avon, Warwickshire, England\" }", "", "required", ""); +} + + +TEST(SchemaValidator, Object_PropertiesRange) { + Document sd; + sd.Parse("{\"type\":\"object\", \"minProperties\":2, \"maxProperties\":3}"); + SchemaDocument s(sd); + + INVALIDATE(s, "{}", "", "minProperties", ""); + INVALIDATE(s, "{\"a\":0}", "", "minProperties", ""); + VALIDATE(s, "{\"a\":0,\"b\":1}", true); + VALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2}", true); + INVALIDATE(s, "{\"a\":0,\"b\":1,\"c\":2,\"d\":3}", "", "maxProperties", ""); +} + +TEST(SchemaValidator, Object_PropertyDependencies) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\": {" + " \"name\": { \"type\": \"string\" }," + " \"credit_card\": { \"type\": \"number\" }," + " \"billing_address\": { \"type\": \"string\" }" + " }," + " \"required\": [\"name\"]," + " \"dependencies\": {" + " \"credit_card\": [\"billing_address\"]" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555, \"billing_address\": \"555 Debtor's Lane\" }", true); + INVALIDATE(s, "{ \"name\": \"John Doe\", \"credit_card\": 5555555555555555 }", "", "dependencies", ""); + VALIDATE(s, "{ \"name\": \"John Doe\"}", true); + VALIDATE(s, "{ \"name\": \"John Doe\", \"billing_address\": \"555 Debtor's Lane\" }", true); +} + +TEST(SchemaValidator, Object_SchemaDependencies) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\" : {" + " \"name\": { \"type\": \"string\" }," + " \"credit_card\" : { \"type\": \"number\" }" + " }," + " \"required\" : [\"name\"]," + " \"dependencies\" : {" + " \"credit_card\": {" + " \"properties\": {" + " \"billing_address\": { \"type\": \"string\" }" + " }," + " \"required\" : [\"billing_address\"]" + " }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555,\"billing_address\" : \"555 Debtor's Lane\"}", true); + INVALIDATE(s, "{\"name\": \"John Doe\", \"credit_card\" : 5555555555555555 }", "", "dependencies", ""); + VALIDATE(s, "{\"name\": \"John Doe\", \"billing_address\" : \"555 Debtor's Lane\"}", true); +} + +#if RAPIDJSON_SCHEMA_HAS_REGEX +TEST(SchemaValidator, Object_PatternProperties) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"patternProperties\": {" + " \"^S_\": { \"type\": \"string\" }," + " \"^I_\": { \"type\": \"integer\" }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"S_25\": \"This is a string\" }", true); + VALIDATE(s, "{ \"I_0\": 42 }", true); + INVALIDATE(s, "{ \"S_0\": 42 }", "", "patternProperties", "/S_0"); + INVALIDATE(s, "{ \"I_42\": \"This is a string\" }", "", "patternProperties", "/I_42"); + VALIDATE(s, "{ \"keyword\": \"value\" }", true); +} + +TEST(SchemaValidator, Object_PatternProperties_AdditionalProperties) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\": {" + " \"builtin\": { \"type\": \"number\" }" + " }," + " \"patternProperties\": {" + " \"^S_\": { \"type\": \"string\" }," + " \"^I_\": { \"type\": \"integer\" }" + " }," + " \"additionalProperties\": { \"type\": \"string\" }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"builtin\": 42 }", true); + VALIDATE(s, "{ \"keyword\": \"value\" }", true); + INVALIDATE(s, "{ \"keyword\": 42 }", "/additionalProperties", "type", "/keyword"); +} +#endif + +TEST(SchemaValidator, Array) { + Document sd; + sd.Parse("{\"type\":\"array\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "[1, 2, 3, 4, 5]", true); + VALIDATE(s, "[3, \"different\", { \"types\" : \"of values\" }]", true); + INVALIDATE(s, "{\"Not\": \"an array\"}", "", "type", ""); +} + +TEST(SchemaValidator, Array_ItemsList) { + Document sd; + sd.Parse( + "{" + " \"type\": \"array\"," + " \"items\" : {" + " \"type\": \"number\"" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "[1, 2, 3, 4, 5]", true); + INVALIDATE(s, "[1, 2, \"3\", 4, 5]", "/items", "type", "/2"); + VALIDATE(s, "[]", true); +} + +TEST(SchemaValidator, Array_ItemsTuple) { + Document sd; + sd.Parse( + "{" + " \"type\": \"array\"," + " \"items\": [" + " {" + " \"type\": \"number\"" + " }," + " {" + " \"type\": \"string\"" + " }," + " {" + " \"type\": \"string\"," + " \"enum\": [\"Street\", \"Avenue\", \"Boulevard\"]" + " }," + " {" + " \"type\": \"string\"," + " \"enum\": [\"NW\", \"NE\", \"SW\", \"SE\"]" + " }" + " ]" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true); + INVALIDATE(s, "[24, \"Sussex\", \"Drive\"]", "/items/2", "enum", "/2"); + INVALIDATE(s, "[\"Palais de l'Elysee\"]", "/items/0", "type", "/0"); + VALIDATE(s, "[10, \"Downing\", \"Street\"]", true); + VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", true); +} + +TEST(SchemaValidator, Array_AdditionalItmes) { + Document sd; + sd.Parse( + "{" + " \"type\": \"array\"," + " \"items\": [" + " {" + " \"type\": \"number\"" + " }," + " {" + " \"type\": \"string\"" + " }," + " {" + " \"type\": \"string\"," + " \"enum\": [\"Street\", \"Avenue\", \"Boulevard\"]" + " }," + " {" + " \"type\": \"string\"," + " \"enum\": [\"NW\", \"NE\", \"SW\", \"SE\"]" + " }" + " ]," + " \"additionalItems\": false" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\"]", true); + VALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\"]", true); + INVALIDATE(s, "[1600, \"Pennsylvania\", \"Avenue\", \"NW\", \"Washington\"]", "", "items", "/4"); +} + +TEST(SchemaValidator, Array_ItemsRange) { + Document sd; + sd.Parse("{\"type\": \"array\",\"minItems\": 2,\"maxItems\" : 3}"); + SchemaDocument s(sd); + + INVALIDATE(s, "[]", "", "minItems", ""); + INVALIDATE(s, "[1]", "", "minItems", ""); + VALIDATE(s, "[1, 2]", true); + VALIDATE(s, "[1, 2, 3]", true); + INVALIDATE(s, "[1, 2, 3, 4]", "", "maxItems", ""); +} + +TEST(SchemaValidator, Array_UniqueItems) { + Document sd; + sd.Parse("{\"type\": \"array\", \"uniqueItems\": true}"); + SchemaDocument s(sd); + + VALIDATE(s, "[1, 2, 3, 4, 5]", true); + INVALIDATE(s, "[1, 2, 3, 3, 4]", "", "uniqueItems", "/3"); + VALIDATE(s, "[]", true); +} + +TEST(SchemaValidator, Boolean) { + Document sd; + sd.Parse("{\"type\":\"boolean\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "true", true); + VALIDATE(s, "false", true); + INVALIDATE(s, "\"true\"", "", "type", ""); + INVALIDATE(s, "0", "", "type", ""); +} + +TEST(SchemaValidator, Null) { + Document sd; + sd.Parse("{\"type\":\"null\"}"); + SchemaDocument s(sd); + + VALIDATE(s, "null", true); + INVALIDATE(s, "false", "", "type", ""); + INVALIDATE(s, "0", "", "type", ""); + INVALIDATE(s, "\"\"", "", "type", ""); +} + +// Additional tests + +TEST(SchemaValidator, ObjectInArray) { + Document sd; + sd.Parse("{\"type\":\"array\", \"items\": { \"type\":\"string\" }}"); + SchemaDocument s(sd); + + VALIDATE(s, "[\"a\"]", true); + INVALIDATE(s, "[1]", "/items", "type", "/0"); + INVALIDATE(s, "[{}]", "/items", "type", "/0"); +} + +TEST(SchemaValidator, MultiTypeInObject) { + Document sd; + sd.Parse( + "{" + " \"type\":\"object\"," + " \"properties\": {" + " \"tel\" : {" + " \"type\":[\"integer\", \"string\"]" + " }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "{ \"tel\": 999 }", true); + VALIDATE(s, "{ \"tel\": \"123-456\" }", true); + INVALIDATE(s, "{ \"tel\": true }", "/properties/tel", "type", "/tel"); +} + +TEST(SchemaValidator, MultiTypeWithObject) { + Document sd; + sd.Parse( + "{" + " \"type\": [\"object\",\"string\"]," + " \"properties\": {" + " \"tel\" : {" + " \"type\": \"integer\"" + " }" + " }" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "\"Hello\"", true); + VALIDATE(s, "{ \"tel\": 999 }", true); + INVALIDATE(s, "{ \"tel\": \"fail\" }", "/properties/tel", "type", "/tel"); +} + +TEST(SchemaValidator, AllOf_Nested) { + Document sd; + sd.Parse( + "{" + " \"allOf\": [" + " { \"type\": \"string\", \"minLength\": 2 }," + " { \"type\": \"string\", \"maxLength\": 5 }," + " { \"allOf\": [ { \"enum\" : [\"ok\", \"okay\", \"OK\", \"o\"] }, { \"enum\" : [\"ok\", \"OK\", \"o\"]} ] }" + " ]" + "}"); + SchemaDocument s(sd); + + VALIDATE(s, "\"ok\"", true); + VALIDATE(s, "\"OK\"", true); + INVALIDATE(s, "\"okay\"", "", "allOf", ""); + INVALIDATE(s, "\"o\"", "", "allOf", ""); + INVALIDATE(s, "\"n\"", "", "allOf", ""); + INVALIDATE(s, "\"too long\"", "", "allOf", ""); + INVALIDATE(s, "123", "", "allOf", ""); +} + +TEST(SchemaValidator, EscapedPointer) { + Document sd; + sd.Parse( + "{" + " \"type\": \"object\"," + " \"properties\": {" + " \"~/\": { \"type\": \"number\" }" + " }" + "}"); + SchemaDocument s(sd); + INVALIDATE(s, "{\"~/\":true}", "/properties/~0~1", "type", "/~0~1"); +} + +template +static char* ReadFile(const char* filename, Allocator& allocator) { + const char *paths[] = { + "", + "bin/", + "../bin/", + "../../bin/", + "../../../bin/" + }; + char buffer[1024]; + FILE *fp = 0; + for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) { + sprintf(buffer, "%s%s", paths[i], filename); + fp = fopen(buffer, "rb"); + if (fp) + break; + } + + if (!fp) + return 0; + + fseek(fp, 0, SEEK_END); + size_t length = static_cast(ftell(fp)); + fseek(fp, 0, SEEK_SET); + char* json = reinterpret_cast(allocator.Malloc(length + 1)); + size_t readLength = fread(json, 1, length, fp); + json[readLength] = '\0'; + fclose(fp); + return json; +} + +TEST(SchemaValidator, ValidateMetaSchema) { + CrtAllocator allocator; + char* json = ReadFile("draft-04/schema", allocator); + Document d; + d.Parse(json); + ASSERT_FALSE(d.HasParseError()); + SchemaDocument sd(d); + SchemaValidator validator(sd); + if (!d.Accept(validator)) { + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + printf("Invalid schema: %s\n", sb.GetString()); + printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + printf("Invalid document: %s\n", sb.GetString()); + ADD_FAILURE(); + } + CrtAllocator::Free(json); +} + +TEST(SchemaValidator, ValidateMetaSchema_UTF16) { + typedef GenericDocument > D; + typedef GenericSchemaDocument SD; + typedef GenericSchemaValidator SV; + + CrtAllocator allocator; + char* json = ReadFile("draft-04/schema", allocator); + + D d; + StringStream ss(json); + d.ParseStream<0, UTF8<> >(ss); + ASSERT_FALSE(d.HasParseError()); + SD sd(d); + SV validator(sd); + if (!d.Accept(validator)) { + GenericStringBuffer > sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + wprintf(L"Invalid schema: %ls\n", sb.GetString()); + wprintf(L"Invalid keyword: %ls\n", validator.GetInvalidSchemaKeyword()); + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + wprintf(L"Invalid document: %ls\n", sb.GetString()); + ADD_FAILURE(); + } + CrtAllocator::Free(json); +} + +template +class RemoteSchemaDocumentProvider : public IGenericRemoteSchemaDocumentProvider { +public: + RemoteSchemaDocumentProvider() : + documentAllocator_(documentBuffer_, sizeof(documentBuffer_)), + schemaAllocator_(schemaBuffer_, sizeof(schemaBuffer_)) + { + const char* filenames[kCount] = { + "jsonschema/remotes/integer.json", + "jsonschema/remotes/subSchemas.json", + "jsonschema/remotes/folder/folderInteger.json", + "draft-04/schema" + }; + + for (size_t i = 0; i < kCount; i++) { + sd_[i] = 0; + + char jsonBuffer[8192]; + MemoryPoolAllocator<> jsonAllocator(jsonBuffer, sizeof(jsonBuffer)); + char* json = ReadFile(filenames[i], jsonAllocator); + if (!json) { + printf("json remote file %s not found", filenames[i]); + ADD_FAILURE(); + } + else { + char stackBuffer[4096]; + MemoryPoolAllocator<> stackAllocator(stackBuffer, sizeof(stackBuffer)); + DocumentType d(&documentAllocator_, 1024, &stackAllocator); + d.Parse(json); + sd_[i] = new SchemaDocumentType(d, 0, &schemaAllocator_); + MemoryPoolAllocator<>::Free(json); + } + }; + } + + ~RemoteSchemaDocumentProvider() { + for (size_t i = 0; i < kCount; i++) + delete sd_[i]; + } + + virtual const SchemaDocumentType* GetRemoteDocument(const char* uri, SizeType length) { + const char* uris[kCount] = { + "http://localhost:1234/integer.json", + "http://localhost:1234/subSchemas.json", + "http://localhost:1234/folder/folderInteger.json", + "http://json-schema.org/draft-04/schema" + }; + + for (size_t i = 0; i < kCount; i++) + if (strncmp(uri, uris[i], length) == 0) + return sd_[i]; + return 0; + } + +private: + typedef GenericDocument, MemoryPoolAllocator<> > DocumentType; + + RemoteSchemaDocumentProvider(const RemoteSchemaDocumentProvider&); + RemoteSchemaDocumentProvider& operator=(const RemoteSchemaDocumentProvider&); + + static const size_t kCount = 4; + SchemaDocumentType* sd_[kCount]; + typename DocumentType::AllocatorType documentAllocator_; + typename SchemaDocumentType::AllocatorType schemaAllocator_; + char documentBuffer_[16384]; + char schemaBuffer_[128 * 1024]; +}; + +TEST(SchemaValidator, TestSuite) { + const char* filenames[] = { + "additionalItems.json", + "additionalProperties.json", + "allOf.json", + "anyOf.json", + "default.json", + "definitions.json", + "dependencies.json", + "enum.json", + "items.json", + "maximum.json", + "maxItems.json", + "maxLength.json", + "maxProperties.json", + "minimum.json", + "minItems.json", + "minLength.json", + "minProperties.json", + "multipleOf.json", + "not.json", + "oneOf.json", + "pattern.json", + "patternProperties.json", + "properties.json", + "ref.json", + "refRemote.json", + "required.json", + "type.json", + "uniqueItems.json" + }; + + const char* onlyRunDescription = 0; + //const char* onlyRunDescription = "a string is a string"; + + unsigned testCount = 0; + unsigned passCount = 0; + + typedef GenericSchemaDocument > SchemaDocumentType; + RemoteSchemaDocumentProvider provider; + + char jsonBuffer[65536]; + char documentBuffer[65536]; + char documentStackBuffer[65536]; + char schemaBuffer[65536]; + char validatorBuffer[65536]; + MemoryPoolAllocator<> jsonAllocator(jsonBuffer, sizeof(jsonBuffer)); + MemoryPoolAllocator<> documentAllocator(documentBuffer, sizeof(documentBuffer)); + MemoryPoolAllocator<> documentStackAllocator(documentStackBuffer, sizeof(documentStackBuffer)); + MemoryPoolAllocator<> schemaAllocator(schemaBuffer, sizeof(schemaBuffer)); + MemoryPoolAllocator<> validatorAllocator(validatorBuffer, sizeof(validatorBuffer)); + + for (size_t i = 0; i < sizeof(filenames) / sizeof(filenames[0]); i++) { + char filename[FILENAME_MAX]; + sprintf(filename, "jsonschema/tests/draft4/%s", filenames[i]); + char* json = ReadFile(filename, jsonAllocator); + if (!json) { + printf("json test suite file %s not found", filename); + ADD_FAILURE(); + } + else { + GenericDocument, MemoryPoolAllocator<>, MemoryPoolAllocator<> > d(&documentAllocator, 1024, &documentStackAllocator); + d.Parse(json); + if (d.HasParseError()) { + printf("json test suite file %s has parse error", filename); + ADD_FAILURE(); + } + else { + for (Value::ConstValueIterator schemaItr = d.Begin(); schemaItr != d.End(); ++schemaItr) { + { + SchemaDocumentType schema((*schemaItr)["schema"], &provider, &schemaAllocator); + GenericSchemaValidator >, MemoryPoolAllocator<> > validator(schema, &validatorAllocator); + const char* description1 = (*schemaItr)["description"].GetString(); + const Value& tests = (*schemaItr)["tests"]; + for (Value::ConstValueIterator testItr = tests.Begin(); testItr != tests.End(); ++testItr) { + const char* description2 = (*testItr)["description"].GetString(); + if (!onlyRunDescription || strcmp(description2, onlyRunDescription) == 0) { + const Value& data = (*testItr)["data"]; + bool expected = (*testItr)["valid"].GetBool(); + testCount++; + validator.Reset(); + bool actual = data.Accept(validator); + if (expected != actual) + printf("Fail: %30s \"%s\" \"%s\"\n", filename, description1, description2); + else + passCount++; + } + } + //printf("%zu %zu %zu\n", documentAllocator.Size(), schemaAllocator.Size(), validatorAllocator.Size()); + } + schemaAllocator.Clear(); + validatorAllocator.Clear(); + } + } + } + documentAllocator.Clear(); + MemoryPoolAllocator<>::Free(json); + jsonAllocator.Clear(); + } + printf("%d / %d passed (%2d%%)\n", passCount, testCount, passCount * 100 / testCount); + // if (passCount != testCount) + // ADD_FAILURE(); +} + +TEST(SchemaValidatingReader, Simple) { + Document sd; + sd.Parse("{ \"type\": \"string\", \"enum\" : [\"red\", \"amber\", \"green\"] }"); + SchemaDocument s(sd); + + Document d; + StringStream ss("\"red\""); + SchemaValidatingReader > reader(ss, s); + d.Populate(reader); + EXPECT_TRUE(reader.GetParseResult()); + EXPECT_TRUE(reader.IsValid()); + EXPECT_TRUE(d.IsString()); + EXPECT_STREQ("red", d.GetString()); +} + +TEST(SchemaValidatingReader, Invalid) { + Document sd; + sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}"); + SchemaDocument s(sd); + + Document d; + StringStream ss("\"ABCD\""); + SchemaValidatingReader > reader(ss, s); + d.Populate(reader); + EXPECT_FALSE(reader.GetParseResult()); + EXPECT_FALSE(reader.IsValid()); + EXPECT_EQ(kParseErrorTermination, reader.GetParseResult().Code()); + EXPECT_STREQ("maxLength", reader.GetInvalidSchemaKeyword()); + EXPECT_TRUE(reader.GetInvalidSchemaPointer() == SchemaDocument::PointerType("")); + EXPECT_TRUE(reader.GetInvalidDocumentPointer() == SchemaDocument::PointerType("")); + EXPECT_TRUE(d.IsNull()); +} + +TEST(SchemaValidatingWriter, Simple) { + Document sd; + sd.Parse("{\"type\":\"string\",\"minLength\":2,\"maxLength\":3}"); + SchemaDocument s(sd); + + Document d; + StringBuffer sb; + Writer writer(sb); + GenericSchemaValidator > validator(s, writer); + + d.Parse("\"red\""); + EXPECT_TRUE(d.Accept(validator)); + EXPECT_TRUE(validator.IsValid()); + EXPECT_STREQ("\"red\"", sb.GetString()); + + sb.Clear(); + validator.Reset(); + d.Parse("\"ABCD\""); + EXPECT_FALSE(d.Accept(validator)); + EXPECT_FALSE(validator.IsValid()); + EXPECT_TRUE(validator.GetInvalidSchemaPointer() == SchemaDocument::PointerType("")); + EXPECT_TRUE(validator.GetInvalidDocumentPointer() == SchemaDocument::PointerType("")); +} + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + +static SchemaDocument ReturnSchemaDocument() { + Document sd; + sd.Parse("{ \"type\": [\"number\", \"string\"] }"); + SchemaDocument s(sd); + return s; +} + +TEST(Schema, Issue552) { + SchemaDocument s = ReturnSchemaDocument(); + VALIDATE(s, "42", true); + VALIDATE(s, "\"Life, the universe, and everything\"", true); + INVALIDATE(s, "[\"Life\", \"the universe\", \"and everything\"]", "", "type", ""); +} + +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + +TEST(SchemaValidator, Issue608) { + Document sd; + sd.Parse("{\"required\": [\"a\", \"b\"] }"); + SchemaDocument s(sd); + + VALIDATE(s, "{\"a\" : null, \"b\": null}", true); + INVALIDATE(s, "{\"a\" : null, \"a\" : null}", "", "required", ""); +} + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/simdtest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/simdtest.cpp new file mode 100644 index 0000000000..b01b559f42 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/simdtest.cpp @@ -0,0 +1,215 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +// Since Travis CI installs old Valgrind 3.7.0, which fails with some SSE4.2 +// The unit tests prefix with SIMD should be skipped by Valgrind test + +// __SSE2__ and __SSE4_2__ are recognized by gcc, clang, and the Intel compiler. +// We use -march=native with gmake to enable -msse2 and -msse4.2, if supported. +#if defined(__SSE4_2__) +# define RAPIDJSON_SSE42 +#elif defined(__SSE2__) +# define RAPIDJSON_SSE2 +#endif + +#define RAPIDJSON_NAMESPACE rapidjson_simd + +#include "unittest.h" + +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" + +#ifdef __GNUC__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(effc++) +#endif + +using namespace rapidjson_simd; + +#ifdef RAPIDJSON_SSE2 +#define SIMD_SUFFIX(name) name##_SSE2 +#elif defined(RAPIDJSON_SSE42) +#define SIMD_SUFFIX(name) name##_SSE42 +#else +#define SIMD_SUFFIX(name) name +#endif + +template +void TestSkipWhitespace() { + for (size_t step = 1; step < 32; step++) { + char buffer[1025]; + for (size_t i = 0; i < 1024; i++) + buffer[i] = " \t\r\n"[i % 4]; + for (size_t i = 0; i < 1024; i += step) + buffer[i] = 'X'; + buffer[1024] = '\0'; + + StreamType s(buffer); + size_t i = 0; + for (;;) { + SkipWhitespace(s); + if (s.Peek() == '\0') + break; + EXPECT_EQ(i, s.Tell()); + EXPECT_EQ('X', s.Take()); + i += step; + } + } +} + +TEST(SIMD, SIMD_SUFFIX(SkipWhitespace)) { + TestSkipWhitespace(); + TestSkipWhitespace(); +} + +TEST(SIMD, SIMD_SUFFIX(SkipWhitespace_EncodedMemoryStream)) { + for (size_t step = 1; step < 32; step++) { + char buffer[1024]; + for (size_t i = 0; i < 1024; i++) + buffer[i] = " \t\r\n"[i % 4]; + for (size_t i = 0; i < 1024; i += step) + buffer[i] = 'X'; + + MemoryStream ms(buffer, 1024); + EncodedInputStream, MemoryStream> s(ms); + size_t i = 0; + for (;;) { + SkipWhitespace(s); + if (s.Peek() == '\0') + break; + //EXPECT_EQ(i, s.Tell()); + EXPECT_EQ('X', s.Take()); + i += step; + } + } +} + +struct ScanCopyUnescapedStringHandler : BaseReaderHandler, ScanCopyUnescapedStringHandler> { + bool String(const char* str, size_t length, bool) { + memcpy(buffer, str, length + 1); + return true; + } + char buffer[1024 + 5 + 32]; +}; + +template +void TestScanCopyUnescapedString() { + char buffer[1024 + 5 + 32]; + char backup[1024 + 5 + 32]; + + // Test "ABCDABCD...\\" + for (size_t offset = 0; offset < 32; offset++) { + for (size_t step = 0; step < 1024; step++) { + char* json = buffer + offset; + char *p = json; + *p++ = '\"'; + for (size_t i = 0; i < step; i++) + *p++ = "ABCD"[i % 4]; + *p++ = '\\'; + *p++ = '\\'; + *p++ = '\"'; + *p++ = '\0'; + strcpy(backup, json); // insitu parsing will overwrite buffer, so need to backup first + + StreamType s(json); + Reader reader; + ScanCopyUnescapedStringHandler h; + reader.Parse(s, h); + EXPECT_TRUE(memcmp(h.buffer, backup + 1, step) == 0); + EXPECT_EQ('\\', h.buffer[step]); // escaped + EXPECT_EQ('\0', h.buffer[step + 1]); + } + } + + // Test "\\ABCDABCD..." + for (size_t offset = 0; offset < 32; offset++) { + for (size_t step = 0; step < 1024; step++) { + char* json = buffer + offset; + char *p = json; + *p++ = '\"'; + *p++ = '\\'; + *p++ = '\\'; + for (size_t i = 0; i < step; i++) + *p++ = "ABCD"[i % 4]; + *p++ = '\"'; + *p++ = '\0'; + strcpy(backup, json); // insitu parsing will overwrite buffer, so need to backup first + + StreamType s(json); + Reader reader; + ScanCopyUnescapedStringHandler h; + reader.Parse(s, h); + EXPECT_TRUE(memcmp(h.buffer + 1, backup + 3, step) == 0); + EXPECT_EQ('\\', h.buffer[0]); // escaped + EXPECT_EQ('\0', h.buffer[step + 1]); + } + } +} + +TEST(SIMD, SIMD_SUFFIX(ScanCopyUnescapedString)) { + TestScanCopyUnescapedString(); + TestScanCopyUnescapedString(); +} + +TEST(SIMD, SIMD_SUFFIX(ScanWriteUnescapedString)) { + char buffer[2048 + 1 + 32]; + for (size_t offset = 0; offset < 32; offset++) { + for (size_t step = 0; step < 1024; step++) { + char* s = buffer + offset; + char* p = s; + for (size_t i = 0; i < step; i++) + *p++ = "ABCD"[i % 4]; + char escape = "\0\n\\\""[step % 4]; + *p++ = escape; + for (size_t i = 0; i < step; i++) + *p++ = "ABCD"[i % 4]; + + StringBuffer sb; + Writer writer(sb); + writer.String(s, SizeType(step * 2 + 1)); + const char* q = sb.GetString(); + EXPECT_EQ('\"', *q++); + for (size_t i = 0; i < step; i++) + EXPECT_EQ("ABCD"[i % 4], *q++); + if (escape == '\0') { + EXPECT_EQ('\\', *q++); + EXPECT_EQ('u', *q++); + EXPECT_EQ('0', *q++); + EXPECT_EQ('0', *q++); + EXPECT_EQ('0', *q++); + EXPECT_EQ('0', *q++); + } + else if (escape == '\n') { + EXPECT_EQ('\\', *q++); + EXPECT_EQ('n', *q++); + } + else if (escape == '\\') { + EXPECT_EQ('\\', *q++); + EXPECT_EQ('\\', *q++); + } + else if (escape == '\"') { + EXPECT_EQ('\\', *q++); + EXPECT_EQ('\"', *q++); + } + for (size_t i = 0; i < step; i++) + EXPECT_EQ("ABCD"[i % 4], *q++); + EXPECT_EQ('\"', *q++); + EXPECT_EQ('\0', *q++); + } + } +} + +#ifdef __GNUC__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/strfunctest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/strfunctest.cpp new file mode 100644 index 0000000000..cc1bb22f0e --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/strfunctest.cpp @@ -0,0 +1,30 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/internal/strfunc.h" + +using namespace rapidjson; +using namespace rapidjson::internal; + +TEST(StrFunc, CountStringCodePoint) { + SizeType count; + EXPECT_TRUE(CountStringCodePoint >("", 0, &count)); + EXPECT_EQ(0u, count); + EXPECT_TRUE(CountStringCodePoint >("Hello", 5, &count)); + EXPECT_EQ(5u, count); + EXPECT_TRUE(CountStringCodePoint >("\xC2\xA2\xE2\x82\xAC\xF0\x9D\x84\x9E", 9, &count)); // cents euro G-clef + EXPECT_EQ(3u, count); + EXPECT_FALSE(CountStringCodePoint >("\xC2\xA2\xE2\x82\xAC\xF0\x9D\x84\x9E\x80", 10, &count)); +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/stringbuffertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/stringbuffertest.cpp new file mode 100644 index 0000000000..ded513cddc --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/stringbuffertest.cpp @@ -0,0 +1,170 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +using namespace rapidjson; + +TEST(StringBuffer, InitialSize) { + StringBuffer buffer; + EXPECT_EQ(0u, buffer.GetSize()); + EXPECT_STREQ("", buffer.GetString()); +} + +TEST(StringBuffer, Put) { + StringBuffer buffer; + buffer.Put('A'); + + EXPECT_EQ(1u, buffer.GetSize()); + EXPECT_STREQ("A", buffer.GetString()); +} + +TEST(StringBuffer, PutN_Issue672) { + GenericStringBuffer, MemoryPoolAllocator<> > buffer; + EXPECT_EQ(0, buffer.GetSize()); + rapidjson::PutN(buffer, ' ', 1); + EXPECT_EQ(1, buffer.GetSize()); +} + +TEST(StringBuffer, Clear) { + StringBuffer buffer; + buffer.Put('A'); + buffer.Put('B'); + buffer.Put('C'); + buffer.Clear(); + + EXPECT_EQ(0u, buffer.GetSize()); + EXPECT_STREQ("", buffer.GetString()); +} + +TEST(StringBuffer, Push) { + StringBuffer buffer; + buffer.Push(5); + + EXPECT_EQ(5u, buffer.GetSize()); + + // Causes sudden expansion to make the stack's capacity equal to size + buffer.Push(65536u); + EXPECT_EQ(5u + 65536u, buffer.GetSize()); +} + +TEST(StringBuffer, Pop) { + StringBuffer buffer; + buffer.Put('A'); + buffer.Put('B'); + buffer.Put('C'); + buffer.Put('D'); + buffer.Put('E'); + buffer.Pop(3); + + EXPECT_EQ(2u, buffer.GetSize()); + EXPECT_STREQ("AB", buffer.GetString()); +} + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + +#if 0 // Many old compiler does not support these. Turn it off temporaily. + +#include + +TEST(StringBuffer, Traits) { + static_assert( std::is_constructible::value, ""); + static_assert( std::is_default_constructible::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_constructible::value, ""); +#endif + static_assert( std::is_move_constructible::value, ""); + + static_assert(!std::is_nothrow_constructible::value, ""); + static_assert(!std::is_nothrow_default_constructible::value, ""); + +#if !defined(_MSC_VER) || _MSC_VER >= 1800 + static_assert(!std::is_nothrow_copy_constructible::value, ""); + static_assert(!std::is_nothrow_move_constructible::value, ""); +#endif + + static_assert( std::is_assignable::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_assignable::value, ""); +#endif + static_assert( std::is_move_assignable::value, ""); + +#if !defined(_MSC_VER) || _MSC_VER >= 1800 + static_assert(!std::is_nothrow_assignable::value, ""); +#endif + + static_assert(!std::is_nothrow_copy_assignable::value, ""); + static_assert(!std::is_nothrow_move_assignable::value, ""); + + static_assert( std::is_destructible::value, ""); +#ifndef _MSC_VER + static_assert(std::is_nothrow_destructible::value, ""); +#endif +} + +#endif + +TEST(StringBuffer, MoveConstructor) { + StringBuffer x; + x.Put('A'); + x.Put('B'); + x.Put('C'); + x.Put('D'); + + EXPECT_EQ(4u, x.GetSize()); + EXPECT_STREQ("ABCD", x.GetString()); + + // StringBuffer y(x); // does not compile (!is_copy_constructible) + StringBuffer y(std::move(x)); + EXPECT_EQ(0u, x.GetSize()); + EXPECT_EQ(4u, y.GetSize()); + EXPECT_STREQ("ABCD", y.GetString()); + + // StringBuffer z = y; // does not compile (!is_copy_assignable) + StringBuffer z = std::move(y); + EXPECT_EQ(0u, y.GetSize()); + EXPECT_EQ(4u, z.GetSize()); + EXPECT_STREQ("ABCD", z.GetString()); +} + +TEST(StringBuffer, MoveAssignment) { + StringBuffer x; + x.Put('A'); + x.Put('B'); + x.Put('C'); + x.Put('D'); + + EXPECT_EQ(4u, x.GetSize()); + EXPECT_STREQ("ABCD", x.GetString()); + + StringBuffer y; + // y = x; // does not compile (!is_copy_assignable) + y = std::move(x); + EXPECT_EQ(0u, x.GetSize()); + EXPECT_EQ(4u, y.GetSize()); + EXPECT_STREQ("ABCD", y.GetString()); +} + +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/strtodtest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/strtodtest.cpp new file mode 100644 index 0000000000..cde836c7eb --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/strtodtest.cpp @@ -0,0 +1,132 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/internal/strtod.h" + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(unreachable-code) +#endif + +#define BIGINTEGER_LITERAL(s) BigInteger(s, sizeof(s) - 1) + +using namespace rapidjson::internal; + +TEST(Strtod, CheckApproximationCase) { + static const int kSignificandSize = 52; + static const int kExponentBias = 0x3FF; + static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000); + static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF); + static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000); + + // http://www.exploringbinary.com/using-integers-to-check-a-floating-point-approximation/ + // Let b = 0x1.465a72e467d88p-149 + // = 5741268244528520 x 2^-201 + union { + double d; + uint64_t u; + }u; + u.u = 0x465a72e467d88 | ((static_cast(-149 + kExponentBias)) << kSignificandSize); + const double b = u.d; + const uint64_t bInt = (u.u & kSignificandMask) | kHiddenBit; + const int bExp = static_cast(((u.u & kExponentMask) >> kSignificandSize) - kExponentBias - kSignificandSize); + EXPECT_DOUBLE_EQ(1.7864e-45, b); + EXPECT_EQ(RAPIDJSON_UINT64_C2(0x001465a7, 0x2e467d88), bInt); + EXPECT_EQ(-201, bExp); + + // Let d = 17864 x 10-49 + const char dInt[] = "17864"; + const int dExp = -49; + + // Let h = 2^(bExp-1) + const int hExp = bExp - 1; + EXPECT_EQ(-202, hExp); + + int dS_Exp2 = 0; + int dS_Exp5 = 0; + int bS_Exp2 = 0; + int bS_Exp5 = 0; + int hS_Exp2 = 0; + int hS_Exp5 = 0; + + // Adjust for decimal exponent + if (dExp >= 0) { + dS_Exp2 += dExp; + dS_Exp5 += dExp; + } + else { + bS_Exp2 -= dExp; + bS_Exp5 -= dExp; + hS_Exp2 -= dExp; + hS_Exp5 -= dExp; + } + + // Adjust for binary exponent + if (bExp >= 0) + bS_Exp2 += bExp; + else { + dS_Exp2 -= bExp; + hS_Exp2 -= bExp; + } + + // Adjust for half ulp exponent + if (hExp >= 0) + hS_Exp2 += hExp; + else { + dS_Exp2 -= hExp; + bS_Exp2 -= hExp; + } + + // Remove common power of two factor from all three scaled values + int common_Exp2 = std::min(dS_Exp2, std::min(bS_Exp2, hS_Exp2)); + dS_Exp2 -= common_Exp2; + bS_Exp2 -= common_Exp2; + hS_Exp2 -= common_Exp2; + + EXPECT_EQ(153, dS_Exp2); + EXPECT_EQ(0, dS_Exp5); + EXPECT_EQ(1, bS_Exp2); + EXPECT_EQ(49, bS_Exp5); + EXPECT_EQ(0, hS_Exp2); + EXPECT_EQ(49, hS_Exp5); + + BigInteger dS = BIGINTEGER_LITERAL(dInt); + dS.MultiplyPow5(static_cast(dS_Exp5)) <<= static_cast(dS_Exp2); + + BigInteger bS(bInt); + bS.MultiplyPow5(static_cast(bS_Exp5)) <<= static_cast(bS_Exp2); + + BigInteger hS(1); + hS.MultiplyPow5(static_cast(hS_Exp5)) <<= static_cast(hS_Exp2); + + EXPECT_TRUE(BIGINTEGER_LITERAL("203970822259994138521801764465966248930731085529088") == dS); + EXPECT_TRUE(BIGINTEGER_LITERAL("203970822259994122305215569213032722473144531250000") == bS); + EXPECT_TRUE(BIGINTEGER_LITERAL("17763568394002504646778106689453125") == hS); + + EXPECT_EQ(1, dS.Compare(bS)); + + BigInteger delta(0); + EXPECT_FALSE(dS.Difference(bS, &delta)); + EXPECT_TRUE(BIGINTEGER_LITERAL("16216586195252933526457586554279088") == delta); + EXPECT_TRUE(bS.Difference(dS, &delta)); + EXPECT_TRUE(BIGINTEGER_LITERAL("16216586195252933526457586554279088") == delta); + + EXPECT_EQ(-1, delta.Compare(hS)); +} + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/unittest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/unittest.cpp new file mode 100644 index 0000000000..b754563ea2 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/unittest.cpp @@ -0,0 +1,51 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/rapidjson.h" + +#ifdef __clang__ +#pragma GCC diagnostic push +#if __has_warning("-Wdeprecated") +#pragma GCC diagnostic ignored "-Wdeprecated" +#endif +#endif + +AssertException::~AssertException() throw() {} + +#ifdef __clang__ +#pragma GCC diagnostic pop +#endif + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + + std::cout << "RapidJSON v" << RAPIDJSON_VERSION_STRING << std::endl; + +#ifdef _MSC_VER + _CrtMemState memoryState = { 0 }; + (void)memoryState; + _CrtMemCheckpoint(&memoryState); + //_CrtSetBreakAlloc(X); + //void *testWhetherMemoryLeakDetectionWorks = malloc(1); +#endif + + int ret = RUN_ALL_TESTS(); + +#ifdef _MSC_VER + // Current gtest constantly leak 2 blocks at exit + _CrtMemDumpAllObjectsSince(&memoryState); +#endif + return ret; +} diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/unittest.h b/thirdparty/rapidjson-1.1.0/test/unittest/unittest.h new file mode 100644 index 0000000000..e125bf88dc --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/unittest.h @@ -0,0 +1,135 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#ifndef UNITTEST_H_ +#define UNITTEST_H_ + +// gtest indirectly included inttypes.h, without __STDC_CONSTANT_MACROS. +#ifndef __STDC_CONSTANT_MACROS +#ifdef __clang__ +#pragma GCC diagnostic push +#if __has_warning("-Wreserved-id-macro") +#pragma GCC diagnostic ignored "-Wreserved-id-macro" +#endif +#endif + +# define __STDC_CONSTANT_MACROS 1 // required by C++ standard + +#ifdef __clang__ +#pragma GCC diagnostic pop +#endif +#endif + +#ifdef _MSC_VER +#define _CRTDBG_MAP_ALLOC +#include +#pragma warning(disable : 4996) // 'function': was declared deprecated +#endif + +#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)) +#if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#pragma GCC diagnostic push +#endif +#pragma GCC diagnostic ignored "-Weffc++" +#endif + +#include "gtest/gtest.h" +#include + +#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +// All TEST() macro generated this warning, disable globally +#pragma GCC diagnostic ignored "-Wglobal-constructors" +#endif + +template +inline unsigned StrLen(const Ch* s) { + const Ch* p = s; + while (*p) p++; + return unsigned(p - s); +} + +template +inline int StrCmp(const Ch* s1, const Ch* s2) { + while(*s1 && (*s1 == *s2)) { s1++; s2++; } + return static_cast(*s1) < static_cast(*s2) ? -1 : static_cast(*s1) > static_cast(*s2); +} + +template +inline Ch* StrDup(const Ch* str) { + size_t bufferSize = sizeof(Ch) * (StrLen(str) + 1); + Ch* buffer = static_cast(malloc(bufferSize)); + memcpy(buffer, str, bufferSize); + return buffer; +} + +inline FILE* TempFile(char *filename) { +#ifdef _MSC_VER + filename = tmpnam(filename); + + // For Visual Studio, tmpnam() adds a backslash in front. Remove it. + if (filename[0] == '\\') + for (int i = 0; filename[i] != '\0'; i++) + filename[i] = filename[i + 1]; + + return fopen(filename, "wb"); +#else + strcpy(filename, "/tmp/fileXXXXXX"); + int fd = mkstemp(filename); + return fdopen(fd, "w"); +#endif +} + +// Use exception for catching assert +#ifdef _MSC_VER +#pragma warning(disable : 4127) +#endif + +#ifdef __clang__ +#pragma GCC diagnostic push +#if __has_warning("-Wdeprecated") +#pragma GCC diagnostic ignored "-Wdeprecated" +#endif +#endif + +class AssertException : public std::logic_error { +public: + AssertException(const char* w) : std::logic_error(w) {} + AssertException(const AssertException& rhs) : std::logic_error(rhs) {} + virtual ~AssertException() throw(); +}; + +#ifdef __clang__ +#pragma GCC diagnostic pop +#endif + +#define RAPIDJSON_ASSERT(x) if (!(x)) throw AssertException(RAPIDJSON_STRINGIFY(x)) + +class Random { +public: + Random(unsigned seed = 0) : mSeed(seed) {} + + unsigned operator()() { + mSeed = 214013 * mSeed + 2531011; + return mSeed; + } + +private: + unsigned mSeed; +}; + +#endif // UNITTEST_H_ diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/valuetest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/valuetest.cpp new file mode 100644 index 0000000000..fefc001d45 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/valuetest.cpp @@ -0,0 +1,1792 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" +#include "rapidjson/document.h" +#include + +#ifdef __clang__ +RAPIDJSON_DIAG_PUSH +RAPIDJSON_DIAG_OFF(c++98-compat) +#endif + +using namespace rapidjson; + +TEST(Value, Size) { + if (sizeof(SizeType) == 4) { +#if RAPIDJSON_48BITPOINTER_OPTIMIZATION + EXPECT_EQ(16, sizeof(Value)); +#elif RAPIDJSON_64BIT + EXPECT_EQ(24, sizeof(Value)); +#else + EXPECT_EQ(16, sizeof(Value)); +#endif + } +} + +TEST(Value, DefaultConstructor) { + Value x; + EXPECT_EQ(kNullType, x.GetType()); + EXPECT_TRUE(x.IsNull()); + + //std::cout << "sizeof(Value): " << sizeof(x) << std::endl; +} + +// Should not pass compilation +//TEST(Value, copy_constructor) { +// Value x(1234); +// Value y = x; +//} + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + +#if 0 // Many old compiler does not support these. Turn it off temporaily. + +#include + +TEST(Value, Traits) { + typedef GenericValue, CrtAllocator> Value; + static_assert(std::is_constructible::value, ""); + static_assert(std::is_default_constructible::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_constructible::value, ""); +#endif + static_assert(std::is_move_constructible::value, ""); + +#ifndef _MSC_VER + static_assert(std::is_nothrow_constructible::value, ""); + static_assert(std::is_nothrow_default_constructible::value, ""); + static_assert(!std::is_nothrow_copy_constructible::value, ""); + static_assert(std::is_nothrow_move_constructible::value, ""); +#endif + + static_assert(std::is_assignable::value, ""); +#ifndef _MSC_VER + static_assert(!std::is_copy_assignable::value, ""); +#endif + static_assert(std::is_move_assignable::value, ""); + +#ifndef _MSC_VER + static_assert(std::is_nothrow_assignable::value, ""); +#endif + static_assert(!std::is_nothrow_copy_assignable::value, ""); +#ifndef _MSC_VER + static_assert(std::is_nothrow_move_assignable::value, ""); +#endif + + static_assert(std::is_destructible::value, ""); +#ifndef _MSC_VER + static_assert(std::is_nothrow_destructible::value, ""); +#endif +} + +#endif + +TEST(Value, MoveConstructor) { + typedef GenericValue, CrtAllocator> V; + V::AllocatorType allocator; + + V x((V(kArrayType))); + x.Reserve(4u, allocator); + x.PushBack(1, allocator).PushBack(2, allocator).PushBack(3, allocator).PushBack(4, allocator); + EXPECT_TRUE(x.IsArray()); + EXPECT_EQ(4u, x.Size()); + + // Value y(x); // does not compile (!is_copy_constructible) + V y(std::move(x)); + EXPECT_TRUE(x.IsNull()); + EXPECT_TRUE(y.IsArray()); + EXPECT_EQ(4u, y.Size()); + + // Value z = y; // does not compile (!is_copy_assignable) + V z = std::move(y); + EXPECT_TRUE(y.IsNull()); + EXPECT_TRUE(z.IsArray()); + EXPECT_EQ(4u, z.Size()); +} + +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS + +TEST(Value, AssignmentOperator) { + Value x(1234); + Value y; + y = x; + EXPECT_TRUE(x.IsNull()); // move semantic + EXPECT_EQ(1234, y.GetInt()); + + y = 5678; + EXPECT_TRUE(y.IsInt()); + EXPECT_EQ(5678, y.GetInt()); + + x = "Hello"; + EXPECT_TRUE(x.IsString()); + EXPECT_STREQ(x.GetString(),"Hello"); + + y = StringRef(x.GetString(),x.GetStringLength()); + EXPECT_TRUE(y.IsString()); + EXPECT_EQ(y.GetString(),x.GetString()); + EXPECT_EQ(y.GetStringLength(),x.GetStringLength()); + + static char mstr[] = "mutable"; + // y = mstr; // should not compile + y = StringRef(mstr); + EXPECT_TRUE(y.IsString()); + EXPECT_EQ(y.GetString(),mstr); + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + // C++11 move assignment + x = Value("World"); + EXPECT_TRUE(x.IsString()); + EXPECT_STREQ("World", x.GetString()); + + x = std::move(y); + EXPECT_TRUE(y.IsNull()); + EXPECT_TRUE(x.IsString()); + EXPECT_EQ(x.GetString(), mstr); + + y = std::move(Value().SetInt(1234)); + EXPECT_TRUE(y.IsInt()); + EXPECT_EQ(1234, y); +#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS +} + +template +void TestEqual(const A& a, const B& b) { + EXPECT_TRUE (a == b); + EXPECT_FALSE(a != b); + EXPECT_TRUE (b == a); + EXPECT_FALSE(b != a); +} + +template +void TestUnequal(const A& a, const B& b) { + EXPECT_FALSE(a == b); + EXPECT_TRUE (a != b); + EXPECT_FALSE(b == a); + EXPECT_TRUE (b != a); +} + +TEST(Value, EqualtoOperator) { + Value::AllocatorType allocator; + Value x(kObjectType); + x.AddMember("hello", "world", allocator) + .AddMember("t", Value(true).Move(), allocator) + .AddMember("f", Value(false).Move(), allocator) + .AddMember("n", Value(kNullType).Move(), allocator) + .AddMember("i", 123, allocator) + .AddMember("pi", 3.14, allocator) + .AddMember("a", Value(kArrayType).Move().PushBack(1, allocator).PushBack(2, allocator).PushBack(3, allocator), allocator); + + // Test templated operator==() and operator!=() + TestEqual(x["hello"], "world"); + const char* cc = "world"; + TestEqual(x["hello"], cc); + char* c = strdup("world"); + TestEqual(x["hello"], c); + free(c); + + TestEqual(x["t"], true); + TestEqual(x["f"], false); + TestEqual(x["i"], 123); + TestEqual(x["pi"], 3.14); + + // Test operator==() (including different allocators) + CrtAllocator crtAllocator; + GenericValue, CrtAllocator> y; + GenericDocument, CrtAllocator> z(&crtAllocator); + y.CopyFrom(x, crtAllocator); + z.CopyFrom(y, z.GetAllocator()); + TestEqual(x, y); + TestEqual(y, z); + TestEqual(z, x); + + // Swapping member order should be fine. + EXPECT_TRUE(y.RemoveMember("t")); + TestUnequal(x, y); + TestUnequal(z, y); + EXPECT_TRUE(z.RemoveMember("t")); + TestUnequal(x, z); + TestEqual(y, z); + y.AddMember("t", false, crtAllocator); + z.AddMember("t", false, z.GetAllocator()); + TestUnequal(x, y); + TestUnequal(z, x); + y["t"] = true; + z["t"] = true; + TestEqual(x, y); + TestEqual(y, z); + TestEqual(z, x); + + // Swapping element order is not OK + x["a"][0].Swap(x["a"][1]); + TestUnequal(x, y); + x["a"][0].Swap(x["a"][1]); + TestEqual(x, y); + + // Array of different size + x["a"].PushBack(4, allocator); + TestUnequal(x, y); + x["a"].PopBack(); + TestEqual(x, y); + + // Issue #129: compare Uint64 + x.SetUint64(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0)); + y.SetUint64(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF)); + TestUnequal(x, y); +} + +template +void TestCopyFrom() { + typename Value::AllocatorType a; + Value v1(1234); + Value v2(v1, a); // deep copy constructor + EXPECT_TRUE(v1.GetType() == v2.GetType()); + EXPECT_EQ(v1.GetInt(), v2.GetInt()); + + v1.SetString("foo"); + v2.CopyFrom(v1, a); + EXPECT_TRUE(v1.GetType() == v2.GetType()); + EXPECT_STREQ(v1.GetString(), v2.GetString()); + EXPECT_EQ(v1.GetString(), v2.GetString()); // string NOT copied + + v1.SetString("bar", a); // copy string + v2.CopyFrom(v1, a); + EXPECT_TRUE(v1.GetType() == v2.GetType()); + EXPECT_STREQ(v1.GetString(), v2.GetString()); + EXPECT_NE(v1.GetString(), v2.GetString()); // string copied + + + v1.SetArray().PushBack(1234, a); + v2.CopyFrom(v1, a); + EXPECT_TRUE(v2.IsArray()); + EXPECT_EQ(v1.Size(), v2.Size()); + + v1.PushBack(Value().SetString("foo", a), a); // push string copy + EXPECT_TRUE(v1.Size() != v2.Size()); + v2.CopyFrom(v1, a); + EXPECT_TRUE(v1.Size() == v2.Size()); + EXPECT_STREQ(v1[1].GetString(), v2[1].GetString()); + EXPECT_NE(v1[1].GetString(), v2[1].GetString()); // string got copied +} + +TEST(Value, CopyFrom) { + TestCopyFrom(); + TestCopyFrom, CrtAllocator> >(); +} + +TEST(Value, Swap) { + Value v1(1234); + Value v2(kObjectType); + + EXPECT_EQ(&v1, &v1.Swap(v2)); + EXPECT_TRUE(v1.IsObject()); + EXPECT_TRUE(v2.IsInt()); + EXPECT_EQ(1234, v2.GetInt()); + + // testing std::swap compatibility + using std::swap; + swap(v1, v2); + EXPECT_TRUE(v1.IsInt()); + EXPECT_TRUE(v2.IsObject()); +} + +TEST(Value, Null) { + // Default constructor + Value x; + EXPECT_EQ(kNullType, x.GetType()); + EXPECT_TRUE(x.IsNull()); + + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsNumber()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // Constructor with type + Value y(kNullType); + EXPECT_TRUE(y.IsNull()); + + // SetNull(); + Value z(true); + z.SetNull(); + EXPECT_TRUE(z.IsNull()); +} + +TEST(Value, True) { + // Constructor with bool + Value x(true); + EXPECT_EQ(kTrueType, x.GetType()); + EXPECT_TRUE(x.GetBool()); + EXPECT_TRUE(x.IsBool()); + EXPECT_TRUE(x.IsTrue()); + + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsNumber()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // Constructor with type + Value y(kTrueType); + EXPECT_TRUE(y.IsTrue()); + + // SetBool() + Value z; + z.SetBool(true); + EXPECT_TRUE(z.IsTrue()); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_TRUE(z.Get()); + EXPECT_FALSE(z.Set(false).Get()); + EXPECT_TRUE(z.Set(true).Get()); +} + +TEST(Value, False) { + // Constructor with bool + Value x(false); + EXPECT_EQ(kFalseType, x.GetType()); + EXPECT_TRUE(x.IsBool()); + EXPECT_TRUE(x.IsFalse()); + + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.GetBool()); + //EXPECT_FALSE((bool)x); + EXPECT_FALSE(x.IsNumber()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // Constructor with type + Value y(kFalseType); + EXPECT_TRUE(y.IsFalse()); + + // SetBool() + Value z; + z.SetBool(false); + EXPECT_TRUE(z.IsFalse()); +} + +TEST(Value, Int) { + // Constructor with int + Value x(1234); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_EQ(1234, x.GetInt()); + EXPECT_EQ(1234u, x.GetUint()); + EXPECT_EQ(1234, x.GetInt64()); + EXPECT_EQ(1234u, x.GetUint64()); + EXPECT_NEAR(1234.0, x.GetDouble(), 0.0); + //EXPECT_EQ(1234, (int)x); + //EXPECT_EQ(1234, (unsigned)x); + //EXPECT_EQ(1234, (int64_t)x); + //EXPECT_EQ(1234, (uint64_t)x); + //EXPECT_EQ(1234, (double)x); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsInt()); + EXPECT_TRUE(x.IsUint()); + EXPECT_TRUE(x.IsInt64()); + EXPECT_TRUE(x.IsUint64()); + + EXPECT_FALSE(x.IsDouble()); + EXPECT_FALSE(x.IsFloat()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + Value nx(-1234); + EXPECT_EQ(-1234, nx.GetInt()); + EXPECT_EQ(-1234, nx.GetInt64()); + EXPECT_TRUE(nx.IsInt()); + EXPECT_TRUE(nx.IsInt64()); + EXPECT_FALSE(nx.IsUint()); + EXPECT_FALSE(nx.IsUint64()); + + // Constructor with type + Value y(kNumberType); + EXPECT_TRUE(y.IsNumber()); + EXPECT_TRUE(y.IsInt()); + EXPECT_EQ(0, y.GetInt()); + + // SetInt() + Value z; + z.SetInt(1234); + EXPECT_EQ(1234, z.GetInt()); + + // operator=(int) + z = 5678; + EXPECT_EQ(5678, z.GetInt()); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(5678, z.Get()); + EXPECT_EQ(5679, z.Set(5679).Get()); + EXPECT_EQ(5680, z.Set(5680).Get()); +} + +TEST(Value, Uint) { + // Constructor with int + Value x(1234u); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_EQ(1234, x.GetInt()); + EXPECT_EQ(1234u, x.GetUint()); + EXPECT_EQ(1234, x.GetInt64()); + EXPECT_EQ(1234u, x.GetUint64()); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsInt()); + EXPECT_TRUE(x.IsUint()); + EXPECT_TRUE(x.IsInt64()); + EXPECT_TRUE(x.IsUint64()); + EXPECT_NEAR(1234.0, x.GetDouble(), 0.0); // Number can always be cast as double but !IsDouble(). + + EXPECT_FALSE(x.IsDouble()); + EXPECT_FALSE(x.IsFloat()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // SetUint() + Value z; + z.SetUint(1234); + EXPECT_EQ(1234u, z.GetUint()); + + // operator=(unsigned) + z = 5678u; + EXPECT_EQ(5678u, z.GetUint()); + + z = 2147483648u; // 2^31, cannot cast as int + EXPECT_EQ(2147483648u, z.GetUint()); + EXPECT_FALSE(z.IsInt()); + EXPECT_TRUE(z.IsInt64()); // Issue 41: Incorrect parsing of unsigned int number types + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(2147483648u, z.Get()); + EXPECT_EQ(2147483649u, z.Set(2147483649u).Get()); + EXPECT_EQ(2147483650u, z.Set(2147483650u).Get()); +} + +TEST(Value, Int64) { + // Constructor with int + Value x(int64_t(1234)); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_EQ(1234, x.GetInt()); + EXPECT_EQ(1234u, x.GetUint()); + EXPECT_EQ(1234, x.GetInt64()); + EXPECT_EQ(1234u, x.GetUint64()); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsInt()); + EXPECT_TRUE(x.IsUint()); + EXPECT_TRUE(x.IsInt64()); + EXPECT_TRUE(x.IsUint64()); + + EXPECT_FALSE(x.IsDouble()); + EXPECT_FALSE(x.IsFloat()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + Value nx(int64_t(-1234)); + EXPECT_EQ(-1234, nx.GetInt()); + EXPECT_EQ(-1234, nx.GetInt64()); + EXPECT_TRUE(nx.IsInt()); + EXPECT_TRUE(nx.IsInt64()); + EXPECT_FALSE(nx.IsUint()); + EXPECT_FALSE(nx.IsUint64()); + + // SetInt64() + Value z; + z.SetInt64(1234); + EXPECT_EQ(1234, z.GetInt64()); + + z.SetInt64(2147483648u); // 2^31, cannot cast as int + EXPECT_FALSE(z.IsInt()); + EXPECT_TRUE(z.IsUint()); + EXPECT_NEAR(2147483648.0, z.GetDouble(), 0.0); + + z.SetInt64(int64_t(4294967295u) + 1); // 2^32, cannot cast as uint + EXPECT_FALSE(z.IsInt()); + EXPECT_FALSE(z.IsUint()); + EXPECT_NEAR(4294967296.0, z.GetDouble(), 0.0); + + z.SetInt64(-int64_t(2147483648u) - 1); // -2^31-1, cannot cast as int + EXPECT_FALSE(z.IsInt()); + EXPECT_NEAR(-2147483649.0, z.GetDouble(), 0.0); + + int64_t i = static_cast(RAPIDJSON_UINT64_C2(0x80000000, 00000000)); + z.SetInt64(i); + EXPECT_DOUBLE_EQ(-9223372036854775808.0, z.GetDouble()); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(i, z.Get()); +#if 0 // signed integer underflow is undefined behaviour + EXPECT_EQ(i - 1, z.Set(i - 1).Get()); + EXPECT_EQ(i - 2, z.Set(i - 2).Get()); +#endif +} + +TEST(Value, Uint64) { + // Constructor with int + Value x(uint64_t(1234)); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_EQ(1234, x.GetInt()); + EXPECT_EQ(1234u, x.GetUint()); + EXPECT_EQ(1234, x.GetInt64()); + EXPECT_EQ(1234u, x.GetUint64()); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsInt()); + EXPECT_TRUE(x.IsUint()); + EXPECT_TRUE(x.IsInt64()); + EXPECT_TRUE(x.IsUint64()); + + EXPECT_FALSE(x.IsDouble()); + EXPECT_FALSE(x.IsFloat()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // SetUint64() + Value z; + z.SetUint64(1234); + EXPECT_EQ(1234u, z.GetUint64()); + + z.SetUint64(uint64_t(2147483648u)); // 2^31, cannot cast as int + EXPECT_FALSE(z.IsInt()); + EXPECT_TRUE(z.IsUint()); + EXPECT_TRUE(z.IsInt64()); + + z.SetUint64(uint64_t(4294967295u) + 1); // 2^32, cannot cast as uint + EXPECT_FALSE(z.IsInt()); + EXPECT_FALSE(z.IsUint()); + EXPECT_TRUE(z.IsInt64()); + + uint64_t u = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000); + z.SetUint64(u); // 2^63 cannot cast as int64 + EXPECT_FALSE(z.IsInt64()); + EXPECT_EQ(u, z.GetUint64()); // Issue 48 + EXPECT_DOUBLE_EQ(9223372036854775808.0, z.GetDouble()); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(u, z.Get()); + EXPECT_EQ(u + 1, z.Set(u + 1).Get()); + EXPECT_EQ(u + 2, z.Set(u + 2).Get()); +} + +TEST(Value, Double) { + // Constructor with double + Value x(12.34); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_NEAR(12.34, x.GetDouble(), 0.0); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsDouble()); + + EXPECT_FALSE(x.IsInt()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // SetDouble() + Value z; + z.SetDouble(12.34); + EXPECT_NEAR(12.34, z.GetDouble(), 0.0); + + z = 56.78; + EXPECT_NEAR(56.78, z.GetDouble(), 0.0); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(56.78, z.Get()); + EXPECT_EQ(57.78, z.Set(57.78).Get()); + EXPECT_EQ(58.78, z.Set(58.78).Get()); +} + +TEST(Value, Float) { + // Constructor with double + Value x(12.34f); + EXPECT_EQ(kNumberType, x.GetType()); + EXPECT_NEAR(12.34f, x.GetFloat(), 0.0); + EXPECT_TRUE(x.IsNumber()); + EXPECT_TRUE(x.IsDouble()); + EXPECT_TRUE(x.IsFloat()); + + EXPECT_FALSE(x.IsInt()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + // SetFloat() + Value z; + z.SetFloat(12.34f); + EXPECT_NEAR(12.34f, z.GetFloat(), 0.0f); + + // Issue 573 + z.SetInt(0); + EXPECT_EQ(0.0f, z.GetFloat()); + + z = 56.78f; + EXPECT_NEAR(56.78f, z.GetFloat(), 0.0f); + + // Templated functions + EXPECT_TRUE(z.Is()); + EXPECT_EQ(56.78f, z.Get()); + EXPECT_EQ(57.78f, z.Set(57.78f).Get()); + EXPECT_EQ(58.78f, z.Set(58.78f).Get()); +} + +TEST(Value, IsLosslessDouble) { + EXPECT_TRUE(Value(0.0).IsLosslessDouble()); + EXPECT_TRUE(Value(12.34).IsLosslessDouble()); + EXPECT_TRUE(Value(-123).IsLosslessDouble()); + EXPECT_TRUE(Value(2147483648u).IsLosslessDouble()); + EXPECT_TRUE(Value(-static_cast(RAPIDJSON_UINT64_C2(0x40000000, 0x00000000))).IsLosslessDouble()); +#if !(defined(_MSC_VER) && _MSC_VER < 1800) // VC2010 has problem + EXPECT_TRUE(Value(RAPIDJSON_UINT64_C2(0xA0000000, 0x00000000)).IsLosslessDouble()); +#endif + + EXPECT_FALSE(Value(static_cast(RAPIDJSON_UINT64_C2(0x7FFFFFFF, 0xFFFFFFFF))).IsLosslessDouble()); // INT64_MAX + EXPECT_FALSE(Value(-static_cast(RAPIDJSON_UINT64_C2(0x7FFFFFFF, 0xFFFFFFFF))).IsLosslessDouble()); // -INT64_MAX + EXPECT_TRUE(Value(-static_cast(RAPIDJSON_UINT64_C2(0x7FFFFFFF, 0xFFFFFFFF)) - 1).IsLosslessDouble()); // INT64_MIN + EXPECT_FALSE(Value(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFFF)).IsLosslessDouble()); // UINT64_MAX + + EXPECT_TRUE(Value(3.4028234e38f).IsLosslessDouble()); // FLT_MAX + EXPECT_TRUE(Value(-3.4028234e38f).IsLosslessDouble()); // -FLT_MAX + EXPECT_TRUE(Value(1.17549435e-38f).IsLosslessDouble()); // FLT_MIN + EXPECT_TRUE(Value(-1.17549435e-38f).IsLosslessDouble()); // -FLT_MIN + EXPECT_TRUE(Value(1.7976931348623157e+308).IsLosslessDouble()); // DBL_MAX + EXPECT_TRUE(Value(-1.7976931348623157e+308).IsLosslessDouble()); // -DBL_MAX + EXPECT_TRUE(Value(2.2250738585072014e-308).IsLosslessDouble()); // DBL_MIN + EXPECT_TRUE(Value(-2.2250738585072014e-308).IsLosslessDouble()); // -DBL_MIN +} + +TEST(Value, IsLosslessFloat) { + EXPECT_TRUE(Value(12.25).IsLosslessFloat()); + EXPECT_TRUE(Value(-123).IsLosslessFloat()); + EXPECT_TRUE(Value(2147483648u).IsLosslessFloat()); + EXPECT_TRUE(Value(3.4028234e38f).IsLosslessFloat()); + EXPECT_TRUE(Value(-3.4028234e38f).IsLosslessFloat()); + EXPECT_FALSE(Value(3.4028235e38).IsLosslessFloat()); + EXPECT_FALSE(Value(0.3).IsLosslessFloat()); +} + +TEST(Value, String) { + // Construction with const string + Value x("Hello", 5); // literal + EXPECT_EQ(kStringType, x.GetType()); + EXPECT_TRUE(x.IsString()); + EXPECT_STREQ("Hello", x.GetString()); + EXPECT_EQ(5u, x.GetStringLength()); + + EXPECT_FALSE(x.IsNumber()); + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsObject()); + EXPECT_FALSE(x.IsArray()); + + static const char cstr[] = "World"; // const array + Value(cstr).Swap(x); + EXPECT_TRUE(x.IsString()); + EXPECT_EQ(x.GetString(), cstr); + EXPECT_EQ(x.GetStringLength(), sizeof(cstr)-1); + + static char mstr[] = "Howdy"; // non-const array + // Value(mstr).Swap(x); // should not compile + Value(StringRef(mstr)).Swap(x); + EXPECT_TRUE(x.IsString()); + EXPECT_EQ(x.GetString(), mstr); + EXPECT_EQ(x.GetStringLength(), sizeof(mstr)-1); + strncpy(mstr,"Hello", sizeof(mstr)); + EXPECT_STREQ(x.GetString(), "Hello"); + + const char* pstr = cstr; + //Value(pstr).Swap(x); // should not compile + Value(StringRef(pstr)).Swap(x); + EXPECT_TRUE(x.IsString()); + EXPECT_EQ(x.GetString(), cstr); + EXPECT_EQ(x.GetStringLength(), sizeof(cstr)-1); + + char* mpstr = mstr; + Value(StringRef(mpstr,sizeof(mstr)-1)).Swap(x); + EXPECT_TRUE(x.IsString()); + EXPECT_EQ(x.GetString(), mstr); + EXPECT_EQ(x.GetStringLength(), 5u); + EXPECT_STREQ(x.GetString(), "Hello"); + + // Constructor with copy string + MemoryPoolAllocator<> allocator; + Value c(x.GetString(), x.GetStringLength(), allocator); + EXPECT_NE(x.GetString(), c.GetString()); + EXPECT_EQ(x.GetStringLength(), c.GetStringLength()); + EXPECT_STREQ(x.GetString(), c.GetString()); + //x.SetString("World"); + x.SetString("World", 5); + EXPECT_STREQ("Hello", c.GetString()); + EXPECT_EQ(5u, c.GetStringLength()); + + // Constructor with type + Value y(kStringType); + EXPECT_TRUE(y.IsString()); + EXPECT_STREQ("", y.GetString()); // Empty string should be "" instead of 0 (issue 226) + EXPECT_EQ(0u, y.GetStringLength()); + + // SetConsttring() + Value z; + z.SetString("Hello"); + EXPECT_TRUE(x.IsString()); + z.SetString("Hello", 5); + EXPECT_STREQ("Hello", z.GetString()); + EXPECT_STREQ("Hello", z.GetString()); + EXPECT_EQ(5u, z.GetStringLength()); + + z.SetString("Hello"); + EXPECT_TRUE(z.IsString()); + EXPECT_STREQ("Hello", z.GetString()); + + //z.SetString(mstr); // should not compile + //z.SetString(pstr); // should not compile + z.SetString(StringRef(mstr)); + EXPECT_TRUE(z.IsString()); + EXPECT_STREQ(z.GetString(), mstr); + + z.SetString(cstr); + EXPECT_TRUE(z.IsString()); + EXPECT_EQ(cstr, z.GetString()); + + z = cstr; + EXPECT_TRUE(z.IsString()); + EXPECT_EQ(cstr, z.GetString()); + + // SetString() + char s[] = "World"; + Value w; + w.SetString(s, static_cast(strlen(s)), allocator); + s[0] = '\0'; + EXPECT_STREQ("World", w.GetString()); + EXPECT_EQ(5u, w.GetStringLength()); + + // templated functions + EXPECT_TRUE(z.Is()); + EXPECT_STREQ(cstr, z.Get()); + EXPECT_STREQ("Apple", z.Set("Apple").Get()); + +#if RAPIDJSON_HAS_STDSTRING + { + std::string str = "Hello World"; + str[5] = '\0'; + EXPECT_STREQ(str.data(),"Hello"); // embedded '\0' + EXPECT_EQ(str.size(), 11u); + + // no copy + Value vs0(StringRef(str)); + EXPECT_TRUE(vs0.IsString()); + EXPECT_EQ(vs0.GetString(), str.data()); + EXPECT_EQ(vs0.GetStringLength(), str.size()); + TestEqual(vs0, str); + + // do copy + Value vs1(str, allocator); + EXPECT_TRUE(vs1.IsString()); + EXPECT_NE(vs1.GetString(), str.data()); + EXPECT_NE(vs1.GetString(), str); // not equal due to embedded '\0' + EXPECT_EQ(vs1.GetStringLength(), str.size()); + TestEqual(vs1, str); + + // SetString + str = "World"; + vs0.SetNull().SetString(str, allocator); + EXPECT_TRUE(vs0.IsString()); + EXPECT_STREQ(vs0.GetString(), str.c_str()); + EXPECT_EQ(vs0.GetStringLength(), str.size()); + TestEqual(str, vs0); + TestUnequal(str, vs1); + + // vs1 = str; // should not compile + vs1 = StringRef(str); + TestEqual(str, vs1); + TestEqual(vs0, vs1); + + // Templated function. + EXPECT_TRUE(vs0.Is()); + EXPECT_EQ(str, vs0.Get()); + vs0.Set(std::string("Apple"), allocator); + EXPECT_EQ(std::string("Apple"), vs0.Get()); + vs0.Set(std::string("Orange"), allocator); + EXPECT_EQ(std::string("Orange"), vs0.Get()); + } +#endif // RAPIDJSON_HAS_STDSTRING +} + +// Issue 226: Value of string type should not point to NULL +TEST(Value, SetStringNullException) { + Value v; + EXPECT_THROW(v.SetString(0, 0), AssertException); +} + +template +static void TestArray(T& x, Allocator& allocator) { + const T& y = x; + + // PushBack() + Value v; + x.PushBack(v, allocator); + v.SetBool(true); + x.PushBack(v, allocator); + v.SetBool(false); + x.PushBack(v, allocator); + v.SetInt(123); + x.PushBack(v, allocator); + //x.PushBack((const char*)"foo", allocator); // should not compile + x.PushBack("foo", allocator); + + EXPECT_FALSE(x.Empty()); + EXPECT_EQ(5u, x.Size()); + EXPECT_FALSE(y.Empty()); + EXPECT_EQ(5u, y.Size()); + EXPECT_TRUE(x[SizeType(0)].IsNull()); + EXPECT_TRUE(x[1].IsTrue()); + EXPECT_TRUE(x[2].IsFalse()); + EXPECT_TRUE(x[3].IsInt()); + EXPECT_EQ(123, x[3].GetInt()); + EXPECT_TRUE(y[SizeType(0)].IsNull()); + EXPECT_TRUE(y[1].IsTrue()); + EXPECT_TRUE(y[2].IsFalse()); + EXPECT_TRUE(y[3].IsInt()); + EXPECT_EQ(123, y[3].GetInt()); + EXPECT_TRUE(y[4].IsString()); + EXPECT_STREQ("foo", y[4].GetString()); + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + // PushBack(GenericValue&&, Allocator&); + { + Value y2(kArrayType); + y2.PushBack(Value(true), allocator); + y2.PushBack(std::move(Value(kArrayType).PushBack(Value(1), allocator).PushBack("foo", allocator)), allocator); + EXPECT_EQ(2u, y2.Size()); + EXPECT_TRUE(y2[0].IsTrue()); + EXPECT_TRUE(y2[1].IsArray()); + EXPECT_EQ(2u, y2[1].Size()); + EXPECT_TRUE(y2[1][0].IsInt()); + EXPECT_TRUE(y2[1][1].IsString()); + } +#endif + + // iterator + typename T::ValueIterator itr = x.Begin(); + EXPECT_TRUE(itr != x.End()); + EXPECT_TRUE(itr->IsNull()); + ++itr; + EXPECT_TRUE(itr != x.End()); + EXPECT_TRUE(itr->IsTrue()); + ++itr; + EXPECT_TRUE(itr != x.End()); + EXPECT_TRUE(itr->IsFalse()); + ++itr; + EXPECT_TRUE(itr != x.End()); + EXPECT_TRUE(itr->IsInt()); + EXPECT_EQ(123, itr->GetInt()); + ++itr; + EXPECT_TRUE(itr != x.End()); + EXPECT_TRUE(itr->IsString()); + EXPECT_STREQ("foo", itr->GetString()); + + // const iterator + typename T::ConstValueIterator citr = y.Begin(); + EXPECT_TRUE(citr != y.End()); + EXPECT_TRUE(citr->IsNull()); + ++citr; + EXPECT_TRUE(citr != y.End()); + EXPECT_TRUE(citr->IsTrue()); + ++citr; + EXPECT_TRUE(citr != y.End()); + EXPECT_TRUE(citr->IsFalse()); + ++citr; + EXPECT_TRUE(citr != y.End()); + EXPECT_TRUE(citr->IsInt()); + EXPECT_EQ(123, citr->GetInt()); + ++citr; + EXPECT_TRUE(citr != y.End()); + EXPECT_TRUE(citr->IsString()); + EXPECT_STREQ("foo", citr->GetString()); + + // PopBack() + x.PopBack(); + EXPECT_EQ(4u, x.Size()); + EXPECT_TRUE(y[SizeType(0)].IsNull()); + EXPECT_TRUE(y[1].IsTrue()); + EXPECT_TRUE(y[2].IsFalse()); + EXPECT_TRUE(y[3].IsInt()); + + // Clear() + x.Clear(); + EXPECT_TRUE(x.Empty()); + EXPECT_EQ(0u, x.Size()); + EXPECT_TRUE(y.Empty()); + EXPECT_EQ(0u, y.Size()); + + // Erase(ValueIterator) + + // Use array of array to ensure removed elements' destructor is called. + // [[0],[1],[2],...] + for (int i = 0; i < 10; i++) + x.PushBack(Value(kArrayType).PushBack(i, allocator).Move(), allocator); + + // Erase the first + itr = x.Erase(x.Begin()); + EXPECT_EQ(x.Begin(), itr); + EXPECT_EQ(9u, x.Size()); + for (int i = 0; i < 9; i++) + EXPECT_EQ(i + 1, x[static_cast(i)][0].GetInt()); + + // Ease the last + itr = x.Erase(x.End() - 1); + EXPECT_EQ(x.End(), itr); + EXPECT_EQ(8u, x.Size()); + for (int i = 0; i < 8; i++) + EXPECT_EQ(i + 1, x[static_cast(i)][0].GetInt()); + + // Erase the middle + itr = x.Erase(x.Begin() + 4); + EXPECT_EQ(x.Begin() + 4, itr); + EXPECT_EQ(7u, x.Size()); + for (int i = 0; i < 4; i++) + EXPECT_EQ(i + 1, x[static_cast(i)][0].GetInt()); + for (int i = 4; i < 7; i++) + EXPECT_EQ(i + 2, x[static_cast(i)][0].GetInt()); + + // Erase(ValueIterator, ValueIterator) + // Exhaustive test with all 0 <= first < n, first <= last <= n cases + const unsigned n = 10; + for (unsigned first = 0; first < n; first++) { + for (unsigned last = first; last <= n; last++) { + x.Clear(); + for (unsigned i = 0; i < n; i++) + x.PushBack(Value(kArrayType).PushBack(i, allocator).Move(), allocator); + + itr = x.Erase(x.Begin() + first, x.Begin() + last); + if (last == n) + EXPECT_EQ(x.End(), itr); + else + EXPECT_EQ(x.Begin() + first, itr); + + size_t removeCount = last - first; + EXPECT_EQ(n - removeCount, x.Size()); + for (unsigned i = 0; i < first; i++) + EXPECT_EQ(i, x[i][0].GetUint()); + for (unsigned i = first; i < n - removeCount; i++) + EXPECT_EQ(i + removeCount, x[static_cast(i)][0].GetUint()); + } + } +} + +TEST(Value, Array) { + Value x(kArrayType); + const Value& y = x; + Value::AllocatorType allocator; + + EXPECT_EQ(kArrayType, x.GetType()); + EXPECT_TRUE(x.IsArray()); + EXPECT_TRUE(x.Empty()); + EXPECT_EQ(0u, x.Size()); + EXPECT_TRUE(y.IsArray()); + EXPECT_TRUE(y.Empty()); + EXPECT_EQ(0u, y.Size()); + + EXPECT_FALSE(x.IsNull()); + EXPECT_FALSE(x.IsBool()); + EXPECT_FALSE(x.IsFalse()); + EXPECT_FALSE(x.IsTrue()); + EXPECT_FALSE(x.IsString()); + EXPECT_FALSE(x.IsObject()); + + TestArray(x, allocator); + + // Working in gcc without C++11, but VS2013 cannot compile. To be diagnosed. + // http://en.wikipedia.org/wiki/Erase-remove_idiom + x.Clear(); + for (int i = 0; i < 10; i++) + if (i % 2 == 0) + x.PushBack(i, allocator); + else + x.PushBack(Value(kNullType).Move(), allocator); + + const Value null(kNullType); + x.Erase(std::remove(x.Begin(), x.End(), null), x.End()); + EXPECT_EQ(5u, x.Size()); + for (int i = 0; i < 5; i++) + EXPECT_EQ(i * 2, x[static_cast(i)]); + + // SetArray() + Value z; + z.SetArray(); + EXPECT_TRUE(z.IsArray()); + EXPECT_TRUE(z.Empty()); +} + +TEST(Value, ArrayHelper) { + Value::AllocatorType allocator; + { + Value x(kArrayType); + Value::Array a = x.GetArray(); + TestArray(a, allocator); + } + + { + Value x(kArrayType); + Value::Array a = x.GetArray(); + a.PushBack(1, allocator); + + Value::Array a2(a); // copy constructor + EXPECT_EQ(1, a2.Size()); + + Value::Array a3 = a; + EXPECT_EQ(1, a3.Size()); + + Value::ConstArray y = static_cast(x).GetArray(); + (void)y; + // y.PushBack(1, allocator); // should not compile + + // Templated functions + x.Clear(); + EXPECT_TRUE(x.Is()); + EXPECT_TRUE(x.Is()); + a.PushBack(1, allocator); + EXPECT_EQ(1, x.Get()[0].GetInt()); + EXPECT_EQ(1, x.Get()[0].GetInt()); + + Value x2; + x2.Set(a); + EXPECT_TRUE(x.IsArray()); // IsArray() is invariant after moving. + EXPECT_EQ(1, x2.Get()[0].GetInt()); + } + + { + Value y(kArrayType); + y.PushBack(123, allocator); + + Value x(y.GetArray()); // Construct value form array. + EXPECT_TRUE(x.IsArray()); + EXPECT_EQ(123, x[0].GetInt()); + EXPECT_TRUE(y.IsArray()); // Invariant + EXPECT_TRUE(y.Empty()); + } + + { + Value x(kArrayType); + Value y(kArrayType); + y.PushBack(123, allocator); + x.PushBack(y.GetArray(), allocator); // Implicit constructor to convert Array to GenericValue + + EXPECT_EQ(1, x.Size()); + EXPECT_EQ(123, x[0][0].GetInt()); + EXPECT_TRUE(y.IsArray()); + EXPECT_TRUE(y.Empty()); + } +} + +#if RAPIDJSON_HAS_CXX11_RANGE_FOR +TEST(Value, ArrayHelperRangeFor) { + Value::AllocatorType allocator; + Value x(kArrayType); + + for (int i = 0; i < 10; i++) + x.PushBack(i, allocator); + + { + int i = 0; + for (auto& v : x.GetArray()) { + EXPECT_EQ(i, v.GetInt()); + i++; + } + EXPECT_EQ(i, 10); + } + { + int i = 0; + for (const auto& v : const_cast(x).GetArray()) { + EXPECT_EQ(i, v.GetInt()); + i++; + } + EXPECT_EQ(i, 10); + } + + // Array a = x.GetArray(); + // Array ca = const_cast(x).GetArray(); +} +#endif + +template +static void TestObject(T& x, Allocator& allocator) { + const T& y = x; // const version + + // AddMember() + x.AddMember("A", "Apple", allocator); + EXPECT_FALSE(x.ObjectEmpty()); + EXPECT_EQ(1u, x.MemberCount()); + + Value value("Banana", 6); + x.AddMember("B", "Banana", allocator); + EXPECT_EQ(2u, x.MemberCount()); + + // AddMember(StringRefType, T, Allocator) + { + Value o(kObjectType); + o.AddMember("true", true, allocator); + o.AddMember("false", false, allocator); + o.AddMember("int", -1, allocator); + o.AddMember("uint", 1u, allocator); + o.AddMember("int64", int64_t(-4294967296), allocator); + o.AddMember("uint64", uint64_t(4294967296), allocator); + o.AddMember("double", 3.14, allocator); + o.AddMember("string", "Jelly", allocator); + + EXPECT_TRUE(o["true"].GetBool()); + EXPECT_FALSE(o["false"].GetBool()); + EXPECT_EQ(-1, o["int"].GetInt()); + EXPECT_EQ(1u, o["uint"].GetUint()); + EXPECT_EQ(int64_t(-4294967296), o["int64"].GetInt64()); + EXPECT_EQ(uint64_t(4294967296), o["uint64"].GetUint64()); + EXPECT_STREQ("Jelly",o["string"].GetString()); + EXPECT_EQ(8u, o.MemberCount()); + } + + // AddMember(Value&, T, Allocator) + { + Value o(kObjectType); + + Value n("s"); + o.AddMember(n, "string", allocator); + EXPECT_EQ(1u, o.MemberCount()); + + Value count("#"); + o.AddMember(count, o.MemberCount(), allocator); + EXPECT_EQ(2u, o.MemberCount()); + } + +#if RAPIDJSON_HAS_STDSTRING + { + // AddMember(StringRefType, const std::string&, Allocator) + Value o(kObjectType); + o.AddMember("b", std::string("Banana"), allocator); + EXPECT_STREQ("Banana", o["b"].GetString()); + + // RemoveMember(const std::string&) + o.RemoveMember(std::string("b")); + EXPECT_TRUE(o.ObjectEmpty()); + } +#endif + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS + // AddMember(GenericValue&&, ...) variants + { + Value o(kObjectType); + o.AddMember(Value("true"), Value(true), allocator); + o.AddMember(Value("false"), Value(false).Move(), allocator); // value is lvalue ref + o.AddMember(Value("int").Move(), Value(-1), allocator); // name is lvalue ref + o.AddMember("uint", std::move(Value().SetUint(1u)), allocator); // name is literal, value is rvalue + EXPECT_TRUE(o["true"].GetBool()); + EXPECT_FALSE(o["false"].GetBool()); + EXPECT_EQ(-1, o["int"].GetInt()); + EXPECT_EQ(1u, o["uint"].GetUint()); + EXPECT_EQ(4u, o.MemberCount()); + } +#endif + + // Tests a member with null character + Value name; + const Value C0D("C\0D", 3); + name.SetString(C0D.GetString(), 3); + value.SetString("CherryD", 7); + x.AddMember(name, value, allocator); + + // HasMember() + EXPECT_TRUE(x.HasMember("A")); + EXPECT_TRUE(x.HasMember("B")); + EXPECT_TRUE(y.HasMember("A")); + EXPECT_TRUE(y.HasMember("B")); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_TRUE(x.HasMember(std::string("A"))); +#endif + + name.SetString("C\0D"); + EXPECT_TRUE(x.HasMember(name)); + EXPECT_TRUE(y.HasMember(name)); + + GenericValue, CrtAllocator> othername("A"); + EXPECT_TRUE(x.HasMember(othername)); + EXPECT_TRUE(y.HasMember(othername)); + othername.SetString("C\0D"); + EXPECT_TRUE(x.HasMember(othername)); + EXPECT_TRUE(y.HasMember(othername)); + + // operator[] + EXPECT_STREQ("Apple", x["A"].GetString()); + EXPECT_STREQ("Banana", x["B"].GetString()); + EXPECT_STREQ("CherryD", x[C0D].GetString()); + EXPECT_STREQ("CherryD", x[othername].GetString()); + EXPECT_THROW(x["nonexist"], AssertException); + + // const operator[] + EXPECT_STREQ("Apple", y["A"].GetString()); + EXPECT_STREQ("Banana", y["B"].GetString()); + EXPECT_STREQ("CherryD", y[C0D].GetString()); + +#if RAPIDJSON_HAS_STDSTRING + EXPECT_STREQ("Apple", x["A"].GetString()); + EXPECT_STREQ("Apple", y[std::string("A")].GetString()); +#endif + + // member iterator + Value::MemberIterator itr = x.MemberBegin(); + EXPECT_TRUE(itr != x.MemberEnd()); + EXPECT_STREQ("A", itr->name.GetString()); + EXPECT_STREQ("Apple", itr->value.GetString()); + ++itr; + EXPECT_TRUE(itr != x.MemberEnd()); + EXPECT_STREQ("B", itr->name.GetString()); + EXPECT_STREQ("Banana", itr->value.GetString()); + ++itr; + EXPECT_TRUE(itr != x.MemberEnd()); + EXPECT_TRUE(memcmp(itr->name.GetString(), "C\0D", 4) == 0); + EXPECT_STREQ("CherryD", itr->value.GetString()); + ++itr; + EXPECT_FALSE(itr != x.MemberEnd()); + + // const member iterator + Value::ConstMemberIterator citr = y.MemberBegin(); + EXPECT_TRUE(citr != y.MemberEnd()); + EXPECT_STREQ("A", citr->name.GetString()); + EXPECT_STREQ("Apple", citr->value.GetString()); + ++citr; + EXPECT_TRUE(citr != y.MemberEnd()); + EXPECT_STREQ("B", citr->name.GetString()); + EXPECT_STREQ("Banana", citr->value.GetString()); + ++citr; + EXPECT_TRUE(citr != y.MemberEnd()); + EXPECT_TRUE(memcmp(citr->name.GetString(), "C\0D", 4) == 0); + EXPECT_STREQ("CherryD", citr->value.GetString()); + ++citr; + EXPECT_FALSE(citr != y.MemberEnd()); + + // member iterator conversions/relations + itr = x.MemberBegin(); + citr = x.MemberBegin(); // const conversion + TestEqual(itr, citr); + EXPECT_TRUE(itr < x.MemberEnd()); + EXPECT_FALSE(itr > y.MemberEnd()); + EXPECT_TRUE(citr < x.MemberEnd()); + EXPECT_FALSE(citr > y.MemberEnd()); + ++citr; + TestUnequal(itr, citr); + EXPECT_FALSE(itr < itr); + EXPECT_TRUE(itr < citr); + EXPECT_FALSE(itr > itr); + EXPECT_TRUE(citr > itr); + EXPECT_EQ(1, citr - x.MemberBegin()); + EXPECT_EQ(0, itr - y.MemberBegin()); + itr += citr - x.MemberBegin(); + EXPECT_EQ(1, itr - y.MemberBegin()); + TestEqual(citr, itr); + EXPECT_TRUE(itr <= citr); + EXPECT_TRUE(citr <= itr); + itr++; + EXPECT_TRUE(itr >= citr); + EXPECT_FALSE(citr >= itr); + + // RemoveMember() + EXPECT_TRUE(x.RemoveMember("A")); + EXPECT_FALSE(x.HasMember("A")); + + EXPECT_TRUE(x.RemoveMember("B")); + EXPECT_FALSE(x.HasMember("B")); + + EXPECT_FALSE(x.RemoveMember("nonexist")); + + EXPECT_TRUE(x.RemoveMember(othername)); + EXPECT_FALSE(x.HasMember(name)); + + EXPECT_TRUE(x.MemberBegin() == x.MemberEnd()); + + // EraseMember(ConstMemberIterator) + + // Use array members to ensure removed elements' destructor is called. + // { "a": [0], "b": [1],[2],...] + const char keys[][2] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" }; + for (int i = 0; i < 10; i++) + x.AddMember(keys[i], Value(kArrayType).PushBack(i, allocator), allocator); + + // MemberCount, iterator difference + EXPECT_EQ(x.MemberCount(), SizeType(x.MemberEnd() - x.MemberBegin())); + + // Erase the first + itr = x.EraseMember(x.MemberBegin()); + EXPECT_FALSE(x.HasMember(keys[0])); + EXPECT_EQ(x.MemberBegin(), itr); + EXPECT_EQ(9u, x.MemberCount()); + for (; itr != x.MemberEnd(); ++itr) { + size_t i = static_cast((itr - x.MemberBegin())) + 1; + EXPECT_STREQ(itr->name.GetString(), keys[i]); + EXPECT_EQ(i, itr->value[0].GetInt()); + } + + // Erase the last + itr = x.EraseMember(x.MemberEnd() - 1); + EXPECT_FALSE(x.HasMember(keys[9])); + EXPECT_EQ(x.MemberEnd(), itr); + EXPECT_EQ(8u, x.MemberCount()); + for (; itr != x.MemberEnd(); ++itr) { + size_t i = static_cast(itr - x.MemberBegin()) + 1; + EXPECT_STREQ(itr->name.GetString(), keys[i]); + EXPECT_EQ(i, itr->value[0].GetInt()); + } + + // Erase the middle + itr = x.EraseMember(x.MemberBegin() + 4); + EXPECT_FALSE(x.HasMember(keys[5])); + EXPECT_EQ(x.MemberBegin() + 4, itr); + EXPECT_EQ(7u, x.MemberCount()); + for (; itr != x.MemberEnd(); ++itr) { + size_t i = static_cast(itr - x.MemberBegin()); + i += (i < 4) ? 1 : 2; + EXPECT_STREQ(itr->name.GetString(), keys[i]); + EXPECT_EQ(i, itr->value[0].GetInt()); + } + + // EraseMember(ConstMemberIterator, ConstMemberIterator) + // Exhaustive test with all 0 <= first < n, first <= last <= n cases + const unsigned n = 10; + for (unsigned first = 0; first < n; first++) { + for (unsigned last = first; last <= n; last++) { + x.RemoveAllMembers(); + for (unsigned i = 0; i < n; i++) + x.AddMember(keys[i], Value(kArrayType).PushBack(i, allocator), allocator); + + itr = x.EraseMember(x.MemberBegin() + static_cast(first), x.MemberBegin() + static_cast(last)); + if (last == n) + EXPECT_EQ(x.MemberEnd(), itr); + else + EXPECT_EQ(x.MemberBegin() + static_cast(first), itr); + + size_t removeCount = last - first; + EXPECT_EQ(n - removeCount, x.MemberCount()); + for (unsigned i = 0; i < first; i++) + EXPECT_EQ(i, x[keys[i]][0].GetUint()); + for (unsigned i = first; i < n - removeCount; i++) + EXPECT_EQ(i + removeCount, x[keys[i+removeCount]][0].GetUint()); + } + } + + // RemoveAllMembers() + x.RemoveAllMembers(); + EXPECT_TRUE(x.ObjectEmpty()); + EXPECT_EQ(0u, x.MemberCount()); +} + +TEST(Value, Object) { + Value x(kObjectType); + const Value& y = x; // const version + Value::AllocatorType allocator; + + EXPECT_EQ(kObjectType, x.GetType()); + EXPECT_TRUE(x.IsObject()); + EXPECT_TRUE(x.ObjectEmpty()); + EXPECT_EQ(0u, x.MemberCount()); + EXPECT_EQ(kObjectType, y.GetType()); + EXPECT_TRUE(y.IsObject()); + EXPECT_TRUE(y.ObjectEmpty()); + EXPECT_EQ(0u, y.MemberCount()); + + TestObject(x, allocator); + + // SetObject() + Value z; + z.SetObject(); + EXPECT_TRUE(z.IsObject()); +} + +TEST(Value, ObjectHelper) { + Value::AllocatorType allocator; + { + Value x(kObjectType); + Value::Object o = x.GetObject(); + TestObject(o, allocator); + } + + { + Value x(kObjectType); + Value::Object o = x.GetObject(); + o.AddMember("1", 1, allocator); + + Value::Object o2(o); // copy constructor + EXPECT_EQ(1, o2.MemberCount()); + + Value::Object o3 = o; + EXPECT_EQ(1, o3.MemberCount()); + + Value::ConstObject y = static_cast(x).GetObject(); + (void)y; + // y.AddMember("1", 1, allocator); // should not compile + + // Templated functions + x.RemoveAllMembers(); + EXPECT_TRUE(x.Is()); + EXPECT_TRUE(x.Is()); + o.AddMember("1", 1, allocator); + EXPECT_EQ(1, x.Get()["1"].GetInt()); + EXPECT_EQ(1, x.Get()["1"].GetInt()); + + Value x2; + x2.Set(o); + EXPECT_TRUE(x.IsObject()); // IsObject() is invariant after moving + EXPECT_EQ(1, x2.Get()["1"].GetInt()); + } + + { + Value x(kObjectType); + x.AddMember("a", "apple", allocator); + Value y(x.GetObject()); + EXPECT_STREQ("apple", y["a"].GetString()); + EXPECT_TRUE(x.IsObject()); // Invariant + } + + { + Value x(kObjectType); + x.AddMember("a", "apple", allocator); + Value y(kObjectType); + y.AddMember("fruits", x.GetObject(), allocator); + EXPECT_STREQ("apple", y["fruits"]["a"].GetString()); + EXPECT_TRUE(x.IsObject()); // Invariant + } +} + +#if RAPIDJSON_HAS_CXX11_RANGE_FOR +TEST(Value, ObjectHelperRangeFor) { + Value::AllocatorType allocator; + Value x(kObjectType); + + for (int i = 0; i < 10; i++) { + char name[10]; + Value n(name, static_cast(sprintf(name, "%d", i)), allocator); + x.AddMember(n, i, allocator); + } + + { + int i = 0; + for (auto& m : x.GetObject()) { + char name[10]; + sprintf(name, "%d", i); + EXPECT_STREQ(name, m.name.GetString()); + EXPECT_EQ(i, m.value.GetInt()); + i++; + } + EXPECT_EQ(i, 10); + } + { + int i = 0; + for (const auto& m : const_cast(x).GetObject()) { + char name[10]; + sprintf(name, "%d", i); + EXPECT_STREQ(name, m.name.GetString()); + EXPECT_EQ(i, m.value.GetInt()); + i++; + } + EXPECT_EQ(i, 10); + } + + // Object a = x.GetObject(); + // Object ca = const_cast(x).GetObject(); +} +#endif + +TEST(Value, EraseMember_String) { + Value::AllocatorType allocator; + Value x(kObjectType); + x.AddMember("A", "Apple", allocator); + x.AddMember("B", "Banana", allocator); + + EXPECT_TRUE(x.EraseMember("B")); + EXPECT_FALSE(x.HasMember("B")); + + EXPECT_FALSE(x.EraseMember("nonexist")); + + GenericValue, CrtAllocator> othername("A"); + EXPECT_TRUE(x.EraseMember(othername)); + EXPECT_FALSE(x.HasMember("A")); + + EXPECT_TRUE(x.MemberBegin() == x.MemberEnd()); +} + +TEST(Value, BigNestedArray) { + MemoryPoolAllocator<> allocator; + Value x(kArrayType); + static const SizeType n = 200; + + for (SizeType i = 0; i < n; i++) { + Value y(kArrayType); + for (SizeType j = 0; j < n; j++) { + Value number(static_cast(i * n + j)); + y.PushBack(number, allocator); + } + x.PushBack(y, allocator); + } + + for (SizeType i = 0; i < n; i++) + for (SizeType j = 0; j < n; j++) { + EXPECT_TRUE(x[i][j].IsInt()); + EXPECT_EQ(static_cast(i * n + j), x[i][j].GetInt()); + } +} + +TEST(Value, BigNestedObject) { + MemoryPoolAllocator<> allocator; + Value x(kObjectType); + static const SizeType n = 200; + + for (SizeType i = 0; i < n; i++) { + char name1[10]; + sprintf(name1, "%d", i); + + // Value name(name1); // should not compile + Value name(name1, static_cast(strlen(name1)), allocator); + Value object(kObjectType); + + for (SizeType j = 0; j < n; j++) { + char name2[10]; + sprintf(name2, "%d", j); + + Value name3(name2, static_cast(strlen(name2)), allocator); + Value number(static_cast(i * n + j)); + object.AddMember(name3, number, allocator); + } + + // x.AddMember(name1, object, allocator); // should not compile + x.AddMember(name, object, allocator); + } + + for (SizeType i = 0; i < n; i++) { + char name1[10]; + sprintf(name1, "%d", i); + + for (SizeType j = 0; j < n; j++) { + char name2[10]; + sprintf(name2, "%d", j); + x[name1]; + EXPECT_EQ(static_cast(i * n + j), x[name1][name2].GetInt()); + } + } +} + +// Issue 18: Error removing last element of object +// http://code.google.com/p/rapidjson/issues/detail?id=18 +TEST(Value, RemoveLastElement) { + rapidjson::Document doc; + rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); + rapidjson::Value objVal(rapidjson::kObjectType); + objVal.AddMember("var1", 123, allocator); + objVal.AddMember("var2", "444", allocator); + objVal.AddMember("var3", 555, allocator); + EXPECT_TRUE(objVal.HasMember("var3")); + objVal.RemoveMember("var3"); // Assertion here in r61 + EXPECT_FALSE(objVal.HasMember("var3")); +} + +// Issue 38: Segmentation fault with CrtAllocator +TEST(Document, CrtAllocator) { + typedef GenericValue, CrtAllocator> V; + + V::AllocatorType allocator; + V o(kObjectType); + o.AddMember("x", 1, allocator); // Should not call destructor on uninitialized name/value of newly allocated members. + + V a(kArrayType); + a.PushBack(1, allocator); // Should not call destructor on uninitialized Value of newly allocated elements. +} + +static void TestShortStringOptimization(const char* str) { + const rapidjson::SizeType len = static_cast(strlen(str)); + + rapidjson::Document doc; + rapidjson::Value val; + val.SetString(str, len, doc.GetAllocator()); + + EXPECT_EQ(val.GetStringLength(), len); + EXPECT_STREQ(val.GetString(), str); +} + +TEST(Value, AllocateShortString) { + TestShortStringOptimization(""); // edge case: empty string + TestShortStringOptimization("12345678"); // regular case for short strings: 8 chars + TestShortStringOptimization("12345678901"); // edge case: 11 chars in 32-bit mode (=> short string) + TestShortStringOptimization("123456789012"); // edge case: 12 chars in 32-bit mode (=> regular string) + TestShortStringOptimization("123456789012345"); // edge case: 15 chars in 64-bit mode (=> short string) + TestShortStringOptimization("1234567890123456"); // edge case: 16 chars in 64-bit mode (=> regular string) +} + +template +struct TerminateHandler { + bool Null() { return e != 0; } + bool Bool(bool) { return e != 1; } + bool Int(int) { return e != 2; } + bool Uint(unsigned) { return e != 3; } + bool Int64(int64_t) { return e != 4; } + bool Uint64(uint64_t) { return e != 5; } + bool Double(double) { return e != 6; } + bool RawNumber(const char*, SizeType, bool) { return e != 7; } + bool String(const char*, SizeType, bool) { return e != 8; } + bool StartObject() { return e != 9; } + bool Key(const char*, SizeType, bool) { return e != 10; } + bool EndObject(SizeType) { return e != 11; } + bool StartArray() { return e != 12; } + bool EndArray(SizeType) { return e != 13; } +}; + +#define TEST_TERMINATION(e, json)\ +{\ + Document d; \ + EXPECT_FALSE(d.Parse(json).HasParseError()); \ + Reader reader; \ + TerminateHandler h;\ + EXPECT_FALSE(d.Accept(h));\ +} + +TEST(Value, AcceptTerminationByHandler) { + TEST_TERMINATION(0, "[null]"); + TEST_TERMINATION(1, "[true]"); + TEST_TERMINATION(1, "[false]"); + TEST_TERMINATION(2, "[-1]"); + TEST_TERMINATION(3, "[2147483648]"); + TEST_TERMINATION(4, "[-1234567890123456789]"); + TEST_TERMINATION(5, "[9223372036854775808]"); + TEST_TERMINATION(6, "[0.5]"); + // RawNumber() is never called + TEST_TERMINATION(8, "[\"a\"]"); + TEST_TERMINATION(9, "[{}]"); + TEST_TERMINATION(10, "[{\"a\":1}]"); + TEST_TERMINATION(11, "[{}]"); + TEST_TERMINATION(12, "{\"a\":[]}"); + TEST_TERMINATION(13, "{\"a\":[]}"); +} + +struct ValueIntComparer { + bool operator()(const Value& lhs, const Value& rhs) const { + return lhs.GetInt() < rhs.GetInt(); + } +}; + +#if RAPIDJSON_HAS_CXX11_RVALUE_REFS +TEST(Value, Sorting) { + Value::AllocatorType allocator; + Value a(kArrayType); + a.PushBack(5, allocator); + a.PushBack(1, allocator); + a.PushBack(3, allocator); + std::sort(a.Begin(), a.End(), ValueIntComparer()); + EXPECT_EQ(1, a[0].GetInt()); + EXPECT_EQ(3, a[1].GetInt()); + EXPECT_EQ(5, a[2].GetInt()); +} +#endif + +// http://stackoverflow.com/questions/35222230/ + +static void MergeDuplicateKey(Value& v, Value::AllocatorType& a) { + if (v.IsObject()) { + // Convert all key:value into key:[value] + for (Value::MemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) + itr->value = Value(kArrayType).Move().PushBack(itr->value, a); + + // Merge arrays if key is duplicated + for (Value::MemberIterator itr = v.MemberBegin(); itr != v.MemberEnd();) { + Value::MemberIterator itr2 = v.FindMember(itr->name); + if (itr != itr2) { + itr2->value.PushBack(itr->value[0], a); + itr = v.EraseMember(itr); + } + else + ++itr; + } + + // Convert key:[values] back to key:value if there is only one value + for (Value::MemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr) { + if (itr->value.Size() == 1) + itr->value = itr->value[0]; + MergeDuplicateKey(itr->value, a); // Recursion on the value + } + } + else if (v.IsArray()) + for (Value::ValueIterator itr = v.Begin(); itr != v.End(); ++itr) + MergeDuplicateKey(*itr, a); +} + +TEST(Value, MergeDuplicateKey) { + Document d; + d.Parse( + "{" + " \"key1\": {" + " \"a\": \"asdf\"," + " \"b\": \"foo\"," + " \"b\": \"bar\"," + " \"c\": \"fdas\"" + " }" + "}"); + + Document d2; + d2.Parse( + "{" + " \"key1\": {" + " \"a\": \"asdf\"," + " \"b\": [" + " \"foo\"," + " \"bar\"" + " ]," + " \"c\": \"fdas\"" + " }" + "}"); + + EXPECT_NE(d2, d); + MergeDuplicateKey(d, d.GetAllocator()); + EXPECT_EQ(d2, d); +} + +#ifdef __clang__ +RAPIDJSON_DIAG_POP +#endif diff --git a/thirdparty/rapidjson-1.1.0/test/unittest/writertest.cpp b/thirdparty/rapidjson-1.1.0/test/unittest/writertest.cpp new file mode 100644 index 0000000000..29f7626092 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/test/unittest/writertest.cpp @@ -0,0 +1,497 @@ +// Tencent is pleased to support the open source community by making RapidJSON available. +// +// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. +// +// Licensed under the MIT License (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software distributed +// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +// CONDITIONS OF ANY KIND, either express or implied. See the License for the +// specific language governing permissions and limitations under the License. + +#include "unittest.h" + +#include "rapidjson/document.h" +#include "rapidjson/reader.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/memorybuffer.h" + +using namespace rapidjson; + +TEST(Writer, Compact) { + StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); + StringBuffer buffer; + Writer writer(buffer); + buffer.ShrinkToFit(); + Reader reader; + reader.Parse<0>(s, writer); + EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", buffer.GetString()); + EXPECT_EQ(77u, buffer.GetSize()); + EXPECT_TRUE(writer.IsComplete()); +} + +// json -> parse -> writer -> json +#define TEST_ROUNDTRIP(json) \ + { \ + StringStream s(json); \ + StringBuffer buffer; \ + Writer writer(buffer); \ + Reader reader; \ + reader.Parse(s, writer); \ + EXPECT_STREQ(json, buffer.GetString()); \ + EXPECT_TRUE(writer.IsComplete()); \ + } + +TEST(Writer, Root) { + TEST_ROUNDTRIP("null"); + TEST_ROUNDTRIP("true"); + TEST_ROUNDTRIP("false"); + TEST_ROUNDTRIP("0"); + TEST_ROUNDTRIP("\"foo\""); + TEST_ROUNDTRIP("[]"); + TEST_ROUNDTRIP("{}"); +} + +TEST(Writer, Int) { + TEST_ROUNDTRIP("[-1]"); + TEST_ROUNDTRIP("[-123]"); + TEST_ROUNDTRIP("[-2147483648]"); +} + +TEST(Writer, UInt) { + TEST_ROUNDTRIP("[0]"); + TEST_ROUNDTRIP("[1]"); + TEST_ROUNDTRIP("[123]"); + TEST_ROUNDTRIP("[2147483647]"); + TEST_ROUNDTRIP("[4294967295]"); +} + +TEST(Writer, Int64) { + TEST_ROUNDTRIP("[-1234567890123456789]"); + TEST_ROUNDTRIP("[-9223372036854775808]"); +} + +TEST(Writer, Uint64) { + TEST_ROUNDTRIP("[1234567890123456789]"); + TEST_ROUNDTRIP("[9223372036854775807]"); +} + +TEST(Writer, String) { + TEST_ROUNDTRIP("[\"Hello\"]"); + TEST_ROUNDTRIP("[\"Hello\\u0000World\"]"); + TEST_ROUNDTRIP("[\"\\\"\\\\/\\b\\f\\n\\r\\t\"]"); + +#if RAPIDJSON_HAS_STDSTRING + { + StringBuffer buffer; + Writer writer(buffer); + writer.String(std::string("Hello\n")); + EXPECT_STREQ("\"Hello\\n\"", buffer.GetString()); + } +#endif +} + +TEST(Writer, ScanWriteUnescapedString) { + const char json[] = "[\" \\\"0123456789ABCDEF\"]"; + // ^ scanning stops here. + char buffer2[sizeof(json) + 32]; + + // Use different offset to test different alignments + for (int i = 0; i < 32; i++) { + char* p = buffer2 + i; + memcpy(p, json, sizeof(json)); + TEST_ROUNDTRIP(p); + } +} + +TEST(Writer, Double) { + TEST_ROUNDTRIP("[1.2345,1.2345678,0.123456789012,1234567.8]"); + TEST_ROUNDTRIP("0.0"); + TEST_ROUNDTRIP("-0.0"); // Issue #289 + TEST_ROUNDTRIP("1e30"); + TEST_ROUNDTRIP("1.0"); + TEST_ROUNDTRIP("5e-324"); // Min subnormal positive double + TEST_ROUNDTRIP("2.225073858507201e-308"); // Max subnormal positive double + TEST_ROUNDTRIP("2.2250738585072014e-308"); // Min normal positive double + TEST_ROUNDTRIP("1.7976931348623157e308"); // Max double + +} + +// UTF8 -> TargetEncoding -> UTF8 +template +void TestTranscode(const char* json) { + StringStream s(json); + GenericStringBuffer buffer; + Writer, UTF8<>, TargetEncoding> writer(buffer); + Reader reader; + reader.Parse(s, writer); + + StringBuffer buffer2; + Writer writer2(buffer2); + GenericReader > reader2; + GenericStringStream s2(buffer.GetString()); + reader2.Parse(s2, writer2); + + EXPECT_STREQ(json, buffer2.GetString()); +} + +TEST(Writer, Transcode) { + const char json[] = "{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3],\"dollar\":\"\x24\",\"cents\":\"\xC2\xA2\",\"euro\":\"\xE2\x82\xAC\",\"gclef\":\"\xF0\x9D\x84\x9E\"}"; + + // UTF8 -> UTF16 -> UTF8 + TestTranscode >(json); + + // UTF8 -> ASCII -> UTF8 + TestTranscode >(json); + + // UTF8 -> UTF16 -> UTF8 + TestTranscode >(json); + + // UTF8 -> UTF32 -> UTF8 + TestTranscode >(json); + + // UTF8 -> AutoUTF -> UTF8 + UTFType types[] = { kUTF8, kUTF16LE , kUTF16BE, kUTF32LE , kUTF32BE }; + for (size_t i = 0; i < 5; i++) { + StringStream s(json); + MemoryBuffer buffer; + AutoUTFOutputStream os(buffer, types[i], true); + Writer, UTF8<>, AutoUTF > writer(os); + Reader reader; + reader.Parse(s, writer); + + StringBuffer buffer2; + Writer writer2(buffer2); + GenericReader, UTF8<> > reader2; + MemoryStream s2(buffer.GetBuffer(), buffer.GetSize()); + AutoUTFInputStream is(s2); + reader2.Parse(is, writer2); + + EXPECT_STREQ(json, buffer2.GetString()); + } + +} + +#include + +class OStreamWrapper { +public: + typedef char Ch; + + OStreamWrapper(std::ostream& os) : os_(os) {} + + Ch Peek() const { assert(false); return '\0'; } + Ch Take() { assert(false); return '\0'; } + size_t Tell() const { return 0; } + + Ch* PutBegin() { assert(false); return 0; } + void Put(Ch c) { os_.put(c); } + void Flush() { os_.flush(); } + size_t PutEnd(Ch*) { assert(false); return 0; } + +private: + OStreamWrapper(const OStreamWrapper&); + OStreamWrapper& operator=(const OStreamWrapper&); + + std::ostream& os_; +}; + +TEST(Writer, OStreamWrapper) { + StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3], \"u64\": 1234567890123456789, \"i64\":-1234567890123456789 } "); + + std::stringstream ss; + OStreamWrapper os(ss); + + Writer writer(os); + + Reader reader; + reader.Parse<0>(s, writer); + + std::string actual = ss.str(); + EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3],\"u64\":1234567890123456789,\"i64\":-1234567890123456789}", actual.c_str()); +} + +TEST(Writer, AssertRootMayBeAnyValue) { +#define T(x)\ + {\ + StringBuffer buffer;\ + Writer writer(buffer);\ + EXPECT_TRUE(x);\ + } + T(writer.Bool(false)); + T(writer.Bool(true)); + T(writer.Null()); + T(writer.Int(0)); + T(writer.Uint(0)); + T(writer.Int64(0)); + T(writer.Uint64(0)); + T(writer.Double(0)); + T(writer.String("foo")); +#undef T +} + +TEST(Writer, AssertIncorrectObjectLevel) { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + writer.EndObject(); + ASSERT_THROW(writer.EndObject(), AssertException); +} + +TEST(Writer, AssertIncorrectArrayLevel) { + StringBuffer buffer; + Writer writer(buffer); + writer.StartArray(); + writer.EndArray(); + ASSERT_THROW(writer.EndArray(), AssertException); +} + +TEST(Writer, AssertIncorrectEndObject) { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + ASSERT_THROW(writer.EndArray(), AssertException); +} + +TEST(Writer, AssertIncorrectEndArray) { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + ASSERT_THROW(writer.EndArray(), AssertException); +} + +TEST(Writer, AssertObjectKeyNotString) { +#define T(x)\ + {\ + StringBuffer buffer;\ + Writer writer(buffer);\ + writer.StartObject();\ + ASSERT_THROW(x, AssertException); \ + } + T(writer.Bool(false)); + T(writer.Bool(true)); + T(writer.Null()); + T(writer.Int(0)); + T(writer.Uint(0)); + T(writer.Int64(0)); + T(writer.Uint64(0)); + T(writer.Double(0)); + T(writer.StartObject()); + T(writer.StartArray()); +#undef T +} + +TEST(Writer, AssertMultipleRoot) { + StringBuffer buffer; + Writer writer(buffer); + + writer.StartObject(); + writer.EndObject(); + ASSERT_THROW(writer.StartObject(), AssertException); + + writer.Reset(buffer); + writer.Null(); + ASSERT_THROW(writer.Int(0), AssertException); + + writer.Reset(buffer); + writer.String("foo"); + ASSERT_THROW(writer.StartArray(), AssertException); + + writer.Reset(buffer); + writer.StartArray(); + writer.EndArray(); + //ASSERT_THROW(writer.Double(3.14), AssertException); +} + +TEST(Writer, RootObjectIsComplete) { + StringBuffer buffer; + Writer writer(buffer); + EXPECT_FALSE(writer.IsComplete()); + writer.StartObject(); + EXPECT_FALSE(writer.IsComplete()); + writer.String("foo"); + EXPECT_FALSE(writer.IsComplete()); + writer.Int(1); + EXPECT_FALSE(writer.IsComplete()); + writer.EndObject(); + EXPECT_TRUE(writer.IsComplete()); +} + +TEST(Writer, RootArrayIsComplete) { + StringBuffer buffer; + Writer writer(buffer); + EXPECT_FALSE(writer.IsComplete()); + writer.StartArray(); + EXPECT_FALSE(writer.IsComplete()); + writer.String("foo"); + EXPECT_FALSE(writer.IsComplete()); + writer.Int(1); + EXPECT_FALSE(writer.IsComplete()); + writer.EndArray(); + EXPECT_TRUE(writer.IsComplete()); +} + +TEST(Writer, RootValueIsComplete) { +#define T(x)\ + {\ + StringBuffer buffer;\ + Writer writer(buffer);\ + EXPECT_FALSE(writer.IsComplete()); \ + x; \ + EXPECT_TRUE(writer.IsComplete()); \ + } + T(writer.Null()); + T(writer.Bool(true)); + T(writer.Bool(false)); + T(writer.Int(0)); + T(writer.Uint(0)); + T(writer.Int64(0)); + T(writer.Uint64(0)); + T(writer.Double(0)); + T(writer.String("")); +#undef T +} + +TEST(Writer, InvalidEncoding) { + // Fail in decoding invalid UTF-8 sequence http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt + { + GenericStringBuffer > buffer; + Writer >, UTF8<>, UTF16<> > writer(buffer); + writer.StartArray(); + EXPECT_FALSE(writer.String("\xfe")); + EXPECT_FALSE(writer.String("\xff")); + EXPECT_FALSE(writer.String("\xfe\xfe\xff\xff")); + writer.EndArray(); + } + + // Fail in encoding + { + StringBuffer buffer; + Writer > writer(buffer); + static const UTF32<>::Ch s[] = { 0x110000, 0 }; // Out of U+0000 to U+10FFFF + EXPECT_FALSE(writer.String(s)); + } + + // Fail in unicode escaping in ASCII output + { + StringBuffer buffer; + Writer, ASCII<> > writer(buffer); + static const UTF32<>::Ch s[] = { 0x110000, 0 }; // Out of U+0000 to U+10FFFF + EXPECT_FALSE(writer.String(s)); + } +} + +TEST(Writer, ValidateEncoding) { + { + StringBuffer buffer; + Writer, UTF8<>, CrtAllocator, kWriteValidateEncodingFlag> writer(buffer); + writer.StartArray(); + EXPECT_TRUE(writer.String("\x24")); // Dollar sign U+0024 + EXPECT_TRUE(writer.String("\xC2\xA2")); // Cents sign U+00A2 + EXPECT_TRUE(writer.String("\xE2\x82\xAC")); // Euro sign U+20AC + EXPECT_TRUE(writer.String("\xF0\x9D\x84\x9E")); // G clef sign U+1D11E + writer.EndArray(); + EXPECT_STREQ("[\"\x24\",\"\xC2\xA2\",\"\xE2\x82\xAC\",\"\xF0\x9D\x84\x9E\"]", buffer.GetString()); + } + + // Fail in decoding invalid UTF-8 sequence http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt + { + StringBuffer buffer; + Writer, UTF8<>, CrtAllocator, kWriteValidateEncodingFlag> writer(buffer); + writer.StartArray(); + EXPECT_FALSE(writer.String("\xfe")); + EXPECT_FALSE(writer.String("\xff")); + EXPECT_FALSE(writer.String("\xfe\xfe\xff\xff")); + writer.EndArray(); + } +} + +TEST(Writer, InvalidEventSequence) { + // {] + { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + EXPECT_THROW(writer.EndArray(), AssertException); + EXPECT_FALSE(writer.IsComplete()); + } + + // [} + { + StringBuffer buffer; + Writer writer(buffer); + writer.StartArray(); + EXPECT_THROW(writer.EndObject(), AssertException); + EXPECT_FALSE(writer.IsComplete()); + } + + // { 1: + { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + EXPECT_THROW(writer.Int(1), AssertException); + EXPECT_FALSE(writer.IsComplete()); + } +} + +TEST(Writer, NaN) { + double nan = std::numeric_limits::quiet_NaN(); + + EXPECT_TRUE(internal::Double(nan).IsNan()); + StringBuffer buffer; + { + Writer writer(buffer); + EXPECT_FALSE(writer.Double(nan)); + } + { + Writer, UTF8<>, CrtAllocator, kWriteNanAndInfFlag> writer(buffer); + EXPECT_TRUE(writer.Double(nan)); + EXPECT_STREQ("NaN", buffer.GetString()); + } + GenericStringBuffer > buffer2; + Writer > > writer2(buffer2); + EXPECT_FALSE(writer2.Double(nan)); +} + +TEST(Writer, Inf) { + double inf = std::numeric_limits::infinity(); + + EXPECT_TRUE(internal::Double(inf).IsInf()); + StringBuffer buffer; + { + Writer writer(buffer); + EXPECT_FALSE(writer.Double(inf)); + } + { + Writer writer(buffer); + EXPECT_FALSE(writer.Double(-inf)); + } + { + Writer, UTF8<>, CrtAllocator, kWriteNanAndInfFlag> writer(buffer); + EXPECT_TRUE(writer.Double(inf)); + } + { + Writer, UTF8<>, CrtAllocator, kWriteNanAndInfFlag> writer(buffer); + EXPECT_TRUE(writer.Double(-inf)); + } + EXPECT_STREQ("Infinity-Infinity", buffer.GetString()); +} + +TEST(Writer, RawValue) { + StringBuffer buffer; + Writer writer(buffer); + writer.StartObject(); + writer.Key("a"); + writer.Int(1); + writer.Key("raw"); + const char json[] = "[\"Hello\\nWorld\", 123.456]"; + writer.RawValue(json, strlen(json), kArrayType); + writer.EndObject(); + EXPECT_TRUE(writer.IsComplete()); + EXPECT_STREQ("{\"a\":1,\"raw\":[\"Hello\\nWorld\", 123.456]}", buffer.GetString()); +} diff --git a/thirdparty/rapidjson-1.1.0/travis-doxygen.sh b/thirdparty/rapidjson-1.1.0/travis-doxygen.sh new file mode 100755 index 0000000000..31a50cfa92 --- /dev/null +++ b/thirdparty/rapidjson-1.1.0/travis-doxygen.sh @@ -0,0 +1,122 @@ +#!/bin/bash +# Update Doxygen documentation after push to 'master'. +# Author: @pah + +set -e + +DOXYGEN_VER=doxygen-1.8.7 +DOXYGEN_TAR=${DOXYGEN_VER}.linux.bin.tar.gz +DOXYGEN_URL="http://ftp.stack.nl/pub/users/dimitri/${DOXYGEN_TAR}" +DOXYGEN_BIN="/usr/local/bin/doxygen" + +: ${GITHUB_REPO:="miloyip/rapidjson"} +GITHUB_HOST="github.com" +GITHUB_CLONE="git://${GITHUB_HOST}/${GITHUB_REPO}" +GITHUB_URL="https://${GITHUB_HOST}/${GITHUB_PUSH-${GITHUB_REPO}}" + +# if not set, ignore password +#GIT_ASKPASS="${TRAVIS_BUILD_DIR}/gh_ignore_askpass.sh" + +skip() { + echo "$@" 1>&2 + echo "Exiting..." 1>&2 + exit 0 +} + +abort() { + echo "Error: $@" 1>&2 + echo "Exiting..." 1>&2 + exit 1 +} + +# TRAVIS_BUILD_DIR not set, exiting +[ -d "${TRAVIS_BUILD_DIR-/nonexistent}" ] || \ + abort '${TRAVIS_BUILD_DIR} not set or nonexistent.' + +# check for pull-requests +[ "${TRAVIS_PULL_REQUEST}" = "false" ] || \ + skip "Not running Doxygen for pull-requests." + +# check for branch name +[ "${TRAVIS_BRANCH}" = "master" ] || \ + skip "Running Doxygen only for updates on 'master' branch (current: ${TRAVIS_BRANCH})." + +# check for job number +# [ "${TRAVIS_JOB_NUMBER}" = "${TRAVIS_BUILD_NUMBER}.1" ] || \ +# skip "Running Doxygen only on first job of build ${TRAVIS_BUILD_NUMBER} (current: ${TRAVIS_JOB_NUMBER})." + +# install doxygen binary distribution +doxygen_install() +{ + wget -O - "${DOXYGEN_URL}" | \ + tar xz -C ${TMPDIR-/tmp} ${DOXYGEN_VER}/bin/doxygen + export PATH="${TMPDIR-/tmp}/${DOXYGEN_VER}/bin:$PATH" +} + +doxygen_run() +{ + cd "${TRAVIS_BUILD_DIR}"; + doxygen ${TRAVIS_BUILD_DIR}/build/doc/Doxyfile; + doxygen ${TRAVIS_BUILD_DIR}/build/doc/Doxyfile.zh-cn; +} + +gh_pages_prepare() +{ + cd "${TRAVIS_BUILD_DIR}/build/doc"; + [ ! -d "html" ] || \ + abort "Doxygen target directory already exists." + git --version + git clone -b gh-pages "${GITHUB_CLONE}" html + cd html + # setup git config (with defaults) + git config user.name "${GIT_NAME-travis}" + git config user.email "${GIT_EMAIL-"travis@localhost"}" + # clean working dir + rm -f .git/index + git clean -df +} + +gh_pages_commit() { + cd "${TRAVIS_BUILD_DIR}/build/doc/html"; + echo "rapidjson.org" > CNAME + git add --all; + git diff-index --quiet HEAD || git commit -m "Automatic doxygen build"; +} + +gh_setup_askpass() { + cat > ${GIT_ASKPASS} < ${HOME}/.git-credentials ; \ + chmod go-rw ${HOME}/.git-credentials ) ) + # push to GitHub + git push origin gh-pages +} + +doxygen_install +gh_pages_prepare +doxygen_run +gh_pages_commit +gh_pages_push +