Merge branch 'master' into travis
This commit is contained in:
commit
62e785babf
4
.gitignore
vendored
4
.gitignore
vendored
@ -20,5 +20,9 @@ Testing
|
||||
/googletest
|
||||
install_manifest.txt
|
||||
Doxyfile
|
||||
Doxyfile.zh-cn
|
||||
DartConfiguration.tcl
|
||||
*.nupkg
|
||||
|
||||
# Files created by OS
|
||||
*.DS_Store
|
||||
|
2
.gitmodules
vendored
2
.gitmodules
vendored
@ -1,3 +1,3 @@
|
||||
[submodule "thirdparty/gtest"]
|
||||
path = thirdparty/gtest
|
||||
url = https://chromium.googlesource.com/external/googletest.git
|
||||
url = https://github.com/google/googletest.git
|
||||
|
100
.travis.yml
100
.travis.yml
@ -1,127 +1,57 @@
|
||||
sudo: required
|
||||
dist: trusty
|
||||
group: edge
|
||||
|
||||
language: cpp
|
||||
sudo: false
|
||||
cache:
|
||||
- ccache
|
||||
|
||||
addons:
|
||||
apt:
|
||||
packages: &default_packages
|
||||
- cmake
|
||||
- valgrind
|
||||
|
||||
env:
|
||||
global:
|
||||
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'
|
||||
- GITHUB_REPO='Tencent/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
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
- env: CONF=release ARCH=x86_64 CXX11=ON
|
||||
compiler: gcc
|
||||
- env: CONF=debug ARCH=x86 CXX11=OFF
|
||||
compiler: gcc
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
- env: CONF=debug ARCH=x86_64 CXX11=OFF
|
||||
compiler: gcc
|
||||
# clang
|
||||
- env: CONF=debug ARCH=x86 CXX11=ON CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
- clang-3.7
|
||||
- env: CONF=debug ARCH=x86_64 CXX11=ON CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- clang-3.7
|
||||
- env: CONF=debug ARCH=x86 CXX11=OFF CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
- clang-3.7
|
||||
- env: CONF=debug ARCH=x86_64 CXX11=OFF CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- clang-3.7
|
||||
- env: CONF=release ARCH=x86 CXX11=ON CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
- clang-3.7
|
||||
- env: CONF=release ARCH=x86_64 CXX11=ON CCACHE_CPP2=yes
|
||||
compiler: clang
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- llvm-toolchain-precise-3.7
|
||||
- ubuntu-toolchain-r-test
|
||||
packages:
|
||||
- *default_packages
|
||||
- clang-3.7
|
||||
# coverage report
|
||||
- env: CONF=debug ARCH=x86 CXX11=ON GCOV_FLAGS='--coverage'
|
||||
compiler: gcc
|
||||
cache:
|
||||
- ccache
|
||||
- pip
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
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
|
||||
@ -130,12 +60,6 @@ matrix:
|
||||
cache:
|
||||
- ccache
|
||||
- pip
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- *default_packages
|
||||
- g++-multilib
|
||||
- libc6-dbg:i386
|
||||
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
|
||||
@ -158,7 +82,7 @@ before_script:
|
||||
- mkdir build
|
||||
|
||||
script:
|
||||
- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.7" CC="clang-3.7"; fi
|
||||
- if [ "$CXX" = "clang++" ]; then export CXXFLAGS="-stdlib=libc++ ${CXXFLAGS}"; fi
|
||||
- >
|
||||
eval "ARCH_FLAGS=\${ARCH_FLAGS_${ARCH}}" ;
|
||||
(cd build && cmake
|
||||
|
91
CHANGELOG.md
91
CHANGELOG.md
@ -4,6 +4,83 @@ 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 <wchar.h> 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<std::string>() 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
|
||||
@ -12,6 +89,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
### 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)
|
||||
|
||||
@ -31,7 +109,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
## [1.0.0] - 2015-04-22
|
||||
|
||||
### Added
|
||||
* 100% [Coverall](https://coveralls.io/r/miloyip/rapidjson?branch=master) coverage.
|
||||
* 100% [Coverall](https://coveralls.io/r/Tencent/rapidjson?branch=master) coverage.
|
||||
* Version macros (#311)
|
||||
|
||||
### Fixed
|
||||
@ -62,7 +140,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
* Redo all documentation (English, Simplified Chinese)
|
||||
|
||||
### Changed
|
||||
* Copyright ownership transfered to THL A29 Limited (a Tencent company).
|
||||
* Copyright ownership transferred to THL A29 Limited (a Tencent company).
|
||||
* Migrating from Premake to CMAKE (#192)
|
||||
* Resolve all warning reports
|
||||
|
||||
@ -73,7 +151,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## 0.1 - 2011-11-18
|
||||
|
||||
[Unreleased]: https://github.com/miloyip/rapidjson/compare/v1.0.2...HEAD
|
||||
[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
|
||||
[Unreleased]: https://github.com/Tencent/rapidjson/compare/v1.1.0...HEAD
|
||||
[1.1.0]: https://github.com/Tencent/rapidjson/compare/v1.0.2...v1.1.0
|
||||
[1.0.2]: https://github.com/Tencent/rapidjson/compare/v1.0.1...v1.0.2
|
||||
[1.0.1]: https://github.com/Tencent/rapidjson/compare/v1.0.0...v1.0.1
|
||||
[1.0.0]: https://github.com/Tencent/rapidjson/compare/v1.0-beta...v1.0.0
|
||||
|
102
CMakeLists.txt
102
CMakeLists.txt
@ -1,11 +1,19 @@
|
||||
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 "0")
|
||||
set(LIB_PATCH_VERSION "2")
|
||||
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
|
||||
@ -24,6 +32,11 @@ option(RAPIDJSON_BUILD_THIRDPARTY_GTEST
|
||||
|
||||
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_ENABLE_INSTRUMENTATION_OPT "Build rapidjson with -march or -mcpu options" ON)
|
||||
|
||||
option(RAPIDJSON_HAS_STDSTRING "" OFF)
|
||||
if(RAPIDJSON_HAS_STDSTRING)
|
||||
add_definitions(-DRAPIDJSON_HAS_STDSTRING)
|
||||
@ -39,7 +52,16 @@ if(CCACHE_FOUND)
|
||||
endif(CCACHE_FOUND)
|
||||
|
||||
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native -Wall -Wextra -Werror")
|
||||
if(${RAPIDJSON_ENABLE_INSTRUMENTATION_OPT})
|
||||
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mcpu=native")
|
||||
else()
|
||||
#FIXME: x86 is -march=native, but doesn't mean every arch is this option. To keep original project's compatibility, I leave this except POWER.
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
|
||||
endif()
|
||||
endif()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror")
|
||||
set(EXTRA_CXX_FLAGS -Weffc++ -Wswitch-default -Wfloat-equal -Wconversion -Wsign-conversion)
|
||||
if (RAPIDJSON_BUILD_CXX11)
|
||||
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7.0")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
|
||||
@ -47,13 +69,47 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
|
||||
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("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "powerpc" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64" OR "${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mcpu=native")
|
||||
else()
|
||||
#FIXME: x86 is -march=native, but doesn't mean every arch is this option. To keep original project's compatibility, I leave this except POWER.
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
|
||||
endif()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror -Wno-missing-field-initializers")
|
||||
set(EXTRA_CXX_FLAGS -Weffc++ -Wswitch-default -Wfloat-equal -Wconversion -Wimplicit-fallthrough)
|
||||
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")
|
||||
elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -qarch=auto")
|
||||
endif()
|
||||
|
||||
#add extra search paths for libraries and includes
|
||||
@ -121,15 +177,37 @@ install(DIRECTORY example/
|
||||
# Provide config and version files to be used by other applications
|
||||
# ===============================
|
||||
|
||||
export(PACKAGE ${PROJECT_NAME})
|
||||
################################################################################
|
||||
# Export package for use from the build tree
|
||||
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)
|
||||
# Create the RapidJSONConfig.cmake file for other cmake projects.
|
||||
# ... for the build tree
|
||||
SET( CONFIG_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
SET( CONFIG_DIR ${CMAKE_CURRENT_BINARY_DIR})
|
||||
SET( ${PROJECT_NAME}_INCLUDE_DIR "\${${PROJECT_NAME}_SOURCE_DIR}/include" )
|
||||
|
||||
CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake @ONLY )
|
||||
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}ConfigVersion.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake @ONLY)
|
||||
|
||||
# ... for the install tree
|
||||
SET( CMAKECONFIG_INSTALL_DIR lib/cmake/${PROJECT_NAME} )
|
||||
FILE( RELATIVE_PATH REL_INCLUDE_DIR
|
||||
"${CMAKE_INSTALL_PREFIX}/${CMAKECONFIG_INSTALL_DIR}"
|
||||
"${CMAKE_INSTALL_PREFIX}/include" )
|
||||
|
||||
SET( ${PROJECT_NAME}_INCLUDE_DIR "\${${PROJECT_NAME}_CMAKE_DIR}/${REL_INCLUDE_DIR}" )
|
||||
SET( CONFIG_SOURCE_DIR )
|
||||
SET( CONFIG_DIR )
|
||||
CONFIGURE_FILE( ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}Config.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake @ONLY )
|
||||
|
||||
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${PROJECT_NAME}Config.cmake"
|
||||
DESTINATION ${CMAKECONFIG_INSTALL_DIR} )
|
||||
|
||||
# Install files
|
||||
INSTALL(FILES
|
||||
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
|
||||
${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
|
||||
|
@ -1,7 +1,7 @@
|
||||
|
||||
SET(GTEST_SEARCH_PATH
|
||||
"${GTEST_SOURCE_DIR}"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/../thirdparty/gtest")
|
||||
"${CMAKE_CURRENT_LIST_DIR}/../thirdparty/gtest/googletest")
|
||||
|
||||
IF(UNIX)
|
||||
IF(RAPIDJSON_BUILD_THIRDPARTY_GTEST)
|
||||
|
@ -3,5 +3,5 @@ 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
|
||||
URL: https://github.com/Tencent/rapidjson
|
||||
Cflags: -I${includedir}
|
||||
|
@ -1,3 +1,15 @@
|
||||
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}")
|
||||
################################################################################
|
||||
# RapidJSON source dir
|
||||
set( RapidJSON_SOURCE_DIR "@CONFIG_SOURCE_DIR@")
|
||||
|
||||
################################################################################
|
||||
# RapidJSON build dir
|
||||
set( RapidJSON_DIR "@CONFIG_DIR@")
|
||||
|
||||
################################################################################
|
||||
# Compute paths
|
||||
get_filename_component(RapidJSON_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
|
||||
|
||||
set( RapidJSON_INCLUDE_DIR "@RapidJSON_INCLUDE_DIR@" )
|
||||
set( RapidJSON_INCLUDE_DIRS "@RapidJSON_INCLUDE_DIR@" )
|
||||
message(STATUS "RapidJSON found. Headers: ${RapidJSON_INCLUDE_DIRS}")
|
||||
|
@ -1,5 +1,5 @@
|
||||
os: Visual Studio 2015 CTP
|
||||
version: 1.0.2.{build}
|
||||
version: 1.1.0.{build}
|
||||
|
||||
configuration:
|
||||
- Debug
|
||||
@ -30,7 +30,7 @@ environment:
|
||||
|
||||
before_build:
|
||||
- git submodule update --init --recursive
|
||||
- cmake -H. -BBuild/VS -G "Visual Studio %VS_VERSION%" -DCMAKE_GENERATOR_PLATFORM=%VS_PLATFORM% -DBUILD_SHARED_LIBS=true -Wno-dev
|
||||
- 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
|
||||
|
BIN
bin/jsonschema/remotes/.DS_Store
vendored
BIN
bin/jsonschema/remotes/.DS_Store
vendored
Binary file not shown.
BIN
bin/jsonschema/tests/.DS_Store
vendored
BIN
bin/jsonschema/tests/.DS_Store
vendored
Binary file not shown.
BIN
bin/jsonschema/tests/draft4/.DS_Store
vendored
BIN
bin/jsonschema/tests/draft4/.DS_Store
vendored
Binary file not shown.
0
bin/types/booleans.json
Executable file → Normal file
0
bin/types/booleans.json
Executable file → Normal file
0
bin/types/floats.json
Executable file → Normal file
0
bin/types/floats.json
Executable file → Normal file
0
bin/types/guids.json
Executable file → Normal file
0
bin/types/guids.json
Executable file → Normal file
0
bin/types/integers.json
Executable file → Normal file
0
bin/types/integers.json
Executable file → Normal file
0
bin/types/mixed.json
Executable file → Normal file
0
bin/types/mixed.json
Executable file → Normal file
0
bin/types/nulls.json
Executable file → Normal file
0
bin/types/nulls.json
Executable file → Normal file
0
bin/types/paragraphs.json
Executable file → Normal file
0
bin/types/paragraphs.json
Executable file → Normal file
45
contrib/natvis/LICENSE
Normal file
45
contrib/natvis/LICENSE
Normal file
@ -0,0 +1,45 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017 Bart Muzzin
|
||||
|
||||
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.
|
||||
|
||||
Derived from:
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 mojmir svoboda
|
||||
|
||||
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.
|
7
contrib/natvis/README.md
Normal file
7
contrib/natvis/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# rapidjson.natvis
|
||||
|
||||
This file can be used as a [Visual Studio Visualizer](https://docs.microsoft.com/en-gb/visualstudio/debugger/create-custom-views-of-native-objects) to aid in visualizing rapidjson structures within the Visual Studio debugger. Natvis visualizers are supported in Visual Studio 2012 and later. To install, copy the file into this directory:
|
||||
|
||||
`%USERPROFILE%\Documents\Visual Studio 2012\Visualizers`
|
||||
|
||||
Each version of Visual Studio has a similar directory, it must be copied into each directory to be used with that particular version. In Visual Studio 2015 and later, this can be done without restarting Visual Studio (a new debugging session must be started).
|
38
contrib/natvis/rapidjson.natvis
Normal file
38
contrib/natvis/rapidjson.natvis
Normal file
@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
|
||||
<!-- rapidjson::GenericValue - basic support -->
|
||||
<Type Name="rapidjson::GenericValue<*,*>">
|
||||
<DisplayString Condition="(data_.f.flags & kTypeMask) == kNullType">null</DisplayString>
|
||||
<DisplayString Condition="data_.f.flags == kTrueFlag">true</DisplayString>
|
||||
<DisplayString Condition="data_.f.flags == kFalseFlag">false</DisplayString>
|
||||
<DisplayString Condition="data_.f.flags == kShortStringFlag">{data_.ss.str}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kTypeMask) == kStringType">{(const char*)((size_t)data_.s.str & 0x0000FFFFFFFFFFFF)}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kNumberIntFlag) == kNumberIntFlag">{data_.n.i.i}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kNumberUintFlag) == kNumberUintFlag">{data_.n.u.u}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kNumberInt64Flag) == kNumberInt64Flag">{data_.n.i64}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kNumberUint64Flag) == kNumberUint64Flag">{data_.n.u64}</DisplayString>
|
||||
<DisplayString Condition="(data_.f.flags & kNumberDoubleFlag) == kNumberDoubleFlag">{data_.n.d}</DisplayString>
|
||||
<DisplayString Condition="data_.f.flags == kObjectType">Object members={data_.o.size}</DisplayString>
|
||||
<DisplayString Condition="data_.f.flags == kArrayType">Array members={data_.a.size}</DisplayString>
|
||||
<Expand>
|
||||
<Item Condition="data_.f.flags == kObjectType" Name="[size]">data_.o.size</Item>
|
||||
<Item Condition="data_.f.flags == kObjectType" Name="[capacity]">data_.o.capacity</Item>
|
||||
<ArrayItems Condition="data_.f.flags == kObjectType">
|
||||
<Size>data_.o.size</Size>
|
||||
<!-- NOTE: Rapidjson stores some extra data in the high bits of pointers, which is why the mask -->
|
||||
<ValuePointer>(rapidjson::GenericMember<$T1,$T2>*)(((size_t)data_.o.members) & 0x0000FFFFFFFFFFFF)</ValuePointer>
|
||||
</ArrayItems>
|
||||
|
||||
<Item Condition="data_.f.flags == kArrayType" Name="[size]">data_.a.size</Item>
|
||||
<Item Condition="data_.f.flags == kArrayType" Name="[capacity]">data_.a.capacity</Item>
|
||||
<ArrayItems Condition="data_.f.flags == kArrayType">
|
||||
<Size>data_.a.size</Size>
|
||||
<!-- NOTE: Rapidjson stores some extra data in the high bits of pointers, which is why the mask -->
|
||||
<ValuePointer>(rapidjson::GenericValue<$T1,$T2>*)(((size_t)data_.a.elements) & 0x0000FFFFFFFFFFFF)</ValuePointer>
|
||||
</ArrayItems>
|
||||
|
||||
</Expand>
|
||||
</Type>
|
||||
|
||||
</AutoVisualizer>
|
||||
|
@ -10,11 +10,13 @@ ELSE()
|
||||
CONFIGURE_FILE(Doxyfile.in Doxyfile @ONLY)
|
||||
CONFIGURE_FILE(Doxyfile.zh-cn.in Doxyfile.zh-cn @ONLY)
|
||||
|
||||
file(GLOB DOXYFILES ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile*)
|
||||
|
||||
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*
|
||||
DEPENDS ${MARKDOWN_DOC} ${SOURCES} ${DOXYFILES}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../
|
||||
)
|
||||
|
||||
|
@ -765,6 +765,7 @@ WARN_LOGFILE =
|
||||
# Note: If this tag is empty the current directory is searched.
|
||||
|
||||
INPUT = readme.md \
|
||||
CHANGELOG.md \
|
||||
include/rapidjson/rapidjson.h \
|
||||
include/ \
|
||||
doc/features.md \
|
||||
|
@ -765,6 +765,7 @@ WARN_LOGFILE =
|
||||
# Note: If this tag is empty the current directory is searched.
|
||||
|
||||
INPUT = readme.zh-cn.md \
|
||||
CHANGELOG.md \
|
||||
include/rapidjson/rapidjson.h \
|
||||
include/ \
|
||||
doc/features.zh-cn.md \
|
||||
@ -776,7 +777,7 @@ INPUT = readme.zh-cn.md \
|
||||
doc/sax.zh-cn.md \
|
||||
doc/schema.zh-cn.md \
|
||||
doc/performance.zh-cn.md \
|
||||
doc/internals.md \
|
||||
doc/internals.zh-cn.md \
|
||||
doc/faq.zh-cn.md
|
||||
|
||||
# This tag can be used to specify the character encoding of the source files
|
||||
|
@ -18,7 +18,7 @@ digraph {
|
||||
|
||||
node [shape=Mrecord, style=filled, colorscheme=spectral7]
|
||||
|
||||
c1 [label="{contact:array|}", fillcolor=4]
|
||||
c1 [label="{contacts:array|}", fillcolor=4]
|
||||
c11 [label="{|}"]
|
||||
c12 [label="{|}"]
|
||||
c13 [shape="none", label="...", style="solid"]
|
||||
@ -41,13 +41,13 @@ digraph {
|
||||
|
||||
node [shape=Mrecord, style=filled, colorscheme=spectral7]
|
||||
|
||||
c2 [label="{contact:array|}", fillcolor=4]
|
||||
c2 [label="{contacts: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]
|
||||
cs [label="{string|\"contacts\"}", fillcolor=5]
|
||||
c31 [label="{|}"]
|
||||
c32 [label="{|}"]
|
||||
c33 [shape="none", label="...", style="solid"]
|
||||
@ -59,4 +59,4 @@ digraph {
|
||||
c3 -> { c31; c32; c33 }
|
||||
}
|
||||
ghost -> o2 [style=invis]
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ digraph {
|
||||
|
||||
node [shape=Mrecord, style=filled, colorscheme=spectral7]
|
||||
|
||||
c1 [label="{contact:array|}", fillcolor=4]
|
||||
c1 [label="{contacts:array|}", fillcolor=4]
|
||||
c11 [label="{|}"]
|
||||
c12 [label="{|}"]
|
||||
c13 [shape=none, label="...", style="solid"]
|
||||
@ -42,13 +42,13 @@ digraph {
|
||||
|
||||
node [shape=Mrecord, style=filled, colorscheme=spectral7]
|
||||
|
||||
c2 [label="{contact:null|}", fillcolor=1]
|
||||
c2 [label="{contacts: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]
|
||||
cs [label="{string|\"contacts\"}", fillcolor=5]
|
||||
c2 -> o2 [style="dashed", constraint=false, label="AddMember", style=invis]
|
||||
|
||||
edge [arrowhead=vee]
|
||||
@ -57,4 +57,4 @@ digraph {
|
||||
cs -> c3 [arrowhead=none]
|
||||
}
|
||||
ghost -> o2 [style=invis]
|
||||
}
|
||||
}
|
||||
|
@ -116,6 +116,9 @@ Parse flags | Meaning
|
||||
`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.
|
||||
|
||||
@ -125,7 +128,7 @@ 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()`.
|
||||
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 GetErrorOffset()`.
|
||||
|
||||
Parse Error Code | Description
|
||||
--------------------------------------------|---------------------------------------------------
|
||||
@ -161,7 +164,7 @@ Document d;
|
||||
if (d.Parse(json).HasParseError()) {
|
||||
fprintf(stderr, "\nError(offset %u): %s\n",
|
||||
(unsigned)d.GetErrorOffset(),
|
||||
GetParseError_En(d.GetParseErrorCode()));
|
||||
GetParseError_En(d.GetParseError()));
|
||||
// ...
|
||||
}
|
||||
~~~~~~~~~~
|
||||
@ -238,7 +241,7 @@ 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.
|
||||
In RapidJSON, stringifying a DOM with `Writer` may be look a little bit weird.
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// ...
|
||||
|
135
doc/dom.zh-cn.md
135
doc/dom.zh-cn.md
@ -1,12 +1,12 @@
|
||||
# DOM
|
||||
|
||||
文档对象模型(Document Object Model, DOM)是一种罝于内存中的JSON表示方式,以供查询及操作。我们己于[教程](doc/tutorial.md)中介绍了DOM的基本用法,本节将讲述一些细节及高级用法。
|
||||
文档对象模型(Document Object Model, DOM)是一种罝于内存中的 JSON 表示方式,以供查询及操作。我们己于 [教程](doc/tutorial.zh-cn.md) 中介绍了 DOM 的基本用法,本节将讲述一些细节及高级用法。
|
||||
|
||||
[TOC]
|
||||
|
||||
# 模板 {#Template}
|
||||
|
||||
教程中使用了`Value`和`Document`类型。与`std::string`相似,这些类型其实是两个模板类的`typedef`:
|
||||
教程中使用了 `Value` 和 `Document` 类型。与 `std::string` 相似,这些类型其实是两个模板类的 `typedef`:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
namespace rapidjson {
|
||||
@ -31,9 +31,9 @@ typedef GenericDocument<UTF8<> > Document;
|
||||
|
||||
## 编码 {#Encoding}
|
||||
|
||||
`Encoding`参数指明在内存中的JSON String使用哪种编码。可行的选项有`UTF8`、`UTF16`、`UTF32`。要注意这3个类型其实也是模板类。`UTF8<>`等同`UTF8<char>`,这代表它使用`char`来存储字符串。更多细节可以参考[编码](encoding.md)。
|
||||
`Encoding` 参数指明在内存中的 JSON String 使用哪种编码。可行的选项有 `UTF8`、`UTF16`、`UTF32`。要注意这 3 个类型其实也是模板类。`UTF8<>` 等同 `UTF8<char>`,这代表它使用 `char` 来存储字符串。更多细节可以参考 [编码](doc/encoding.zh-cn.md)。
|
||||
|
||||
这里是一个例子。假设一个Windows应用软件希望查询存储于JSON中的本地化字符串。Windows中含Unicode的函数使用UTF-16(宽字符)编码。无论JSON文件使用哪种编码,我们都可以把字符串以UTF-16形式存储在内存。
|
||||
这里是一个例子。假设一个 Windows 应用软件希望查询存储于 JSON 中的本地化字符串。Windows 中含 Unicode 的函数使用 UTF-16(宽字符)编码。无论 JSON 文件使用哪种编码,我们都可以把字符串以 UTF-16 形式存储在内存。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
using namespace rapidjson;
|
||||
@ -41,12 +41,12 @@ using namespace rapidjson;
|
||||
typedef GenericDocument<UTF16<> > WDocument;
|
||||
typedef GenericValue<UTF16<> > WValue;
|
||||
|
||||
FILE* fp = fopen("localization.json", "rb"); // 非Windows平台使用"r"
|
||||
FILE* fp = fopen("localization.json", "rb"); // 非 Windows 平台使用 "r"
|
||||
|
||||
char readBuffer[256];
|
||||
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
|
||||
|
||||
AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // 包装bis成eis
|
||||
AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // 包装 bis 成 eis
|
||||
|
||||
WDocument d;
|
||||
d.ParseStream<0, AutoUTF<unsigned> >(eis);
|
||||
@ -58,15 +58,15 @@ MessageBoxW(hWnd, d[locale].GetString(), L"Test", MB_OK);
|
||||
|
||||
## 分配器 {#Allocator}
|
||||
|
||||
`Allocator`定义当`Document`/`Value`分配或释放内存时使用那个分配类。`Document`拥有或引用到一个`Allocator`实例。而为了节省内存,`Value`没有这么做。
|
||||
`Allocator` 定义当 `Document`/`Value` 分配或释放内存时使用那个分配类。`Document` 拥有或引用到一个 `Allocator` 实例。而为了节省内存,`Value` 没有这么做。
|
||||
|
||||
`GenericDocument`的缺省分配器是`MemoryPoolAllocator`。此分配器实际上会顺序地分配内存,并且不能逐一释放。当要解析一个JSON并生成DOM,这种分配器是非常合适的。
|
||||
`GenericDocument` 的缺省分配器是 `MemoryPoolAllocator`。此分配器实际上会顺序地分配内存,并且不能逐一释放。当要解析一个 JSON 并生成 DOM,这种分配器是非常合适的。
|
||||
|
||||
RapidJSON还提供另一个分配器`CrtAllocator`,当中CRT是C运行库(C RunTime library)的缩写。此分配器简单地读用标准的`malloc()`/`realloc()`/`free()`。当我们需要许多增减操作,这种分配器会更为适合。然而这种分配器远远比`MemoryPoolAllocator`低效。
|
||||
RapidJSON 还提供另一个分配器 `CrtAllocator`,当中 CRT 是 C 运行库(C RunTime library)的缩写。此分配器简单地读用标准的 `malloc()`/`realloc()`/`free()`。当我们需要许多增减操作,这种分配器会更为适合。然而这种分配器远远比 `MemoryPoolAllocator` 低效。
|
||||
|
||||
# 解析 {#Parsing}
|
||||
|
||||
`Document`提供几个解析函数。以下的(1)是根本的函数,其他都是调用(1)的协助函数。
|
||||
`Document` 提供几个解析函数。以下的 (1) 是根本的函数,其他都是调用 (1) 的协助函数。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
using namespace rapidjson;
|
||||
@ -94,7 +94,7 @@ GenericDocument& GenericDocument::ParseInsitu(Ch* str);
|
||||
template <unsigned parseFlags, typename SourceEncoding>
|
||||
GenericDocument& GenericDocument::Parse(const Ch* str);
|
||||
|
||||
// (7) 正常解析一个字符串,使用Document的编码
|
||||
// (7) 正常解析一个字符串,使用 Document 的编码
|
||||
template <unsigned parseFlags>
|
||||
GenericDocument& GenericDocument::Parse(const Ch* str);
|
||||
|
||||
@ -102,30 +102,33 @@ GenericDocument& GenericDocument::Parse(const Ch* str);
|
||||
GenericDocument& GenericDocument::Parse(const Ch* str);
|
||||
~~~~~~~~~~
|
||||
|
||||
[教程](tutorial.md)中的例使用(8)去正常解析字符串。而[流](stream.md)的例子使用前3个函数。我们将稍后介绍原位(*In situ*) 解析。
|
||||
[教程](doc/tutorial.zh-cn.md) 中的例使用 (8) 去正常解析字符串。而 [流](doc/stream.zh-cn.md) 的例子使用前 3 个函数。我们将稍后介绍原位(*In situ*) 解析。
|
||||
|
||||
`parseFlags`是以下位标置的组合:
|
||||
`parseFlags` 是以下位标置的组合:
|
||||
|
||||
解析位标志 | 意义
|
||||
------------------------------|-----------------------------------
|
||||
`kParseNoFlags` | 没有任何标志。
|
||||
`kParseDefaultFlags` | 缺省的解析选项。它等于`RAPIDJSON_PARSE_DEFAULT_FLAGS`宏,此宏定义为`kParseNoFlags`。
|
||||
`kParseDefaultFlags` | 缺省的解析选项。它等于 `RAPIDJSON_PARSE_DEFAULT_FLAGS` 宏,此宏定义为 `kParseNoFlags`。
|
||||
`kParseInsituFlag` | 原位(破坏性)解析。
|
||||
`kParseValidateEncodingFlag` | 校验JSON字符串的编码。
|
||||
`kParseValidateEncodingFlag` | 校验 JSON 字符串的编码。
|
||||
`kParseIterativeFlag` | 迭代式(调用堆栈大小为常数复杂度)解析。
|
||||
`kParseStopWhenDoneFlag` | 当从流解析了一个完整的JSON根节点之后,停止继续处理余下的流。当使用了此标志,解析器便不会产生`kParseErrorDocumentRootNotSingular`错误。可使用本标志去解析同一个流里的多个JSON。
|
||||
`kParseFullPrecisionFlag` | 使用完整的精确度去解析数字(较慢)。如不设置此标节,则会使用正常的精确度(较快)。正常精确度会有最多3个[ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place)的误差。
|
||||
`kParseCommentsFlag` | 容许单行 `// ...` 及多行 `/* ... */` 注释(放宽的JSON语法)。
|
||||
`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++编译器能为个别组合生成代码,以改善性能及减少代码尺寸(当只用单种特化)。缺点是需要在编译期决定标志。
|
||||
由于使用了非类型模板参数,而不是函数参数,C++ 编译器能为个别组合生成代码,以改善性能及减少代码尺寸(当只用单种特化)。缺点是需要在编译期决定标志。
|
||||
|
||||
`SourceEncoding`参数定义流使用了什么编码。这与`Document`的`Encoding`不相同。细节可参考[转码和校验](#TranscodingAndValidation)一节。
|
||||
`SourceEncoding` 参数定义流使用了什么编码。这与 `Document` 的 `Encoding` 不相同。细节可参考 [转码和校验](#TranscodingAndValidation) 一节。
|
||||
|
||||
此外`InputStream`是输入流的类型。
|
||||
此外 `InputStream` 是输入流的类型。
|
||||
|
||||
## 解析错误 {#ParseError}
|
||||
|
||||
当解析过程顺利完成,`Document`便会含有解析结果。当过程出现错误,原来的DOM会*维持不便*。可使用`bool HasParseError()`、`ParseErrorCode GetParseError()`及`size_t GetParseOffset()`获取解析的错误状态。
|
||||
当解析过程顺利完成,`Document` 便会含有解析结果。当过程出现错误,原来的 DOM 会*维持不变*。可使用 `bool HasParseError()`、`ParseErrorCode GetParseError()` 及 `size_t GetErrorOffset()` 获取解析的错误状态。
|
||||
|
||||
解析错误代号 | 描述
|
||||
--------------------------------------------|---------------------------------------------------
|
||||
@ -133,22 +136,22 @@ GenericDocument& GenericDocument::Parse(const Ch* str);
|
||||
`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缺少了指数。
|
||||
`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在`rapidjson/error/en.h`中提供了英文错误讯息。使用者可以修改它用于其他语言环境,或使用一个自定义的本地化系统。
|
||||
要取得错误讯息,RapidJSON 在 `rapidjson/error/en.h` 中提供了英文错误讯息。使用者可以修改它用于其他语言环境,或使用一个自定义的本地化系统。
|
||||
|
||||
以下是一个处理错误的例子。
|
||||
|
||||
@ -168,7 +171,7 @@ if (d.Parse(json).HasParseError()) {
|
||||
|
||||
## 原位解析 {#InSituParsing}
|
||||
|
||||
根据[维基百科](http://en.wikipedia.org/wiki/In_situ):
|
||||
根据 [维基百科](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.
|
||||
> ...
|
||||
@ -176,24 +179,24 @@ if (d.Parse(json).HasParseError()) {
|
||||
|
||||
> 翻译:*In situ*……是一个拉丁文片语,字面上的意思是指「现场」、「在位置」。在许多不同语境中,它描述一个事件发生的位置,意指「本地」、「现场」、「在处所」、「就位」。
|
||||
> ……
|
||||
> (在计算机科学中)一个算法若称为原位算法,或在位算法,是指执行该算法所需的额外内存空间是O(1)的,换句话说,无论输入大小都只需要常数空间。例如,堆排序是一个原位排序算法。
|
||||
> (在计算机科学中)一个算法若称为原位算法,或在位算法,是指执行该算法所需的额外内存空间是 O(1) 的,换句话说,无论输入大小都只需要常数空间。例如,堆排序是一个原位排序算法。
|
||||
|
||||
在正常的解析过程中,对JSON string解码并复制至其他缓冲区是一个很大的开销。原位解析(*in situ* parsing)把这些JSON string直接解码于它原来存储的地方。由于解码后的string长度总是短于或等于原来储存于JSON的string,所以这是可行的。在这个语境下,对JSON string进行解码是指处理转义符,如`"\n"`、`"\u1234"`等,以及在string末端加入空终止符号(`'\0'`)。
|
||||
在正常的解析过程中,对 JSON string 解码并复制至其他缓冲区是一个很大的开销。原位解析(*in situ* parsing)把这些 JSON string 直接解码于它原来存储的地方。由于解码后的 string 长度总是短于或等于原来储存于 JSON 的 string,所以这是可行的。在这个语境下,对 JSON string 进行解码是指处理转义符,如 `"\n"`、`"\u1234"` 等,以及在 string 末端加入空终止符号 (`'\0'`)。
|
||||
|
||||
以下的图比较正常及原位解析。JSON string值包含指向解码后的字符串。
|
||||
以下的图比较正常及原位解析。JSON string 值包含指向解码后的字符串。
|
||||
|
||||

|
||||
|
||||
在正常解析中,解码后的字符串被复制至全新分配的缓冲区中。`"\\n"`(2个字符)被解码成`"\n"`(1个字符)。`"\\u0073"`(6个字符)被解码成`"s"`(1个字符)。
|
||||
在正常解析中,解码后的字符串被复制至全新分配的缓冲区中。`"\\n"`(2 个字符)被解码成 `"\n"`(1 个字符)。`"\\u0073"`(6 个字符)被解码成 `"s"`(1 个字符)。
|
||||
|
||||

|
||||
|
||||
原位解析直接修改了原来的JSON。图中高亮了被更新的字符。若JSON string不含转义符,例如`"msg"`,那么解析过程仅仅是以空字符代替结束双引号。
|
||||
原位解析直接修改了原来的 JSON。图中高亮了被更新的字符。若 JSON string 不含转义符,例如 `"msg"`,那么解析过程仅仅是以空字符代替结束双引号。
|
||||
|
||||
由于原位解析修改了输入,其解析API需要`char*`而非`const char*`。
|
||||
由于原位解析修改了输入,其解析 API 需要 `char*` 而非 `const char*`。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// 把整个文件读入buffer
|
||||
// 把整个文件读入 buffer
|
||||
FILE* fp = fopen("test.json", "r");
|
||||
fseek(fp, 0, SEEK_END);
|
||||
size_t filesize = (size_t)ftell(fp);
|
||||
@ -203,46 +206,46 @@ size_t readLength = fread(buffer, 1, filesize, fp);
|
||||
buffer[readLength] = '\0';
|
||||
fclose(fp);
|
||||
|
||||
// 原位解析buffer至d,buffer内容会被修改。
|
||||
// 原位解析 buffer 至 d,buffer 内容会被修改。
|
||||
Document d;
|
||||
d.ParseInsitu(buffer);
|
||||
|
||||
// 在此查询、修改DOM……
|
||||
// 在此查询、修改 DOM……
|
||||
|
||||
free(buffer);
|
||||
// 注意:在这个位置,d可能含有指向已被释放的buffer的悬空指针
|
||||
// 注意:在这个位置,d 可能含有指向已被释放的 buffer 的悬空指针
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON string会被打上const-string的标志。但它们可能并非真正的「常数」。它的生命周期取决于存储JSON的缓冲区。
|
||||
JSON string 会被打上 const-string 的标志。但它们可能并非真正的「常数」。它的生命周期取决于存储 JSON 的缓冲区。
|
||||
|
||||
原位解析把分配开销及内存复制减至最小。通常这样做能改善缓存一致性,而这对现代计算机来说是一个重要的性能因素。
|
||||
|
||||
原位解析有以下限制:
|
||||
|
||||
1. 整个JSON须存储在内存之中。
|
||||
1. 整个 JSON 须存储在内存之中。
|
||||
2. 流的来源缓码与文档的目标编码必须相同。
|
||||
3. 需要保留缓冲区,直至文档不再被使用。
|
||||
4. 若DOM需要在解析后被长期使用,而DOM内只有很少JSON string,保留缓冲区可能造成内存浪费。
|
||||
4. 若 DOM 需要在解析后被长期使用,而 DOM 内只有很少 JSON string,保留缓冲区可能造成内存浪费。
|
||||
|
||||
原位解析最适合用于短期的、用完即弃的JSON。实际应用中,这些场合是非常普遍的,例如反序列化JSON至C++对象、处理以JSON表示的web请求等。
|
||||
原位解析最适合用于短期的、用完即弃的 JSON。实际应用中,这些场合是非常普遍的,例如反序列化 JSON 至 C++ 对象、处理以 JSON 表示的 web 请求等。
|
||||
|
||||
## 转码与校验 {#TranscodingAndValidation}
|
||||
|
||||
RapidJSON内部支持不同Unicode格式(正式的术语是UCS变换格式)间的转换。在DOM解析时,流的来源编码与DOM的编码可以不同。例如,来源流可能含有UTF-8的JSON,而DOM则使用UTF-16编码。在[EncodedInputStream](doc/stream.md)一节里有一个例子。
|
||||
RapidJSON 内部支持不同 Unicode 格式(正式的术语是 UCS 变换格式)间的转换。在 DOM 解析时,流的来源编码与 DOM 的编码可以不同。例如,来源流可能含有 UTF-8 的 JSON,而 DOM 则使用 UTF-16 编码。在 [EncodedInputStream](doc/stream.zh-cn.md) 一节里有一个例子。
|
||||
|
||||
当从DOM输出一个JSON至输出流之时,也可以使用转码功能。在[EncodedOutputStream](doc/stream.md)一节里有一个例子。
|
||||
当从 DOM 输出一个 JSON 至输出流之时,也可以使用转码功能。在 [EncodedOutputStream](doc/stream.zh-cn.md) 一节里有一个例子。
|
||||
|
||||
在转码过程中,会把来源string解码成Unicode码点,然后把码点编码成目标格式。在解码时,它会校验来源string的字节序列是否合法。若遇上非合法序列,解析器会停止并返回`kParseErrorStringInvalidEncoding`错误。
|
||||
在转码过程中,会把来源 string 解码成 Unicode 码点,然后把码点编码成目标格式。在解码时,它会校验来源 string 的字节序列是否合法。若遇上非合法序列,解析器会停止并返回 `kParseErrorStringInvalidEncoding` 错误。
|
||||
|
||||
当来源编码与DOM的编码相同,解析器缺省地*不会*校验序列。使用者可开启`kParseValidateEncodingFlag`去强制校验。
|
||||
当来源编码与 DOM 的编码相同,解析器缺省地 * 不会 * 校验序列。使用者可开启 `kParseValidateEncodingFlag` 去强制校验。
|
||||
|
||||
# 技巧 {#Techniques}
|
||||
|
||||
这里讨论一些DOM API的使用技巧。
|
||||
这里讨论一些 DOM API 的使用技巧。
|
||||
|
||||
## 把DOM作为SAX事件发表者
|
||||
## 把 DOM 作为 SAX 事件发表者
|
||||
|
||||
在RapidJSON中,利用`Writer`把DOM生成JSON的做法,看来有点奇怪。
|
||||
在 RapidJSON 中,利用 `Writer` 把 DOM 生成 JSON 的做法,看来有点奇怪。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// ...
|
||||
@ -250,19 +253,19 @@ Writer<StringBuffer> writer(buffer);
|
||||
d.Accept(writer);
|
||||
~~~~~~~~~~
|
||||
|
||||
实际上,`Value::Accept()`是负责发布该值相关的SAX事件至处理器的。通过这个设计,`Value`及`Writer`解除了偶合。`Value`可生成SAX事件,而`Writer`则可以处理这些事件。
|
||||
实际上,`Value::Accept()` 是负责发布该值相关的 SAX 事件至处理器的。通过这个设计,`Value` 及 `Writer` 解除了偶合。`Value` 可生成 SAX 事件,而 `Writer` 则可以处理这些事件。
|
||||
|
||||
使用者可以创建自定义的处理器,去把DOM转换成其它格式。例如,一个把DOM转换成XML的处理器。
|
||||
使用者可以创建自定义的处理器,去把 DOM 转换成其它格式。例如,一个把 DOM 转换成 XML 的处理器。
|
||||
|
||||
要知道更多关于SAX事件与处理器,可参阅[SAX](doc/sax.md)。
|
||||
要知道更多关于 SAX 事件与处理器,可参阅 [SAX](doc/sax.zh-cn.md)。
|
||||
|
||||
## 使用者缓冲区{ #UserBuffer}
|
||||
## 使用者缓冲区 {#UserBuffer}
|
||||
|
||||
许多应用软件可能需要尽量减少内存分配。
|
||||
|
||||
`MemoryPoolAllocator`可以帮助这方面,它容许使用者提供一个缓冲区。该缓冲区可能置于程序堆栈,或是一个静态分配的「草稿缓冲区(scratch buffer)」(一个静态/全局的数组),用于储存临时数据。
|
||||
`MemoryPoolAllocator` 可以帮助这方面,它容许使用者提供一个缓冲区。该缓冲区可能置于程序堆栈,或是一个静态分配的「草稿缓冲区(scratch buffer)」(一个静态/全局的数组),用于储存临时数据。
|
||||
|
||||
`MemoryPoolAllocator`会先用使用者缓冲区去解决分配请求。当使用者缓冲区用完,就会从基础分配器(缺省为`CrtAllocator`)分配一块内存。
|
||||
`MemoryPoolAllocator` 会先用使用者缓冲区去解决分配请求。当使用者缓冲区用完,就会从基础分配器(缺省为 `CrtAllocator`)分配一块内存。
|
||||
|
||||
以下是使用堆栈内存的例子,第一个分配器用于存储值,第二个用于解析时的临时缓冲。
|
||||
|
||||
@ -276,6 +279,6 @@ DocumentType d(&valueAllocator, sizeof(parseBuffer), &parseAllocator);
|
||||
d.Parse(json);
|
||||
~~~~~~~~~~
|
||||
|
||||
若解析时分配总量少于4096+1024字节时,这段代码不会造成任何堆内存分配(经`new`或`malloc()`)。
|
||||
若解析时分配总量少于 4096+1024 字节时,这段代码不会造成任何堆内存分配(经 `new` 或 `malloc()`)。
|
||||
|
||||
使用者可以通过`MemoryPoolAllocator::Size()`查询当前已分的内存大小。那么使用者可以拟定使用者缓冲区的合适大小。
|
||||
使用者可以通过 `MemoryPoolAllocator::Size()` 查询当前已分的内存大小。那么使用者可以拟定使用者缓冲区的合适大小。
|
||||
|
@ -10,7 +10,7 @@ The earlier [RFC4627](http://www.ietf.org/rfc/rfc4627.txt) stated that,
|
||||
|
||||
> (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/)).
|
||||
RapidJSON supports various encodings. It can also validate the encodings of JSON, and transcoding JSON among encodings. All these features are implemented internally, without the need for external libraries (e.g. [ICU](http://site.icu-project.org/)).
|
||||
|
||||
[TOC]
|
||||
|
||||
@ -131,8 +131,8 @@ StringStream source(s);
|
||||
GenericStringBuffer<UTF16<> > target;
|
||||
|
||||
bool hasError = false;
|
||||
while (source.Peak() != '\0')
|
||||
if (!Transcoder::Transcode<UTF8<>, UTF16<> >(source, target)) {
|
||||
while (source.Peek() != '\0')
|
||||
if (!Transcoder<UTF8<>, UTF16<> >::Transcode(source, target)) {
|
||||
hasError = true;
|
||||
break;
|
||||
}
|
||||
|
@ -1,45 +1,45 @@
|
||||
# 编码
|
||||
|
||||
根据[ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf):
|
||||
根据 [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码点的序列。
|
||||
> 翻译:JSON 文本是 Unicode 码点的序列。
|
||||
|
||||
较早的[RFC4627](http://www.ietf.org/rfc/rfc4627.txt)申明:
|
||||
较早的 [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。
|
||||
> 翻译: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写入,就必须使用二进制的内容传送编码。
|
||||
> 翻译:JSON 可使用 UTF-8、UTF-16 或 UTF-32 表示。当 JSON 以 UTF-8 写入,该 JSON 是 8 位兼容的。当 JSON 以 UTF-16 或 UTF-32 写入,就必须使用二进制的内容传送编码。
|
||||
|
||||
RapidJSON支持多种编码。它也能检查JSON的编码,以及在不同编码中进行转码。所有这些功能都是在内部实现,无需使用外部的程序库(如[ICU](http://site.icu-project.org/))。
|
||||
RapidJSON 支持多种编码。它也能检查 JSON 的编码,以及在不同编码中进行转码。所有这些功能都是在内部实现,无需使用外部的程序库(如 [ICU](http://site.icu-project.org/))。
|
||||
|
||||
[TOC]
|
||||
|
||||
# Unicode {#Unicode}
|
||||
根据 [Unicode的官方网站](http://www.unicode.org/standard/translations/t-chinese.html):
|
||||
>Unicode给每个字符提供了一个唯一的数字,
|
||||
根据 [Unicode 的官方网站](http://www.unicode.org/standard/translations/t-chinese.html):
|
||||
>Unicode 给每个字符提供了一个唯一的数字,
|
||||
不论是什么平台、
|
||||
不论是什么程序、
|
||||
不论是什么语言。
|
||||
|
||||
这些唯一数字称为码点(code point),其范围介乎`0x0`至`0x10FFFF`之间。
|
||||
这些唯一数字称为码点(code point),其范围介乎 `0x0` 至 `0x10FFFF` 之间。
|
||||
|
||||
## Unicode转换格式 {#UTF}
|
||||
## Unicode 转换格式 {#UTF}
|
||||
|
||||
存储Unicode码点有多种编码方式。这些称为Unicode转换格式(Unicode Transformation Format, UTF)。RapidJSON支持最常用的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-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)。
|
||||
对于 UTF-16 及 UTF-32 来说,字节序(endianness)是有影响的。在内存中,它们通常都是以该计算机的字节序来存储。然而,当要储存在文件中或在网上传输,我们需要指明字节序列的字节序,是小端(little endian, LE)还是大端(big-endian, BE)。
|
||||
|
||||
RapidJSON通过`rapidjson/encodings.h`中的struct去提供各种编码:
|
||||
RapidJSON 通过 `rapidjson/encodings.h` 中的 struct 去提供各种编码:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
namespace rapidjson {
|
||||
@ -68,38 +68,38 @@ struct UTF32BE;
|
||||
} // namespace rapidjson
|
||||
~~~~~~~~~~
|
||||
|
||||
对于在内存中的文本,我们正常会使用`UTF8`、`UTF16`或`UTF32`。对于处理经过I/O的文本,我们可使用`UTF8`、`UTF16LE`、`UTF16BE`、`UTF32LE`或`UTF32BE`。
|
||||
对于在内存中的文本,我们正常会使用 `UTF8`、`UTF16` 或 `UTF32`。对于处理经过 I/O 的文本,我们可使用 `UTF8`、`UTF16LE`、`UTF16BE`、`UTF32LE` 或 `UTF32BE`。
|
||||
|
||||
当使用DOM风格的API,`GenericValue<Encoding>`及`GenericDocument<Encoding>`里的`Encoding`模板参数是用于指明内存中存储的JSON字符串使用哪种编码。因此通常我们会在此参数中使用`UTF8`、`UTF16`或`UTF32`。如何选择,视乎应用软件所使用的操作系统及其他程序库。例如,Windows API使用UTF-16表示Unicode字符,而多数的Linux发行版本及应用软件则更喜欢UTF-8。
|
||||
当使用 DOM 风格的 API,`GenericValue<Encoding>` 及 `GenericDocument<Encoding>` 里的 `Encoding` 模板参数是用于指明内存中存储的 JSON 字符串使用哪种编码。因此通常我们会在此参数中使用 `UTF8`、`UTF16` 或 `UTF32`。如何选择,视乎应用软件所使用的操作系统及其他程序库。例如,Windows API 使用 UTF-16 表示 Unicode 字符,而多数的 Linux 发行版本及应用软件则更喜欢 UTF-8。
|
||||
|
||||
使用UTF-16的DOM声明例子:
|
||||
使用 UTF-16 的 DOM 声明例子:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
typedef GenericDocument<UTF16<> > WDocument;
|
||||
typedef GenericValue<UTF16<> > WValue;
|
||||
~~~~~~~~~~
|
||||
|
||||
可以在[DOM's Encoding](doc/stream.md)一节看到更详细的使用例子。
|
||||
可以在 [DOM's Encoding](doc/stream.zh-cn.md) 一节看到更详细的使用例子。
|
||||
|
||||
## 字符类型 {#CharacterType}
|
||||
|
||||
从之前的声明中可以看到,每个编码都有一个`CharType`模板参数。这可能比较容易混淆,实际上,每个`CharType`存储一个编码单元,而不是一个字符(码点)。如之前所谈及,在UTF-8中一个码点可能会编码成1至4个编码单元。
|
||||
从之前的声明中可以看到,每个编码都有一个 `CharType` 模板参数。这可能比较容易混淆,实际上,每个 `CharType` 存储一个编码单元,而不是一个字符(码点)。如之前所谈及,在 UTF-8 中一个码点可能会编码成 1 至 4 个编码单元。
|
||||
|
||||
对于`UTF16(LE|BE)`及`UTF32(LE|BE)`来说,`CharType`必须分别是一个至少2及4字节的整数类型。
|
||||
对于 `UTF16(LE|BE)` 及 `UTF32(LE|BE)` 来说,`CharType` 必须分别是一个至少 2 及 4 字节的整数类型。
|
||||
|
||||
注意C++11新添了`char16_t`及`char32_t`类型,也可分别用于`UTF16`及`UTF32`。
|
||||
注意 C++11 新添了 `char16_t` 及 `char32_t` 类型,也可分别用于 `UTF16` 及 `UTF32`。
|
||||
|
||||
## AutoUTF {#AutoUTF}
|
||||
|
||||
上述所介绍的编码都是在编译期静态挷定的。换句话说,使用者必须知道内存或流之中使用了哪种编码。然而,有时候我们可能需要读写不同编码的文件,而且这些编码需要在运行时才能决定。
|
||||
|
||||
`AutoUTF`是为此而设计的编码。它根据输入或输出流来选择使用哪种编码。目前它应该与`EncodedInputStream`及`EncodedOutputStream`结合使用。
|
||||
`AutoUTF` 是为此而设计的编码。它根据输入或输出流来选择使用哪种编码。目前它应该与 `EncodedInputStream` 及 `EncodedOutputStream` 结合使用。
|
||||
|
||||
## ASCII {#ASCII}
|
||||
|
||||
虽然JSON标准并未提及[ASCII](http://en.wikipedia.org/wiki/ASCII),有时候我们希望写入7位的ASCII JSON,以供未能处理UTF-8的应用程序使用。由于任JSON都可以把Unicode字符表示为`\uXXXX`转义序列,JSON总是可用ASCII来编码。
|
||||
虽然 JSON 标准并未提及 [ASCII](http://en.wikipedia.org/wiki/ASCII),有时候我们希望写入 7 位的 ASCII JSON,以供未能处理 UTF-8 的应用程序使用。由于任 JSON 都可以把 Unicode 字符表示为 `\uXXXX` 转义序列,JSON 总是可用 ASCII 来编码。
|
||||
|
||||
以下的例子把UTF-8的DOM写成ASCII的JSON:
|
||||
以下的例子把 UTF-8 的 DOM 写成 ASCII 的 JSON:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
using namespace rapidjson;
|
||||
@ -111,21 +111,21 @@ d.Accept(writer);
|
||||
std::cout << buffer.GetString();
|
||||
~~~~~~~~~~
|
||||
|
||||
ASCII可用于输入流。当输入流包含大于127的字节,就会导致`kParseErrorStringInvalidEncoding`错误。
|
||||
ASCII 可用于输入流。当输入流包含大于 127 的字节,就会导致 `kParseErrorStringInvalidEncoding` 错误。
|
||||
|
||||
ASCII *不能* 用于内存(`Document`的编码,或`Reader`的目标编码),因为它不能表示Unicode码点。
|
||||
ASCII * 不能 * 用于内存(`Document` 的编码,或 `Reader` 的目标编码),因为它不能表示 Unicode 码点。
|
||||
|
||||
# 校验及转码 {#ValidationTranscoding}
|
||||
|
||||
当RapidJSON解析一个JSON时,它能校验输入JSON,判断它是否所标明编码的合法序列。要开启此选项,请把`kParseValidateEncodingFlag`加入`parseFlags`模板参数。
|
||||
当 RapidJSON 解析一个 JSON 时,它能校验输入 JSON,判断它是否所标明编码的合法序列。要开启此选项,请把 `kParseValidateEncodingFlag` 加入 `parseFlags` 模板参数。
|
||||
|
||||
若输入编码和输出编码并不相同,`Reader`及`Writer`会算把文本转码。在这种情况下,并不需要`kParseValidateEncodingFlag`,因为它必须解码输入序列。若序列不能被解码,它必然是不合法的。
|
||||
若输入编码和输出编码并不相同,`Reader` 及 `Writer` 会算把文本转码。在这种情况下,并不需要 `kParseValidateEncodingFlag`,因为它必须解码输入序列。若序列不能被解码,它必然是不合法的。
|
||||
|
||||
## 转码器 {#Transcoder}
|
||||
|
||||
虽然RapidJSON的编码功能是为JSON解析/生成而设计,使用者也可以“滥用”它们来为非JSON字符串转码。
|
||||
虽然 RapidJSON 的编码功能是为 JSON 解析/生成而设计,使用者也可以“滥用”它们来为非 JSON 字符串转码。
|
||||
|
||||
以下的例子把UTF-8字符串转码成UTF-16:
|
||||
以下的例子把 UTF-8 字符串转码成 UTF-16:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/encodings.h"
|
||||
@ -137,8 +137,8 @@ StringStream source(s);
|
||||
GenericStringBuffer<UTF16<> > target;
|
||||
|
||||
bool hasError = false;
|
||||
while (source.Peak() != '\0')
|
||||
if (!Transcoder::Transcode<UTF8<>, UTF16<> >(source, target)) {
|
||||
while (source.Peek() != '\0')
|
||||
if (!Transcoder<UTF8<>, UTF16<> >::Transcode(source, target)) {
|
||||
hasError = true;
|
||||
break;
|
||||
}
|
||||
@ -149,4 +149,4 @@ if (!hasError) {
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
你也可以用`AutoUTF`及对应的流来在运行时设置内源/目的之编码。
|
||||
你也可以用 `AutoUTF` 及对应的流来在运行时设置内源/目的之编码。
|
||||
|
24
doc/faq.md
24
doc/faq.md
@ -18,7 +18,7 @@
|
||||
|
||||
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).
|
||||
Yes, it is free under MIT license. It can be used in commercial applications. Please check the details in [license.txt](https://github.com/Tencent/rapidjson/blob/master/license.txt).
|
||||
|
||||
5. Is RapidJSON small? What are its dependencies?
|
||||
|
||||
@ -44,7 +44,7 @@
|
||||
|
||||
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.
|
||||
RapidJSON contains a unit test suite for automatic testing. [Travis](https://travis-ci.org/Tencent/rapidjson/)(for Linux) and [AppVeyor](https://ci.appveyor.com/project/Tencent/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?
|
||||
|
||||
@ -70,7 +70,7 @@
|
||||
|
||||
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).
|
||||
Currently no. RapidJSON only support the strict standardized format. Support on related syntax is under discussion in this [issue](https://github.com/Tencent/rapidjson/issues/36).
|
||||
|
||||
## DOM and SAX
|
||||
|
||||
@ -116,7 +116,7 @@
|
||||
~~~~~~~~~~cpp
|
||||
Value(kObjectType).Swap(d);
|
||||
~~~~~~~~~~
|
||||
or equivalent, but sightly longer to type:
|
||||
or equivalent, but slightly longer to type:
|
||||
~~~~~~~~~~cpp
|
||||
d.Swap(Value(kObjectType).Move());
|
||||
~~~~~~~~~~
|
||||
@ -140,11 +140,11 @@
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
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.
|
||||
The most important requirement to take care of document and value life-cycle as well as consistent memory management 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());
|
||||
Document address(person.GetAllocator());
|
||||
...
|
||||
person["person"].AddMember("address", address["address"], person.GetAllocator());
|
||||
~~~~~~~~~~
|
||||
@ -174,7 +174,7 @@ Alternatively, if we don't want to explicitly refer to the root value of `addres
|
||||
|
||||
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.
|
||||
Since C string is null-terminated, the length of string needs to be computed via `strlen()`, with linear runtime complexity. This incurs an unnecessary 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.
|
||||
|
||||
@ -204,7 +204,7 @@ Alternatively, if we don't want to explicitly refer to the root value of `addres
|
||||
|
||||
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.
|
||||
Yes, just pass `kParseValidateEncodingFlag` to `Parse()`. If there is invalid encoding in the stream, it will generate `kParseErrorStringInvalidEncoding` error.
|
||||
|
||||
3. What is surrogate pair? Does RapidJSON support it?
|
||||
|
||||
@ -248,7 +248,7 @@ Alternatively, if we don't want to explicitly refer to the root value of `addres
|
||||
|
||||
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.
|
||||
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 libraries.
|
||||
|
||||
2. Why is it fast?
|
||||
|
||||
@ -256,19 +256,19 @@ Alternatively, if we don't want to explicitly refer to the root value of `addres
|
||||
|
||||
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.
|
||||
[SIMD](http://en.wikipedia.org/wiki/SIMD) instructions can perform parallel computation in modern CPUs. RapidJSON support Intel's SSE2/SSE4.2 and ARM's Neon to accelerate whitespace/tabspace/carriage-return/line-feed skipping. This improves performance of parsing indent formatted JSON. Define `RAPIDJSON_SSE2`, `RAPIDJSON_SSE42` or `RAPIDJSON_NEON` 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 SAX API, `Reader` consumes memory proportional 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.
|
||||
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 throughput. In a broad sense, it will also save energy.
|
||||
|
||||
## Gossip
|
||||
|
||||
|
202
doc/faq.zh-cn.md
202
doc/faq.zh-cn.md
@ -4,107 +4,107 @@
|
||||
|
||||
## 一般问题
|
||||
|
||||
1. RapidJSON是什么?
|
||||
1. RapidJSON 是什么?
|
||||
|
||||
RapidJSON是一个C++库,用于解析及生成JSON。读者可参考它的所有[特点](doc/features.zh-cn.md)。
|
||||
RapidJSON 是一个 C++ 库,用于解析及生成 JSON。读者可参考它的所有 [特点](doc/features.zh-cn.md)。
|
||||
|
||||
2. 为什么称作RapidJSON?
|
||||
2. 为什么称作 RapidJSON?
|
||||
|
||||
它的灵感来自于[RapidXML](http://rapidxml.sourceforge.net/),RapidXML是一个高速的XML DOM解析器。
|
||||
它的灵感来自于 [RapidXML](http://rapidxml.sourceforge.net/),RapidXML 是一个高速的 XML DOM 解析器。
|
||||
|
||||
3. RapidJSON与RapidXML相似么?
|
||||
3. RapidJSON 与 RapidXML 相似么?
|
||||
|
||||
RapidJSON借镜了RapidXML的一些设计, 包括原位(*in situ*)解析、只有头文件的库。但两者的API是完全不同的。此外RapidJSON也提供许多RapidXML没有的特点。
|
||||
RapidJSON 借镜了 RapidXML 的一些设计, 包括原位(*in situ*)解析、只有头文件的库。但两者的 API 是完全不同的。此外 RapidJSON 也提供许多 RapidXML 没有的特点。
|
||||
|
||||
4. RapidJSON是免费的么?
|
||||
4. RapidJSON 是免费的么?
|
||||
|
||||
是的,它在MIT特許條款下免费。它可用于商业软件。详情请参看[license.txt](https://github.com/miloyip/rapidjson/blob/master/license.txt)。
|
||||
是的,它在 MIT 特許條款下免费。它可用于商业软件。详情请参看 [license.txt](https://github.com/Tencent/rapidjson/blob/master/license.txt)。
|
||||
|
||||
5. RapidJSON很小么?它有何依赖?
|
||||
5. RapidJSON 很小么?它有何依赖?
|
||||
|
||||
是的。在Windows上,一个解析JSON并打印出统计的可执行文件少于30KB。
|
||||
是的。在 Windows 上,一个解析 JSON 并打印出统计的可执行文件少于 30KB。
|
||||
|
||||
RapidJSON仅依赖于C++标准库。
|
||||
RapidJSON 仅依赖于 C++ 标准库。
|
||||
|
||||
6. 怎样安装RapidJSON?
|
||||
6. 怎样安装 RapidJSON?
|
||||
|
||||
见[安装一节](../readme.zh-cn.md#安装)。
|
||||
见 [安装一节](../readme.zh-cn.md#安装)。
|
||||
|
||||
7. RapidJSON能否运行于我的平台?
|
||||
7. RapidJSON 能否运行于我的平台?
|
||||
|
||||
社区已在多个操作系统/编译器/CPU架构的组合上测试RapidJSON。但我们无法确保它能运行于你特定的平台上。只需要生成及执行单元测试便能获取答案。
|
||||
社区已在多个操作系统/编译器/CPU 架构的组合上测试 RapidJSON。但我们无法确保它能运行于你特定的平台上。只需要生成及执行单元测试便能获取答案。
|
||||
|
||||
8. RapidJSON支持C++03么?C++11呢?
|
||||
8. RapidJSON 支持 C++03 么?C++11 呢?
|
||||
|
||||
RapidJSON开始时在C++03上实现。后来加入了可选的C++11特性支持(如转移构造函数、`noexcept`)。RapidJSON应该兼容所有遵从C++03或C++11的编译器。
|
||||
RapidJSON 开始时在 C++03 上实现。后来加入了可选的 C++11 特性支持(如转移构造函数、`noexcept`)。RapidJSON 应该兼容所有遵从 C++03 或 C++11 的编译器。
|
||||
|
||||
9. RapidJSON是否真的用于实际应用?
|
||||
9. RapidJSON 是否真的用于实际应用?
|
||||
|
||||
是的。它被配置于前台及后台的真实应用中。一个社区成员说RapidJSON在他们的系统中每日解析5千万个JSON。
|
||||
是的。它被配置于前台及后台的真实应用中。一个社区成员说 RapidJSON 在他们的系统中每日解析 5 千万个 JSON。
|
||||
|
||||
10. RapidJSON是如何被测试的?
|
||||
10. RapidJSON 是如何被测试的?
|
||||
|
||||
RapidJSON包含一组单元测试去执行自动测试。[Travis](https://travis-ci.org/miloyip/rapidjson/)(供Linux平台)及[AppVeyor](https://ci.appveyor.com/project/miloyip/rapidjson/)(供Windows平台)会对所有修改进行编译及执行单元测试。在Linux下还会使用Valgrind去检测内存泄漏。
|
||||
RapidJSON 包含一组单元测试去执行自动测试。[Travis](https://travis-ci.org/Tencent/rapidjson/)(供 Linux 平台)及 [AppVeyor](https://ci.appveyor.com/project/Tencent/rapidjson/)(供 Windows 平台)会对所有修改进行编译及执行单元测试。在 Linux 下还会使用 Valgrind 去检测内存泄漏。
|
||||
|
||||
11. RapidJSON是否有完整的文档?
|
||||
11. RapidJSON 是否有完整的文档?
|
||||
|
||||
RapidJSON提供了使用手册及API说明文档。
|
||||
RapidJSON 提供了使用手册及 API 说明文档。
|
||||
|
||||
12. 有没有其他替代品?
|
||||
|
||||
有许多替代品。例如[nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark)列出了一些开源的C/C++ JSON库。[json.org](http://www.json.org/)也有一个列表。
|
||||
有许多替代品。例如 [nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) 列出了一些开源的 C/C++ JSON 库。[json.org](http://www.json.org/) 也有一个列表。
|
||||
|
||||
## JSON
|
||||
|
||||
1. 什么是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)。
|
||||
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有什么应用场合?
|
||||
2. JSON 有什么应用场合?
|
||||
|
||||
JSON常用于网页应用程序,以传送结构化数据。它也可作为文件格式用于数据持久化。
|
||||
JSON 常用于网页应用程序,以传送结构化数据。它也可作为文件格式用于数据持久化。
|
||||
|
||||
2. RapidJSON是否符合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)。
|
||||
是。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是否支持宽松的语法?
|
||||
3. RapidJSON 是否支持宽松的语法?
|
||||
|
||||
现时不支持。RapidJSON只支持严格的标准格式。宽松语法现时在这[issue](https://github.com/miloyip/rapidjson/issues/36)中进行讨论。
|
||||
现时不支持。RapidJSON 只支持严格的标准格式。宽松语法现时在这 [issue](https://github.com/Tencent/rapidjson/issues/36) 中进行讨论。
|
||||
|
||||
## DOM与SAX
|
||||
## DOM 与 SAX
|
||||
|
||||
1. 什么是DOM风格API?
|
||||
1. 什么是 DOM 风格 API?
|
||||
|
||||
Document Object Model(DOM)是一个储存于内存的JSON表示方式,用于查询及修改JSON。
|
||||
Document Object Model(DOM)是一个储存于内存的 JSON 表示方式,用于查询及修改 JSON。
|
||||
|
||||
2. 什么是SAX风格API?
|
||||
2. 什么是 SAX 风格 API?
|
||||
|
||||
SAX是一个事件驱动的API,用于解析及生成JSON。
|
||||
SAX 是一个事件驱动的 API,用于解析及生成 JSON。
|
||||
|
||||
3. 我应用DOM还是SAX?
|
||||
3. 我应用 DOM 还是 SAX?
|
||||
|
||||
DOM易于查询及修改。SAX则是非常快及省内存的,但通常较难使用。
|
||||
DOM 易于查询及修改。SAX 则是非常快及省内存的,但通常较难使用。
|
||||
|
||||
4. 什么是原位(*in situ*)解析?
|
||||
|
||||
原位解析会把JSON字符串直接解码至输入的JSON中。这是一个优化,可减少内存消耗及提升性能,但输入的JSON会被更改。进一步细节请参考[原位解析](doc/dom.md) 。
|
||||
原位解析会把 JSON 字符串直接解码至输入的 JSON 中。这是一个优化,可减少内存消耗及提升性能,但输入的 JSON 会被更改。进一步细节请参考 [原位解析](doc/dom.zh-cn.md) 。
|
||||
|
||||
5. 什么时候会产生解析错误?
|
||||
|
||||
当输入的JSON包含非法语法,或不能表示一个值(如Number太大),或解析器的处理器中断解析过程,解析器都会产生一个错误。详情请参考[解析错误](doc/dom.md)。
|
||||
当输入的 JSON 包含非法语法,或不能表示一个值(如 Number 太大),或解析器的处理器中断解析过程,解析器都会产生一个错误。详情请参考 [解析错误](doc/dom.zh-cn.md)。
|
||||
|
||||
6. 有什么错误信息?
|
||||
|
||||
错误信息存储在`ParseResult`,它包含错误代号及偏移值(从JSON开始至错误处的字符数目)。可以把错误代号翻译为人类可读的错误讯息。
|
||||
错误信息存储在 `ParseResult`,它包含错误代号及偏移值(从 JSON 开始至错误处的字符数目)。可以把错误代号翻译为人类可读的错误讯息。
|
||||
|
||||
7. 为何不只使用`double`去表示JSON number?
|
||||
7. 为何不只使用 `double` 去表示 JSON number?
|
||||
|
||||
一些应用需要使用64位无号/有号整数。这些整数不能无损地转换成`double`。因此解析器会检测一个JSON number是否能转换至各种整数类型及`double`。
|
||||
一些应用需要使用 64 位无号/有号整数。这些整数不能无损地转换成 `double`。因此解析器会检测一个 JSON number 是否能转换至各种整数类型及 `double`。
|
||||
|
||||
8. 如何清空并最小化`document`或`value`的容量?
|
||||
8. 如何清空并最小化 `document` 或 `value` 的容量?
|
||||
|
||||
调用 `SetXXX()` 方法 - 这些方法会调用析构函数,并重建空的Object或Array:
|
||||
调用 `SetXXX()` 方法 - 这些方法会调用析构函数,并重建空的 Object 或 Array:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Document d;
|
||||
@ -112,7 +112,7 @@
|
||||
d.SetObject(); // clear and minimize
|
||||
~~~~~~~~~~
|
||||
|
||||
另外,也可以参考在 [C++ swap with temporary idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/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);
|
||||
~~~~~~~~~~
|
||||
@ -121,9 +121,9 @@
|
||||
d.Swap(Value(kObjectType).Move());
|
||||
~~~~~~~~~~
|
||||
|
||||
9. 如何将一个`document`节点插入到另一个`document`中?
|
||||
9. 如何将一个 `document` 节点插入到另一个 `document` 中?
|
||||
|
||||
比如有以下两个document(DOM):
|
||||
比如有以下两个 document(DOM):
|
||||
~~~~~~~~~~cpp
|
||||
Document person;
|
||||
person.Parse("{\"person\":{\"name\":{\"first\":\"Adam\",\"last\":\"Thomas\"}}}");
|
||||
@ -131,7 +131,7 @@
|
||||
Document address;
|
||||
address.Parse("{\"address\":{\"city\":\"Moscow\",\"street\":\"Quiet\"}}");
|
||||
~~~~~~~~~~
|
||||
假设我们希望将整个 `address` 插入到`person`中,作为其的一个子节点:
|
||||
假设我们希望将整个 `address` 插入到 `person` 中,作为其的一个子节点:
|
||||
~~~~~~~~~~js
|
||||
{ "person": {
|
||||
"name": { "first": "Adam", "last": "Thomas" },
|
||||
@ -140,22 +140,22 @@
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
在插入节点的过程中需要注意`document`和`value`的生命周期并且正确地使用allocator进行内存分配和管理。
|
||||
在插入节点的过程中需要注意 `document` 和 `value` 的生命周期并且正确地使用 allocator 进行内存分配和管理。
|
||||
|
||||
一个简单有效的方法就是修改上述`address`变量的定义,让其使用`person`的allocator初始化,然后将其添加到根节点。
|
||||
一个简单有效的方法就是修改上述 `address` 变量的定义,让其使用 `person` 的 allocator 初始化,然后将其添加到根节点。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Documnet address(person.GetAllocator());
|
||||
...
|
||||
person["person"].AddMember("address", address["address"], person.GetAllocator());
|
||||
~~~~~~~~~~
|
||||
当然,如果你不想通过显式地写出`address`的key来得到其值,可以使用迭代器来实现:
|
||||
当然,如果你不想通过显式地写出 `address` 的 key 来得到其值,可以使用迭代器来实现:
|
||||
~~~~~~~~~~cpp
|
||||
auto addressRoot = address.MemberBegin();
|
||||
person["person"].AddMember(addressRoot->name, addressRoot->value, person.GetAllocator());
|
||||
~~~~~~~~~~
|
||||
|
||||
此外,还可以通过深拷贝address document来实现:
|
||||
此外,还可以通过深拷贝 address document 来实现:
|
||||
~~~~~~~~~~cpp
|
||||
Value addressValue = Value(address["address"], person.GetAllocator());
|
||||
person["person"].AddMember("address", addressValue, person.GetAllocator());
|
||||
@ -163,128 +163,128 @@
|
||||
|
||||
## Document/Value (DOM)
|
||||
|
||||
1. 什么是转移语意?为什么?
|
||||
1. 什么是转移语义?为什么?
|
||||
|
||||
`Value`不用复制语意,而使用了转移语意。这是指,当把来源值赋值于目标值时,来源值的所有权会转移至目标值。
|
||||
`Value` 不用复制语义,而使用了转移语义。这是指,当把来源值赋值于目标值时,来源值的所有权会转移至目标值。
|
||||
|
||||
由于转移快于复制,此设计决定强迫使用者注意到复制的消耗。
|
||||
|
||||
2. 怎样去复制一个值?
|
||||
|
||||
有两个API可用:含allocator的构造函数,以及`CopyFrom()`。可参考[深复制Value](doc/tutorial.md)里的用例。
|
||||
有两个 API 可用:含 allocator 的构造函数,以及 `CopyFrom()`。可参考 [深复制 Value](doc/tutorial.zh-cn.md) 里的用例。
|
||||
|
||||
3. 为什么我需要提供字符串的长度?
|
||||
|
||||
由于C字符串是空字符结尾的,需要使用`strlen()`去计算其长度,这是线性复杂度的操作。若使用者已知字符串的长度,对很多操作来说会造成不必要的消耗。
|
||||
由于 C 字符串是空字符结尾的,需要使用 `strlen()` 去计算其长度,这是线性复杂度的操作。若使用者已知字符串的长度,对很多操作来说会造成不必要的消耗。
|
||||
|
||||
此外,RapidJSON可处理含有`\u0000`(空字符)的字符串。若一个字符串含有空字符,`strlen()`便不能返回真正的字符串长度。在这种情况下使用者必须明确地提供字符串长度。
|
||||
此外,RapidJSON 可处理含有 `\u0000`(空字符)的字符串。若一个字符串含有空字符,`strlen()` 便不能返回真正的字符串长度。在这种情况下使用者必须明确地提供字符串长度。
|
||||
|
||||
4. 为什么在许多DOM操作API中要提供分配器作为参数?
|
||||
4. 为什么在许多 DOM 操作 API 中要提供分配器作为参数?
|
||||
|
||||
由于这些API是`Value`的成员函数,我们不希望为每个`Value`储存一个分配器指针。
|
||||
由于这些 API 是 `Value` 的成员函数,我们不希望为每个 `Value` 储存一个分配器指针。
|
||||
|
||||
5. 它会转换各种数值类型么?
|
||||
|
||||
当使用`GetInt()`、`GetUint()`等API时,可能会发生转换。对于整数至整数转换,仅当保证转换安全才会转换(否则会断言失败)。然而,当把一个64位有号/无号整数转换至double时,它会转换,但有可能会损失精度。含有小数的数字、或大于64位的整数,都只能使用`GetDouble()`获取其值。
|
||||
当使用 `GetInt()`、`GetUint()` 等 API 时,可能会发生转换。对于整数至整数转换,仅当保证转换安全才会转换(否则会断言失败)。然而,当把一个 64 位有号/无号整数转换至 double 时,它会转换,但有可能会损失精度。含有小数的数字、或大于 64 位的整数,都只能使用 `GetDouble()` 获取其值。
|
||||
|
||||
## Reader/Writer (SAX)
|
||||
|
||||
1. 为什么不仅仅用`printf`输出一个JSON?为什么需要`Writer`?
|
||||
1. 为什么不仅仅用 `printf` 输出一个 JSON?为什么需要 `Writer`?
|
||||
|
||||
最重要的是,`Writer`能确保输出的JSON是格式正确的。错误地调用SAX事件(如`StartObject()`错配`EndArray()`)会造成断言失败。此外,`Writer`会把字符串进行转义(如`\n`)。最后,`printf()`的数值输出可能并不是一个合法的JSON number,特别是某些locale会有数字分隔符。而且`Writer`的数值字符串转换是使用非常快的算法来实现的,胜过`printf()`及`iostream`。
|
||||
最重要的是,`Writer` 能确保输出的 JSON 是格式正确的。错误地调用 SAX 事件(如 `StartObject()` 错配 `EndArray()`)会造成断言失败。此外,`Writer` 会把字符串进行转义(如 `\n`)。最后,`printf()` 的数值输出可能并不是一个合法的 JSON number,特别是某些 locale 会有数字分隔符。而且 `Writer` 的数值字符串转换是使用非常快的算法来实现的,胜过 `printf()` 及 `iostream`。
|
||||
|
||||
2. 我能否暂停解析过程,并在稍后继续?
|
||||
|
||||
基于性能考虑,目前版本并不直接支持此功能。然而,若执行环境支持多线程,使用者可以在另一线程解析JSON,并通过阻塞输入流去暂停。
|
||||
基于性能考虑,目前版本并不直接支持此功能。然而,若执行环境支持多线程,使用者可以在另一线程解析 JSON,并通过阻塞输入流去暂停。
|
||||
|
||||
## Unicode
|
||||
|
||||
1. 它是否支持UTF-8、UTF-16及其他格式?
|
||||
1. 它是否支持 UTF-8、UTF-16 及其他格式?
|
||||
|
||||
是。它完全支持UTF-8、UTF-16(大端/小端)、UTF-32(大端/小端)及ASCII。
|
||||
是。它完全支持 UTF-8、UTF-16(大端/小端)、UTF-32(大端/小端)及 ASCII。
|
||||
|
||||
2. 它能否检测编码的合法性?
|
||||
|
||||
能。只需把`kParseValidateEncodingFlag`参考传给`Parse()`。若发现在输入流中有非法的编码,它就会产生`kParseErrorStringInvalidEncoding`错误。
|
||||
能。只需把 `kParseValidateEncodingFlag` 参考传给 `Parse()`。若发现在输入流中有非法的编码,它就会产生 `kParseErrorStringInvalidEncoding` 错误。
|
||||
|
||||
3. 什么是代理对(surrogate pair)?RapidJSON是否支持?
|
||||
3. 什么是代理对(surrogate pair)?RapidJSON 是否支持?
|
||||
|
||||
JSON使用UTF-16编码去转义Unicode字符,例如`\u5927`表示中文字“大”。要处理基本多文种平面(basic multilingual plane,BMP)以外的字符时,UTF-16会把那些字符编码成两个16位值,这称为UTF-16代理对。例如,绘文字字符U+1F602在JSON中可被编码成`\uD83D\uDE02`。
|
||||
JSON 使用 UTF-16 编码去转义 Unicode 字符,例如 `\u5927` 表示中文字“大”。要处理基本多文种平面(basic multilingual plane,BMP)以外的字符时,UTF-16 会把那些字符编码成两个 16 位值,这称为 UTF-16 代理对。例如,绘文字字符 U+1F602 在 JSON 中可被编码成 `\uD83D\uDE02`。
|
||||
|
||||
RapidJSON完全支持解析及生成UTF-16代理对。
|
||||
RapidJSON 完全支持解析及生成 UTF-16 代理对。
|
||||
|
||||
4. 它能否处理JSON字符串中的`\u0000`(空字符)?
|
||||
4. 它能否处理 JSON 字符串中的 `\u0000`(空字符)?
|
||||
|
||||
能。RapidJSON完全支持JSON字符串中的空字符。然而,使用者需要注意到这件事,并使用`GetStringLength()`及相关API去取得字符串真正长度。
|
||||
能。RapidJSON 完全支持 JSON 字符串中的空字符。然而,使用者需要注意到这件事,并使用 `GetStringLength()` 及相关 API 去取得字符串真正长度。
|
||||
|
||||
5. 能否对所有非ASCII字符输出成`\uxxxx`形式?
|
||||
5. 能否对所有非 ASCII 字符输出成 `\uxxxx` 形式?
|
||||
|
||||
可以。只要在`Writer`中使用`ASCII<>`作为输出编码参数,就可以强逼转义那些字符。
|
||||
可以。只要在 `Writer` 中使用 `ASCII<>` 作为输出编码参数,就可以强逼转义那些字符。
|
||||
|
||||
## 流
|
||||
|
||||
1. 我有一个很大的JSON文件。我应否把它整个载入内存中?
|
||||
1. 我有一个很大的 JSON 文件。我应否把它整个载入内存中?
|
||||
|
||||
使用者可使用`FileReadStream`去逐块读入文件。但若使用于原位解析,必须载入整个文件。
|
||||
使用者可使用 `FileReadStream` 去逐块读入文件。但若使用于原位解析,必须载入整个文件。
|
||||
|
||||
2. 我能否解析一个从网络上串流进来的JSON?
|
||||
2. 我能否解析一个从网络上串流进来的 JSON?
|
||||
|
||||
可以。使用者可根据`FileReadStream`的实现,去实现一个自定义的流。
|
||||
可以。使用者可根据 `FileReadStream` 的实现,去实现一个自定义的流。
|
||||
|
||||
3. 我不知道一些JSON将会使用哪种编码。怎样处理它们?
|
||||
3. 我不知道一些 JSON 将会使用哪种编码。怎样处理它们?
|
||||
|
||||
你可以使用`AutoUTFInputStream`,它能自动检测输入流的编码。然而,它会带来一些性能开销。
|
||||
你可以使用 `AutoUTFInputStream`,它能自动检测输入流的编码。然而,它会带来一些性能开销。
|
||||
|
||||
4. 什么是BOM?RapidJSON怎样处理它?
|
||||
4. 什么是 BOM?RapidJSON 怎样处理它?
|
||||
|
||||
[字节顺序标记(byte order mark, BOM)](http://en.wikipedia.org/wiki/Byte_order_mark)有时会出现于文件/流的开始,以表示其UTF编码类型。
|
||||
[字节顺序标记(byte order mark, BOM)](http://en.wikipedia.org/wiki/Byte_order_mark) 有时会出现于文件/流的开始,以表示其 UTF 编码类型。
|
||||
|
||||
RapidJSON的`EncodedInputStream`可检测/跳过BOM。`EncodedOutputStream`可选择是否写入BOM。可参考[编码流](doc/stream.md)中的例子。
|
||||
RapidJSON 的 `EncodedInputStream` 可检测/跳过 BOM。`EncodedOutputStream` 可选择是否写入 BOM。可参考 [编码流](doc/stream.zh-cn.md) 中的例子。
|
||||
|
||||
5. 为什么会涉及大端/小端?
|
||||
|
||||
流的大端/小端是UTF-16及UTF-32流要处理的问题,而UTF-8不需要处理。
|
||||
流的大端/小端是 UTF-16 及 UTF-32 流要处理的问题,而 UTF-8 不需要处理。
|
||||
|
||||
## 性能
|
||||
|
||||
1. RapidJSON是否真的快?
|
||||
1. RapidJSON 是否真的快?
|
||||
|
||||
是。它可能是最快的开源JSON库。有一个[评测](https://github.com/miloyip/nativejson-benchmark)评估C/C++ JSON库的性能。
|
||||
是。它可能是最快的开源 JSON 库。有一个 [评测](https://github.com/miloyip/nativejson-benchmark) 评估 C/C++ JSON 库的性能。
|
||||
|
||||
2. 为什么它会快?
|
||||
|
||||
RapidJSON的许多设计是针对时间/空间性能来设计的,这些决定可能会影响API的易用性。此外,它也使用了许多底层优化(内部函数/intrinsic、SIMD)及特别的算法(自定义的double至字符串转换、字符串至double的转换)。
|
||||
RapidJSON 的许多设计是针对时间/空间性能来设计的,这些决定可能会影响 API 的易用性。此外,它也使用了许多底层优化(内部函数/intrinsic、SIMD)及特别的算法(自定义的 double 至字符串转换、字符串至 double 的转换)。
|
||||
|
||||
3. 什是是SIMD?它如何用于RapidJSON?
|
||||
3. 什是是 SIMD?它如何用于 RapidJSON?
|
||||
|
||||
[SIMD](http://en.wikipedia.org/wiki/SIMD)指令可以在现代CPU中执行并行运算。RapidJSON支持了Intel的SSE2/SSE4.2去加速跳过空白字符。在解析含缩进的JSON时,这能提升性能。只要定义名为`RAPIDJSON_SSE2`或`RAPIDJSON_SSE42`的宏,就能启动这个功能。然而,若在不支持这些指令集的机器上执行这些可执行文件,会导致崩溃。
|
||||
[SIMD](http://en.wikipedia.org/wiki/SIMD) 指令可以在现代 CPU 中执行并行运算。RapidJSON 支持使用 Intel 的 SSE2/SSE4.2 和 ARM 的 Neon 来加速对空白符、制表符、回车符和换行符的过滤处理。在解析含缩进的 JSON 时,这能提升性能。只要定义名为 `RAPIDJSON_SSE2` ,`RAPIDJSON_SSE42` 或 `RAPIDJSON_NEON` 的宏,就能启动这个功能。然而,若在不支持这些指令集的机器上执行这些可执行文件,会导致崩溃。
|
||||
|
||||
4. 它会消耗许多内存么?
|
||||
|
||||
RapidJSON的设计目标是减低内存占用。
|
||||
RapidJSON 的设计目标是减低内存占用。
|
||||
|
||||
在SAX API中,`Reader`消耗的内存与JSON树深度加上最长JSON字符成正比。
|
||||
在 SAX API 中,`Reader` 消耗的内存与 JSON 树深度加上最长 JSON 字符成正比。
|
||||
|
||||
在DOM API中,每个`Value`在32/64位架构下分别消耗16/24字节。RapidJSON也使用一个特殊的内存分配器去减少分配的额外开销。
|
||||
在 DOM API 中,每个 `Value` 在 32/64 位架构下分别消耗 16/24 字节。RapidJSON 也使用一个特殊的内存分配器去减少分配的额外开销。
|
||||
|
||||
5. 高性能的意义何在?
|
||||
|
||||
有些应用程序需要处理非常大的JSON文件。而有些后台应用程序需要处理大量的JSON。达到高性能同时改善延时及吞吐量。更广义来说,这也可以节省能源。
|
||||
有些应用程序需要处理非常大的 JSON 文件。而有些后台应用程序需要处理大量的 JSON。达到高性能同时改善延时及吞吐量。更广义来说,这也可以节省能源。
|
||||
|
||||
## 八挂
|
||||
|
||||
1. 谁是RapidJSON的开发者?
|
||||
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))提供了一个非常灵巧的短字符串优化。也需要感谢其他献者及社区成员。
|
||||
叶劲峰(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?
|
||||
2. 为何你要开发 RapidJSON?
|
||||
|
||||
在2011年开始这项目是,它仅一个兴趣项目。Milo Yip是一个游戏程序员,他在那时候认识到JSON并希望在未来的项目中使用。由于JSON好像很简单,他希望写一个仅有头文件并且快速的程序库。
|
||||
在 2011 年开始这项目是,它仅一个兴趣项目。Milo Yip 是一个游戏程序员,他在那时候认识到 JSON 并希望在未来的项目中使用。由于 JSON 好像很简单,他希望写一个仅有头文件并且快速的程序库。
|
||||
|
||||
3. 为什么开发中段有一段长期空档?
|
||||
|
||||
主要是个人因素,例如加入新家庭成员。另外,Milo Yip也花了许多业馀时间去翻译Jason Gregory的《Game Engine Architecture》至中文版《游戏引擎架构》。
|
||||
主要是个人因素,例如加入新家庭成员。另外,Milo Yip 也花了许多业馀时间去翻译 Jason Gregory 的《Game Engine Architecture》至中文版《游戏引擎架构》。
|
||||
|
||||
4. 为什么这个项目从Google Code搬到GitHub?
|
||||
4. 为什么这个项目从 Google Code 搬到 GitHub?
|
||||
|
||||
这是大势所趋,而且GitHub更为强大及方便。
|
||||
这是大势所趋,而且 GitHub 更为强大及方便。
|
||||
|
@ -20,11 +20,16 @@
|
||||
## 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.
|
||||
* 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/Tencent/rapidjson/blob/master/doc/npm.md).
|
||||
|
||||
## Unicode
|
||||
|
||||
@ -68,7 +73,7 @@
|
||||
* 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, 15 characters in 64-bit.
|
||||
* 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
|
||||
@ -96,3 +101,4 @@
|
||||
* Some C++11 support (optional)
|
||||
* Rvalue reference
|
||||
* `noexcept` specifier
|
||||
* Range-based for loop
|
||||
|
@ -3,49 +3,54 @@
|
||||
## 总体
|
||||
|
||||
* 跨平台
|
||||
* 编译器:Visual Studio、gcc、clang等
|
||||
* 架构:x86、x64、ARM等
|
||||
* 操作系统:Windows、Mac OS X、Linux、iOS、Android等
|
||||
* 编译器:Visual Studio、gcc、clang 等
|
||||
* 架构:x86、x64、ARM 等
|
||||
* 操作系统:Windows、Mac OS X、Linux、iOS、Android 等
|
||||
* 容易安装
|
||||
* 只有头文件的库。只需把头文件复制至你的项目中。
|
||||
* 独立、最小依赖
|
||||
* 不需依赖STL、BOOST等。
|
||||
* 只包含`<cstdio>`, `<cstdlib>`, `<cstring>`, `<inttypes.h>`, `<new>`, `<stdint.h>`。
|
||||
* 没使用C++异常、RTTI
|
||||
* 不需依赖 STL、BOOST 等。
|
||||
* 只包含 `<cstdio>`, `<cstdlib>`, `<cstring>`, `<inttypes.h>`, `<new>`, `<stdint.h>`。
|
||||
* 没使用 C++ 异常、RTTI
|
||||
* 高性能
|
||||
* 使用模版及内联函数去降低函数调用开销。
|
||||
* 内部经优化的Grisu2及浮点数解析实现。
|
||||
* 可选的SSE2/SSE4.2支持。
|
||||
* 内部经优化的 Grisu2 及浮点数解析实现。
|
||||
* 可选的 SSE2/SSE4.2 支持。
|
||||
|
||||
## 符合标准
|
||||
|
||||
* RapidJSON应完全符合RFC4627/ECMA-404标准。
|
||||
* 支持Unicod代理对(surrogate pair)。
|
||||
* RapidJSON 应完全符合 RFC4627/ECMA-404 标准。
|
||||
* 支持 JSON Pointer (RFC6901).
|
||||
* 支持 JSON Schema Draft v4.
|
||||
* 支持 Unicode 代理对(surrogate pair)。
|
||||
* 支持空字符(`"\u0000"`)。
|
||||
* 例如,可以优雅地解析及处理`["Hello\u0000World"]`。含读写字符串长度的API。
|
||||
* 支持放宽的可选语法
|
||||
* 单行(`// ...`)及多行(`/* ... */`) 注释。
|
||||
* 例如,可以优雅地解析及处理 `["Hello\u0000World"]`。含读写字符串长度的 API。
|
||||
* 支持可选的放宽语法
|
||||
* 单行(`// ...`)及多行(`/* ... */`) 注释 (`kParseCommentsFlag`)。
|
||||
* 在对象和数组结束前含逗号 (`kParseTrailingCommasFlag`)。
|
||||
* `NaN`、`Inf`、`Infinity`、`-Inf` 及 `-Infinity` 作为 `double` 值 (`kParseNanAndInfFlag`)
|
||||
* [NPM 兼容](https://github.com/Tencent/rapidjson/blob/master/doc/npm.md).
|
||||
|
||||
## Unicode
|
||||
|
||||
* 支持UTF-8、UTF-16、UTF-32编码,包括小端序和大端序。
|
||||
* 支持 UTF-8、UTF-16、UTF-32 编码,包括小端序和大端序。
|
||||
* 这些编码用于输入输出流,以及内存中的表示。
|
||||
* 支持从输入流自动检测编码。
|
||||
* 内部支持编码的转换。
|
||||
* 例如,你可以读取一个UTF-8文件,让RapidJSON把JSON字符串转换至UTF-16的DOM。
|
||||
* 例如,你可以读取一个 UTF-8 文件,让 RapidJSON 把 JSON 字符串转换至 UTF-16 的 DOM。
|
||||
* 内部支持编码校验。
|
||||
* 例如,你可以读取一个UTF-8文件,让RapidJSON检查是否所有JSON字符串是合法的UTF-8字节序列。
|
||||
* 例如,你可以读取一个 UTF-8 文件,让 RapidJSON 检查是否所有 JSON 字符串是合法的 UTF-8 字节序列。
|
||||
* 支持自定义的字符类型。
|
||||
* 预设的字符类型是:UTF-8为`char`,UTF-16为`wchar_t`,UTF32为`uint32_t`。
|
||||
* 预设的字符类型是:UTF-8 为 `char`,UTF-16 为 `wchar_t`,UTF32 为 `uint32_t`。
|
||||
* 支持自定义的编码。
|
||||
|
||||
## API风格
|
||||
## 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更易用。用户可根据情况作出选择。
|
||||
* 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 更易用。用户可根据情况作出选择。
|
||||
|
||||
## 解析
|
||||
|
||||
@ -53,45 +58,46 @@
|
||||
* 递归式解析器较快,但在极端情况下可出现堆栈溢出。
|
||||
* 迭代式解析器使用自定义的堆栈去维持解析状态。
|
||||
* 支持原位(*in situ*)解析。
|
||||
* 把JSON字符串的值解析至原JSON之中,然后让DOM指向那些字符串。
|
||||
* 把 JSON 字符串的值解析至原 JSON 之中,然后让 DOM 指向那些字符串。
|
||||
* 比常规分析更快:不需字符串的内存分配、不需复制(如字符串不含转义符)、缓存友好。
|
||||
* 对于JSON数字类型,支持32-bit/64-bit的有号/无号整数,以及`double`。
|
||||
* 对于 JSON 数字类型,支持 32-bit/64-bit 的有号/无号整数,以及 `double`。
|
||||
* 错误处理
|
||||
* 支持详尽的解析错误代号。
|
||||
* 支持本地化错误信息。
|
||||
|
||||
## DOM (Document)
|
||||
|
||||
* RapidJSON在类型转换时会检查数值的范围。
|
||||
* RapidJSON 在类型转换时会检查数值的范围。
|
||||
* 字符串字面量的优化
|
||||
* 只储存指针,不作复制
|
||||
* 优化“短”字符串
|
||||
* 在`Value`内储存短字符串,无需额外分配。
|
||||
* 对UTF-8字符串来说,32位架构下可存储最多11字符,64位下15字符。
|
||||
* 可选地支持`std::string`(定义`RAPIDJSON_HAS_STDSTRING=1`)
|
||||
* 在 `Value` 内储存短字符串,无需额外分配。
|
||||
* 对 UTF-8 字符串来说,32 位架构下可存储最多 11 字符,64 位下 21 字符(x86-64 下 13 字符)。
|
||||
* 可选地支持 `std::string`(定义 `RAPIDJSON_HAS_STDSTRING=1`)
|
||||
|
||||
## 生成
|
||||
|
||||
* 支持`rapidjson::PrettyWriter`去加入换行及缩进。
|
||||
* 支持 `rapidjson::PrettyWriter` 去加入换行及缩进。
|
||||
|
||||
## 输入输出流
|
||||
|
||||
* 支持`rapidjson::GenericStringBuffer`,把输出的JSON储存于字符串内。
|
||||
* 支持`rapidjson::FileReadStream`及`rapidjson::FileWriteStream`,使用`FILE`对象作输入输出。
|
||||
* 支持 `rapidjson::GenericStringBuffer`,把输出的 JSON 储存于字符串内。
|
||||
* 支持 `rapidjson::FileReadStream` 及 `rapidjson::FileWriteStream`,使用 `FILE` 对象作输入输出。
|
||||
* 支持自定义输入输出流。
|
||||
|
||||
## 内存
|
||||
|
||||
* 最小化DOM的内存开销。
|
||||
* 对大部分32/64位机器而言,每个JSON值只占16或20字节(不包含字符串)。
|
||||
* 最小化 DOM 的内存开销。
|
||||
* 对大部分 32/64 位机器而言,每个 JSON 值只占 16 或 20 字节(不包含字符串)。
|
||||
* 支持快速的预设分配器。
|
||||
* 它是一个堆栈形式的分配器(顺序分配,不容许单独释放,适合解析过程之用)。
|
||||
* 使用者也可提供一个预分配的缓冲区。(有可能达至无需CRT分配就能解析多个JSON)
|
||||
* 支持标准CRT(C-runtime)分配器。
|
||||
* 使用者也可提供一个预分配的缓冲区。(有可能达至无需 CRT 分配就能解析多个 JSON)
|
||||
* 支持标准 CRT(C-runtime)分配器。
|
||||
* 支持自定义分配器。
|
||||
|
||||
## 其他
|
||||
|
||||
* 一些C++11的支持(可选)
|
||||
* 一些 C++11 的支持(可选)
|
||||
* 右值引用(rvalue reference)
|
||||
* `noexcept`修饰符
|
||||
* `noexcept` 修饰符
|
||||
* 范围 for 循环
|
||||
|
@ -114,7 +114,7 @@ Number is a bit more complicated. For normal integer values, it can contains `kI
|
||||
|
||||
## Short-String Optimization {#ShortString}
|
||||
|
||||
Kosta (@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.
|
||||
[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|
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
@ -126,7 +126,7 @@ A special technique is applied. Instead of storing the length of string directly
|
||||
|
||||
This optimization can reduce memory usage for copy-string. It can also improve cache-coherence thus improve runtime performance.
|
||||
|
||||
# Allocator {#Allocator}
|
||||
# Allocator {#InternalAllocator}
|
||||
|
||||
`Allocator` is a concept in RapidJSON:
|
||||
~~~cpp
|
||||
@ -158,7 +158,7 @@ Note that `Malloc()` and `Realloc()` are member functions but `Free()` is static
|
||||
|
||||
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](dom.md))
|
||||
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.
|
||||
|
||||
@ -183,17 +183,20 @@ void SkipWhitespace(InputStream& s) {
|
||||
|
||||
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 accelerate this process, SIMD was applied to compare 16 characters with 4 white spaces for each iteration. Currently RapidJSON supports SSE2, SSE4.2 and ARM Neon 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`:
|
||||
To enable this optimization, need to define `RAPIDJSON_SSE2`, `RAPIDJSON_SSE42` or `RAPIDJSON_NEON` 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.
|
||||
// Likewise, __ARM_NEON is used to detect Neon.
|
||||
#if defined(__SSE4_2__)
|
||||
# define RAPIDJSON_SSE42
|
||||
#elif defined(__SSE2__)
|
||||
# define RAPIDJSON_SSE2
|
||||
#elif defined(__ARM_NEON)
|
||||
# define RAPIDJSON_NEON
|
||||
#endif
|
||||
~~~
|
||||
|
||||
@ -211,7 +214,7 @@ In [Intel® 64 and IA-32 Architectures Optimization Reference Manual
|
||||
|
||||
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).
|
||||
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/Tencent/rapidjson/issues/85).
|
||||
|
||||
## Local Stream Copy {#LocalStreamCopy}
|
||||
|
||||
|
363
doc/internals.zh-cn.md
Normal file
363
doc/internals.zh-cn.md
Normal file
@ -0,0 +1,363 @@
|
||||
# 内部架构
|
||||
|
||||
本部分记录了一些设计和实现细节。
|
||||
|
||||
[TOC]
|
||||
|
||||
# 架构 {#Architecture}
|
||||
|
||||
## SAX 和 DOM
|
||||
|
||||
下面的 UML 图显示了 SAX 和 DOM 的基本关系。
|
||||
|
||||

|
||||
|
||||
关系的核心是 `Handler` 概念。在 SAX 一边,`Reader` 从流解析 JSON 并将事件发送到 `Handler`。`Writer` 实现了 `Handler` 概念,用于处理相同的事件。在 DOM 一边,`Document` 实现了 `Handler` 概念,用于通过这些时间来构建 DOM。`Value` 支持了 `Value::Accept(Handler&)` 函数,它可以将 DOM 转换为事件进行发送。
|
||||
|
||||
在这个设计,SAX 是不依赖于 DOM 的。甚至 `Reader` 和 `Writer` 之间也没有依赖。这提供了连接事件发送器和处理器的灵活性。除此之外,`Value` 也是不依赖于 SAX 的。所以,除了将 DOM 序列化为 JSON 之外,用户也可以将其序列化为 XML,或者做任何其他事情。
|
||||
|
||||
## 工具类
|
||||
|
||||
SAX 和 DOM API 都依赖于3个额外的概念:`Allocator`、`Encoding` 和 `Stream`。它们的继承层次结构如下图所示。
|
||||
|
||||

|
||||
|
||||
# 值(Value) {#Value}
|
||||
|
||||
`Value` (实际上被定义为 `GenericValue<UTF8<>>`)是 DOM API 的核心。本部分描述了它的设计。
|
||||
|
||||
## 数据布局 {#DataLayout}
|
||||
|
||||
`Value` 是[可变类型](http://en.wikipedia.org/wiki/Variant_type)。在 RapidJSON 的上下文中,一个 `Value` 的实例可以包含6种 JSON 数据类型之一。通过使用 `union` ,这是可能实现的。每一个 `Value` 包含两个成员:`union Data data_` 和 `unsigned flags_`。`flags_` 表明了 JSON 类型,以及附加的信息。
|
||||
|
||||
下表显示了所有类型的数据布局。32位/64位列表明了字段所占用的字节数。
|
||||
|
||||
| Null | | 32位 | 64位 |
|
||||
|-------------------|----------------------------------|:----:|:----:|
|
||||
| (未使用) | |4 |8 |
|
||||
| (未使用) | |4 |4 |
|
||||
| (未使用) | |4 |4 |
|
||||
| `unsigned flags_` | `kNullType kNullFlag` |4 |4 |
|
||||
|
||||
| Bool | | 32位 | 64位 |
|
||||
|-------------------|----------------------------------------------------|:----:|:----:|
|
||||
| (未使用) | |4 |8 |
|
||||
| (未使用) | |4 |4 |
|
||||
| (未使用) | |4 |4 |
|
||||
| `unsigned flags_` | `kBoolType` (either `kTrueFlag` or `kFalseFlag`) |4 |4 |
|
||||
|
||||
| String | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `Ch* str` | 指向字符串的指针(可能拥有所有权) |4 |8 |
|
||||
| `SizeType length` | 字符串长度 |4 |4 |
|
||||
| (未使用) | |4 |4 |
|
||||
| `unsigned flags_` | `kStringType kStringFlag ...` |4 |4 |
|
||||
|
||||
| Object | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `Member* members` | 指向成员数组的指针(拥有所有权) |4 |8 |
|
||||
| `SizeType size` | 成员数量 |4 |4 |
|
||||
| `SizeType capacity` | 成员容量 |4 |4 |
|
||||
| `unsigned flags_` | `kObjectType kObjectFlag` |4 |4 |
|
||||
|
||||
| Array | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `Value* values` | 指向值数组的指针(拥有所有权) |4 |8 |
|
||||
| `SizeType size` | 值数量 |4 |4 |
|
||||
| `SizeType capacity` | 值容量 |4 |4 |
|
||||
| `unsigned flags_` | `kArrayType kArrayFlag` |4 |4 |
|
||||
|
||||
| Number (Int) | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `int i` | 32位有符号整数 |4 |4 |
|
||||
| (零填充) | 0 |4 |4 |
|
||||
| (未使用) | |4 |8 |
|
||||
| `unsigned flags_` | `kNumberType kNumberFlag kIntFlag kInt64Flag ...` |4 |4 |
|
||||
|
||||
| Number (UInt) | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `unsigned u` | 32位无符号整数 |4 |4 |
|
||||
| (零填充) | 0 |4 |4 |
|
||||
| (未使用) | |4 |8 |
|
||||
| `unsigned flags_` | `kNumberType kNumberFlag kUIntFlag kUInt64Flag ...` |4 |4 |
|
||||
|
||||
| Number (Int64) | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `int64_t i64` | 64位有符号整数 |8 |8 |
|
||||
| (未使用) | |4 |8 |
|
||||
| `unsigned flags_` | `kNumberType kNumberFlag kInt64Flag ...` |4 |4 |
|
||||
|
||||
| Number (Uint64) | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `uint64_t i64` | 64位无符号整数 |8 |8 |
|
||||
| (未使用) | |4 |8 |
|
||||
| `unsigned flags_` | `kNumberType kNumberFlag kInt64Flag ...` |4 |4 |
|
||||
|
||||
| Number (Double) | | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `uint64_t i64` | 双精度浮点数 |8 |8 |
|
||||
| (未使用) | |4 |8 |
|
||||
| `unsigned flags_` |`kNumberType kNumberFlag kDoubleFlag`|4 |4 |
|
||||
|
||||
这里有一些需要注意的地方:
|
||||
* 为了减少在64位架构上的内存消耗,`SizeType` 被定义为 `unsigned` 而不是 `size_t`。
|
||||
* 32位整数的零填充可能被放在实际类型的前面或后面,这依赖于字节序。这使得它可以将32位整数不经过任何转换就可以解释为64位整数。
|
||||
* `Int` 永远是 `Int64`,反之不然。
|
||||
|
||||
## 标志 {#Flags}
|
||||
|
||||
32位的 `flags_` 包含了 JSON 类型和其他信息。如前文中的表所述,每一种 JSON 类型包含了冗余的 `kXXXType` 和 `kXXXFlag`。这个设计是为了优化测试位标志(`IsNumber()`)和获取每一种类型的序列号(`GetType()`)。
|
||||
|
||||
字符串有两个可选的标志。`kCopyFlag` 表明这个字符串拥有字符串拷贝的所有权。而 `kInlineStrFlag` 意味着使用了[短字符串优化](#ShortString)。
|
||||
|
||||
数字更加复杂一些。对于普通的整数值,它可以包含 `kIntFlag`、`kUintFlag`、 `kInt64Flag` 和/或 `kUint64Flag`,这由整数的范围决定。带有小数或者超过64位所能表达的范围的整数的数字会被存储为带有 `kDoubleFlag` 的 `double`。
|
||||
|
||||
## 短字符串优化 {#ShortString}
|
||||
|
||||
[Kosta](https://github.com/Kosta-Github) 提供了很棒的短字符串优化。这个优化的xxx如下所述。除去 `flags_` ,`Value` 有12或16字节(对于32位或64位)来存储实际的数据。这为在其内部直接存储短字符串而不是存储字符串的指针创造了可能。对于1字节的字符类型(例如 `char`),它可以在 `Value` 类型内部存储至多11或15个字符的字符串。
|
||||
|
||||
|ShortString (Ch=char)| | 32位 | 64位 |
|
||||
|---------------------|-------------------------------------|:----:|:----:|
|
||||
| `Ch str[MaxChars]` | 字符串缓冲区 |11 |15 |
|
||||
| `Ch invLength` | MaxChars - Length |1 |1 |
|
||||
| `unsigned flags_` | `kStringType kStringFlag ...` |4 |4 |
|
||||
|
||||
这里使用了一项特殊的技术。它存储了 (MaxChars - length) 而不直接存储字符串的长度。这使得存储11个字符并且带有后缀 `\0` 成为可能。
|
||||
|
||||
这个优化可以减少字符串拷贝内存占用。它也改善了缓存一致性,并进一步提高了运行时性能。
|
||||
|
||||
# 分配器(Allocator) {#InternalAllocator}
|
||||
|
||||
`Allocator` 是 RapidJSON 中的概念:
|
||||
~~~cpp
|
||||
concept Allocator {
|
||||
static const bool kNeedFree; //!< 表明这个分配器是否需要调用 Free()。
|
||||
|
||||
// 申请内存块。
|
||||
// \param size 内存块的大小,以字节记。
|
||||
// \returns 指向内存块的指针。
|
||||
void* Malloc(size_t size);
|
||||
|
||||
// 调整内存块的大小。
|
||||
// \param originalPtr 当前内存块的指针。空指针是被允许的。
|
||||
// \param originalSize 当前大小,以字节记。(设计问题:因为有些分配器可能不会记录它,显示的传递它可以节约内存。)
|
||||
// \param newSize 新大小,以字节记。
|
||||
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
|
||||
|
||||
// 释放内存块。
|
||||
// \param ptr 指向内存块的指针。空指针是被允许的。
|
||||
static void Free(void *ptr);
|
||||
};
|
||||
~~~
|
||||
|
||||
需要注意的是 `Malloc()` 和 `Realloc()` 是成员函数而 `Free()` 是静态成员函数。
|
||||
|
||||
## MemoryPoolAllocator {#MemoryPoolAllocator}
|
||||
|
||||
`MemoryPoolAllocator` 是 DOM 的默认内存分配器。它只申请内存而不释放内存。这对于构建 DOM 树非常合适。
|
||||
|
||||
在它的内部,它从基础的内存分配器申请内存块(默认为 `CrtAllocator`)并将这些内存块存储为单向链表。当用户请求申请内存,它会遵循下列步骤来申请内存:
|
||||
|
||||
1. 如果可用,使用用户提供的缓冲区。(见 [User Buffer section in DOM](doc/dom.md))
|
||||
2. 如果用户提供的缓冲区已满,使用当前内存块。
|
||||
3. 如果当前内存块已满,申请新的内存块。
|
||||
|
||||
# 解析优化 {#ParsingOptimization}
|
||||
|
||||
## 使用 SIMD 跳过空格 {#SkipwhitespaceWithSIMD}
|
||||
|
||||
当从流中解析 JSON 时,解析器需要跳过4种空格字符:
|
||||
|
||||
1. 空格 (`U+0020`)
|
||||
2. 制表符 (`U+000B`)
|
||||
3. 换行 (`U+000A`)
|
||||
4. 回车 (`U+000D`)
|
||||
|
||||
这是一份简单的实现:
|
||||
~~~cpp
|
||||
void SkipWhitespace(InputStream& s) {
|
||||
while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t')
|
||||
s.Take();
|
||||
}
|
||||
~~~
|
||||
|
||||
但是,这需要对每个字符进行4次比较以及一些分支。这被发现是一个热点。
|
||||
|
||||
为了加速这一处理,RapidJSON 使用 SIMD 来在一次迭代中比较16个字符和4个空格。目前 RapidJSON 支持 SSE2 , SSE4.2 和 ARM Neon 指令。同时它也只会对 UTF-8 内存流启用,包括字符串流或 *原位* 解析。
|
||||
|
||||
你可以通过在包含 `rapidjson.h` 之前定义 `RAPIDJSON_SSE2` , `RAPIDJSON_SSE42` 或 `RAPIDJSON_NEON` 来启用这个优化。一些编译器可以检测这个设置,如 `perftest.h`:
|
||||
|
||||
~~~cpp
|
||||
// __SSE2__ 和 __SSE4_2__ 可被 gcc、clang 和 Intel 编译器识别:
|
||||
// 如果支持的话,我们在 gmake 中使用了 -march=native 来启用 -msse2 和 -msse4.2
|
||||
// 同样的, __ARM_NEON 被用于识别Neon
|
||||
#if defined(__SSE4_2__)
|
||||
# define RAPIDJSON_SSE42
|
||||
#elif defined(__SSE2__)
|
||||
# define RAPIDJSON_SSE2
|
||||
#elif defined(__ARM_NEON)
|
||||
# define RAPIDJSON_NEON
|
||||
#endif
|
||||
~~~
|
||||
|
||||
需要注意的是,这是编译期的设置。在不支持这些指令的机器上运行可执行文件会使它崩溃。
|
||||
|
||||
### 页面对齐问题
|
||||
|
||||
在 RapidJSON 的早期版本中,被报告了[一个问题](https://code.google.com/archive/p/rapidjson/issues/104):`SkipWhitespace_SIMD()` 会罕见地导致崩溃(约五十万分之一的几率)。在调查之后,怀疑是 `_mm_loadu_si128()` 访问了 `'\0'` 之后的内存,并越过被保护的页面边界。
|
||||
|
||||
在 [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) 中,章节 10.2.1:
|
||||
|
||||
> 为了支持需要费对齐的128位 SIMD 内存访问的算法,调用者的内存缓冲区申请应当考虑添加一些填充空间,这样被调用的函数可以安全地将地址指针用于未对齐的128位 SIMD 内存操作。
|
||||
> 在结合非对齐的 SIMD 内存操作中,最小的对齐大小应该等于 SIMD 寄存器的大小。
|
||||
|
||||
对于 RapidJSON 来说,这显然是不可行的,因为 RapidJSON 不应当强迫用户进行内存对齐。
|
||||
|
||||
为了修复这个问题,当前的代码会先按字节处理直到下一个对齐的地址。在这之后,使用对齐读取来进行 SIMD 处理。见 [#85](https://github.com/Tencent/rapidjson/issues/85)。
|
||||
|
||||
## 局部流拷贝 {#LocalStreamCopy}
|
||||
|
||||
在优化的过程中,我们发现一些编译器不能将访问流的一些成员数据放入局部变量或者寄存器中。测试结果显示,对于一些流类型,创建流的拷贝并将其用于内层循环中可以改善性能。例如,实际(非 SIMD)的 `SkipWhitespace()` 被实现为:
|
||||
|
||||
~~~cpp
|
||||
template<typename InputStream>
|
||||
void SkipWhitespace(InputStream& is) {
|
||||
internal::StreamLocalCopy<InputStream> copy(is);
|
||||
InputStream& s(copy.s);
|
||||
|
||||
while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t')
|
||||
s.Take();
|
||||
}
|
||||
~~~
|
||||
|
||||
基于流的特征,`StreamLocalCopy` 会创建(或不创建)流对象的拷贝,在局部使用它并将流的状态拷贝回原来的流。
|
||||
|
||||
## 解析为双精度浮点数 {#ParsingDouble}
|
||||
|
||||
将字符串解析为 `double` 并不简单。标准库函数 `strtod()` 可以胜任这项工作,但它比较缓慢。默认情况下,解析器使用默认的精度设置。这最多有 3[ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) 的误差,并实现在 `internal::StrtodNormalPrecision()` 中。
|
||||
|
||||
当使用 `kParseFullPrecisionFlag` 时,编译器会改为调用 `internal::StrtodFullPrecision()` ,这个函数会自动调用三个版本的转换。
|
||||
1. [Fast-Path](http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/)。
|
||||
2. [double-conversion](https://github.com/floitsch/double-conversion) 中的自定义 DIY-FP 实现。
|
||||
3. (Clinger, William D. How to read floating point numbers accurately. Vol. 25. No. 6. ACM, 1990) 中的大整数算法。
|
||||
|
||||
如果第一个转换方法失败,则尝试使用第二种方法,以此类推。
|
||||
|
||||
# 生成优化 {#GenerationOptimization}
|
||||
|
||||
## 整数到字符串的转换 {#itoa}
|
||||
|
||||
整数到字符串转换的朴素算法需要对每一个十进制位进行一次处罚。我们实现了若干版本并在 [itoa-benchmark](https://github.com/miloyip/itoa-benchmark) 中对它们进行了评估。
|
||||
|
||||
虽然 SSE2 版本是最快的,但它和第二快的 `branchlut` 差距不大。而且 `branchlut` 是纯C++实现,所以我们在 RapidJSON 中使用了 `branchlut`。
|
||||
|
||||
## 双精度浮点数到字符串的转换 {#dtoa}
|
||||
|
||||
原来 RapidJSON 使用 `snprintf(..., ..., "%g")` 来进行双精度浮点数到字符串的转换。这是不准确的,因为默认的精度是6。随后我们发现它很缓慢,而且有其它的替代品。
|
||||
|
||||
Google 的 V8 [double-conversion](https://github.com/floitsch/double-conversion
|
||||
) 实现了更新的、快速的被称为 Grisu3 的算法(Loitsch, Florian. "Printing floating-point numbers quickly and accurately with integers." ACM Sigplan Notices 45.6 (2010): 233-243.)。
|
||||
|
||||
然而,这个实现不是仅头文件的,所以我们实现了一个仅头文件的 Grisu2 版本。这个算法保证了结果永远精确。而且在大多数情况下,它会生成最短的(可选)字符串表示。
|
||||
|
||||
这个仅头文件的转换函数在 [dtoa-benchmark](https://github.com/miloyip/dtoa-benchmark) 中进行评估。
|
||||
|
||||
# 解析器 {#Parser}
|
||||
|
||||
## 迭代解析 {#IterativeParser}
|
||||
|
||||
迭代解析器是一个以非递归方式实现的递归下降的 LL(1) 解析器。
|
||||
|
||||
### 语法 {#IterativeParserGrammar}
|
||||
|
||||
解析器使用的语法是基于严格 JSON 语法的:
|
||||
~~~~~~~~~~
|
||||
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
|
||||
~~~~~~~~~~
|
||||
|
||||
注意到左因子被加入了非终结符的 `values` 和 `members` 来保证语法是 LL(1) 的。
|
||||
|
||||
### 解析表 {#IterativeParserParsingTable}
|
||||
|
||||
基于这份语法,我们可以构造 FIRST 和 FOLLOW 集合。
|
||||
|
||||
非终结符的 FIRST 集合如下所示:
|
||||
|
||||
| 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 { [ |
|
||||
|
||||
FOLLOW 集合如下所示:
|
||||
|
||||
| NON-TERMINAL | FOLLOW |
|
||||
|:-----------------:|:-------:|
|
||||
| S | $ |
|
||||
| array | , $ } ] |
|
||||
| object | , $ } ] |
|
||||
| values | ] |
|
||||
| non-empty-values | ] |
|
||||
| addition-values | ] |
|
||||
| members | } |
|
||||
| non-empty-members | } |
|
||||
| addition-members | } |
|
||||
| member | , } |
|
||||
| value | , } ] |
|
||||
|
||||
最终可以从 FIRST 和 FOLLOW 集合生成解析表:
|
||||
|
||||
| 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 |
|
||||
|
||||
对于上面的语法分析,这里有一个很棒的[工具](http://hackingoff.com/compilers/predict-first-follow-set)。
|
||||
|
||||
### 实现 {#IterativeParserImplementation}
|
||||
|
||||
基于这份解析表,一个直接的(常规的)将规则反向入栈的实现可以正常工作。
|
||||
|
||||
在 RapidJSON 中,对直接的实现进行了一些修改:
|
||||
|
||||
首先,在 RapidJSON 中,这份解析表被编码为状态机。
|
||||
规则由头部和主体组成。
|
||||
状态转换由规则构造。
|
||||
除此之外,额外的状态被添加到与 `array` 和 `object` 有关的规则。
|
||||
通过这种方式,生成数组值或对象成员可以只用一次状态转移便可完成,
|
||||
而不需要在直接的实现中的多次出栈/入栈操作。
|
||||
这也使得估计栈的大小更加容易。
|
||||
|
||||
状态图如如下所示:
|
||||
|
||||

|
||||
|
||||
第二,迭代解析器也在内部栈保存了数组的值个数和对象成员的数量,这也与传统的实现不同。
|
@ -7,21 +7,5 @@
|
||||
</ul>
|
||||
</div>
|
||||
<!--END GENERATE_TREEVIEW-->
|
||||
<script type="text/javascript">
|
||||
/* * * CONFIGURATION VARIABLES * * */
|
||||
var disqus_shortname = 'rapidjson-doc';
|
||||
|
||||
/* * * DON'T EDIT BELOW THIS LINE * * */
|
||||
(function() {
|
||||
var dt = document.createElement('div');
|
||||
dt.id = "disqus_thread";
|
||||
(document.getElementsByClassName('contents')[0]).appendChild(dt);
|
||||
|
||||
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
|
||||
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
|
||||
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
|
||||
})();
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
@ -16,18 +16,9 @@ $mathjax
|
||||
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
|
||||
$extrastylesheet
|
||||
</head>
|
||||
<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
|
||||
|
||||
ga('create', 'UA-63929386-1', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>
|
||||
<body>
|
||||
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
|
||||
<div id="topbanner"><a href="https://github.com/miloyip/rapidjson" title="RapidJSON GitHub"><i class="githublogo"></i></a></div>
|
||||
<div id="topbanner"><a href="https://github.com/Tencent/rapidjson" title="RapidJSON GitHub"><i class="githublogo"></i></a></div>
|
||||
$searchbox
|
||||
<!--END TITLEAREA-->
|
||||
<!-- end header part -->
|
||||
|
31
doc/npm.md
Normal file
31
doc/npm.md
Normal file
@ -0,0 +1,31 @@
|
||||
## NPM
|
||||
|
||||
# package.json {#package}
|
||||
|
||||
~~~~~~~~~~js
|
||||
{
|
||||
...
|
||||
"dependencies": {
|
||||
...
|
||||
"rapidjson": "git@github.com:Tencent/rapidjson.git"
|
||||
},
|
||||
...
|
||||
"gypfile": true
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
# binding.gyp {#binding}
|
||||
|
||||
~~~~~~~~~~js
|
||||
{
|
||||
...
|
||||
'targets': [
|
||||
{
|
||||
...
|
||||
'include_dirs': [
|
||||
'<!(node -e \'require("rapidjson")\')'
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
~~~~~~~~~~
|
@ -1,6 +1,6 @@
|
||||
# Performance
|
||||
|
||||
There is a [native JSON benchmark collection] [1] which evaluates speed, memory usage and code size of various operations among 20 JSON libaries.
|
||||
There is a [native JSON benchmark collection] [1] which evaluates speed, memory usage and code size of various operations among 37 JSON libraries.
|
||||
|
||||
[1]: https://github.com/miloyip/nativejson-benchmark
|
||||
|
||||
@ -15,12 +15,12 @@ Additionally, you may refer to the following third-party benchmarks.
|
||||
* [json_spirit](https://github.com/cierelabs/json_spirit)
|
||||
* [jsoncpp](http://jsoncpp.sourceforge.net/)
|
||||
* [libjson](http://sourceforge.net/projects/libjson/)
|
||||
* [rapidjson](https://github.com/miloyip/rapidjson/)
|
||||
* [rapidjson](https://github.com/Tencent/rapidjson/)
|
||||
* [QJsonDocument](http://qt-project.org/doc/qt-5.0/qtcore/qjsondocument.html)
|
||||
|
||||
* [JSON Parser Benchmarking](http://chadaustin.me/2013/01/json-parser-benchmarking/) by Chad Austin (Jan 2013)
|
||||
* [sajson](https://github.com/chadaustin/sajson)
|
||||
* [rapidjson](https://github.com/miloyip/rapidjson/)
|
||||
* [rapidjson](https://github.com/Tencent/rapidjson/)
|
||||
* [vjson](https://code.google.com/p/vjson/)
|
||||
* [YAJL](http://lloyd.github.com/yajl/)
|
||||
* [Jansson](http://www.digip.org/jansson/)
|
||||
|
@ -1,10 +1,10 @@
|
||||
# 性能
|
||||
|
||||
有一个[native JSON benchmark collection][1]项目,能评估20个JSON库在不同操作下的速度、內存用量及代码大小。
|
||||
有一个 [native JSON benchmark collection][1] 项目,能评估 37 个 JSON 库在不同操作下的速度、內存用量及代码大小。
|
||||
|
||||
[1]: https://github.com/miloyip/nativejson-benchmark
|
||||
|
||||
RapidJSON 0.1版本的性能测试文章位于[这里](https://code.google.com/p/rapidjson/wiki/Performance).
|
||||
RapidJSON 0.1 版本的性能测试文章位于 [这里](https://code.google.com/p/rapidjson/wiki/Performance).
|
||||
|
||||
此外,你也可以参考以下这些第三方的评测。
|
||||
|
||||
@ -15,12 +15,12 @@ RapidJSON 0.1版本的性能测试文章位于[这里](https://code.google.com/p
|
||||
* [json_spirit](https://github.com/cierelabs/json_spirit)
|
||||
* [jsoncpp](http://jsoncpp.sourceforge.net/)
|
||||
* [libjson](http://sourceforge.net/projects/libjson/)
|
||||
* [rapidjson](https://github.com/miloyip/rapidjson/)
|
||||
* [rapidjson](https://github.com/Tencent/rapidjson/)
|
||||
* [QJsonDocument](http://qt-project.org/doc/qt-5.0/qtcore/qjsondocument.html)
|
||||
|
||||
* [JSON Parser Benchmarking](http://chadaustin.me/2013/01/json-parser-benchmarking/) by Chad Austin (Jan 2013)
|
||||
* [sajson](https://github.com/chadaustin/sajson)
|
||||
* [rapidjson](https://github.com/miloyip/rapidjson/)
|
||||
* [rapidjson](https://github.com/Tencent/rapidjson/)
|
||||
* [vjson](https://code.google.com/p/vjson/)
|
||||
* [YAJL](http://lloyd.github.com/yajl/)
|
||||
* [Jansson](http://www.digip.org/jansson/)
|
||||
|
@ -1,6 +1,6 @@
|
||||
# Pointer
|
||||
|
||||
## Status: experimental, shall be included in v1.1
|
||||
(This feature was released in v1.1.0)
|
||||
|
||||
JSON Pointer is a standardized ([RFC6901]) way to select a value inside a JSON Document (DOM). This can be analogous to XPath for XML document. However, JSON Pointer is much simpler, and a single JSON Pointer only pointed to a single value.
|
||||
|
||||
@ -211,7 +211,7 @@ p.Stringify(sb);
|
||||
std::cout << sb.GetString() << std::endl;
|
||||
~~~
|
||||
|
||||
It can also stringify to URI fragment reprsentation by `StringifyUriFragment()`.
|
||||
It can also stringify to URI fragment representation by `StringifyUriFragment()`.
|
||||
|
||||
# User-Supplied Tokens {#UserSuppliedTokens}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
# Pointer
|
||||
|
||||
## 状态: 实验性,应该会合进 v1.1
|
||||
(本功能于 v1.1.0 发布)
|
||||
|
||||
JSON Pointer 是一个标准化([RFC6901])的方式去选取一个 JSON Document(DOM)中的值。这类似于 XML 的 XPath。然而,JSON Pointer 简单得多,而且每个 JSON Pointer 仅指向单个值。
|
||||
|
||||
@ -25,7 +25,7 @@ JSON Pointer 是一个标准化([RFC6901])的方式去选取一个 JSON Docu
|
||||
3. `"/foo/1"` → `"baz"`
|
||||
4. `"/pi"` → `3.1416`
|
||||
|
||||
要注意,一个空 JSON Pointer `""` (零个token)解析为整个 JSON。
|
||||
要注意,一个空 JSON Pointer `""` (零个 token)解析为整个 JSON。
|
||||
|
||||
# 基本使用方法 {#BasicUsage}
|
||||
|
||||
@ -123,7 +123,7 @@ assert(success);
|
||||
|
||||
Token `"0"` 在第一个 pointer 中被当作成员名字。它在第二个 pointer 中被当作成数组索引。
|
||||
|
||||
其他函数会改变 DOM,包括`Create()`、`GetWithDefault()`、`Set()`、`Swap()`。这些函数总是成功的。若一些父值不存在,就会创建它们。若父值类型不匹配 token,也会强行改变其类型。改变类型也意味着完全移除其 DOM 子树的内容。
|
||||
其他函数会改变 DOM,包括 `Create()`、`GetWithDefault()`、`Set()`、`Swap()`。这些函数总是成功的。若一些父值不存在,就会创建它们。若父值类型不匹配 token,也会强行改变其类型。改变类型也意味着完全移除其 DOM 子树的内容。
|
||||
|
||||
例如,把上面的 JSON 解译至 `d` 之后,
|
||||
|
||||
@ -185,7 +185,7 @@ private:
|
||||
|
||||
# URI 片段表示方式 {#URIFragment}
|
||||
|
||||
除了我们一直在使用的字符串方式表示 JSON pointer,[RFC6901]也定义了一个 JSON Pointer 的 URI 片段(fragment)表示方式。URI 片段是定义于 [RFC3986] "Uniform Resource Identifier (URI): Generic Syntax"。
|
||||
除了我们一直在使用的字符串方式表示 JSON pointer,[RFC6901] 也定义了一个 JSON Pointer 的 URI 片段(fragment)表示方式。URI 片段是定义于 [RFC3986] "Uniform Resource Identifier (URI): Generic Syntax"。
|
||||
|
||||
URI 片段的主要分别是必然以 `#` (pound sign)开头,而一些字符也会以百分比编码成 UTF-8 序列。例如,以下的表展示了不同表示法下的 C/C++ 字符串常数。
|
||||
|
||||
|
74
doc/sax.md
74
doc/sax.md
@ -8,7 +8,7 @@ In RapidJSON, `Reader` (typedef of `GenericReader<...>`) is the SAX-style parser
|
||||
|
||||
# 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.
|
||||
`Reader` parses a JSON from a stream. While it reads characters from the stream, it analyzes the characters according to the syntax of JSON, and publishes events to a handler.
|
||||
|
||||
For example, here is a JSON.
|
||||
|
||||
@ -24,7 +24,7 @@ For example, here is a JSON.
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
While a `Reader` parses this JSON, it publishes the following events to the handler sequentially:
|
||||
When a `Reader` parses this JSON, it publishes the following events to the handler sequentially:
|
||||
|
||||
~~~~~~~~~~
|
||||
StartObject()
|
||||
@ -50,7 +50,7 @@ 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:
|
||||
These events can be easily matched with the JSON, but 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"
|
||||
@ -59,7 +59,7 @@ These events can be easily matched with the JSON, except some event parameters n
|
||||
using namespace rapidjson;
|
||||
using namespace std;
|
||||
|
||||
struct MyHandler {
|
||||
struct MyHandler : public BaseReaderHandler<UTF8<>, 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; }
|
||||
@ -91,11 +91,11 @@ void main() {
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
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.
|
||||
Note that RapidJSON uses templates to statically bind the `Reader` type and the handler type, instead of using classes with virtual functions. This paradigm can improve 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.
|
||||
As shown in the previous example, the user needs to implement a handler which consumes the events (via function calls) from the `Reader`. The handler must contain the following member functions.
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
class Handler {
|
||||
@ -106,6 +106,7 @@ class Handler {
|
||||
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);
|
||||
@ -119,17 +120,17 @@ class Handler {
|
||||
|
||||
`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)`.
|
||||
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.
|
||||
`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 be aware 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.
|
||||
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 repeat until calling `EndObject(SizeType memberCount)`. Note that the `memberCount` parameter is just an aid for the handler; users who do not need this parameter may ignore it.
|
||||
|
||||
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.
|
||||
Arrays are similar to objects, but simpler. At the beginning of an array, the `Reader` calls `BeginArray()`. 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.
|
||||
Every handler function returns a `bool`. Normally it should return `true`. If the handler encounters an error, it can return `false` to notify the 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`.
|
||||
For example, when we parse a JSON with `Reader` and the handler detects that the JSON does not conform to the required schema, the handler can return `false` and let the `Reader` stop further parsing. This will place the `Reader` in an error state, with error code `kParseErrorTermination`.
|
||||
|
||||
## GenericReader {#GenericReader}
|
||||
|
||||
@ -148,19 +149,19 @@ typedef GenericReader<UTF8<>, 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:
|
||||
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 output UTF-16 string events, you can define a reader by:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
GenericReader<UTF8<>, 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.
|
||||
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 {#Parsing}
|
||||
## Parsing {#SaxParsing}
|
||||
|
||||
The one and only one function of `Reader` is to parse JSON.
|
||||
The main function of `Reader` is used to parse JSON.
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
template <unsigned parseFlags, typename InputStream, typename Handler>
|
||||
@ -171,7 +172,30 @@ template <typename InputStream, typename Handler>
|
||||
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.
|
||||
If an error occurs during parsing, it will return `false`. User can also call `bool HasParseError()`, `ParseErrorCode GetParseErrorCode()` and `size_t GetErrorOffset()` to obtain the error states. In fact, `Document` uses these `Reader` functions to obtain parse errors. Please refer to [DOM](doc/dom.md) for details about parse errors.
|
||||
|
||||
## Token-by-Token Parsing {#TokenByTokenParsing}
|
||||
|
||||
Some users may wish to parse a JSON input stream a single token at a time, instead of immediately parsing an entire document without stopping. To parse JSON this way, instead of calling `Parse`, you can use the `IterativeParse` set of functions:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
void IterativeParseInit();
|
||||
|
||||
template <unsigned parseFlags, typename InputStream, typename Handler>
|
||||
bool IterativeParseNext(InputStream& is, Handler& handler);
|
||||
|
||||
bool IterativeParseComplete();
|
||||
~~~~~~~~~~
|
||||
|
||||
Here is an example of iteratively parsing JSON, token by token:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
reader.IterativeParseInit();
|
||||
while (!reader.IterativeParseComplete()) {
|
||||
reader.IterativeParseNext<kParseDefaultFlags>(is, handler);
|
||||
// Your handler has been called once.
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
# Writer {#Writer}
|
||||
|
||||
@ -243,7 +267,7 @@ Anyway, using `Writer` API is even simpler than generating a JSON by ad hoc meth
|
||||
~~~~~~~~~~cpp
|
||||
namespace rapidjson {
|
||||
|
||||
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<> >
|
||||
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = CrtAllocator<>, unsigned writeFlags = kWriteDefaultFlags>
|
||||
class Writer {
|
||||
public:
|
||||
Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth)
|
||||
@ -259,7 +283,16 @@ The `SourceEncoding` template parameter specifies the encoding to be used in `St
|
||||
|
||||
The `TargetEncoding` template parameter specifies the encoding in the output stream.
|
||||
|
||||
The last one, `Allocator` is the type of allocator, which is used for allocating internal data structure (a stack).
|
||||
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.
|
||||
|
||||
@ -277,7 +310,7 @@ A `Writer` can only output a single JSON, which can be any JSON type at the root
|
||||
|
||||
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 {#Techniques}
|
||||
# Techniques {#SaxTechniques}
|
||||
|
||||
## Parsing JSON to Custom Data Structure {#CustomDataStructure}
|
||||
|
||||
@ -419,6 +452,7 @@ struct CapitalizeFilter {
|
||||
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++)
|
||||
|
133
doc/sax.zh-cn.md
133
doc/sax.zh-cn.md
@ -1,16 +1,16 @@
|
||||
# SAX
|
||||
|
||||
"SAX"此术语源于[Simple API for XML](http://en.wikipedia.org/wiki/Simple_API_for_XML)。我们借了此术语去套用在JSON的解析及生成。
|
||||
"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风格生成器。
|
||||
在 RapidJSON 中,`Reader`(`GenericReader<...>` 的 typedef)是 JSON 的 SAX 风格解析器,而 `Writer`(`GenericWriter<...>` 的 typedef)则是 JSON 的 SAX 风格生成器。
|
||||
|
||||
[TOC]
|
||||
|
||||
# Reader {#Reader}
|
||||
|
||||
`Reader`从输入流解析一个JSON。当它从流中读取字符时,它会基于JSON的语法去分析字符,并向处理器发送事件。
|
||||
`Reader` 从输入流解析一个 JSON。当它从流中读取字符时,它会基于 JSON 的语法去分析字符,并向处理器发送事件。
|
||||
|
||||
例如,以下是一个JSON。
|
||||
例如,以下是一个 JSON。
|
||||
|
||||
~~~~~~~~~~js
|
||||
{
|
||||
@ -24,7 +24,7 @@
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
当一个`Reader`解析此JSON时,它会顺序地向处理器发送以下的事件:
|
||||
当一个 `Reader` 解析此 JSON 时,它会顺序地向处理器发送以下的事件:
|
||||
|
||||
~~~~~~~~~~
|
||||
StartObject()
|
||||
@ -50,7 +50,7 @@ EndArray(4)
|
||||
EndObject(7)
|
||||
~~~~~~~~~~
|
||||
|
||||
除了一些事件参数需要再作解释,这些事件可以轻松地与JSON对上。我们可以看看`simplereader`例子怎样产生和以上完全相同的结果:
|
||||
除了一些事件参数需要再作解释,这些事件可以轻松地与 JSON 对上。我们可以看看 `simplereader` 例子怎样产生和以上完全相同的结果:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/reader.h"
|
||||
@ -59,7 +59,7 @@ EndObject(7)
|
||||
using namespace rapidjson;
|
||||
using namespace std;
|
||||
|
||||
struct MyHandler {
|
||||
struct MyHandler : public BaseReaderHandler<UTF8<>, 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; }
|
||||
@ -91,11 +91,11 @@ void main() {
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
注意RapidJSON使用模板去静态挷定`Reader`类型及处理器的类形,而不是使用含虚函数的类。这个范式可以通过把函数内联而改善性能。
|
||||
注意 RapidJSON 使用模板去静态挷定 `Reader` 类型及处理器的类形,而不是使用含虚函数的类。这个范式可以通过把函数内联而改善性能。
|
||||
|
||||
## 处理器 {#Handler}
|
||||
|
||||
如前例所示,使用者需要实现一个处理器(handler),用于处理来自`Reader`的事件(函数调用)。处理器必须包含以下的成员函数。
|
||||
如前例所示,使用者需要实现一个处理器(handler),用于处理来自 `Reader` 的事件(函数调用)。处理器必须包含以下的成员函数。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
class Handler {
|
||||
@ -106,6 +106,7 @@ class Handler {
|
||||
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);
|
||||
@ -115,25 +116,25 @@ class Handler {
|
||||
};
|
||||
~~~~~~~~~~
|
||||
|
||||
当`Reader`遇到JSON null值时会调用`Null()`。
|
||||
当 `Reader` 遇到 JSON null 值时会调用 `Null()`。
|
||||
|
||||
当`Reader`遇到JSON true或false值时会调用`Bool(bool)`。
|
||||
当 `Reader` 遇到 JSON true 或 false 值时会调用 `Bool(bool)`。
|
||||
|
||||
当`Reader`遇到JSON number,它会选择一个合适的C++类型映射,然后调用`Int(int)`、`Uint(unsigned)`、`Int64(int64_t)`、`Uint64(uint64_t)`及`Double(double)`的*其中之一个*。
|
||||
当 `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 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`参数对处理器来说只是协助性质,使用者可能不需要此参数。
|
||||
当 `Reader` 遇到 JSON object 的开始之时,它会调用 `StartObject()`。JSON 的 object 是一个键值对(成员)的集合。若 object 包含成员,它会先为成员的名字调用 `Key()`,然后再按值的类型调用函数。它不断调用这些键值对,直至最终调用 `EndObject(SizeType memberCount)`。注意 `memberCount` 参数对处理器来说只是协助性质,使用者可能不需要此参数。
|
||||
|
||||
JSON array与object相似,但更简单。在array开始时,`Reader`会调用`BeginArary()`。若array含有元素,它会按元素的类型来读用函数。相似地,最后它会调用`EndArray(SizeType elementCount)`,其中`elementCount`参数对处理器来说只是协助性质。
|
||||
JSON array 与 object 相似,但更简单。在 array 开始时,`Reader` 会调用 `BeginArary()`。若 array 含有元素,它会按元素的类型来读用函数。相似地,最后它会调用 `EndArray(SizeType elementCount)`,其中 `elementCount` 参数对处理器来说只是协助性质。
|
||||
|
||||
每个处理器函数都返回一个`bool`。正常它们应返回`true`。若处理器遇到错误,它可以返回`false`去通知事件发送方停止继续处理。
|
||||
每个处理器函数都返回一个 `bool`。正常它们应返回 `true`。若处理器遇到错误,它可以返回 `false` 去通知事件发送方停止继续处理。
|
||||
|
||||
例如,当我们用`Reader`解析一个JSON时,处理器检测到该JSON并不符合所需的schema,那么处理器可以返回`false`,令`Reader`停止之后的解析工作。而`Reader`会进入一个错误状态,并以`kParseErrorTermination`错误码标识。
|
||||
例如,当我们用 `Reader` 解析一个 JSON 时,处理器检测到该 JSON 并不符合所需的 schema,那么处理器可以返回 `false`,令 `Reader` 停止之后的解析工作。而 `Reader` 会进入一个错误状态,并以 `kParseErrorTermination` 错误码标识。
|
||||
|
||||
## GenericReader {#GenericReader}
|
||||
|
||||
前面提及,`Reader`是`GenericReader`模板类的typedef:
|
||||
前面提及,`Reader` 是 `GenericReader` 模板类的 typedef:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
namespace rapidjson {
|
||||
@ -148,19 +149,19 @@ typedef GenericReader<UTF8<>, UTF8<> > Reader;
|
||||
} // namespace rapidjson
|
||||
~~~~~~~~~~
|
||||
|
||||
`Reader`使用UTF-8作为来源及目标编码。来源编码是指JSON流的编码。目标编码是指`String()`的`str`参数所用的编码。例如,要解析一个UTF-8流并输出至UTF-16 string事件,你需要这么定义一个reader:
|
||||
`Reader` 使用 UTF-8 作为来源及目标编码。来源编码是指 JSON 流的编码。目标编码是指 `String()` 的 `str` 参数所用的编码。例如,要解析一个 UTF-8 流并输出至 UTF-16 string 事件,你需要这么定义一个 reader:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
GenericReader<UTF8<>, UTF16<> > reader;
|
||||
~~~~~~~~~~
|
||||
|
||||
注意到`UTF16`的缺省类型是`wchar_t`。因此这个`reader`需要调用处理器的`String(const wchar_t*, SizeType, bool)`。
|
||||
注意到 `UTF16` 的缺省类型是 `wchar_t`。因此这个 `reader` 需要调用处理器的 `String(const wchar_t*, SizeType, bool)`。
|
||||
|
||||
第三个模板参数`Allocator`是内部数据结构(实际上是一个堆栈)的分配器类型。
|
||||
第三个模板参数 `Allocator` 是内部数据结构(实际上是一个堆栈)的分配器类型。
|
||||
|
||||
## 解析 {#Parsing}
|
||||
## 解析 {#SaxParsing}
|
||||
|
||||
`Reader`的唯一功能就是解析JSON。
|
||||
`Reader` 的唯一功能就是解析 JSON。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
template <unsigned parseFlags, typename InputStream, typename Handler>
|
||||
@ -171,15 +172,15 @@ template <typename InputStream, typename Handler>
|
||||
bool Parse(InputStream& is, Handler& handler);
|
||||
~~~~~~~~~~
|
||||
|
||||
若在解析中出现错误,它会返回`false`。使用者可调用`bool HasParseEror()`, `ParseErrorCode GetParseErrorCode()`及`size_t GetErrorOffset()`获取错误状态。实际上`Document`使用这些`Reader`函数去获取解析错误。请参考[DOM](doc/dom.md)去了解有关解析错误的细节。
|
||||
若在解析中出现错误,它会返回 `false`。使用者可调用 `bool HasParseEror()`, `ParseErrorCode GetParseErrorCode()` 及 `size_t GetErrorOffset()` 获取错误状态。实际上 `Document` 使用这些 `Reader` 函数去获取解析错误。请参考 [DOM](doc/dom.zh-cn.md) 去了解有关解析错误的细节。
|
||||
|
||||
# Writer {#Writer}
|
||||
|
||||
`Reader`把JSON转换(解析)成为事件。`Writer`做完全相反的事情。它把事件转换成JSON。
|
||||
`Reader` 把 JSON 转换(解析)成为事件。`Writer` 做完全相反的事情。它把事件转换成 JSON。
|
||||
|
||||
`Writer`是非常容易使用的。若你的应用程序只需把一些数据转换成JSON,可能直接使用`Writer`,会比建立一个`Document`然后用`Writer`把它转换成JSON更加方便。
|
||||
`Writer` 是非常容易使用的。若你的应用程序只需把一些数据转换成 JSON,可能直接使用 `Writer`,会比建立一个 `Document` 然后用 `Writer` 把它转换成 JSON 更加方便。
|
||||
|
||||
在`simplewriter`例子里,我们做`simplereader`完全相反的事情。
|
||||
在 `simplewriter` 例子里,我们做 `simplereader` 完全相反的事情。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/writer.h"
|
||||
@ -221,24 +222,24 @@ void main() {
|
||||
{"hello":"world","t":true,"f":false,"n":null,"i":123,"pi":3.1416,"a":[0,1,2,3]}
|
||||
~~~~~~~~~~
|
||||
|
||||
`String()`及`Key()`各有两个重载。一个是如处理器concept般,有3个参数。它能处理含空字符的字符串。另一个是如上中使用的较简单版本。
|
||||
`String()` 及 `Key()` 各有两个重载。一个是如处理器 concept 般,有 3 个参数。它能处理含空字符的字符串。另一个是如上中使用的较简单版本。
|
||||
|
||||
注意到,例子代码中的`EndArray()`及`EndObject()`并没有参数。可以传递一个`SizeType`的参数,但它会被`Writer`忽略。
|
||||
注意到,例子代码中的 `EndArray()` 及 `EndObject()` 并没有参数。可以传递一个 `SizeType` 的参数,但它会被 `Writer` 忽略。
|
||||
|
||||
你可能会怀疑,为什么不使用`sprintf()`或`std::stringstream`去建立一个JSON?
|
||||
你可能会怀疑,为什么不使用 `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`可对不同平台进行优化。
|
||||
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甚至乎比这些临时方法更简单。
|
||||
无论如何,使用 `Writer` API 去生成 JSON 甚至乎比这些临时方法更简单。
|
||||
|
||||
## 模板 {#WriterTemplate}
|
||||
|
||||
`Writer`与`Reader`有少许设计区别。`Writer`是一个模板类,而不是一个typedef。 并没有`GenericWriter`。以下是`Writer`的声明。
|
||||
`Writer` 与 `Reader` 有少许设计区别。`Writer` 是一个模板类,而不是一个 typedef。 并没有 `GenericWriter`。以下是 `Writer` 的声明。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
namespace rapidjson {
|
||||
@ -253,39 +254,48 @@ public:
|
||||
} // namespace rapidjson
|
||||
~~~~~~~~~~
|
||||
|
||||
`OutputStream`模板参数是输出流的类型。它的类型不可以被自动推断,必须由使用者提供。
|
||||
`OutputStream` 模板参数是输出流的类型。它的类型不可以被自动推断,必须由使用者提供。
|
||||
|
||||
`SourceEncoding`模板参数指定了`String(const Ch*, ...)`的编码。
|
||||
`SourceEncoding` 模板参数指定了 `String(const Ch*, ...)` 的编码。
|
||||
|
||||
`TargetEncoding`模板参数指定输出流的编码。
|
||||
`TargetEncoding` 模板参数指定输出流的编码。
|
||||
|
||||
最后一个`Allocator`是分配器的类型,用于分配内部数据结构(一个堆栈)。
|
||||
`Allocator` 是分配器的类型,用于分配内部数据结构(一个堆栈)。
|
||||
|
||||
此外,`Writer`的构造函数有一`levelDepth`参数。存储每层阶信息的初始内存分配量受此参数影响。
|
||||
`writeFlags` 是以下位标志的组合:
|
||||
|
||||
写入位标志 | 意义
|
||||
------------------------------|-----------------------------------
|
||||
`kWriteNoFlags` | 没有任何标志。
|
||||
`kWriteDefaultFlags` | 缺省的解析选项。它等于 `RAPIDJSON_WRITE_DEFAULT_FLAGS` 宏,此宏定义为 `kWriteNoFlags`。
|
||||
`kWriteValidateEncodingFlag` | 校验 JSON 字符串的编码。
|
||||
`kWriteNanAndInfFlag` | 容许写入 `Infinity`, `-Infinity` 及 `NaN`。
|
||||
|
||||
此外,`Writer` 的构造函数有一 `levelDepth` 参数。存储每层阶信息的初始内存分配量受此参数影响。
|
||||
|
||||
## PrettyWriter {#PrettyWriter}
|
||||
|
||||
`Writer`所输出的是没有空格字符的最紧凑JSON,适合网络传输或储存,但不适合人类阅读。
|
||||
`Writer` 所输出的是没有空格字符的最紧凑 JSON,适合网络传输或储存,但不适合人类阅读。
|
||||
|
||||
因此,RapidJSON提供了一个`PrettyWriter`,它在输出中加入缩进及换行。
|
||||
因此,RapidJSON 提供了一个 `PrettyWriter`,它在输出中加入缩进及换行。
|
||||
|
||||
`PrettyWriter`的用法与`Writer`几乎一样,不同之处是`PrettyWriter`提供了一个`SetIndent(Ch indentChar, unsigned indentCharCount)`函数。缺省的缩进是4个空格。
|
||||
`PrettyWriter` 的用法与 `Writer` 几乎一样,不同之处是 `PrettyWriter` 提供了一个 `SetIndent(Ch indentChar, unsigned indentCharCount)` 函数。缺省的缩进是 4 个空格。
|
||||
|
||||
## 完整性及重置 {#CompletenessReset}
|
||||
|
||||
一个`Writer`只可输出单个JSON,其根节点可以是任何JSON类型。当处理完单个根节点事件(如`String()`),或匹配的最后`EndObject()`或`EndArray()`事件,输出的JSON是结构完整(well-formed)及完整的。使用者可调用`Writer::IsComplete()`去检测完整性。
|
||||
一个 `Writer` 只可输出单个 JSON,其根节点可以是任何 JSON 类型。当处理完单个根节点事件(如 `String()`),或匹配的最后 `EndObject()` 或 `EndArray()` 事件,输出的 JSON 是结构完整(well-formed)及完整的。使用者可调用 `Writer::IsComplete()` 去检测完整性。
|
||||
|
||||
当JSON完整时,`Writer`不能再接受新的事件。不然其输出便会是不合法的(例如有超过一个根节点)。为了重新利用`Writer`对象,使用者可调用`Writer::Reset(OutputStream& os)`去重置其所有内部状态及设置新的输出流。
|
||||
当 JSON 完整时,`Writer` 不能再接受新的事件。不然其输出便会是不合法的(例如有超过一个根节点)。为了重新利用 `Writer` 对象,使用者可调用 `Writer::Reset(OutputStream& os)` 去重置其所有内部状态及设置新的输出流。
|
||||
|
||||
# 技巧 {#Techniques}
|
||||
# 技巧 {#SaxTechniques}
|
||||
|
||||
## 解析JSON至自定义结构 {#CustomDataStructure}
|
||||
## 解析 JSON 至自定义结构 {#CustomDataStructure}
|
||||
|
||||
`Document`的解析功能完全依靠`Reader`。实际上`Document`是一个处理器,在解析JSON时接收事件去建立一个DOM。
|
||||
`Document` 的解析功能完全依靠 `Reader`。实际上 `Document` 是一个处理器,在解析 JSON 时接收事件去建立一个 DOM。
|
||||
|
||||
使用者可以直接使用`Reader`去建立其他数据结构。这消除了建立DOM的步骤,从而减少了内存开销并改善性能。
|
||||
使用者可以直接使用 `Reader` 去建立其他数据结构。这消除了建立 DOM 的步骤,从而减少了内存开销并改善性能。
|
||||
|
||||
在以下的`messagereader`例子中,`ParseMessages()`解析一个JSON,该JSON应该是一个含键值对的object。
|
||||
在以下的 `messagereader` 例子中,`ParseMessages()` 解析一个 JSON,该 JSON 应该是一个含键值对的 object。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/reader.h"
|
||||
@ -386,15 +396,15 @@ Error: Terminate parsing due to Handler error.
|
||||
at offset 59 near '} }...'
|
||||
~~~~~~~~~~
|
||||
|
||||
第一个JSON(`json1`)被成功地解析至`MessageMap`。由于`MessageMap`是一个`std::map`,打印次序按键值排序。此次序与JSON中的次序不同。
|
||||
第一个 JSON(`json1`)被成功地解析至 `MessageMap`。由于 `MessageMap` 是一个 `std::map`,打印次序按键值排序。此次序与 JSON 中的次序不同。
|
||||
|
||||
在第二个JSON(`json2`)中,`foo`的值是一个空object。由于它是一个object,`MessageHandler::StartObject()`会被调用。然而,在`state_ = kExpectValue`的情况下,该函数会返回`false`,并导致解析过程终止。错误代码是`kParseErrorTermination`。
|
||||
在第二个 JSON(`json2`)中,`foo` 的值是一个空 object。由于它是一个 object,`MessageHandler::StartObject()` 会被调用。然而,在 `state_ = kExpectValue` 的情况下,该函数会返回 `false`,并导致解析过程终止。错误代码是 `kParseErrorTermination`。
|
||||
|
||||
## 过滤JSON {#Filtering}
|
||||
## 过滤 JSON {#Filtering}
|
||||
|
||||
如前面提及过,`Writer`可处理`Reader`发出的事件。`example/condense/condense.cpp`例子简单地设置`Writer`作为一个`Reader`的处理器,因此它能移除JSON中的所有空白字符。`example/pretty/pretty.cpp`例子使用同样的关系,只是以`PrettyWriter`取代`Writer`。因此`pretty`能够重新格式化JSON,加入缩进及换行。
|
||||
如前面提及过,`Writer` 可处理 `Reader` 发出的事件。`example/condense/condense.cpp` 例子简单地设置 `Writer` 作为一个 `Reader` 的处理器,因此它能移除 JSON 中的所有空白字符。`example/pretty/pretty.cpp` 例子使用同样的关系,只是以 `PrettyWriter` 取代 `Writer`。因此 `pretty` 能够重新格式化 JSON,加入缩进及换行。
|
||||
|
||||
实际上,我们可以使用SAX风格API去加入(多个)中间层去过滤JSON的内容。例如`capitalize`例子可以把所有JSON string改为大写。
|
||||
实际上,我们可以使用 SAX 风格 API 去加入(多个)中间层去过滤 JSON 的内容。例如 `capitalize` 例子可以把所有 JSON string 改为大写。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/reader.h"
|
||||
@ -419,6 +429,7 @@ struct CapitalizeFilter {
|
||||
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++)
|
||||
@ -457,20 +468,20 @@ int main(int, char*[]) {
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
注意到,不可简单地把JSON当作字符串去改为大写。例如:
|
||||
注意到,不可简单地把 JSON 当作字符串去改为大写。例如:
|
||||
~~~~~~~~~~
|
||||
["Hello\nWorld"]
|
||||
~~~~~~~~~~
|
||||
|
||||
简单地把整个JSON转为大写的话会产生错误的转义符:
|
||||
简单地把整个 JSON 转为大写的话会产生错误的转义符:
|
||||
~~~~~~~~~~
|
||||
["HELLO\NWORLD"]
|
||||
~~~~~~~~~~
|
||||
|
||||
而`capitalize`就会产生正确的结果:
|
||||
而 `capitalize` 就会产生正确的结果:
|
||||
~~~~~~~~~~
|
||||
["HELLO\nWORLD"]
|
||||
~~~~~~~~~~
|
||||
|
||||
我们还可以开发更复杂的过滤器。然而,由于SAX风格API在某一时间点只能提供单一事件的信息,使用者需要自行记录一些上下文信息(例如从根节点起的路径、储存其他相关值)。对于处理某些情况,用DOM会比SAX更容易实现。
|
||||
我们还可以开发更复杂的过滤器。然而,由于 SAX 风格 API 在某一时间点只能提供单一事件的信息,使用者需要自行记录一些上下文信息(例如从根节点起的路径、储存其他相关值)。对于处理某些情况,用 DOM 会比 SAX 更容易实现。
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
# Schema
|
||||
|
||||
## Status: experimental, shall be included in v1.1
|
||||
(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.
|
||||
|
||||
@ -8,7 +8,7 @@ RapidJSON implemented a JSON Schema validator for [JSON Schema Draft v4](http://
|
||||
|
||||
[TOC]
|
||||
|
||||
## Basic Usage
|
||||
# Basic Usage {#BasicUsage}
|
||||
|
||||
First of all, you need to parse a JSON Schema into `Document`, and then compile the `Document` into a `SchemaDocument`.
|
||||
|
||||
@ -20,7 +20,7 @@ Secondly, construct a `SchemaValidator` with the `SchemaDocument`. It is similar
|
||||
// ...
|
||||
|
||||
Document sd;
|
||||
if (!sd.Parse(schemaJson)) {
|
||||
if (sd.Parse(schemaJson).HasParseError()) {
|
||||
// the schema is not a valid JSON.
|
||||
// ...
|
||||
}
|
||||
@ -28,7 +28,7 @@ SchemaDocument schema(sd); // Compile a Document to SchemaDocument
|
||||
// sd is no longer needed here.
|
||||
|
||||
Document d;
|
||||
if (!d.Parse(inputJson)) {
|
||||
if (d.Parse(inputJson).HasParseError()) {
|
||||
// the input is not a valid JSON.
|
||||
// ...
|
||||
}
|
||||
@ -49,14 +49,14 @@ if (!d.Accept(validator)) {
|
||||
|
||||
Some notes:
|
||||
|
||||
* One `SchemaDocment` can be referenced by multiple `SchemaValidator`s. It will not be modified by `SchemaValidator`s.
|
||||
* One `SchemaDocument` 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
|
||||
# Validation during parsing/serialization {#ParsingSerialization}
|
||||
|
||||
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
|
||||
## DOM parsing {#DomParsing}
|
||||
|
||||
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.
|
||||
|
||||
@ -97,7 +97,7 @@ if (!reader.GetParseResult()) {
|
||||
}
|
||||
~~~
|
||||
|
||||
### SAX parsing
|
||||
## SAX parsing {#SaxParsing}
|
||||
|
||||
For using SAX in parsing, it is much simpler. If it only need to validate the JSON without further processing, it is simply:
|
||||
|
||||
@ -126,7 +126,7 @@ if (!reader.Parse(ss, validator)) {
|
||||
}
|
||||
~~~
|
||||
|
||||
### Serialization
|
||||
## Serialization {#Serialization}
|
||||
|
||||
It is also possible to do validation during serializing. This can ensure the result JSON is valid according to the JSON schema.
|
||||
|
||||
@ -144,20 +144,20 @@ if (!d.Accept(validator)) {
|
||||
|
||||
Of course, if your application only needs SAX-style serialization, it can simply send SAX events to `SchemaValidator` instead of `Writer`.
|
||||
|
||||
## Remote Schema
|
||||
# Remote Schema {#RemoteSchema}
|
||||
|
||||
JSON Schema supports [`$ref` keyword](http://spacetelescope.github.io/understanding-json-schema/structuring.html), which is a [JSON pointer](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:
|
||||
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 `SchemaValidator` does not know how to resolve such URI, it needs a user-provided `IRemoteSchemaDocumentProvider` instance to do so.
|
||||
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) {
|
||||
virtual const SchemaDocument* GetRemoteDocument(const char* uri, SizeType length) {
|
||||
// Resolve the uri and returns a pointer to that schema.
|
||||
}
|
||||
};
|
||||
@ -165,10 +165,10 @@ public:
|
||||
// ...
|
||||
|
||||
MyRemoteSchemaDocumentProvider provider;
|
||||
SchemaValidator validator(schema, &provider);
|
||||
SchemaDocument schema(sd, &provider);
|
||||
~~~
|
||||
|
||||
## Conformance
|
||||
# Conformance {#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).
|
||||
|
||||
@ -176,7 +176,7 @@ The failed test is "changed scope ref invalid" of "change resolution scope" in `
|
||||
|
||||
Besides, the `format` schema keyword for string values is ignored, since it is not required by the specification.
|
||||
|
||||
### Regular Expression
|
||||
## Regular Expression {#RegEx}
|
||||
|
||||
The schema keyword `pattern` and `patternProperties` uses regular expression to match the required pattern.
|
||||
|
||||
@ -184,34 +184,34 @@ RapidJSON implemented a simple NFA regular expression engine, which is used by d
|
||||
|
||||
|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)
|
||||
|`ab` | Concatenation |
|
||||
|<code>a|b</code> | 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) |
|
||||
|<code>\\|</code>, `\\`, ... | 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
|
||||
# Performance {#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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
# Schema
|
||||
|
||||
## 状态: 实验性,应该会合进 v1.1
|
||||
(本功能于 v1.1.0 发布)
|
||||
|
||||
JSON Schema 是描述 JSON 格式的一个标准草案。一个 schema 本身也是一个 JSON。使用 JSON Schema 去校验 JSON,可以让你的代码安全地访问 DOM,而无须检查类型或键值是否存在等。这也能确保输出的 JSON 是符合指定的 schema。
|
||||
|
||||
@ -8,7 +8,7 @@ RapidJSON 实现了一个 [JSON Schema Draft v4](http://json-schema.org/document
|
||||
|
||||
[TOC]
|
||||
|
||||
## 基本用法
|
||||
# 基本用法 {#BasicUsage}
|
||||
|
||||
首先,你要把 JSON Schema 解析成 `Document`,再把它编译成一个 `SchemaDocument`。
|
||||
|
||||
@ -20,23 +20,23 @@ RapidJSON 实现了一个 [JSON Schema Draft v4](http://json-schema.org/document
|
||||
// ...
|
||||
|
||||
Document sd;
|
||||
if (!sd.Parse(schemaJson)) {
|
||||
// the schema is not a valid JSON.
|
||||
if (sd.Parse(schemaJson).HasParseError()) {
|
||||
// 此 schema 不是合法的 JSON
|
||||
// ...
|
||||
}
|
||||
SchemaDocument schema(sd); // Compile a Document to SchemaDocument
|
||||
// sd is no longer needed here.
|
||||
SchemaDocument schema(sd); // 把一个 Document 编译至 SchemaDocument
|
||||
// 之后不再需要 sd
|
||||
|
||||
Document d;
|
||||
if (!d.Parse(inputJson)) {
|
||||
// the input is not a valid JSON.
|
||||
if (d.Parse(inputJson).HasParseError()) {
|
||||
// 输入不是一个合法的 JSON
|
||||
// ...
|
||||
}
|
||||
|
||||
SchemaValidator validator(schema);
|
||||
if (!d.Accept(validator)) {
|
||||
// Input JSON is invalid according to the schema
|
||||
// Output diagnostic information
|
||||
// 输入的 JSON 不合乎 schema
|
||||
// 打印诊断信息
|
||||
StringBuffer sb;
|
||||
validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
|
||||
printf("Invalid schema: %s\n", sb.GetString());
|
||||
@ -49,14 +49,14 @@ if (!d.Accept(validator)) {
|
||||
|
||||
一些注意点:
|
||||
|
||||
* 一个 `SchemaDocment` 能被多个 `SchemaValidator` 吊用。它不会被 `SchemaValidator` 修改。
|
||||
* 一个 `SchemaValidator` 可以重复使用来校验多个文件。在校验其他文件前,先调用 `validator.Reset()`。
|
||||
* 一个 `SchemaDocment` 能被多个 `SchemaValidator` 引用。它不会被 `SchemaValidator` 修改。
|
||||
* 可以重复使用一个 `SchemaValidator` 来校验多个文件。在校验其他文件前,须先调用 `validator.Reset()`。
|
||||
|
||||
## 在解析/生成时进行校验
|
||||
# 在解析/生成时进行校验 {#ParsingSerialization}
|
||||
|
||||
与大部分 JSON Schema 校验器有所不同,RapidJSON 提供了一个基于 SAX 的 schema 校验器实现。因此,你可以在输入流解析 JSON 的同时进行校验。若校验器遇到一个与 schema 不符的值,就会立即终止解析。这设计对于解析大型 JSON 文件时特别有用。
|
||||
|
||||
### DOM 解析
|
||||
## DOM 解析 {#DomParsing}
|
||||
|
||||
在使用 DOM 进行解析时,`Document` 除了接收 SAX 事件外,还需做一些准备及结束工作,因此,为了连接 `Reader`、`SchemaValidator` 和 `Document` 要做多一点事情。`SchemaValidatingReader` 是一个辅助类去做那些工作。
|
||||
|
||||
@ -64,28 +64,28 @@ if (!d.Accept(validator)) {
|
||||
#include "rapidjson/filereadstream.h"
|
||||
|
||||
// ...
|
||||
SchemaDocument schema(sd); // Compile a Document to SchemaDocument
|
||||
SchemaDocument schema(sd); // 把一个 Document 编译至 SchemaDocument
|
||||
|
||||
// Use reader to parse the JSON
|
||||
// 使用 reader 解析 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.
|
||||
// 用 reader 解析 JSON,校验它的 SAX 事件,并存储至 d
|
||||
Document d;
|
||||
SchemaValidatingReader<kParseDefaultFlags, FileReadStream, UTF8<> > 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.
|
||||
// 不是一个合法的 JSON
|
||||
// 当 reader.GetParseResult().Code() == kParseErrorTermination,
|
||||
// 它可能是被以下原因中止:
|
||||
// (1) 校验器发现 JSON 不合乎 schema;或
|
||||
// (2) 输入流有 I/O 错误。
|
||||
|
||||
// Check the validation result
|
||||
// 检查校验结果
|
||||
if (!reader.IsValid()) {
|
||||
// Input JSON is invalid according to the schema
|
||||
// Output diagnostic information
|
||||
// 输入的 JSON 不合乎 schema
|
||||
// 打印诊断信息
|
||||
StringBuffer sb;
|
||||
reader.GetInvalidSchemaPointer().StringifyUriFragment(sb);
|
||||
printf("Invalid schema: %s\n", sb.GetString());
|
||||
@ -97,7 +97,7 @@ if (!reader.GetParseResult()) {
|
||||
}
|
||||
~~~
|
||||
|
||||
### SAX 解析
|
||||
## SAX 解析 {#SaxParsing}
|
||||
|
||||
使用 SAX 解析时,情况就简单得多。若只需要校验 JSON 而无需进一步处理,那么仅需要:
|
||||
|
||||
@ -126,7 +126,7 @@ if (!reader.Parse(ss, validator)) {
|
||||
}
|
||||
~~~
|
||||
|
||||
### 生成
|
||||
## 生成 {#Serialization}
|
||||
|
||||
我们也可以在生成(serialization)的时候进行校验。这能确保输出的 JSON 符合一个 JSON Schema。
|
||||
|
||||
@ -144,20 +144,20 @@ if (!d.Accept(validator)) {
|
||||
|
||||
当然,如果你的应用仅需要 SAX 风格的生成,那么只需要把 SAX 事件由原来发送到 `Writer`,改为发送到 `SchemaValidator`。
|
||||
|
||||
## 远程 Schema
|
||||
# 远程 Schema {#RemoteSchema}
|
||||
|
||||
JSON Schema 支持 [`$ref` 关键字](http://spacetelescope.github.io/understanding-json-schema/structuring.html),它是一个[JSON pointer](pointer.md) 引用至一个本地(local)或远程(remote) schema。本地指针的首字符是 `#`,而远程指针是一个相对或绝对 URI。例如:
|
||||
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" }
|
||||
~~~
|
||||
|
||||
由于 `SchemaValidator` 并不知道如何处理那些 URI,它需要使用者提供一个 `IRemoteSchemaDocumentProvider` 的实例去处理。
|
||||
由于 `SchemaDocument` 并不知道如何处理那些 URI,它需要使用者提供一个 `IRemoteSchemaDocumentProvider` 的实例去处理。
|
||||
|
||||
~~~
|
||||
class MyRemoteSchemaDocumentProvider : public IRemoteSchemaDocumentProvider {
|
||||
public:
|
||||
virtual const SchemaDocument* GetRemoteDocument(const char* uri, SizeTyp length) {
|
||||
virtual const SchemaDocument* GetRemoteDocument(const char* uri, SizeType length) {
|
||||
// Resolve the uri and returns a pointer to that schema.
|
||||
}
|
||||
};
|
||||
@ -165,10 +165,10 @@ public:
|
||||
// ...
|
||||
|
||||
MyRemoteSchemaDocumentProvider provider;
|
||||
SchemaValidator validator(schema, &provider);
|
||||
SchemaDocument schema(sd, &provider);
|
||||
~~~
|
||||
|
||||
## 标准的符合程度
|
||||
# 标准的符合程度 {#Conformance}
|
||||
|
||||
RapidJSON 通过了 [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (Json Schema draft 4) 中 263 个测试的 262 个。
|
||||
|
||||
@ -176,7 +176,7 @@ RapidJSON 通过了 [JSON Schema Test Suite](https://github.com/json-schema/JSON
|
||||
|
||||
除此以外,关于字符串类型的 `format` schema 关键字也会被忽略,因为标准中并没需求必须实现。
|
||||
|
||||
### 正则表达式
|
||||
## 正则表达式 {#RegEx}
|
||||
|
||||
`pattern` 及 `patternProperties` 这两个 schema 关键字使用了正则表达式去匹配所需的模式。
|
||||
|
||||
@ -184,34 +184,34 @@ 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)
|
||||
|`ab` | 串联 |
|
||||
|<code>a|b</code> | 交替 |
|
||||
|`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) |
|
||||
|<code>\\|</code>, `\\`, ... | 转义字符 |
|
||||
|`\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`,可以把两个宏都设为零,以禁用此功能,这样做可节省一些代码体积。
|
||||
|
||||
## 性能
|
||||
# 性能 {#Performance}
|
||||
|
||||
大部分 C++ JSON 库都未支持 JSON Schema。因此我们尝试按照 [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) 去评估 RapidJSON 的 JSON Schema 校验器。该评测测试了 11 个运行在 node.js 上的 JavaScript 库。
|
||||
|
||||
|
@ -1,16 +1,16 @@
|
||||
# 流
|
||||
|
||||
在RapidJSON中,`rapidjson::Stream`是用於读写JSON的概念(概念是指C++的concept)。在这里我们先介绍如何使用RapidJSON提供的各种流。然后再看看如何自行定义流。
|
||||
在 RapidJSON 中,`rapidjson::Stream` 是用於读写 JSON 的概念(概念是指 C++ 的 concept)。在这里我们先介绍如何使用 RapidJSON 提供的各种流。然后再看看如何自行定义流。
|
||||
|
||||
[TOC]
|
||||
|
||||
# 内存流 {#MemoryStreams}
|
||||
|
||||
内存流把JSON存储在内存之中。
|
||||
内存流把 JSON 存储在内存之中。
|
||||
|
||||
## StringStream(输入){#StringStream}
|
||||
|
||||
`StringStream`是最基本的输入流,它表示一个完整的、只读的、存储于内存的JSON。它在`rapidjson/rapidjson.h`中定义。
|
||||
`StringStream` 是最基本的输入流,它表示一个完整的、只读的、存储于内存的 JSON。它在 `rapidjson/rapidjson.h` 中定义。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/document.h" // 会包含 "rapidjson/rapidjson.h"
|
||||
@ -25,7 +25,7 @@ Document d;
|
||||
d.ParseStream(s);
|
||||
~~~~~~~~~~
|
||||
|
||||
由于这是非常常用的用法,RapidJSON提供`Document::Parse(const char*)`去做完全相同的事情:
|
||||
由于这是非常常用的用法,RapidJSON 提供 `Document::Parse(const char*)` 去做完全相同的事情:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// ...
|
||||
@ -34,11 +34,11 @@ Document d;
|
||||
d.Parse(json);
|
||||
~~~~~~~~~~
|
||||
|
||||
需要注意,`StringStream`是`GenericStringStream<UTF8<> >`的typedef,使用者可用其他编码类去代表流所使用的字符集。
|
||||
需要注意,`StringStream` 是 `GenericStringStream<UTF8<> >` 的 typedef,使用者可用其他编码类去代表流所使用的字符集。
|
||||
|
||||
## StringBuffer(输出){#StringBuffer}
|
||||
|
||||
`StringBuffer`是一个简单的输出流。它分配一个内存缓冲区,供写入整个JSON。可使用`GetString()`来获取该缓冲区。
|
||||
`StringBuffer` 是一个简单的输出流。它分配一个内存缓冲区,供写入整个 JSON。可使用 `GetString()` 来获取该缓冲区。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
@ -50,26 +50,26 @@ d.Accept(writer);
|
||||
const char* output = buffer.GetString();
|
||||
~~~~~~~~~~
|
||||
|
||||
当缓冲区满溢,它将自动增加容量。缺省容量是256个字符(UTF8是256字节,UTF16是512字节等)。使用者能自行提供分配器及初始容量。
|
||||
当缓冲区满溢,它将自动增加容量。缺省容量是 256 个字符(UTF8 是 256 字节,UTF16 是 512 字节等)。使用者能自行提供分配器及初始容量。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
StringBuffer buffer1(0, 1024); // 使用它的分配器,初始大小 = 1024
|
||||
StringBuffer buffer2(allocator, 1024);
|
||||
~~~~~~~~~~
|
||||
|
||||
如无设置分配器,`StringBuffer`会自行实例化一个内部分配器。
|
||||
如无设置分配器,`StringBuffer` 会自行实例化一个内部分配器。
|
||||
|
||||
相似地,`StringBuffer`是`GenericStringBuffer<UTF8<> >`的typedef。
|
||||
相似地,`StringBuffer` 是 `GenericStringBuffer<UTF8<> >` 的 typedef。
|
||||
|
||||
# 文件流 {#FileStreams}
|
||||
|
||||
当要从文件解析一个JSON,你可以把整个JSON读入内存并使用上述的`StringStream`。
|
||||
当要从文件解析一个 JSON,你可以把整个 JSON 读入内存并使用上述的 `StringStream`。
|
||||
|
||||
然而,若JSON很大,或是内存有限,你可以改用`FileReadStream`。它只会从文件读取一部分至缓冲区,然后让那部分被解析。若缓冲区的字符都被读完,它会再从文件读取下一部分。
|
||||
然而,若 JSON 很大,或是内存有限,你可以改用 `FileReadStream`。它只会从文件读取一部分至缓冲区,然后让那部分被解析。若缓冲区的字符都被读完,它会再从文件读取下一部分。
|
||||
|
||||
## FileReadStream(输入) {#FileReadStream}
|
||||
|
||||
`FileReadStream`通过`FILE`指针读取文件。使用者需要提供一个缓冲区。
|
||||
`FileReadStream` 通过 `FILE` 指针读取文件。使用者需要提供一个缓冲区。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/filereadstream.h"
|
||||
@ -77,7 +77,7 @@ StringBuffer buffer2(allocator, 1024);
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
FILE* fp = fopen("big.json", "rb"); // 非Windows平台使用"r"
|
||||
FILE* fp = fopen("big.json", "rb"); // 非 Windows 平台使用 "r"
|
||||
|
||||
char readBuffer[65536];
|
||||
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
|
||||
@ -88,13 +88,13 @@ d.ParseStream(is);
|
||||
fclose(fp);
|
||||
~~~~~~~~~~
|
||||
|
||||
与`StringStreams`不一样,`FileReadStream`是一个字节流。它不处理编码。若文件并非UTF-8编码,可以把字节流用`EncodedInputStream`包装。我们很快会讨论这个问题。
|
||||
与 `StringStreams` 不一样,`FileReadStream` 是一个字节流。它不处理编码。若文件并非 UTF-8 编码,可以把字节流用 `EncodedInputStream` 包装。我们很快会讨论这个问题。
|
||||
|
||||
除了读取文件,使用者也可以使用`FileReadStream`来读取`stdin`。
|
||||
除了读取文件,使用者也可以使用 `FileReadStream` 来读取 `stdin`。
|
||||
|
||||
## FileWriteStream(输出){#FileWriteStream}
|
||||
|
||||
`FileWriteStream`是一个含缓冲功能的输出流。它的用法与`FileReadStream`非常相似。
|
||||
`FileWriteStream` 是一个含缓冲功能的输出流。它的用法与 `FileReadStream` 非常相似。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/filewritestream.h"
|
||||
@ -106,7 +106,7 @@ Document d;
|
||||
d.Parse(json);
|
||||
// ...
|
||||
|
||||
FILE* fp = fopen("output.json", "wb"); // 非Windows平台使用"w"
|
||||
FILE* fp = fopen("output.json", "wb"); // 非 Windows 平台使用 "w"
|
||||
|
||||
char writeBuffer[65536];
|
||||
FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
|
||||
@ -117,11 +117,11 @@ d.Accept(writer);
|
||||
fclose(fp);
|
||||
~~~~~~~~~~
|
||||
|
||||
它也可以把输出导向`stdout`。
|
||||
它也可以把输出导向 `stdout`。
|
||||
|
||||
# iostream 包装类 {#iostreamWrapper}
|
||||
|
||||
基于用户的要求,RapidJSON提供了正式的 `std::basic_istream` 和 `std::basic_ostream` 包装类。然而,请注意其性能会大大低于以上的其他流。
|
||||
基于用户的要求,RapidJSON 提供了正式的 `std::basic_istream` 和 `std::basic_ostream` 包装类。然而,请注意其性能会大大低于以上的其他流。
|
||||
|
||||
## IStreamWrapper {#IStreamWrapper}
|
||||
|
||||
@ -173,19 +173,19 @@ d.Accept(writer);
|
||||
|
||||
# 编码流 {#EncodedStreams}
|
||||
|
||||
编码流(encoded streams)本身不存储JSON,它们是通过包装字节流来提供基本的编码/解码功能。
|
||||
编码流(encoded streams)本身不存储 JSON,它们是通过包装字节流来提供基本的编码/解码功能。
|
||||
|
||||
如上所述,我们可以直接读入UTF-8字节流。然而,UTF-16及UTF-32有字节序(endian)问题。要正确地处理字节序,需要在读取时把字节转换成字符(如对UTF-16使用`wchar_t`),以及在写入时把字符转换为字节。
|
||||
如上所述,我们可以直接读入 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。
|
||||
除此以外,我们也需要处理 [字节顺序标记(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` 及 `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`。第二个参数是被包装的流的类型。
|
||||
`EncodedInputStream` 含两个模板参数。第一个是 `Encoding` 类型,例如定义于 `rapidjson/encodings.h` 的 `UTF8`、`UTF16LE`。第二个参数是被包装的流的类型。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/document.h"
|
||||
@ -195,50 +195,50 @@ d.Accept(writer);
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
FILE* fp = fopen("utf16le.json", "rb"); // 非Windows平台使用"r"
|
||||
FILE* fp = fopen("utf16le.json", "rb"); // 非 Windows 平台使用 "r"
|
||||
|
||||
char readBuffer[256];
|
||||
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
|
||||
|
||||
EncodedInputStream<UTF16LE<>, FileReadStream> eis(bis); // 用eis包装bis
|
||||
EncodedInputStream<UTF16LE<>, FileReadStream> eis(bis); // 用 eis 包装 bis
|
||||
|
||||
Document d; // Document为GenericDocument<UTF8<> >
|
||||
d.ParseStream<0, UTF16LE<> >(eis); // 把UTF-16LE文件解析至内存中的UTF-8
|
||||
Document d; // Document 为 GenericDocument<UTF8<> >
|
||||
d.ParseStream<0, UTF16LE<> >(eis); // 把 UTF-16LE 文件解析至内存中的 UTF-8
|
||||
|
||||
fclose(fp);
|
||||
~~~~~~~~~~
|
||||
|
||||
## EncodedOutputStream {#EncodedOutputStream}
|
||||
|
||||
`EncodedOutputStream`也是相似的,但它的构造函数有一个`bool putBOM`参数,用于控制是否在输出字节流写入BOM。
|
||||
`EncodedOutputStream` 也是相似的,但它的构造函数有一个 `bool putBOM` 参数,用于控制是否在输出字节流写入 BOM。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/filewritestream.h" // FileWriteStream
|
||||
#include "rapidjson/encodedstream.h" // EncodedOutputStream
|
||||
#include <cstdio>
|
||||
|
||||
Document d; // Document为GenericDocument<UTF8<> >
|
||||
Document d; // Document 为 GenericDocument<UTF8<> >
|
||||
// ...
|
||||
|
||||
FILE* fp = fopen("output_utf32le.json", "wb"); // 非Windows平台使用"w"
|
||||
FILE* fp = fopen("output_utf32le.json", "wb"); // 非 Windows 平台使用 "w"
|
||||
|
||||
char writeBuffer[256];
|
||||
FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer));
|
||||
|
||||
typedef EncodedOutputStream<UTF32LE<>, FileWriteStream> OutputStream;
|
||||
OutputStream eos(bos, true); // 写入BOM
|
||||
OutputStream eos(bos, true); // 写入 BOM
|
||||
|
||||
Writer<OutputStream, UTF32LE<>, UTF8<>> writer(eos);
|
||||
d.Accept(writer); // 这里从内存的UTF-8生成UTF32-LE文件
|
||||
d.Accept(writer); // 这里从内存的 UTF-8 生成 UTF32-LE 文件
|
||||
|
||||
fclose(fp);
|
||||
~~~~~~~~~~
|
||||
|
||||
## AutoUTFInputStream {#AutoUTFInputStream}
|
||||
|
||||
有时候,应用软件可能需要㲃理所有可支持的JSON编码。`AutoUTFInputStream`会先使用BOM来检测编码。若BOM不存在,它便会使用合法JSON的特性来检测。若两种方法都失败,它就会倒退至构造函数提供的UTF类型。
|
||||
有时候,应用软件可能需要㲃理所有可支持的 JSON 编码。`AutoUTFInputStream` 会先使用 BOM 来检测编码。若 BOM 不存在,它便会使用合法 JSON 的特性来检测。若两种方法都失败,它就会倒退至构造函数提供的 UTF 类型。
|
||||
|
||||
由于字符(编码单元/code unit)可能是8位、16位或32位,`AutoUTFInputStream` 需要一个能至少储存32位的字符类型。我们可以使用`unsigned`作为模板参数:
|
||||
由于字符(编码单元/code unit)可能是 8 位、16 位或 32 位,`AutoUTFInputStream` 需要一个能至少储存 32 位的字符类型。我们可以使用 `unsigned` 作为模板参数:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/document.h"
|
||||
@ -248,26 +248,26 @@ fclose(fp);
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
FILE* fp = fopen("any.json", "rb"); // 非Windows平台使用"r"
|
||||
FILE* fp = fopen("any.json", "rb"); // 非 Windows 平台使用 "r"
|
||||
|
||||
char readBuffer[256];
|
||||
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
|
||||
|
||||
AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // 用eis包装bis
|
||||
AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // 用 eis 包装 bis
|
||||
|
||||
Document d; // Document为GenericDocument<UTF8<> >
|
||||
d.ParseStream<0, AutoUTF<unsigned> >(eis); // 把任何UTF编码的文件解析至内存中的UTF-8
|
||||
Document d; // Document 为 GenericDocument<UTF8<> >
|
||||
d.ParseStream<0, AutoUTF<unsigned> >(eis); // 把任何 UTF 编码的文件解析至内存中的 UTF-8
|
||||
|
||||
fclose(fp);
|
||||
~~~~~~~~~~
|
||||
|
||||
当要指定流的编码,可使用上面例子中`ParseStream()`的参数`AutoUTF<CharType>`。
|
||||
当要指定流的编码,可使用上面例子中 `ParseStream()` 的参数 `AutoUTF<CharType>`。
|
||||
|
||||
你可以使用`UTFType GetType()`去获取UTF类型,并且用`HasBOM()`检测输入流是否含有BOM。
|
||||
你可以使用 `UTFType GetType()` 去获取 UTF 类型,并且用 `HasBOM()` 检测输入流是否含有 BOM。
|
||||
|
||||
## AutoUTFOutputStream {#AutoUTFOutputStream}
|
||||
|
||||
相似地,要在运行时选择输出的编码,我们可使用`AutoUTFOutputStream`。这个类本身并非「自动」。你需要在运行时指定UTF类型,以及是否写入BOM。
|
||||
相似地,要在运行时选择输出的编码,我们可使用 `AutoUTFOutputStream`。这个类本身并非「自动」。你需要在运行时指定 UTF 类型,以及是否写入 BOM。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
using namespace rapidjson;
|
||||
@ -284,13 +284,13 @@ void WriteJSONFile(FILE* fp, UTFType type, bool putBOM, const Document& d) {
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
`AutoUTFInputStream`/`AutoUTFOutputStream`是比`EncodedInputStream`/`EncodedOutputStream`方便。但前者会产生一点运行期额外开销。
|
||||
`AutoUTFInputStream`/`AutoUTFOutputStream` 是比 `EncodedInputStream`/`EncodedOutputStream` 方便。但前者会产生一点运行期额外开销。
|
||||
|
||||
# 自定义流 {#CustomStream}
|
||||
|
||||
除了内存/文件流,使用者可创建自行定义适配RapidJSON API的流类。例如,你可以创建网络流、从压缩文件读取的流等等。
|
||||
除了内存/文件流,使用者可创建自行定义适配 RapidJSON API 的流类。例如,你可以创建网络流、从压缩文件读取的流等等。
|
||||
|
||||
RapidJSON利用模板结合不同的类型。只要一个类包含所有所需的接口,就可以作为一个流。流的接合定义在`rapidjson/rapidjson.h`的注释里:
|
||||
RapidJSON 利用模板结合不同的类型。只要一个类包含所有所需的接口,就可以作为一个流。流的接合定义在 `rapidjson/rapidjson.h` 的注释里:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
concept Stream {
|
||||
@ -317,19 +317,19 @@ concept Stream {
|
||||
void Flush();
|
||||
|
||||
//! 完成写作操作。
|
||||
//! \param begin PutBegin()返回的开始写入指针。
|
||||
//! \param begin PutBegin() 返回的开始写入指针。
|
||||
//! \return 已写入的字符数量。
|
||||
size_t PutEnd(Ch* begin);
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
输入流必须实现`Peek()`、`Take()`及`Tell()`。
|
||||
输出流必须实现`Put()`及`Flush()`。
|
||||
`PutBegin()`及`PutEnd()`是特殊的接口,仅用于原位(*in situ*)解析。一般的流不需实现它们。然而,即使接口不需用于某些流,仍然需要提供空实现,否则会产生编译错误。
|
||||
输入流必须实现 `Peek()`、`Take()` 及 `Tell()`。
|
||||
输出流必须实现 `Put()` 及 `Flush()`。
|
||||
`PutBegin()` 及 `PutEnd()` 是特殊的接口,仅用于原位(*in situ*)解析。一般的流不需实现它们。然而,即使接口不需用于某些流,仍然需要提供空实现,否则会产生编译错误。
|
||||
|
||||
## 例子:istream的包装类 {#ExampleIStreamWrapper}
|
||||
## 例子:istream 的包装类 {#ExampleIStreamWrapper}
|
||||
|
||||
以下的简单例子是`std::istream`的包装类,它只需现3个函数。
|
||||
以下的简单例子是 `std::istream` 的包装类,它只需现 3 个函数。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
class MyIStreamWrapper {
|
||||
@ -364,7 +364,7 @@ private:
|
||||
};
|
||||
~~~~~~~~~~
|
||||
|
||||
使用者能用它来包装`std::stringstream`、`std::ifstream`的实例。
|
||||
使用者能用它来包装 `std::stringstream`、`std::ifstream` 的实例。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
const char* json = "[1,2,3,4]";
|
||||
@ -375,11 +375,11 @@ Document d;
|
||||
d.ParseStream(is);
|
||||
~~~~~~~~~~
|
||||
|
||||
但要注意,由于标准库的内部开销问,此实现的性能可能不如RapidJSON的内存/文件流。
|
||||
但要注意,由于标准库的内部开销问,此实现的性能可能不如 RapidJSON 的内存/文件流。
|
||||
|
||||
## 例子:ostream的包装类 {#ExampleOStreamWrapper}
|
||||
## 例子:ostream 的包装类 {#ExampleOStreamWrapper}
|
||||
|
||||
以下的例子是`std::istream`的包装类,它只需实现2个函数。
|
||||
以下的例子是 `std::istream` 的包装类,它只需实现 2 个函数。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
class MyOStreamWrapper {
|
||||
@ -406,7 +406,7 @@ private:
|
||||
};
|
||||
~~~~~~~~~~
|
||||
|
||||
使用者能用它来包装`std::stringstream`、`std::ofstream`的实例。
|
||||
使用者能用它来包装 `std::stringstream`、`std::ofstream` 的实例。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Document d;
|
||||
@ -419,8 +419,8 @@ Writer<MyOStreamWrapper> writer(os);
|
||||
d.Accept(writer);
|
||||
~~~~~~~~~~
|
||||
|
||||
但要注意,由于标准库的内部开销问,此实现的性能可能不如RapidJSON的内存/文件流。
|
||||
但要注意,由于标准库的内部开销问,此实现的性能可能不如 RapidJSON 的内存/文件流。
|
||||
|
||||
# 总结 {#Summary}
|
||||
|
||||
本节描述了RapidJSON提供的各种流的类。内存流很简单。若JSON存储在文件中,文件流可减少JSON解析及生成所需的内存量。编码流在字节流和字符流之间作转换。最后,使用者可使用一个简单接口创建自定义的流。
|
||||
本节描述了 RapidJSON 提供的各种流的类。内存流很简单。若 JSON 存储在文件中,文件流可减少 JSON 解析及生成所需的内存量。编码流在字节流和字符流之间作转换。最后,使用者可使用一个简单接口创建自定义的流。
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
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.
|
||||
As shown in [Usage at a glance](@ref index), JSON can be parsed into a DOM, and then the DOM can be queried and modified easily, and finally be converted back to JSON.
|
||||
|
||||
[TOC]
|
||||
|
||||
@ -14,7 +14,7 @@ Each JSON value is stored in a type called `Value`. A `Document`, representing t
|
||||
|
||||
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`):
|
||||
Assume we have the following JSON stored in a C string (`const char* json`):
|
||||
~~~~~~~~~~js
|
||||
{
|
||||
"hello": "world",
|
||||
@ -55,7 +55,7 @@ printf("hello = %s\n", document["hello"].GetString());
|
||||
~~~~~~~~~~
|
||||
|
||||
~~~~~~~~~~
|
||||
world
|
||||
hello = world
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON true/false values are represented as `bool`.
|
||||
@ -65,16 +65,16 @@ printf("t = %s\n", document["t"].GetBool() ? "true" : "false");
|
||||
~~~~~~~~~~
|
||||
|
||||
~~~~~~~~~~
|
||||
true
|
||||
t = true
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON null can be queryed by `IsNull()`.
|
||||
JSON null can be queried with `IsNull()`.
|
||||
~~~~~~~~~~cpp
|
||||
printf("n = %s\n", document["n"].IsNull() ? "null" : "?");
|
||||
~~~~~~~~~~
|
||||
|
||||
~~~~~~~~~~
|
||||
null
|
||||
n = null
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON number type represents all numeric values. However, C++ needs more specific type for manipulation.
|
||||
@ -115,15 +115,15 @@ 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.
|
||||
In the following sections we discuss details about querying individual types.
|
||||
|
||||
## Query Array {#QueryArray}
|
||||
|
||||
By default, `SizeType` is typedef of `unsigned`. In most systems, array is limited to store up to 2^32-1 elements.
|
||||
By default, `SizeType` is typedef of `unsigned`. In most systems, an 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]`.
|
||||
You may access the elements in an 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.
|
||||
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());
|
||||
@ -133,9 +133,18 @@ 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:
|
||||
Similar to Array, we can access all object members by iterator:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
static const char* kTypeNames[] =
|
||||
@ -166,16 +175,26 @@ If we are unsure whether a member exists, we need to call `HasMember()` before c
|
||||
~~~~~~~~~~cpp
|
||||
Value::ConstMemberIterator itr = document.FindMember("hello");
|
||||
if (itr != document.MemberEnd())
|
||||
printf("%s %s\n", itr->value.GetString());
|
||||
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.
|
||||
JSON provides a single numerical type called Number. Number can be an integer or a real number. RFC 4627 says the range of Number is specified by the parser implementation.
|
||||
|
||||
As C++ provides several integer and floating point number types, the DOM tries to handle these with widest possible range and good performance.
|
||||
As C++ provides several integer and floating point number types, the DOM tries to handle these with the widest possible range and good performance.
|
||||
|
||||
When a Number is parsed, it is stored in the DOM as either one of the following type:
|
||||
When a Number is parsed, it is stored in the DOM as one of the following types:
|
||||
|
||||
Type | Description
|
||||
-----------|---------------------------------------
|
||||
@ -185,7 +204,7 @@ Type | Description
|
||||
`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:
|
||||
When querying a number, you can check whether the number can be obtained as the target type:
|
||||
|
||||
Checking | Obtaining
|
||||
------------------|---------------------
|
||||
@ -196,9 +215,9 @@ Checking | Obtaining
|
||||
`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`.
|
||||
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 make `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).
|
||||
When obtaining the numeric values, `GetDouble()` will convert internal integer representation to a `double`. Note that, `int` and `unsigned` can be safely converted to `double`, but `int64_t` and `uint64_t` may lose precision (since mantissa of `double` is only 52-bits).
|
||||
|
||||
## Query String {#QueryString}
|
||||
|
||||
@ -206,7 +225,7 @@ In addition to `GetString()`, the `Value` class also contains `GetStringLength()
|
||||
|
||||
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.
|
||||
To conform RFC 4627, RapidJSON supports string containing `U+0000`. If you need to handle this, you can use `GetStringLength()` to obtain the correct string length.
|
||||
|
||||
For example, after parsing a the following JSON to `Document d`:
|
||||
|
||||
@ -341,14 +360,14 @@ a.PushBack(Value(42).Move(), allocator); // same as above
|
||||
~~~~~~~~~~
|
||||
|
||||
## Create String {#CreateString}
|
||||
RapidJSON provide two strategies for storing string.
|
||||
RapidJSON provides 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.
|
||||
Copy-string is always safe because it owns a copy of the data. Const-string can be used for storing a string literal, and for in-situ parsing which will be mentioned in the DOM 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.
|
||||
To make memory allocation customizable, RapidJSON requires users 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:
|
||||
|
||||
@ -366,7 +385,7 @@ In this example, we get the allocator from a `Document` instance. This is a comm
|
||||
|
||||
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:
|
||||
Finally, for a string literal or string with a safe life-cycle one can use the const-string version of `SetString()`, which lacks an allocator parameter. For string literals (or constant character arrays), simply passing the literal as parameter is safe and efficient:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value s;
|
||||
@ -374,7 +393,7 @@ s.SetString("rapidjson"); // can contain null character, length derived at co
|
||||
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:
|
||||
For a character pointer, RapidJSON requires it to be marked as safe before using it without copying. This can be achieved by using the `StringRef` function:
|
||||
|
||||
~~~~~~~~~cpp
|
||||
const char * cstr = getenv("USER");
|
||||
@ -389,7 +408,7 @@ s = StringRef(cstr,cstr_len); // shortcut, same as above
|
||||
~~~~~~~~~
|
||||
|
||||
## Modify Array {#ModifyArray}
|
||||
Value with array type provides similar APIs as `std::vector`.
|
||||
Value with array type provides an API similar to `std::vector`.
|
||||
|
||||
* `Clear()`
|
||||
* `Reserve(SizeType, Allocator&)`
|
||||
@ -399,7 +418,7 @@ Value with array type provides similar APIs as `std::vector`.
|
||||
* `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.
|
||||
Note that, `Reserve(...)` and `PushBack(...)` may allocate memory for the array elements, therefore requiring an allocator.
|
||||
|
||||
Here is an example of `PushBack()`:
|
||||
|
||||
@ -414,7 +433,7 @@ for (int i = 5; i <= 10; i++)
|
||||
a.PushBack("Lua", allocator).PushBack("Mio", allocator);
|
||||
~~~~~~~~~~
|
||||
|
||||
Differs from STL, `PushBack()`/`PopBack()` returns the array reference itself. This is called _fluent interface_.
|
||||
This API differs from STL in that `PushBack()`/`PopBack()` return 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:
|
||||
|
||||
@ -429,7 +448,7 @@ 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:
|
||||
The Object class 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 API is for adding members:
|
||||
|
||||
* `Value& AddMember(Value&, Value&, Allocator& allocator)`
|
||||
* `Value& AddMember(StringRefType, Value&, Allocator&)`
|
||||
@ -443,7 +462,7 @@ 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.
|
||||
The name parameter with `StringRefType` is similar to the interface of the `SetString` function for string values. These overloads are used to avoid the need for copying the `name` string, since 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:
|
||||
|
||||
|
@ -2,19 +2,19 @@
|
||||
|
||||
本教程简介文件对象模型(Document Object Model, DOM)API。
|
||||
|
||||
如[用法一览](../readme.zh-cn.md#用法一览)中所示,可以解析一个JSON至DOM,然后就可以轻松查询及修改DOM,并最终转换回JSON。
|
||||
如 [用法一览](../readme.zh-cn.md#用法一览) 中所示,可以解析一个 JSON 至 DOM,然后就可以轻松查询及修改 DOM,并最终转换回 JSON。
|
||||
|
||||
[TOC]
|
||||
|
||||
# Value 及 Document {#ValueDocument}
|
||||
|
||||
每个JSON值都储存为`Value`类,而`Document`类则表示整个DOM,它存储了一个DOM树的根`Value`。RapidJSON的所有公开类型及函数都在`rapidjson`命名空间中。
|
||||
每个 JSON 值都储存为 `Value` 类,而 `Document` 类则表示整个 DOM,它存储了一个 DOM 树的根 `Value`。RapidJSON 的所有公开类型及函数都在 `rapidjson` 命名空间中。
|
||||
|
||||
# 查询Value {#QueryValue}
|
||||
# 查询 Value {#QueryValue}
|
||||
|
||||
在本节中,我们会使用到`example/tutorial/tutorial.cpp`中的代码片段。
|
||||
在本节中,我们会使用到 `example/tutorial/tutorial.cpp` 中的代码片段。
|
||||
|
||||
假设我们用C语言的字符串储存一个JSON(`const char* json`):
|
||||
假设我们用 C 语言的字符串储存一个 JSON(`const char* json`):
|
||||
~~~~~~~~~~js
|
||||
{
|
||||
"hello": "world",
|
||||
@ -27,7 +27,7 @@
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||
把它解析至一个`Document`:
|
||||
把它解析至一个 `Document`:
|
||||
~~~~~~~~~~cpp
|
||||
#include "rapidjson/document.h"
|
||||
|
||||
@ -38,16 +38,16 @@ Document document;
|
||||
document.Parse(json);
|
||||
~~~~~~~~~~
|
||||
|
||||
那么现在该JSON就会被解析至`document`中,成为一棵*DOM树*:
|
||||
那么现在该 JSON 就会被解析至 `document` 中,成为一棵 *DOM 树 *:
|
||||
|
||||

|
||||

|
||||
|
||||
自从RFC 7159作出更新,合法JSON文件的根可以是任何类型的JSON值。而在较早的RFC 4627中,根值只允许是Object或Array。而在上述例子中,根是一个Object。
|
||||
自从 RFC 7159 作出更新,合法 JSON 文件的根可以是任何类型的 JSON 值。而在较早的 RFC 4627 中,根值只允许是 Object 或 Array。而在上述例子中,根是一个 Object。
|
||||
~~~~~~~~~~cpp
|
||||
assert(document.IsObject());
|
||||
~~~~~~~~~~
|
||||
|
||||
让我们查询一下根Object中有没有`"hello"`成员。由于一个`Value`可包含不同类型的值,我们可能需要验证它的类型,并使用合适的API去获取其值。在此例中,`"hello"`成员关联到一个JSON String。
|
||||
让我们查询一下根 Object 中有没有 `"hello"` 成员。由于一个 `Value` 可包含不同类型的值,我们可能需要验证它的类型,并使用合适的 API 去获取其值。在此例中,`"hello"` 成员关联到一个 JSON String。
|
||||
~~~~~~~~~~cpp
|
||||
assert(document.HasMember("hello"));
|
||||
assert(document["hello"].IsString());
|
||||
@ -58,7 +58,7 @@ printf("hello = %s\n", document["hello"].GetString());
|
||||
world
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON True/False值是以`bool`表示的。
|
||||
JSON True/False 值是以 `bool` 表示的。
|
||||
~~~~~~~~~~cpp
|
||||
assert(document["t"].IsBool());
|
||||
printf("t = %s\n", document["t"].GetBool() ? "true" : "false");
|
||||
@ -68,7 +68,7 @@ printf("t = %s\n", document["t"].GetBool() ? "true" : "false");
|
||||
true
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON Null值可用`IsNull()`查询。
|
||||
JSON Null 值可用 `IsNull()` 查询。
|
||||
~~~~~~~~~~cpp
|
||||
printf("n = %s\n", document["n"].IsNull() ? "null" : "?");
|
||||
~~~~~~~~~~
|
||||
@ -77,12 +77,12 @@ printf("n = %s\n", document["n"].IsNull() ? "null" : "?");
|
||||
null
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON Number类型表示所有数值。然而,C++需要使用更专门的类型。
|
||||
JSON Number 类型表示所有数值。然而,C++ 需要使用更专门的类型。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
assert(document["i"].IsNumber());
|
||||
|
||||
// 在此情况下,IsUint()/IsInt64()/IsUInt64()也会返回 true
|
||||
// 在此情况下,IsUint()/IsInt64()/IsUInt64() 也会返回 true
|
||||
assert(document["i"].IsInt());
|
||||
printf("i = %d\n", document["i"].GetInt());
|
||||
// 另一种用法: (int)document["i"]
|
||||
@ -97,7 +97,7 @@ i = 123
|
||||
pi = 3.1416
|
||||
~~~~~~~~~~
|
||||
|
||||
JSON Array包含一些元素。
|
||||
JSON Array 包含一些元素。
|
||||
~~~~~~~~~~cpp
|
||||
// 使用引用来连续访问,方便之余还更高效。
|
||||
const Value& a = document["a"];
|
||||
@ -113,17 +113,17 @@ a[2] = 3
|
||||
a[3] = 4
|
||||
~~~~~~~~~~
|
||||
|
||||
注意,RapidJSON并不自动转换各种JSON类型。例如,对一个String的Value调用`GetInt()`是非法的。在调试模式下,它会被断言失败。在发布模式下,其行为是未定义的。
|
||||
注意,RapidJSON 并不自动转换各种 JSON 类型。例如,对一个 String 的 Value 调用 `GetInt()` 是非法的。在调试模式下,它会被断言失败。在发布模式下,其行为是未定义的。
|
||||
|
||||
以下将会讨论有关查询各类型的细节。
|
||||
|
||||
## 查询Array {#QueryArray}
|
||||
## 查询 Array {#QueryArray}
|
||||
|
||||
缺省情况下,`SizeType`是`unsigned`的typedef。在多数系统中,Array最多能存储2^32-1个元素。
|
||||
缺省情况下,`SizeType` 是 `unsigned` 的 typedef。在多数系统中,Array 最多能存储 2^32-1 个元素。
|
||||
|
||||
你可以用整数字面量访问元素,如`a[0]`、`a[1]`、`a[2]`。
|
||||
你可以用整数字面量访问元素,如 `a[0]`、`a[1]`、`a[2]`。
|
||||
|
||||
Array与`std::vector`相似,除了使用索引,也可使用迭代器来访问所有元素。
|
||||
Array 与 `std::vector` 相似,除了使用索引,也可使用迭代器来访问所有元素。
|
||||
~~~~~~~~~~cpp
|
||||
for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
|
||||
printf("%d ", itr->GetInt());
|
||||
@ -133,9 +133,18 @@ for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
|
||||
* `SizeType Capacity() const`
|
||||
* `bool Empty() const`
|
||||
|
||||
## 查询Object {#QueryObject}
|
||||
### 范围 for 循环 (v1.1.0 中的新功能)
|
||||
|
||||
和Array相似,我们可以用迭代器去访问所有Object成员:
|
||||
当使用 C++11 功能时,你可使用范围 for 循环去访问 Array 内的所有元素。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
for (auto& v : a.GetArray())
|
||||
printf("%d ", v.GetInt());
|
||||
~~~~~~~~~~
|
||||
|
||||
## 查询 Object {#QueryObject}
|
||||
|
||||
和 Array 相似,我们可以用迭代器去访问所有 Object 成员:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
static const char* kTypeNames[] =
|
||||
@ -159,33 +168,43 @@ Type of member pi is Number
|
||||
Type of member a is Array
|
||||
~~~~~~~~~~
|
||||
|
||||
注意,当`operator[](const char*)`找不到成员,它会断言失败。
|
||||
注意,当 `operator[](const char*)` 找不到成员,它会断言失败。
|
||||
|
||||
若我们不确定一个成员是否存在,便需要在调用`operator[](const char*)`前先调用`HasMember()`。然而,这会导致两次查找。更好的做法是调用`FindMember()`,它能同时检查成员是否存在并返回它的Value:
|
||||
若我们不确定一个成员是否存在,便需要在调用 `operator[](const char*)` 前先调用 `HasMember()`。然而,这会导致两次查找。更好的做法是调用 `FindMember()`,它能同时检查成员是否存在并返回它的 Value:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value::ConstMemberIterator itr = document.FindMember("hello");
|
||||
if (itr != document.MemberEnd())
|
||||
printf("%s %s\n", itr->value.GetString());
|
||||
printf("%s\n", itr->value.GetString());
|
||||
~~~~~~~~~~
|
||||
|
||||
## 查询Number {#QueryNumber}
|
||||
### 范围 for 循环 (v1.1.0 中的新功能)
|
||||
|
||||
JSON只提供一种数值类型──Number。数字可以是整数或实数。RFC 4627规定数字的范围由解析器指定。
|
||||
当使用 C++11 功能时,你可使用范围 for 循环去访问 Object 内的所有成员。
|
||||
|
||||
由于C++提供多种整数及浮点数类型,DOM尝试尽量提供最广的范围及良好性能。
|
||||
~~~~~~~~~~cpp
|
||||
for (auto& m : document.GetObject())
|
||||
printf("Type of member %s is %s\n",
|
||||
m.name.GetString(), kTypeNames[m.value.GetType()]);
|
||||
~~~~~~~~~~
|
||||
|
||||
当解析一个Number时, 它会被存储在DOM之中,成为下列其中一个类型:
|
||||
## 查询 Number {#QueryNumber}
|
||||
|
||||
JSON 只提供一种数值类型──Number。数字可以是整数或实数。RFC 4627 规定数字的范围由解析器指定。
|
||||
|
||||
由于 C++ 提供多种整数及浮点数类型,DOM 尝试尽量提供最广的范围及良好性能。
|
||||
|
||||
当解析一个 Number 时, 它会被存储在 DOM 之中,成为下列其中一个类型:
|
||||
|
||||
类型 | 描述
|
||||
-----------|---------------------------------------
|
||||
`unsigned` | 32位无号整数
|
||||
`int` | 32位有号整数
|
||||
`uint64_t` | 64位无号整数
|
||||
`int64_t` | 64位有号整数
|
||||
`double` | 64位双精度浮点数
|
||||
`unsigned` | 32 位无号整数
|
||||
`int` | 32 位有号整数
|
||||
`uint64_t` | 64 位无号整数
|
||||
`int64_t` | 64 位有号整数
|
||||
`double` | 64 位双精度浮点数
|
||||
|
||||
当查询一个Number时, 你可以检查该数字是否能以目标类型来提取:
|
||||
当查询一个 Number 时, 你可以检查该数字是否能以目标类型来提取:
|
||||
|
||||
查检 | 提取
|
||||
------------------|---------------------
|
||||
@ -196,28 +215,28 @@ JSON只提供一种数值类型──Number。数字可以是整数或实数。R
|
||||
`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`。
|
||||
注意,一个整数可能用几种类型来提取,而无需转换。例如,一个名为 `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位)。
|
||||
当要提取 Number 类型,`GetDouble()` 是会把内部整数的表示转换成 `double`。注意 `int` 和 `unsigned` 可以安全地转换至 `double`,但 `int64_t` 及 `uint64_t` 可能会丧失精度(因为 `double` 的尾数只有 52 位)。
|
||||
|
||||
## 查询String {#QueryString}
|
||||
## 查询 String {#QueryString}
|
||||
|
||||
除了`GetString()`,`Value`类也有一个`GetStringLength()`。这里会解释个中原因。
|
||||
除了 `GetString()`,`Value` 类也有一个 `GetStringLength()`。这里会解释个中原因。
|
||||
|
||||
根据RFC 4627,JSON String可包含Unicode字符`U+0000`,在JSON中会表示为`"\u0000"`。问题是,C/C++通常使用空字符结尾字符串(null-terminated string),这种字符串把``\0'`作为结束符号。
|
||||
根据 RFC 4627,JSON String 可包含 Unicode 字符 `U+0000`,在 JSON 中会表示为 `"\u0000"`。问题是,C/C++ 通常使用空字符结尾字符串(null-terminated string),这种字符串把 ``\0'` 作为结束符号。
|
||||
|
||||
为了符合RFC 4627,RapidJSON支持包含`U+0000`的String。若你需要处理这些String,便可使用`GetStringLength()`去获得正确的字符串长度。
|
||||
为了符合 RFC 4627,RapidJSON 支持包含 `U+0000` 的 String。若你需要处理这些 String,便可使用 `GetStringLength()` 去获得正确的字符串长度。
|
||||
|
||||
例如,当解析以下的JSON至`Document d`之后:
|
||||
例如,当解析以下的 JSON 至 `Document d` 之后:
|
||||
|
||||
~~~~~~~~~~js
|
||||
{ "s" : "a\u0000b" }
|
||||
~~~~~~~~~~
|
||||
`"a\u0000b"`值的正确长度应该是3。但`strlen()`会返回1。
|
||||
`"a\u0000b"` 值的正确长度应该是 3。但 `strlen()` 会返回 1。
|
||||
|
||||
`GetStringLength()`也可以提高性能,因为用户可能需要调用`strlen()`去分配缓冲。
|
||||
`GetStringLength()` 也可以提高性能,因为用户可能需要调用 `strlen()` 去分配缓冲。
|
||||
|
||||
此外,`std::string`也支持这个构造函数:
|
||||
此外,`std::string` 也支持这个构造函数:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
string(const char* s, size_t count);
|
||||
@ -225,27 +244,27 @@ string(const char* s, size_t count);
|
||||
|
||||
此构造函数接受字符串长度作为参数。它支持在字符串中存储空字符,也应该会有更好的性能。
|
||||
|
||||
## 比较两个Value
|
||||
## 比较两个 Value
|
||||
|
||||
你可使用`==`及`!=`去比较两个Value。当且仅当两个Value的类型及内容相同,它们才当作相等。你也可以比较Value和它的原生类型值。以下是一个例子。
|
||||
你可使用 `==` 及 `!=` 去比较两个 Value。当且仅当两个 Value 的类型及内容相同,它们才当作相等。你也可以比较 Value 和它的原生类型值。以下是一个例子。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
if (document["hello"] == document["n"]) /*...*/; // 比较两个值
|
||||
if (document["hello"] == "world") /*...*/; // 与字符串家面量作比较
|
||||
if (document["i"] != 123) /*...*/; // 与整数作比较
|
||||
if (document["pi"] != 3.14) /*...*/; // 与double作比较
|
||||
if (document["pi"] != 3.14) /*...*/; // 与 double 作比较
|
||||
~~~~~~~~~~
|
||||
|
||||
Array/Object顺序以它们的元素/成员作比较。当且仅当它们的整个子树相等,它们才当作相等。
|
||||
Array/Object 顺序以它们的元素/成员作比较。当且仅当它们的整个子树相等,它们才当作相等。
|
||||
|
||||
注意,现时若一个Object含有重复命名的成员,它与任何Object作比较都总会返回`false`。
|
||||
注意,现时若一个 Object 含有重复命名的成员,它与任何 Object 作比较都总会返回 `false`。
|
||||
|
||||
# 创建/修改值 {#CreateModifyValues}
|
||||
|
||||
有多种方法去创建值。 当一个DOM树被创建或修改后,可使用`Writer`再次存储为JSON。
|
||||
有多种方法去创建值。 当一个 DOM 树被创建或修改后,可使用 `Writer` 再次存储为 JSON。
|
||||
|
||||
## 改变Value类型 {#ChangeValueType}
|
||||
当使用默认构造函数创建一个Value或Document,它的类型便会是Null。要改变其类型,需调用`SetXXX()`或赋值操作,例如:
|
||||
## 改变 Value 类型 {#ChangeValueType}
|
||||
当使用默认构造函数创建一个 Value 或 Document,它的类型便会是 Null。要改变其类型,需调用 `SetXXX()` 或赋值操作,例如:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Document d; // Null
|
||||
@ -260,75 +279,75 @@ v = 10; // 简写,和上面的相同
|
||||
几个类型也有重载构造函数:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value b(true); // 调用Value(bool)
|
||||
Value b(true); // 调用 Value(bool)
|
||||
Value i(-123); // 调用 Value(int)
|
||||
Value u(123u); // 调用Value(unsigned)
|
||||
Value d(1.5); // 调用Value(double)
|
||||
Value u(123u); // 调用 Value(unsigned)
|
||||
Value d(1.5); // 调用 Value(double)
|
||||
~~~~~~~~~~
|
||||
|
||||
要重建空Object或Array,可在默认构造函数后使用 `SetObject()`/`SetArray()`,或一次性使用`Value(Type)`:
|
||||
要重建空 Object 或 Array,可在默认构造函数后使用 `SetObject()`/`SetArray()`,或一次性使用 `Value(Type)`:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value o(kObjectType);
|
||||
Value a(kArrayType);
|
||||
~~~~~~~~~~
|
||||
|
||||
## 转移语意(Move Semantics) {#MoveSemantics}
|
||||
## 转移语义(Move Semantics) {#MoveSemantics}
|
||||
|
||||
在设计RapidJSON时有一个非常特别的决定,就是Value赋值并不是把来源Value复制至目的Value,而是把把来源Value转移(move)至目的Value。例如:
|
||||
在设计 RapidJSON 时有一个非常特别的决定,就是 Value 赋值并不是把来源 Value 复制至目的 Value,而是把把来源 Value 转移(move)至目的 Value。例如:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value a(123);
|
||||
Value b(456);
|
||||
b = a; // a变成Null,b变成数字123。
|
||||
b = a; // a 变成 Null,b 变成数字 123。
|
||||
~~~~~~~~~~
|
||||
|
||||

|
||||

|
||||
|
||||
为什么?此语意有何优点?
|
||||
为什么?此语义有何优点?
|
||||
|
||||
最简单的答案就是性能。对于固定大小的JSON类型(Number、True、False、Null),复制它们是简单快捷。然而,对于可变大小的JSON类型(String、Array、Object),复制它们会产生大量开销,而且这些开销常常不被察觉。尤其是当我们需要创建临时Object,把它复制至另一变量,然后再析构它。
|
||||
最简单的答案就是性能。对于固定大小的 JSON 类型(Number、True、False、Null),复制它们是简单快捷。然而,对于可变大小的 JSON 类型(String、Array、Object),复制它们会产生大量开销,而且这些开销常常不被察觉。尤其是当我们需要创建临时 Object,把它复制至另一变量,然后再析构它。
|
||||
|
||||
例如,若使用正常*复制*语意:
|
||||
例如,若使用正常 * 复制 * 语义:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value o(kObjectType);
|
||||
{
|
||||
Value contacts(kArrayType);
|
||||
// 把元素加进contacts数组。
|
||||
// 把元素加进 contacts 数组。
|
||||
// ...
|
||||
o.AddMember("contacts", contacts, d.GetAllocator()); // 深度复制contacts (可能有大量内存分配)
|
||||
// 析构contacts。
|
||||
o.AddMember("contacts", contacts, d.GetAllocator()); // 深度复制 contacts (可能有大量内存分配)
|
||||
// 析构 contacts。
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||

|
||||

|
||||
|
||||
那个`o` Object需要分配一个和contacts相同大小的缓冲区,对conacts做深度复制,并最终要析构contacts。这样会产生大量无必要的内存分配/释放,以及内存复制。
|
||||
那个 `o` Object 需要分配一个和 contacts 相同大小的缓冲区,对 conacts 做深度复制,并最终要析构 contacts。这样会产生大量无必要的内存分配/释放,以及内存复制。
|
||||
|
||||
有一些方案可避免实质地复制这些数据,例如引用计数(reference counting)、垃圾回收(garbage collection, GC)。
|
||||
|
||||
为了使RapidJSON简单及快速,我们选择了对赋值采用*转移*语意。这方法与`std::auto_ptr`相似,都是在赋值时转移拥有权。转移快得多简单得多,只需要析构原来的Value,把来源`memcpy()`至目标,最后把来源设置为Null类型。
|
||||
为了使 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。它的析构是平凡的。
|
||||
o.AddMember("contacts", contacts, d.GetAllocator()); // 只需 memcpy() contacts 本身至新成员的 Value(16 字节)
|
||||
// contacts 在这里变成 Null。它的析构是平凡的。
|
||||
}
|
||||
~~~~~~~~~~
|
||||
|
||||

|
||||

|
||||
|
||||
在C++11中这称为转移赋值操作(move assignment operator)。由于RapidJSON 支持C++03,它在赋值操作采用转移语意,其它修改形函数如`AddMember()`, `PushBack()`也采用转移语意。
|
||||
在 C++11 中这称为转移赋值操作(move assignment operator)。由于 RapidJSON 支持 C++03,它在赋值操作采用转移语义,其它修改型函数如 `AddMember()`, `PushBack()` 也采用转移语义。
|
||||
|
||||
### 转移语意及临时值 {#TemporaryValues}
|
||||
### 转移语义及临时值 {#TemporaryValues}
|
||||
|
||||
有时候,我们想直接构造一个Value并传递给一个“转移”函数(如`PushBack()`、`AddMember()`)。由于临时对象是不能转换为正常的Value引用,我们加入了一个方便的`Move()`函数:
|
||||
有时候,我们想直接构造一个 Value 并传递给一个“转移”函数(如 `PushBack()`、`AddMember()`)。由于临时对象是不能转换为正常的 Value 引用,我们加入了一个方便的 `Move()` 函数:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value a(kArrayType);
|
||||
@ -338,17 +357,17 @@ a.PushBack(Value().SetInt(42), allocator); // fluent API
|
||||
a.PushBack(Value(42).Move(), allocator); // 和上一行相同
|
||||
~~~~~~~~~~
|
||||
|
||||
## 创建String {#CreateString}
|
||||
RapidJSON提供两个String的存储策略。
|
||||
## 创建 String {#CreateString}
|
||||
RapidJSON 提供两个 String 的存储策略。
|
||||
|
||||
1. copy-string: 分配缓冲区,然后把来源数据复制至它。
|
||||
2. const-string: 简单地储存字符串的指针。
|
||||
|
||||
Copy-string总是安全的,因为它拥有数据的克隆。Const-string可用于存储字符串字面量,以及用于在DOM一节中将会提到的in-situ解析中。
|
||||
Copy-string 总是安全的,因为它拥有数据的克隆。Const-string 可用于存储字符串字面量,以及用于在 DOM 一节中将会提到的 in-situ 解析中。
|
||||
|
||||
为了让用户自定义内存分配方式,当一个操作可能需要内存分配时,RapidJSON要求用户传递一个allocator实例作为API参数。此设计避免了在每个Value存储allocator(或document)的指针。
|
||||
为了让用户自定义内存分配方式,当一个操作可能需要内存分配时,RapidJSON 要求用户传递一个 allocator 实例作为 API 参数。此设计避免了在每个 Value 存储 allocator(或 document)的指针。
|
||||
|
||||
因此,当我们把一个copy-string赋值时, 调用含有allocator的`SetString()`重载函数:
|
||||
因此,当我们把一个 copy-string 赋值时, 调用含有 allocator 的 `SetString()` 重载函数:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Document document;
|
||||
@ -357,14 +376,14 @@ 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"
|
||||
// 清空 buffer 后 author.GetString() 仍然包含 "Milo Yip"
|
||||
~~~~~~~~~~
|
||||
|
||||
在此例子中,我们使用`Document`实例的allocator。这是使用RapidJSON时常用的惯用法。但你也可以用其他allocator实例。
|
||||
在此例子中,我们使用 `Document` 实例的 allocator。这是使用 RapidJSON 时常用的惯用法。但你也可以用其他 allocator 实例。
|
||||
|
||||
另外,上面的`SetString()`需要长度参数。这个API能处理含有空字符的字符串。另一个`SetString()`重载函数没有长度参数,它假设输入是空字符结尾的,并会调用类似`strlen()`的函数去获取长度。
|
||||
另外,上面的 `SetString()` 需要长度参数。这个 API 能处理含有空字符的字符串。另一个 `SetString()` 重载函数没有长度参数,它假设输入是空字符结尾的,并会调用类似 `strlen()` 的函数去获取长度。
|
||||
|
||||
最后,对于字符串字面量或有安全生命周期的字符串,可以使用const-string版本的`SetString()`,它没有allocator参数。对于字符串家面量(或字符数组常量),只需简单地传递字面量,又安全又高效:
|
||||
最后,对于字符串字面量或有安全生命周期的字符串,可以使用 const-string 版本的 `SetString()`,它没有 allocator 参数。对于字符串家面量(或字符数组常量),只需简单地传递字面量,又安全又高效:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value s;
|
||||
@ -372,22 +391,22 @@ s.SetString("rapidjson"); // 可包含空字符,长度在编译萁推导
|
||||
s = "rapidjson"; // 上行的缩写
|
||||
~~~~~~~~~~
|
||||
|
||||
对于字符指针,RapidJSON需要作一个标记,代表它不复制也是安全的。可以使用`StringRef`函数:
|
||||
对于字符指针,RapidJSON 需要作一个标记,代表它不复制也是安全的。可以使用 `StringRef` 函数:
|
||||
|
||||
~~~~~~~~~cpp
|
||||
const char * cstr = getenv("USER");
|
||||
size_t cstr_len = ...; // 如果有长度
|
||||
Value s;
|
||||
// s.SetString(cstr); // 这不能通过编译
|
||||
s.SetString(StringRef(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。
|
||||
## 修改 Array {#ModifyArray}
|
||||
Array 类型的 Value 提供与 `std::vector` 相似的 API。
|
||||
|
||||
* `Clear()`
|
||||
* `Reserve(SizeType, Allocator&)`
|
||||
@ -397,37 +416,37 @@ Array类型的Value提供与`std::vector`相似的API。
|
||||
* `ValueIterator Erase(ConstValueIterator pos)`
|
||||
* `ValueIterator Erase(ConstValueIterator first, ConstValueIterator last)`
|
||||
|
||||
注意,`Reserve(...)`及`PushBack(...)`可能会为数组元素分配内存,所以需要一个allocator。
|
||||
注意,`Reserve(...)` 及 `PushBack(...)` 可能会为数组元素分配内存,所以需要一个 allocator。
|
||||
|
||||
以下是`PushBack()`的例子:
|
||||
以下是 `PushBack()` 的例子:
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value a(kArrayType);
|
||||
Document::AllocatorType& allocator = document.GetAllocator();
|
||||
|
||||
for (int i = 5; i <= 10; i++)
|
||||
a.PushBack(i, allocator); // 可能需要调用realloc()所以需要allocator
|
||||
a.PushBack(i, allocator); // 可能需要调用 realloc() 所以需要 allocator
|
||||
|
||||
// 流畅接口(Fluent interface)
|
||||
a.PushBack("Lua", allocator).PushBack("Mio", allocator);
|
||||
~~~~~~~~~~
|
||||
|
||||
与STL不一样的是,`PushBack()`/`PopBack()`返回Array本身的引用。这称为流畅接口(_fluent interface_)。
|
||||
与 STL 不一样的是,`PushBack()`/`PopBack()` 返回 Array 本身的引用。这称为流畅接口(_fluent interface_)。
|
||||
|
||||
如果你想在Array中加入一个非常量字符串,或是一个没有足够生命周期的字符串(见[Create String](#CreateString)),你需要使用copy-string API去创建一个String。为了避免加入中间变量,可以就地使用一个[临时值](#TemporaryValues):
|
||||
如果你想在 Array 中加入一个非常量字符串,或是一个没有足够生命周期的字符串(见 [Create String](#CreateString)),你需要使用 copy-string API 去创建一个 String。为了避免加入中间变量,可以就地使用一个 [临时值](#TemporaryValues):
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// 就地Value参数
|
||||
// 就地 Value 参数
|
||||
contact.PushBack(Value("copy", document.GetAllocator()).Move(), // copy string
|
||||
document.GetAllocator());
|
||||
|
||||
// 显式Value参数
|
||||
// 显式 Value 参数
|
||||
Value val("key", document.GetAllocator()); // copy string
|
||||
contact.PushBack(val, document.GetAllocator());
|
||||
~~~~~~~~~~
|
||||
|
||||
## 修改Object {#ModifyObject}
|
||||
Object是键值对的集合。每个键必须为String。要修改Object,方法是增加或移除成员。以下的API用来增加城员:
|
||||
## 修改 Object {#ModifyObject}
|
||||
Object 是键值对的集合。每个键必须为 String。要修改 Object,方法是增加或移除成员。以下的 API 用来增加城员:
|
||||
|
||||
* `Value& AddMember(Value&, Value&, Allocator& allocator)`
|
||||
* `Value& AddMember(StringRefType, Value&, Allocator&)`
|
||||
@ -441,34 +460,34 @@ contact.AddMember("name", "Milo", document.GetAllocator());
|
||||
contact.AddMember("married", true, document.GetAllocator());
|
||||
~~~~~~~~~~
|
||||
|
||||
使用`StringRefType`作为name参数的重载版本与字符串的`SetString`的接口相似。 这些重载是为了避免复制`name`字符串,因为JSON object中经常会使用常数键名。
|
||||
使用 `StringRefType` 作为 name 参数的重载版本与字符串的 `SetString` 的接口相似。 这些重载是为了避免复制 `name` 字符串,因为 JSON object 中经常会使用常数键名。
|
||||
|
||||
如果你需要从非常数字符串或生命周期不足的字符串创建键名(见[创建String](#CreateString)),你需要使用copy-string API。为了避免中间变量,可以就地使用[临时值](#TemporaryValues):
|
||||
如果你需要从非常数字符串或生命周期不足的字符串创建键名(见 [创建 String](#CreateString)),你需要使用 copy-string API。为了避免中间变量,可以就地使用 [临时值](#TemporaryValues):
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// 就地Value参数
|
||||
// 就地 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
|
||||
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)`:使用迭代器移除成员(_常数_时间复杂度)。
|
||||
* `bool RemoveMember(const Value& name)`:除了 `name` 是一个 Value,和上一行相同。
|
||||
* `MemberIterator RemoveMember(MemberIterator)`:使用迭代器移除成员(_ 常数 _ 时间复杂度)。
|
||||
* `MemberIterator EraseMember(MemberIterator)`:和上行相似但维持成员次序(线性时间复杂度)。
|
||||
* `MemberIterator EraseMember(MemberIterator first, MemberIterator last)`:移除一个范围内的成员,维持次序(线性时间复杂度)。
|
||||
|
||||
`MemberIterator RemoveMember(MemberIterator)`使用了“转移最后”手法来达成常数时间复杂度。基本上就是析构迭代器位置的成员,然后把最后的成员转移至迭代器位置。因此,成员的次序会被改变。
|
||||
`MemberIterator RemoveMember(MemberIterator)` 使用了“转移最后”手法来达成常数时间复杂度。基本上就是析构迭代器位置的成员,然后把最后的成员转移至迭代器位置。因此,成员的次序会被改变。
|
||||
|
||||
## 深复制Value {#DeepCopyValue}
|
||||
若我们真的要复制一个DOM树,我们可使用两个APIs作深复制:含allocator的构造函数及`CopyFrom()`。
|
||||
## 深复制 Value {#DeepCopyValue}
|
||||
若我们真的要复制一个 DOM 树,我们可使用两个 APIs 作深复制:含 allocator 的构造函数及 `CopyFrom()`。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Document d;
|
||||
@ -477,19 +496,19 @@ Value v1("foo");
|
||||
// Value v2(v1); // 不容许
|
||||
|
||||
Value v2(v1, a); // 制造一个克隆
|
||||
assert(v1.IsString()); // v1不变
|
||||
assert(v1.IsString()); // v1 不变
|
||||
d.SetArray().PushBack(v1, a).PushBack(v2, a);
|
||||
assert(v1.IsNull() && v2.IsNull()); // 两个都转移动d
|
||||
assert(v1.IsNull() && v2.IsNull()); // 两个都转移动 d
|
||||
|
||||
v2.CopyFrom(d, a); // 把整个document复制至v2
|
||||
assert(d.IsArray() && d.Size() == 2); // 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}
|
||||
## 交换 Value {#SwapValues}
|
||||
|
||||
RapidJSON也提供`Swap()`。
|
||||
RapidJSON 也提供 `Swap()`。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
Value a(123);
|
||||
@ -499,17 +518,17 @@ assert(a.IsString());
|
||||
assert(b.IsInt());
|
||||
~~~~~~~~~~
|
||||
|
||||
无论两棵DOM树有多复杂,交换是很快的(常数时间)。
|
||||
无论两棵 DOM 树有多复杂,交换是很快的(常数时间)。
|
||||
|
||||
# 下一部分 {#WhatsNext}
|
||||
|
||||
本教程展示了如何询查及修改DOM树。RapidJSON还有一个重要概念:
|
||||
本教程展示了如何询查及修改 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.zh-cn.md)讲述一些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 内部的设计及技术。
|
||||
|
||||
你也可以参考[常见问题](faq.zh-cn.md)、API文档、例子及单元测试。
|
||||
你也可以参考 [常见问题](doc/faq.zh-cn.md)、API 文档、例子及单元测试。
|
||||
|
@ -1,9 +1,16 @@
|
||||
cmake_minimum_required(VERSION 2.8)
|
||||
|
||||
if(POLICY CMP0054)
|
||||
cmake_policy(SET CMP0054 NEW)
|
||||
endif()
|
||||
|
||||
set(EXAMPLES
|
||||
capitalize
|
||||
condense
|
||||
filterkey
|
||||
filterkeydom
|
||||
jsonx
|
||||
lookaheadparser
|
||||
messagereader
|
||||
parsebyparts
|
||||
pretty
|
||||
@ -12,21 +19,21 @@ set(EXAMPLES
|
||||
serialize
|
||||
simpledom
|
||||
simplereader
|
||||
simplepullreader
|
||||
simplewriter
|
||||
tutorial)
|
||||
|
||||
include_directories("../include/")
|
||||
|
||||
add_definitions(-D__STDC_FORMAT_MACROS)
|
||||
set_property(DIRECTORY PROPERTY COMPILE_OPTIONS ${EXTRA_CXX_FLAGS})
|
||||
|
||||
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")
|
||||
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS=1)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
|
||||
endif()
|
||||
|
||||
add_executable(archivertest archiver/archiver.cpp archiver/archivertest.cpp)
|
||||
|
||||
foreach (example ${EXAMPLES})
|
||||
add_executable(${example} ${example}/${example}.cpp)
|
||||
endforeach()
|
||||
|
292
example/archiver/archiver.cpp
Normal file
292
example/archiver/archiver.cpp
Normal file
@ -0,0 +1,292 @@
|
||||
#include "archiver.h"
|
||||
#include <cassert>
|
||||
#include <stack>
|
||||
#include "rapidjson/document.h"
|
||||
#include "rapidjson/prettywriter.h"
|
||||
#include "rapidjson/stringbuffer.h"
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
struct JsonReaderStackItem {
|
||||
enum State {
|
||||
BeforeStart, //!< An object/array is in the stack but it is not yet called by StartObject()/StartArray().
|
||||
Started, //!< An object/array is called by StartObject()/StartArray().
|
||||
Closed //!< An array is closed after read all element, but before EndArray().
|
||||
};
|
||||
|
||||
JsonReaderStackItem(const Value* value, State state) : value(value), state(state), index() {}
|
||||
|
||||
const Value* value;
|
||||
State state;
|
||||
SizeType index; // For array iteration
|
||||
};
|
||||
|
||||
typedef std::stack<JsonReaderStackItem> JsonReaderStack;
|
||||
|
||||
#define DOCUMENT reinterpret_cast<Document*>(mDocument)
|
||||
#define STACK (reinterpret_cast<JsonReaderStack*>(mStack))
|
||||
#define TOP (STACK->top())
|
||||
#define CURRENT (*TOP.value)
|
||||
|
||||
JsonReader::JsonReader(const char* json) : mDocument(), mStack(), mError(false) {
|
||||
mDocument = new Document;
|
||||
DOCUMENT->Parse(json);
|
||||
if (DOCUMENT->HasParseError())
|
||||
mError = true;
|
||||
else {
|
||||
mStack = new JsonReaderStack;
|
||||
STACK->push(JsonReaderStackItem(DOCUMENT, JsonReaderStackItem::BeforeStart));
|
||||
}
|
||||
}
|
||||
|
||||
JsonReader::~JsonReader() {
|
||||
delete DOCUMENT;
|
||||
delete STACK;
|
||||
}
|
||||
|
||||
// Archive concept
|
||||
JsonReader& JsonReader::StartObject() {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsObject() && TOP.state == JsonReaderStackItem::BeforeStart)
|
||||
TOP.state = JsonReaderStackItem::Started;
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::EndObject() {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsObject() && TOP.state == JsonReaderStackItem::Started)
|
||||
Next();
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::Member(const char* name) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsObject() && TOP.state == JsonReaderStackItem::Started) {
|
||||
Value::ConstMemberIterator memberItr = CURRENT.FindMember(name);
|
||||
if (memberItr != CURRENT.MemberEnd())
|
||||
STACK->push(JsonReaderStackItem(&memberItr->value, JsonReaderStackItem::BeforeStart));
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool JsonReader::HasMember(const char* name) const {
|
||||
if (!mError && CURRENT.IsObject() && TOP.state == JsonReaderStackItem::Started)
|
||||
return CURRENT.HasMember(name);
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::StartArray(size_t* size) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsArray() && TOP.state == JsonReaderStackItem::BeforeStart) {
|
||||
TOP.state = JsonReaderStackItem::Started;
|
||||
if (size)
|
||||
*size = CURRENT.Size();
|
||||
|
||||
if (!CURRENT.Empty()) {
|
||||
const Value* value = &CURRENT[TOP.index];
|
||||
STACK->push(JsonReaderStackItem(value, JsonReaderStackItem::BeforeStart));
|
||||
}
|
||||
else
|
||||
TOP.state = JsonReaderStackItem::Closed;
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::EndArray() {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsArray() && TOP.state == JsonReaderStackItem::Closed)
|
||||
Next();
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::operator&(bool& b) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsBool()) {
|
||||
b = CURRENT.GetBool();
|
||||
Next();
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::operator&(unsigned& u) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsUint()) {
|
||||
u = CURRENT.GetUint();
|
||||
Next();
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::operator&(int& i) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsInt()) {
|
||||
i = CURRENT.GetInt();
|
||||
Next();
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::operator&(double& d) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsNumber()) {
|
||||
d = CURRENT.GetDouble();
|
||||
Next();
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::operator&(std::string& s) {
|
||||
if (!mError) {
|
||||
if (CURRENT.IsString()) {
|
||||
s = CURRENT.GetString();
|
||||
Next();
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonReader& JsonReader::SetNull() {
|
||||
// This function is for JsonWriter only.
|
||||
mError = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void JsonReader::Next() {
|
||||
if (!mError) {
|
||||
assert(!STACK->empty());
|
||||
STACK->pop();
|
||||
|
||||
if (!STACK->empty() && CURRENT.IsArray()) {
|
||||
if (TOP.state == JsonReaderStackItem::Started) { // Otherwise means reading array item pass end
|
||||
if (TOP.index < CURRENT.Size() - 1) {
|
||||
const Value* value = &CURRENT[++TOP.index];
|
||||
STACK->push(JsonReaderStackItem(value, JsonReaderStackItem::BeforeStart));
|
||||
}
|
||||
else
|
||||
TOP.state = JsonReaderStackItem::Closed;
|
||||
}
|
||||
else
|
||||
mError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#undef DOCUMENT
|
||||
#undef STACK
|
||||
#undef TOP
|
||||
#undef CURRENT
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// JsonWriter
|
||||
|
||||
#define WRITER reinterpret_cast<PrettyWriter<StringBuffer>*>(mWriter)
|
||||
#define STREAM reinterpret_cast<StringBuffer*>(mStream)
|
||||
|
||||
JsonWriter::JsonWriter() : mWriter(), mStream() {
|
||||
mStream = new StringBuffer;
|
||||
mWriter = new PrettyWriter<StringBuffer>(*STREAM);
|
||||
}
|
||||
|
||||
JsonWriter::~JsonWriter() {
|
||||
delete WRITER;
|
||||
delete STREAM;
|
||||
}
|
||||
|
||||
const char* JsonWriter::GetString() const {
|
||||
return STREAM->GetString();
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::StartObject() {
|
||||
WRITER->StartObject();
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::EndObject() {
|
||||
WRITER->EndObject();
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::Member(const char* name) {
|
||||
WRITER->String(name, static_cast<SizeType>(strlen(name)));
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool JsonWriter::HasMember(const char*) const {
|
||||
// This function is for JsonReader only.
|
||||
assert(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::StartArray(size_t*) {
|
||||
WRITER->StartArray();
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::EndArray() {
|
||||
WRITER->EndArray();
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::operator&(bool& b) {
|
||||
WRITER->Bool(b);
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::operator&(unsigned& u) {
|
||||
WRITER->Uint(u);
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::operator&(int& i) {
|
||||
WRITER->Int(i);
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::operator&(double& d) {
|
||||
WRITER->Double(d);
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::operator&(std::string& s) {
|
||||
WRITER->String(s.c_str(), static_cast<SizeType>(s.size()));
|
||||
return *this;
|
||||
}
|
||||
|
||||
JsonWriter& JsonWriter::SetNull() {
|
||||
WRITER->Null();
|
||||
return *this;
|
||||
}
|
||||
|
||||
#undef STREAM
|
||||
#undef WRITER
|
139
example/archiver/archiver.h
Normal file
139
example/archiver/archiver.h
Normal file
@ -0,0 +1,139 @@
|
||||
#ifndef ARCHIVER_H_
|
||||
#define ARCHIVER_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
\class Archiver
|
||||
\brief Archiver concept
|
||||
|
||||
Archiver can be a reader or writer for serialization or deserialization respectively.
|
||||
|
||||
class Archiver {
|
||||
public:
|
||||
/// \returns true if the archiver is in normal state. false if it has errors.
|
||||
operator bool() const;
|
||||
|
||||
/// Starts an object
|
||||
Archiver& StartObject();
|
||||
|
||||
/// After calling StartObject(), assign a member with a name
|
||||
Archiver& Member(const char* name);
|
||||
|
||||
/// After calling StartObject(), check if a member presents
|
||||
bool HasMember(const char* name) const;
|
||||
|
||||
/// Ends an object
|
||||
Archiver& EndObject();
|
||||
|
||||
/// Starts an array
|
||||
/// \param size If Archiver::IsReader is true, the size of array is written.
|
||||
Archiver& StartArray(size_t* size = 0);
|
||||
|
||||
/// Ends an array
|
||||
Archiver& EndArray();
|
||||
|
||||
/// Read/Write primitive types.
|
||||
Archiver& operator&(bool& b);
|
||||
Archiver& operator&(unsigned& u);
|
||||
Archiver& operator&(int& i);
|
||||
Archiver& operator&(double& d);
|
||||
Archiver& operator&(std::string& s);
|
||||
|
||||
/// Write primitive types.
|
||||
Archiver& SetNull();
|
||||
|
||||
//! Whether it is a reader.
|
||||
static const bool IsReader;
|
||||
|
||||
//! Whether it is a writer.
|
||||
static const bool IsWriter;
|
||||
};
|
||||
*/
|
||||
|
||||
/// Represents a JSON reader which implements Archiver concept.
|
||||
class JsonReader {
|
||||
public:
|
||||
/// Constructor.
|
||||
/**
|
||||
\param json A non-const source json string for in-situ parsing.
|
||||
\note in-situ means the source JSON string will be modified after parsing.
|
||||
*/
|
||||
JsonReader(const char* json);
|
||||
|
||||
/// Destructor.
|
||||
~JsonReader();
|
||||
|
||||
// Archive concept
|
||||
|
||||
operator bool() const { return !mError; }
|
||||
|
||||
JsonReader& StartObject();
|
||||
JsonReader& Member(const char* name);
|
||||
bool HasMember(const char* name) const;
|
||||
JsonReader& EndObject();
|
||||
|
||||
JsonReader& StartArray(size_t* size = nullptr);
|
||||
JsonReader& EndArray();
|
||||
|
||||
JsonReader& operator&(bool& b);
|
||||
JsonReader& operator&(unsigned& u);
|
||||
JsonReader& operator&(int& i);
|
||||
JsonReader& operator&(double& d);
|
||||
JsonReader& operator&(std::string& s);
|
||||
|
||||
JsonReader& SetNull();
|
||||
|
||||
static const bool IsReader = true;
|
||||
static const bool IsWriter = !IsReader;
|
||||
|
||||
private:
|
||||
void Next();
|
||||
|
||||
// PIMPL
|
||||
void* mDocument; ///< DOM result of parsing.
|
||||
void* mStack; ///< Stack for iterating the DOM
|
||||
bool mError; ///< Whether an error is occured.
|
||||
};
|
||||
|
||||
class JsonWriter {
|
||||
public:
|
||||
/// Constructor.
|
||||
JsonWriter();
|
||||
|
||||
/// Destructor.
|
||||
~JsonWriter();
|
||||
|
||||
/// Obtains the serialized JSON string.
|
||||
const char* GetString() const;
|
||||
|
||||
// Archive concept
|
||||
|
||||
operator bool() const { return true; }
|
||||
|
||||
JsonWriter& StartObject();
|
||||
JsonWriter& Member(const char* name);
|
||||
bool HasMember(const char* name) const;
|
||||
JsonWriter& EndObject();
|
||||
|
||||
JsonWriter& StartArray(size_t* size = 0);
|
||||
JsonWriter& EndArray();
|
||||
|
||||
JsonWriter& operator&(bool& b);
|
||||
JsonWriter& operator&(unsigned& u);
|
||||
JsonWriter& operator&(int& i);
|
||||
JsonWriter& operator&(double& d);
|
||||
JsonWriter& operator&(std::string& s);
|
||||
JsonWriter& SetNull();
|
||||
|
||||
static const bool IsReader = false;
|
||||
static const bool IsWriter = !IsReader;
|
||||
|
||||
private:
|
||||
// PIMPL idiom
|
||||
void* mWriter; ///< JSON writer.
|
||||
void* mStream; ///< Stream buffer.
|
||||
};
|
||||
|
||||
#endif // ARCHIVER_H__
|
281
example/archiver/archivertest.cpp
Normal file
281
example/archiver/archivertest.cpp
Normal file
@ -0,0 +1,281 @@
|
||||
#include "archiver.h"
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Test1: simple object
|
||||
|
||||
struct Student {
|
||||
std::string name;
|
||||
unsigned age;
|
||||
double height;
|
||||
bool canSwim;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Student& s) {
|
||||
ar.StartObject();
|
||||
ar.Member("name") & s.name;
|
||||
ar.Member("age") & s.age;
|
||||
ar.Member("height") & s.height;
|
||||
ar.Member("canSwim") & s.canSwim;
|
||||
return ar.EndObject();
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const Student& s) {
|
||||
return os << s.name << " " << s.age << " " << s.height << " " << s.canSwim;
|
||||
}
|
||||
|
||||
void test1() {
|
||||
std::string json;
|
||||
|
||||
// Serialize
|
||||
{
|
||||
Student s = { "Lua", 9, 150.5, true };
|
||||
|
||||
JsonWriter writer;
|
||||
writer & s;
|
||||
json = writer.GetString();
|
||||
std::cout << json << std::endl;
|
||||
}
|
||||
|
||||
// Deserialize
|
||||
{
|
||||
Student s;
|
||||
JsonReader reader(json.c_str());
|
||||
reader & s;
|
||||
std::cout << s << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Test2: std::vector <=> JSON array
|
||||
//
|
||||
// You can map a JSON array to other data structures as well
|
||||
|
||||
struct Group {
|
||||
std::string groupName;
|
||||
std::vector<Student> students;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Group& g) {
|
||||
ar.StartObject();
|
||||
|
||||
ar.Member("groupName");
|
||||
ar & g.groupName;
|
||||
|
||||
ar.Member("students");
|
||||
size_t studentCount = g.students.size();
|
||||
ar.StartArray(&studentCount);
|
||||
if (ar.IsReader)
|
||||
g.students.resize(studentCount);
|
||||
for (size_t i = 0; i < studentCount; i++)
|
||||
ar & g.students[i];
|
||||
ar.EndArray();
|
||||
|
||||
return ar.EndObject();
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const Group& g) {
|
||||
os << g.groupName << std::endl;
|
||||
for (std::vector<Student>::const_iterator itr = g.students.begin(); itr != g.students.end(); ++itr)
|
||||
os << *itr << std::endl;
|
||||
return os;
|
||||
}
|
||||
|
||||
void test2() {
|
||||
std::string json;
|
||||
|
||||
// Serialize
|
||||
{
|
||||
Group g;
|
||||
g.groupName = "Rainbow";
|
||||
|
||||
Student s1 = { "Lua", 9, 150.5, true };
|
||||
Student s2 = { "Mio", 7, 120.0, false };
|
||||
g.students.push_back(s1);
|
||||
g.students.push_back(s2);
|
||||
|
||||
JsonWriter writer;
|
||||
writer & g;
|
||||
json = writer.GetString();
|
||||
std::cout << json << std::endl;
|
||||
}
|
||||
|
||||
// Deserialize
|
||||
{
|
||||
Group g;
|
||||
JsonReader reader(json.c_str());
|
||||
reader & g;
|
||||
std::cout << g << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Test3: polymorphism & friend
|
||||
//
|
||||
// Note that friendship is not necessary but make things simpler.
|
||||
|
||||
class Shape {
|
||||
public:
|
||||
virtual ~Shape() {}
|
||||
virtual const char* GetType() const = 0;
|
||||
virtual void Print(std::ostream& os) const = 0;
|
||||
|
||||
protected:
|
||||
Shape() {}
|
||||
Shape(double x, double y) : x_(x), y_(y) {}
|
||||
|
||||
template <typename Archiver>
|
||||
friend Archiver& operator&(Archiver& ar, Shape& s);
|
||||
|
||||
double x_, y_;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Shape& s) {
|
||||
ar.Member("x") & s.x_;
|
||||
ar.Member("y") & s.y_;
|
||||
return ar;
|
||||
}
|
||||
|
||||
class Circle : public Shape {
|
||||
public:
|
||||
Circle() {}
|
||||
Circle(double x, double y, double radius) : Shape(x, y), radius_(radius) {}
|
||||
~Circle() {}
|
||||
|
||||
const char* GetType() const { return "Circle"; }
|
||||
|
||||
void Print(std::ostream& os) const {
|
||||
os << "Circle (" << x_ << ", " << y_ << ")" << " radius = " << radius_;
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Archiver>
|
||||
friend Archiver& operator&(Archiver& ar, Circle& c);
|
||||
|
||||
double radius_;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Circle& c) {
|
||||
ar & static_cast<Shape&>(c);
|
||||
ar.Member("radius") & c.radius_;
|
||||
return ar;
|
||||
}
|
||||
|
||||
class Box : public Shape {
|
||||
public:
|
||||
Box() {}
|
||||
Box(double x, double y, double width, double height) : Shape(x, y), width_(width), height_(height) {}
|
||||
~Box() {}
|
||||
|
||||
const char* GetType() const { return "Box"; }
|
||||
|
||||
void Print(std::ostream& os) const {
|
||||
os << "Box (" << x_ << ", " << y_ << ")" << " width = " << width_ << " height = " << height_;
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Archiver>
|
||||
friend Archiver& operator&(Archiver& ar, Box& b);
|
||||
|
||||
double width_, height_;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Box& b) {
|
||||
ar & static_cast<Shape&>(b);
|
||||
ar.Member("width") & b.width_;
|
||||
ar.Member("height") & b.height_;
|
||||
return ar;
|
||||
}
|
||||
|
||||
class Canvas {
|
||||
public:
|
||||
Canvas() {}
|
||||
~Canvas() { Clear(); }
|
||||
|
||||
void Clear() {
|
||||
for (std::vector<Shape*>::iterator itr = shapes_.begin(); itr != shapes_.end(); ++itr)
|
||||
delete *itr;
|
||||
}
|
||||
|
||||
void AddShape(Shape* shape) { shapes_.push_back(shape); }
|
||||
|
||||
void Print(std::ostream& os) {
|
||||
for (std::vector<Shape*>::iterator itr = shapes_.begin(); itr != shapes_.end(); ++itr) {
|
||||
(*itr)->Print(os);
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Archiver>
|
||||
friend Archiver& operator&(Archiver& ar, Canvas& c);
|
||||
|
||||
std::vector<Shape*> shapes_;
|
||||
};
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Shape*& shape) {
|
||||
std::string type = ar.IsReader ? "" : shape->GetType();
|
||||
ar.StartObject();
|
||||
ar.Member("type") & type;
|
||||
if (type == "Circle") {
|
||||
if (ar.IsReader) shape = new Circle;
|
||||
ar & static_cast<Circle&>(*shape);
|
||||
}
|
||||
else if (type == "Box") {
|
||||
if (ar.IsReader) shape = new Box;
|
||||
ar & static_cast<Box&>(*shape);
|
||||
}
|
||||
return ar.EndObject();
|
||||
}
|
||||
|
||||
template <typename Archiver>
|
||||
Archiver& operator&(Archiver& ar, Canvas& c) {
|
||||
size_t shapeCount = c.shapes_.size();
|
||||
ar.StartArray(&shapeCount);
|
||||
if (ar.IsReader) {
|
||||
c.Clear();
|
||||
c.shapes_.resize(shapeCount);
|
||||
}
|
||||
for (size_t i = 0; i < shapeCount; i++)
|
||||
ar & c.shapes_[i];
|
||||
return ar.EndArray();
|
||||
}
|
||||
|
||||
void test3() {
|
||||
std::string json;
|
||||
|
||||
// Serialize
|
||||
{
|
||||
Canvas c;
|
||||
c.AddShape(new Circle(1.0, 2.0, 3.0));
|
||||
c.AddShape(new Box(4.0, 5.0, 6.0, 7.0));
|
||||
|
||||
JsonWriter writer;
|
||||
writer & c;
|
||||
json = writer.GetString();
|
||||
std::cout << json << std::endl;
|
||||
}
|
||||
|
||||
// Deserialize
|
||||
{
|
||||
Canvas c;
|
||||
JsonReader reader(json.c_str());
|
||||
reader & c;
|
||||
c.Print(std::cout);
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
int main() {
|
||||
test1();
|
||||
test2();
|
||||
test3();
|
||||
}
|
135
example/filterkey/filterkey.cpp
Normal file
135
example/filterkey/filterkey.cpp
Normal file
@ -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 <stack>
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
// This handler forwards event into an output handler, with filtering the descendent events of specified key.
|
||||
template <typename OutputHandler>
|
||||
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<SizeType> 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<FileWriteStream> writer(os);
|
||||
|
||||
// Prepare Filter
|
||||
FilterKeyHandler<Writer<FileWriteStream> > filter(writer, argv[1], static_cast<SizeType>(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<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
170
example/filterkeydom/filterkeydom.cpp
Normal file
170
example/filterkeydom/filterkeydom.cpp
Normal file
@ -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 <stack>
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
// This handler forwards event into an output handler, with filtering the descendent events of specified key.
|
||||
template <typename OutputHandler>
|
||||
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<SizeType> filteredKeyCount_;
|
||||
};
|
||||
|
||||
// Implements a generator for Document::Populate()
|
||||
template <typename InputStream>
|
||||
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 <typename Handler>
|
||||
bool operator()(Handler& handler) {
|
||||
FilterKeyHandler<Handler> 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<FileReadStream> reader(is, argv[1], static_cast<SizeType>(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<unsigned>(pr.Offset()), GetParseError_En(pr.Code()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Prepare JSON writer and output stream.
|
||||
char writeBuffer[65536];
|
||||
FileWriteStream os(stdout, writeBuffer, sizeof(writeBuffer));
|
||||
Writer<FileWriteStream> writer(os);
|
||||
|
||||
// Write the document to standard output
|
||||
document.Accept(writer);
|
||||
return 0;
|
||||
}
|
350
example/lookaheadparser/lookaheadparser.cpp
Normal file
350
example/lookaheadparser/lookaheadparser.cpp
Normal file
@ -0,0 +1,350 @@
|
||||
#include "rapidjson/reader.h"
|
||||
#include "rapidjson/document.h"
|
||||
#include <iostream>
|
||||
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
#ifdef __GNUC__
|
||||
RAPIDJSON_DIAG_OFF(effc++)
|
||||
#endif
|
||||
|
||||
// This example demonstrates JSON token-by-token parsing with an API that is
|
||||
// more direct; you don't need to design your logic around a handler object and
|
||||
// callbacks. Instead, you retrieve values from the JSON stream by calling
|
||||
// GetInt(), GetDouble(), GetString() and GetBool(), traverse into structures
|
||||
// by calling EnterObject() and EnterArray(), and skip over unwanted data by
|
||||
// calling SkipValue(). When you know your JSON's structure, this can be quite
|
||||
// convenient.
|
||||
//
|
||||
// If you aren't sure of what's next in the JSON data, you can use PeekType() and
|
||||
// PeekValue() to look ahead to the next object before reading it.
|
||||
//
|
||||
// If you call the wrong retrieval method--e.g. GetInt when the next JSON token is
|
||||
// not an int, EnterObject or EnterArray when there isn't actually an object or array
|
||||
// to read--the stream parsing will end immediately and no more data will be delivered.
|
||||
//
|
||||
// After calling EnterObject, you retrieve keys via NextObjectKey() and values via
|
||||
// the normal getters. When NextObjectKey() returns null, you have exited the
|
||||
// object, or you can call SkipObject() to skip to the end of the object
|
||||
// immediately. If you fetch the entire object (i.e. NextObjectKey() returned null),
|
||||
// you should not call SkipObject().
|
||||
//
|
||||
// After calling EnterArray(), you must alternate between calling NextArrayValue()
|
||||
// to see if the array has more data, and then retrieving values via the normal
|
||||
// getters. You can call SkipArray() to skip to the end of the array immediately.
|
||||
// If you fetch the entire array (i.e. NextArrayValue() returned null),
|
||||
// you should not call SkipArray().
|
||||
//
|
||||
// This parser uses in-situ strings, so the JSON buffer will be altered during the
|
||||
// parse.
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
|
||||
class LookaheadParserHandler {
|
||||
public:
|
||||
bool Null() { st_ = kHasNull; v_.SetNull(); return true; }
|
||||
bool Bool(bool b) { st_ = kHasBool; v_.SetBool(b); return true; }
|
||||
bool Int(int i) { st_ = kHasNumber; v_.SetInt(i); return true; }
|
||||
bool Uint(unsigned u) { st_ = kHasNumber; v_.SetUint(u); return true; }
|
||||
bool Int64(int64_t i) { st_ = kHasNumber; v_.SetInt64(i); return true; }
|
||||
bool Uint64(uint64_t u) { st_ = kHasNumber; v_.SetUint64(u); return true; }
|
||||
bool Double(double d) { st_ = kHasNumber; v_.SetDouble(d); return true; }
|
||||
bool RawNumber(const char*, SizeType, bool) { return false; }
|
||||
bool String(const char* str, SizeType length, bool) { st_ = kHasString; v_.SetString(str, length); return true; }
|
||||
bool StartObject() { st_ = kEnteringObject; return true; }
|
||||
bool Key(const char* str, SizeType length, bool) { st_ = kHasKey; v_.SetString(str, length); return true; }
|
||||
bool EndObject(SizeType) { st_ = kExitingObject; return true; }
|
||||
bool StartArray() { st_ = kEnteringArray; return true; }
|
||||
bool EndArray(SizeType) { st_ = kExitingArray; return true; }
|
||||
|
||||
protected:
|
||||
LookaheadParserHandler(char* str);
|
||||
void ParseNext();
|
||||
|
||||
protected:
|
||||
enum LookaheadParsingState {
|
||||
kInit,
|
||||
kError,
|
||||
kHasNull,
|
||||
kHasBool,
|
||||
kHasNumber,
|
||||
kHasString,
|
||||
kHasKey,
|
||||
kEnteringObject,
|
||||
kExitingObject,
|
||||
kEnteringArray,
|
||||
kExitingArray
|
||||
};
|
||||
|
||||
Value v_;
|
||||
LookaheadParsingState st_;
|
||||
Reader r_;
|
||||
InsituStringStream ss_;
|
||||
|
||||
static const int parseFlags = kParseDefaultFlags | kParseInsituFlag;
|
||||
};
|
||||
|
||||
LookaheadParserHandler::LookaheadParserHandler(char* str) : v_(), st_(kInit), r_(), ss_(str) {
|
||||
r_.IterativeParseInit();
|
||||
ParseNext();
|
||||
}
|
||||
|
||||
void LookaheadParserHandler::ParseNext() {
|
||||
if (r_.HasParseError()) {
|
||||
st_ = kError;
|
||||
return;
|
||||
}
|
||||
|
||||
r_.IterativeParseNext<parseFlags>(ss_, *this);
|
||||
}
|
||||
|
||||
class LookaheadParser : protected LookaheadParserHandler {
|
||||
public:
|
||||
LookaheadParser(char* str) : LookaheadParserHandler(str) {}
|
||||
|
||||
bool EnterObject();
|
||||
bool EnterArray();
|
||||
const char* NextObjectKey();
|
||||
bool NextArrayValue();
|
||||
int GetInt();
|
||||
double GetDouble();
|
||||
const char* GetString();
|
||||
bool GetBool();
|
||||
void GetNull();
|
||||
|
||||
void SkipObject();
|
||||
void SkipArray();
|
||||
void SkipValue();
|
||||
Value* PeekValue();
|
||||
int PeekType(); // returns a rapidjson::Type, or -1 for no value (at end of object/array)
|
||||
|
||||
bool IsValid() { return st_ != kError; }
|
||||
|
||||
protected:
|
||||
void SkipOut(int depth);
|
||||
};
|
||||
|
||||
bool LookaheadParser::EnterObject() {
|
||||
if (st_ != kEnteringObject) {
|
||||
st_ = kError;
|
||||
return false;
|
||||
}
|
||||
|
||||
ParseNext();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LookaheadParser::EnterArray() {
|
||||
if (st_ != kEnteringArray) {
|
||||
st_ = kError;
|
||||
return false;
|
||||
}
|
||||
|
||||
ParseNext();
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* LookaheadParser::NextObjectKey() {
|
||||
if (st_ == kHasKey) {
|
||||
const char* result = v_.GetString();
|
||||
ParseNext();
|
||||
return result;
|
||||
}
|
||||
|
||||
if (st_ != kExitingObject) {
|
||||
st_ = kError;
|
||||
return 0;
|
||||
}
|
||||
|
||||
ParseNext();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool LookaheadParser::NextArrayValue() {
|
||||
if (st_ == kExitingArray) {
|
||||
ParseNext();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (st_ == kError || st_ == kExitingObject || st_ == kHasKey) {
|
||||
st_ = kError;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int LookaheadParser::GetInt() {
|
||||
if (st_ != kHasNumber || !v_.IsInt()) {
|
||||
st_ = kError;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int result = v_.GetInt();
|
||||
ParseNext();
|
||||
return result;
|
||||
}
|
||||
|
||||
double LookaheadParser::GetDouble() {
|
||||
if (st_ != kHasNumber) {
|
||||
st_ = kError;
|
||||
return 0.;
|
||||
}
|
||||
|
||||
double result = v_.GetDouble();
|
||||
ParseNext();
|
||||
return result;
|
||||
}
|
||||
|
||||
bool LookaheadParser::GetBool() {
|
||||
if (st_ != kHasBool) {
|
||||
st_ = kError;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool result = v_.GetBool();
|
||||
ParseNext();
|
||||
return result;
|
||||
}
|
||||
|
||||
void LookaheadParser::GetNull() {
|
||||
if (st_ != kHasNull) {
|
||||
st_ = kError;
|
||||
return;
|
||||
}
|
||||
|
||||
ParseNext();
|
||||
}
|
||||
|
||||
const char* LookaheadParser::GetString() {
|
||||
if (st_ != kHasString) {
|
||||
st_ = kError;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char* result = v_.GetString();
|
||||
ParseNext();
|
||||
return result;
|
||||
}
|
||||
|
||||
void LookaheadParser::SkipOut(int depth) {
|
||||
do {
|
||||
if (st_ == kEnteringArray || st_ == kEnteringObject) {
|
||||
++depth;
|
||||
}
|
||||
else if (st_ == kExitingArray || st_ == kExitingObject) {
|
||||
--depth;
|
||||
}
|
||||
else if (st_ == kError) {
|
||||
return;
|
||||
}
|
||||
|
||||
ParseNext();
|
||||
}
|
||||
while (depth > 0);
|
||||
}
|
||||
|
||||
void LookaheadParser::SkipValue() {
|
||||
SkipOut(0);
|
||||
}
|
||||
|
||||
void LookaheadParser::SkipArray() {
|
||||
SkipOut(1);
|
||||
}
|
||||
|
||||
void LookaheadParser::SkipObject() {
|
||||
SkipOut(1);
|
||||
}
|
||||
|
||||
Value* LookaheadParser::PeekValue() {
|
||||
if (st_ >= kHasNull && st_ <= kHasKey) {
|
||||
return &v_;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int LookaheadParser::PeekType() {
|
||||
if (st_ >= kHasNull && st_ <= kHasKey) {
|
||||
return v_.GetType();
|
||||
}
|
||||
|
||||
if (st_ == kEnteringArray) {
|
||||
return kArrayType;
|
||||
}
|
||||
|
||||
if (st_ == kEnteringObject) {
|
||||
return kObjectType;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
//-------------------------------------------------------------------------
|
||||
|
||||
int main() {
|
||||
using namespace std;
|
||||
|
||||
char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null,"
|
||||
"\"i\":123, \"pi\": 3.1416, \"a\":[-1, 2, 3, 4, \"array\", []], \"skipArrays\":[1, 2, [[[3]]]], "
|
||||
"\"skipObject\":{ \"i\":0, \"t\":true, \"n\":null, \"d\":123.45 }, "
|
||||
"\"skipNested\":[[[[{\"\":0}, {\"\":[-9.87]}]]], [], []], "
|
||||
"\"skipString\":\"zzz\", \"reachedEnd\":null, \"t\":true }";
|
||||
|
||||
LookaheadParser r(json);
|
||||
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kObjectType);
|
||||
|
||||
r.EnterObject();
|
||||
while (const char* key = r.NextObjectKey()) {
|
||||
if (0 == strcmp(key, "hello")) {
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kStringType);
|
||||
cout << key << ":" << r.GetString() << endl;
|
||||
}
|
||||
else if (0 == strcmp(key, "t") || 0 == strcmp(key, "f")) {
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kTrueType || r.PeekType() == kFalseType);
|
||||
cout << key << ":" << r.GetBool() << endl;
|
||||
continue;
|
||||
}
|
||||
else if (0 == strcmp(key, "n")) {
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kNullType);
|
||||
r.GetNull();
|
||||
cout << key << endl;
|
||||
continue;
|
||||
}
|
||||
else if (0 == strcmp(key, "pi")) {
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kNumberType);
|
||||
cout << key << ":" << r.GetDouble() << endl;
|
||||
continue;
|
||||
}
|
||||
else if (0 == strcmp(key, "a")) {
|
||||
RAPIDJSON_ASSERT(r.PeekType() == kArrayType);
|
||||
|
||||
r.EnterArray();
|
||||
|
||||
cout << key << ":[ ";
|
||||
while (r.NextArrayValue()) {
|
||||
if (r.PeekType() == kNumberType) {
|
||||
cout << r.GetDouble() << " ";
|
||||
}
|
||||
else if (r.PeekType() == kStringType) {
|
||||
cout << r.GetString() << " ";
|
||||
}
|
||||
else {
|
||||
r.SkipArray();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
cout << "]" << endl;
|
||||
}
|
||||
else {
|
||||
cout << key << ":skipped" << endl;
|
||||
r.SkipValue();
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
RAPIDJSON_DIAG_POP
|
@ -1,7 +1,8 @@
|
||||
// Example of parsing JSON to document by parts.
|
||||
|
||||
// Using C++11 threads
|
||||
#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1700)
|
||||
// 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"
|
||||
@ -20,12 +21,15 @@ public:
|
||||
AsyncDocumentParser(Document& d)
|
||||
: stream_(*this)
|
||||
, d_(d)
|
||||
, parseThread_(&AsyncDocumentParser::Parse, this)
|
||||
, parseThread_()
|
||||
, mutex_()
|
||||
, notEmpty_()
|
||||
, finish_()
|
||||
, completed_()
|
||||
{}
|
||||
{
|
||||
// Create and execute thread after all member variables are initialized.
|
||||
parseThread_ = std::thread(&AsyncDocumentParser::Parse, this);
|
||||
}
|
||||
|
||||
~AsyncDocumentParser() {
|
||||
if (!parseThread_.joinable())
|
||||
|
53
example/simplepullreader/simplepullreader.cpp
Normal file
53
example/simplepullreader/simplepullreader.cpp
Normal file
@ -0,0 +1,53 @@
|
||||
#include "rapidjson/reader.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
using namespace rapidjson;
|
||||
using namespace std;
|
||||
|
||||
// If you can require C++11, you could use std::to_string here
|
||||
template <typename T> std::string stringify(T x) {
|
||||
std::stringstream ss;
|
||||
ss << x;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
struct MyHandler {
|
||||
const char* type;
|
||||
std::string data;
|
||||
|
||||
MyHandler() : type(), data() {}
|
||||
|
||||
bool Null() { type = "Null"; data.clear(); return true; }
|
||||
bool Bool(bool b) { type = "Bool:"; data = b? "true": "false"; return true; }
|
||||
bool Int(int i) { type = "Int:"; data = stringify(i); return true; }
|
||||
bool Uint(unsigned u) { type = "Uint:"; data = stringify(u); return true; }
|
||||
bool Int64(int64_t i) { type = "Int64:"; data = stringify(i); return true; }
|
||||
bool Uint64(uint64_t u) { type = "Uint64:"; data = stringify(u); return true; }
|
||||
bool Double(double d) { type = "Double:"; data = stringify(d); return true; }
|
||||
bool RawNumber(const char* str, SizeType length, bool) { type = "Number:"; data = std::string(str, length); return true; }
|
||||
bool String(const char* str, SizeType length, bool) { type = "String:"; data = std::string(str, length); return true; }
|
||||
bool StartObject() { type = "StartObject"; data.clear(); return true; }
|
||||
bool Key(const char* str, SizeType length, bool) { type = "Key:"; data = std::string(str, length); return true; }
|
||||
bool EndObject(SizeType memberCount) { type = "EndObject:"; data = stringify(memberCount); return true; }
|
||||
bool StartArray() { type = "StartArray"; data.clear(); return true; }
|
||||
bool EndArray(SizeType elementCount) { type = "EndArray:"; data = stringify(elementCount); return true; }
|
||||
private:
|
||||
MyHandler(const MyHandler& noCopyConstruction);
|
||||
MyHandler& operator=(const MyHandler& noAssignment);
|
||||
};
|
||||
|
||||
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.IterativeParseInit();
|
||||
while (!reader.IterativeParseComplete()) {
|
||||
reader.IterativeParseNext<kParseDefaultFlags>(ss, handler);
|
||||
cout << handler.type << handler.data << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
@ -9,26 +9,27 @@ int main() {
|
||||
StringBuffer s;
|
||||
Writer<StringBuffer> writer(s);
|
||||
|
||||
writer.StartObject();
|
||||
writer.String("hello");
|
||||
writer.String("world");
|
||||
writer.String("t");
|
||||
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.String("f");
|
||||
writer.Key("f");
|
||||
writer.Bool(false);
|
||||
writer.String("n");
|
||||
writer.Key("n");
|
||||
writer.Null();
|
||||
writer.String("i");
|
||||
writer.Key("i");
|
||||
writer.Uint(123);
|
||||
writer.String("pi");
|
||||
writer.Key("pi");
|
||||
writer.Double(3.1416);
|
||||
writer.String("a");
|
||||
writer.StartArray();
|
||||
writer.Key("a");
|
||||
writer.StartArray(); // Between StartArray()/EndArray(),
|
||||
for (unsigned i = 0; i < 4; i++)
|
||||
writer.Uint(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;
|
||||
|
@ -179,7 +179,8 @@ public:
|
||||
|
||||
size = RAPIDJSON_ALIGN(size);
|
||||
if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
|
||||
AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size);
|
||||
if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
|
||||
return NULL;
|
||||
|
||||
void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
|
||||
chunkHead_->size += size;
|
||||
@ -211,11 +212,13 @@ public:
|
||||
}
|
||||
|
||||
// Realloc process: allocate and copy memory, do not free original buffer.
|
||||
void* newBuffer = Malloc(newSize);
|
||||
RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly.
|
||||
if (originalSize)
|
||||
std::memcpy(newBuffer, originalPtr, originalSize);
|
||||
return newBuffer;
|
||||
if (void* newBuffer = Malloc(newSize)) {
|
||||
if (originalSize)
|
||||
std::memcpy(newBuffer, originalPtr, originalSize);
|
||||
return newBuffer;
|
||||
}
|
||||
else
|
||||
return NULL;
|
||||
}
|
||||
|
||||
//! Frees a memory block (concept Allocator)
|
||||
@ -229,15 +232,20 @@ private:
|
||||
|
||||
//! Creates a new chunk.
|
||||
/*! \param capacity Capacity of the chunk in bytes.
|
||||
\return true if success.
|
||||
*/
|
||||
void AddChunk(size_t capacity) {
|
||||
bool AddChunk(size_t capacity) {
|
||||
if (!baseAllocator_)
|
||||
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
|
||||
ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity));
|
||||
chunk->capacity = capacity;
|
||||
chunk->size = 0;
|
||||
chunk->next = chunkHead_;
|
||||
chunkHead_ = chunk;
|
||||
ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator)();
|
||||
if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(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.
|
||||
|
78
include/rapidjson/cursorstreamwrapper.h
Normal file
78
include/rapidjson/cursorstreamwrapper.h
Normal file
@ -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_CURSORSTREAMWRAPPER_H_
|
||||
#define RAPIDJSON_CURSORSTREAMWRAPPER_H_
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
#if defined(__GNUC__)
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(effc++)
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1800
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(4702) // unreachable code
|
||||
RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
|
||||
#endif
|
||||
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
|
||||
|
||||
//! Cursor stream wrapper for counting line and column number if error exists.
|
||||
/*!
|
||||
\tparam InputStream Any stream that implements Stream Concept
|
||||
*/
|
||||
template <typename InputStream, typename Encoding = UTF8<> >
|
||||
class CursorStreamWrapper : public GenericStreamWrapper<InputStream, Encoding> {
|
||||
public:
|
||||
typedef typename Encoding::Ch Ch;
|
||||
|
||||
CursorStreamWrapper(InputStream& is):
|
||||
GenericStreamWrapper<InputStream, Encoding>(is), line_(1), col_(0) {}
|
||||
|
||||
// counting line and column number
|
||||
Ch Take() {
|
||||
Ch ch = this->is_.Take();
|
||||
if(ch == '\n') {
|
||||
line_ ++;
|
||||
col_ = 0;
|
||||
} else {
|
||||
col_ ++;
|
||||
}
|
||||
return ch;
|
||||
}
|
||||
|
||||
//! Get the error line number, if error exists.
|
||||
size_t GetLine() const { return line_; }
|
||||
//! Get the error column number, if error exists.
|
||||
size_t GetColumn() const { return col_; }
|
||||
|
||||
private:
|
||||
size_t line_; //!< Current Line
|
||||
size_t col_; //!< Current Column
|
||||
};
|
||||
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1800
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__)
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#endif // RAPIDJSON_CURSORSTREAMWRAPPER_H_
|
@ -23,26 +23,29 @@
|
||||
#include "memorystream.h"
|
||||
#include "encodedstream.h"
|
||||
#include <new> // placement new
|
||||
#include <limits>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
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_PUSH
|
||||
RAPIDJSON_DIAG_OFF(padded)
|
||||
RAPIDJSON_DIAG_OFF(switch-enum)
|
||||
RAPIDJSON_DIAG_OFF(c++98-compat)
|
||||
#endif
|
||||
|
||||
#ifdef __GNUC__
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
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 <iterator> // std::iterator, std::random_access_iterator_tag
|
||||
#include <iterator> // std::random_access_iterator_tag
|
||||
#endif
|
||||
|
||||
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
||||
@ -95,16 +98,13 @@ struct GenericMember {
|
||||
\see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
|
||||
*/
|
||||
template <bool Const, typename Encoding, typename Allocator>
|
||||
class GenericMemberIterator
|
||||
: public std::iterator<std::random_access_iterator_tag
|
||||
, typename internal::MaybeAddConst<Const,GenericMember<Encoding,Allocator> >::Type> {
|
||||
class GenericMemberIterator {
|
||||
|
||||
friend class GenericValue<Encoding,Allocator>;
|
||||
template <bool, typename, typename> friend class GenericMemberIterator;
|
||||
|
||||
typedef GenericMember<Encoding,Allocator> PlainType;
|
||||
typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
|
||||
typedef std::iterator<std::random_access_iterator_tag,ValueType> BaseType;
|
||||
|
||||
public:
|
||||
//! Iterator type itself
|
||||
@ -114,12 +114,21 @@ public:
|
||||
//! Non-constant iterator type
|
||||
typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator;
|
||||
|
||||
/** \name std::iterator_traits support */
|
||||
//@{
|
||||
typedef ValueType value_type;
|
||||
typedef ValueType * pointer;
|
||||
typedef ValueType & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
//@}
|
||||
|
||||
//! Pointer to (const) GenericMember
|
||||
typedef typename BaseType::pointer Pointer;
|
||||
typedef pointer Pointer;
|
||||
//! Reference to (const) GenericMember
|
||||
typedef typename BaseType::reference Reference;
|
||||
typedef reference Reference;
|
||||
//! Signed integer type (e.g. \c ptrdiff_t)
|
||||
typedef typename BaseType::difference_type DifferenceType;
|
||||
typedef difference_type DifferenceType;
|
||||
|
||||
//! Default constructor (singular value)
|
||||
/*! Creates an iterator pointing to no element.
|
||||
@ -297,7 +306,7 @@ struct GenericStringRef {
|
||||
*/
|
||||
#endif
|
||||
explicit GenericStringRef(const CharType* str)
|
||||
: s(str), length(internal::StrLen(str)){ RAPIDJSON_ASSERT(s != 0); }
|
||||
: s(str), length(NotNullStrLen(str)) {}
|
||||
|
||||
//! Create constant string reference from pointer and length
|
||||
#ifndef __clang__ // -Wdocumentation
|
||||
@ -309,7 +318,9 @@ struct GenericStringRef {
|
||||
*/
|
||||
#endif
|
||||
GenericStringRef(const CharType* str, SizeType len)
|
||||
: s(str), length(len) { RAPIDJSON_ASSERT(s != 0); }
|
||||
: s(RAPIDJSON_LIKELY(str) ? str : emptyString), length(len) { RAPIDJSON_ASSERT(str != 0 || len == 0u); }
|
||||
|
||||
GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {}
|
||||
|
||||
//! implicit conversion to plain CharType pointer
|
||||
operator const Ch *() const { return s; }
|
||||
@ -318,11 +329,24 @@ struct GenericStringRef {
|
||||
const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
|
||||
|
||||
private:
|
||||
SizeType NotNullStrLen(const CharType* str) {
|
||||
RAPIDJSON_ASSERT(str != 0);
|
||||
return internal::StrLen(str);
|
||||
}
|
||||
|
||||
/// Empty string - used when passing in a NULL pointer
|
||||
static const Ch emptyString[];
|
||||
|
||||
//! Disallow construction from non-const array
|
||||
template<SizeType N>
|
||||
GenericStringRef(CharType (&str)[N]) /* = delete */;
|
||||
//! Copy assignment operator not permitted - immutable type
|
||||
GenericStringRef& operator=(const GenericStringRef& rhs) /* = delete */;
|
||||
};
|
||||
|
||||
template<typename CharType>
|
||||
const CharType GenericStringRef<CharType>::emptyString[] = { CharType() };
|
||||
|
||||
//! 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
|
||||
@ -337,7 +361,7 @@ private:
|
||||
*/
|
||||
template<typename CharType>
|
||||
inline GenericStringRef<CharType> StringRef(const CharType* str) {
|
||||
return GenericStringRef<CharType>(str, internal::StrLen(str));
|
||||
return GenericStringRef<CharType>(str);
|
||||
}
|
||||
|
||||
//! Mark a character pointer as constant string
|
||||
@ -473,7 +497,7 @@ template<typename ValueType>
|
||||
struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > {
|
||||
typedef std::basic_string<typename ValueType::Ch> StringType;
|
||||
static bool Is(const ValueType& v) { return v.IsString(); }
|
||||
static StringType Get(const ValueType& v) { return v.GetString(); }
|
||||
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
|
||||
@ -500,7 +524,7 @@ struct TypeHelper<ValueType, typename ValueType::Object> {
|
||||
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; }
|
||||
static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { return v = data; }
|
||||
};
|
||||
|
||||
template<typename ValueType>
|
||||
@ -587,7 +611,7 @@ public:
|
||||
kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag,
|
||||
kNumberAnyFlag
|
||||
};
|
||||
RAPIDJSON_ASSERT(type <= kNumberType);
|
||||
RAPIDJSON_ASSERT(type >= kNullType && type <= kNumberType);
|
||||
data_.f.flags = defaultFlags[type];
|
||||
|
||||
// Use ShortString to store empty string.
|
||||
@ -600,10 +624,50 @@ public:
|
||||
\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().
|
||||
\param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
|
||||
\see CopyFrom()
|
||||
*/
|
||||
template< typename SourceAllocator >
|
||||
GenericValue(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator & allocator);
|
||||
template <typename SourceAllocator>
|
||||
GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) {
|
||||
switch (rhs.GetType()) {
|
||||
case kObjectType: {
|
||||
SizeType count = rhs.data_.o.size;
|
||||
Member* lm = reinterpret_cast<Member*>(allocator.Malloc(count * sizeof(Member)));
|
||||
const typename GenericValue<Encoding,SourceAllocator>::Member* rm = rhs.GetMembersPointer();
|
||||
for (SizeType i = 0; i < count; i++) {
|
||||
new (&lm[i].name) GenericValue(rm[i].name, allocator, copyConstStrings);
|
||||
new (&lm[i].value) GenericValue(rm[i].value, allocator, copyConstStrings);
|
||||
}
|
||||
data_.f.flags = kObjectFlag;
|
||||
data_.o.size = data_.o.capacity = count;
|
||||
SetMembersPointer(lm);
|
||||
}
|
||||
break;
|
||||
case kArrayType: {
|
||||
SizeType count = rhs.data_.a.size;
|
||||
GenericValue* le = reinterpret_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue)));
|
||||
const GenericValue<Encoding,SourceAllocator>* re = rhs.GetElementsPointer();
|
||||
for (SizeType i = 0; i < count; i++)
|
||||
new (&le[i]) GenericValue(re[i], allocator, copyConstStrings);
|
||||
data_.f.flags = kArrayFlag;
|
||||
data_.a.size = data_.a.capacity = count;
|
||||
SetElementsPointer(le);
|
||||
}
|
||||
break;
|
||||
case kStringType:
|
||||
if (rhs.data_.f.flags == kConstStringFlag && !copyConstStrings) {
|
||||
data_.f.flags = rhs.data_.f.flags;
|
||||
data_ = *reinterpret_cast<const Data*>(&rhs.data_);
|
||||
}
|
||||
else
|
||||
SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
|
||||
break;
|
||||
default:
|
||||
data_.f.flags = rhs.data_.f.flags;
|
||||
data_ = *reinterpret_cast<const Data*>(&rhs.data_);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//! Constructor for boolean value.
|
||||
/*! \param b Boolean value
|
||||
@ -665,6 +729,9 @@ public:
|
||||
//! Constructor for double value.
|
||||
explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; }
|
||||
|
||||
//! Constructor for float value.
|
||||
explicit GenericValue(float f) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = static_cast<double>(f); 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)); }
|
||||
|
||||
@ -793,12 +860,13 @@ public:
|
||||
\tparam SourceAllocator Allocator type of \c rhs
|
||||
\param rhs Value to copy from (read-only)
|
||||
\param allocator Allocator to use for copying
|
||||
\param copyConstStrings Force copying of constant strings (e.g. referencing an in-situ buffer)
|
||||
*/
|
||||
template <typename SourceAllocator>
|
||||
GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator) {
|
||||
GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator, bool copyConstStrings = false) {
|
||||
RAPIDJSON_ASSERT(static_cast<void*>(this) != static_cast<void const*>(&rhs));
|
||||
this->~GenericValue();
|
||||
new (this) GenericValue(rhs, allocator);
|
||||
new (this) GenericValue(rhs, allocator, copyConstStrings);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@ -947,12 +1015,16 @@ public:
|
||||
if (IsUint64()) {
|
||||
uint64_t u = GetUint64();
|
||||
volatile double d = static_cast<double>(u);
|
||||
return static_cast<uint64_t>(d) == u;
|
||||
return (d >= 0.0)
|
||||
&& (d < static_cast<double>((std::numeric_limits<uint64_t>::max)()))
|
||||
&& (u == static_cast<uint64_t>(d));
|
||||
}
|
||||
if (IsInt64()) {
|
||||
int64_t i = GetInt64();
|
||||
volatile double d = static_cast<double>(i);
|
||||
return static_cast< int64_t>(d) == i;
|
||||
return (d >= static_cast<double>((std::numeric_limits<int64_t>::min)()))
|
||||
&& (d < static_cast<double>((std::numeric_limits<int64_t>::max)()))
|
||||
&& (i == static_cast<int64_t>(d));
|
||||
}
|
||||
return true; // double, int, uint are always lossless
|
||||
}
|
||||
@ -968,6 +1040,9 @@ public:
|
||||
bool IsLosslessFloat() const {
|
||||
if (!IsNumber()) return false;
|
||||
double a = GetDouble();
|
||||
if (a < static_cast<double>(-(std::numeric_limits<float>::max)())
|
||||
|| a > static_cast<double>((std::numeric_limits<float>::max)()))
|
||||
return false;
|
||||
double b = static_cast<double>(static_cast<float>(a));
|
||||
return a >= b && a <= b; // Prevent -Wfloat-equal
|
||||
}
|
||||
@ -1001,6 +1076,9 @@ public:
|
||||
//! Get the number of members in the object.
|
||||
SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; }
|
||||
|
||||
//! Get the capacity of object.
|
||||
SizeType MemberCapacity() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.capacity; }
|
||||
|
||||
//! Check whether the object is empty.
|
||||
bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; }
|
||||
|
||||
@ -1069,6 +1147,21 @@ public:
|
||||
/*! \pre IsObject() == true */
|
||||
MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); }
|
||||
|
||||
//! Request the object to have enough capacity to store members.
|
||||
/*! \param newCapacity The capacity that the object 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& MemberReserve(SizeType newCapacity, Allocator &allocator) {
|
||||
RAPIDJSON_ASSERT(IsObject());
|
||||
if (newCapacity > data_.o.capacity) {
|
||||
SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), data_.o.capacity * sizeof(Member), newCapacity * sizeof(Member))));
|
||||
data_.o.capacity = newCapacity;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Check whether a member exists in the object.
|
||||
/*!
|
||||
\param name Member name to be searched.
|
||||
@ -1155,8 +1248,8 @@ public:
|
||||
\return Iterator to member, if it exists.
|
||||
Otherwise returns \ref MemberEnd().
|
||||
*/
|
||||
MemberIterator FindMember(const std::basic_string<Ch>& name) { return FindMember(StringRef(name)); }
|
||||
ConstMemberIterator FindMember(const std::basic_string<Ch>& name) const { return FindMember(StringRef(name)); }
|
||||
MemberIterator FindMember(const std::basic_string<Ch>& name) { return FindMember(GenericValue(StringRef(name))); }
|
||||
ConstMemberIterator FindMember(const std::basic_string<Ch>& name) const { return FindMember(GenericValue(StringRef(name))); }
|
||||
#endif
|
||||
|
||||
//! Add a member (name-value pair) to the object.
|
||||
@ -1174,17 +1267,8 @@ public:
|
||||
RAPIDJSON_ASSERT(name.IsString());
|
||||
|
||||
ObjectData& o = data_.o;
|
||||
if (o.size >= o.capacity) {
|
||||
if (o.capacity == 0) {
|
||||
o.capacity = kDefaultObjectCapacity;
|
||||
SetMembersPointer(reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member))));
|
||||
}
|
||||
else {
|
||||
SizeType oldCapacity = o.capacity;
|
||||
o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5
|
||||
SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), oldCapacity * sizeof(Member), o.capacity * sizeof(Member))));
|
||||
}
|
||||
}
|
||||
if (o.size >= o.capacity)
|
||||
MemberReserve(o.capacity == 0 ? kDefaultObjectCapacity : (o.capacity + (o.capacity + 1) / 2), allocator);
|
||||
Member* members = GetMembersPointer();
|
||||
members[o.size].name.RawAssign(name);
|
||||
members[o.size].value.RawAssign(value);
|
||||
@ -1649,7 +1733,6 @@ public:
|
||||
/*! \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 {
|
||||
RAPIDJSON_ASSERT(IsFloat());
|
||||
return static_cast<float>(GetDouble());
|
||||
}
|
||||
|
||||
@ -1658,7 +1741,7 @@ public:
|
||||
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; }
|
||||
GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(static_cast<double>(f)); return *this; }
|
||||
|
||||
//@}
|
||||
|
||||
@ -1697,7 +1780,7 @@ public:
|
||||
\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; }
|
||||
GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { return SetString(StringRef(s, length), allocator); }
|
||||
|
||||
//! Set this value as a string by copying from source string.
|
||||
/*! \param s source string.
|
||||
@ -1705,7 +1788,15 @@ public:
|
||||
\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); }
|
||||
GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
|
||||
|
||||
//! Set this value as a string by copying from source string.
|
||||
/*! \param s source string reference
|
||||
\param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
|
||||
\return The value itself for fluent API.
|
||||
\post IsString() == true && GetString() != s.s && strcmp(GetString(),s) == 0 && GetStringLength() == length
|
||||
*/
|
||||
GenericValue& SetString(StringRefType s, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, allocator); return *this; }
|
||||
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
//! Set this value as a string by copying from source string.
|
||||
@ -1715,7 +1806,7 @@ public:
|
||||
\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<Ch>& s, Allocator& allocator) { return SetString(s.data(), SizeType(s.size()), allocator); }
|
||||
GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(StringRef(s), allocator); }
|
||||
#endif
|
||||
|
||||
//@}
|
||||
@ -2025,7 +2116,7 @@ public:
|
||||
GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
|
||||
{
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
}
|
||||
|
||||
//! Constructor
|
||||
@ -2038,7 +2129,7 @@ public:
|
||||
allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
|
||||
{
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
}
|
||||
|
||||
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
||||
@ -2099,6 +2190,10 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Allow Swap with ValueType.
|
||||
// Refer to Effective C++ 3rd Edition/Item 33: Avoid hiding inherited names.
|
||||
using ValueType::Swap;
|
||||
|
||||
//! free-standing swap function helper
|
||||
/*!
|
||||
Helper function to enable support for common swap implementation pattern based on \c std::swap:
|
||||
@ -2230,7 +2325,7 @@ public:
|
||||
template <unsigned parseFlags, typename SourceEncoding>
|
||||
GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) {
|
||||
RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
|
||||
MemoryStream ms(static_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch));
|
||||
MemoryStream ms(reinterpret_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch));
|
||||
EncodedInputStream<SourceEncoding, MemoryStream> is(ms);
|
||||
ParseStream<parseFlags, SourceEncoding>(is);
|
||||
return *this;
|
||||
@ -2388,35 +2483,6 @@ private:
|
||||
//! GenericDocument with UTF8 encoding
|
||||
typedef GenericDocument<UTF8<> > Document;
|
||||
|
||||
// defined here due to the dependency on GenericDocument
|
||||
template <typename Encoding, typename Allocator>
|
||||
template <typename SourceAllocator>
|
||||
inline
|
||||
GenericValue<Encoding,Allocator>::GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator)
|
||||
{
|
||||
switch (rhs.GetType()) {
|
||||
case kObjectType:
|
||||
case kArrayType: { // perform deep copy via SAX Handler
|
||||
GenericDocument<Encoding,Allocator> d(&allocator);
|
||||
rhs.Accept(d);
|
||||
RawAssign(*d.stack_.template Pop<GenericValue>(1));
|
||||
}
|
||||
break;
|
||||
case kStringType:
|
||||
if (rhs.data_.f.flags == kConstStringFlag) {
|
||||
data_.f.flags = rhs.data_.f.flags;
|
||||
data_ = *reinterpret_cast<const Data*>(&rhs.data_);
|
||||
} else {
|
||||
SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
data_.f.flags = rhs.data_.f.flags;
|
||||
data_ = *reinterpret_cast<const Data*>(&rhs.data_);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//! Helper class for accessing Value of array type.
|
||||
/*!
|
||||
Instance of this helper class is obtained by \c GenericValue::GetArray().
|
||||
@ -2497,6 +2563,7 @@ public:
|
||||
~GenericObject() {}
|
||||
|
||||
SizeType MemberCount() const { return value_.MemberCount(); }
|
||||
SizeType MemberCapacity() const { return value_.MemberCapacity(); }
|
||||
bool ObjectEmpty() const { return value_.ObjectEmpty(); }
|
||||
template <typename T> ValueType& operator[](T* name) const { return value_[name]; }
|
||||
template <typename SourceAllocator> ValueType& operator[](const GenericValue<EncodingType, SourceAllocator>& name) const { return value_[name]; }
|
||||
@ -2505,13 +2572,14 @@ public:
|
||||
#endif
|
||||
MemberIterator MemberBegin() const { return value_.MemberBegin(); }
|
||||
MemberIterator MemberEnd() const { return value_.MemberEnd(); }
|
||||
GenericObject MemberReserve(SizeType newCapacity, AllocatorType &allocator) const { value_.MemberReserve(newCapacity, allocator); return *this; }
|
||||
bool HasMember(const Ch* name) const { return value_.HasMember(name); }
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
bool HasMember(const std::basic_string<Ch>& name) const { return value_.HasMember(name); }
|
||||
#endif
|
||||
template <typename SourceAllocator> bool HasMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.HasMember(name); }
|
||||
MemberIterator FindMember(const Ch* name) const { value_.FindMember(name); }
|
||||
template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<EncodingType, SourceAllocator>& name) const { value_.FindMember(name); }
|
||||
MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); }
|
||||
template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.FindMember(name); }
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
MemberIterator FindMember(const std::basic_string<Ch>& name) const { return value_.FindMember(name); }
|
||||
#endif
|
||||
@ -2530,7 +2598,7 @@ public:
|
||||
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 <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
|
||||
void RemoveAllMembers() { return value_.RemoveAllMembers(); }
|
||||
void RemoveAllMembers() { value_.RemoveAllMembers(); }
|
||||
bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); }
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
bool RemoveMember(const std::basic_string<Ch>& name) const { return value_.RemoveMember(name); }
|
||||
@ -2557,17 +2625,6 @@ private:
|
||||
};
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#ifdef _MSC_VER
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef __clang__
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef __GNUC__
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#endif // RAPIDJSON_DOCUMENT_H_
|
||||
|
@ -85,6 +85,10 @@ public:
|
||||
size_t PutEnd(Ch*) { return 0; }
|
||||
|
||||
MemoryStream& is_;
|
||||
|
||||
private:
|
||||
EncodedInputStream(const EncodedInputStream&);
|
||||
EncodedInputStream& operator=(const EncodedInputStream&);
|
||||
};
|
||||
|
||||
//! Output byte stream wrapper with statically bound encoding.
|
||||
@ -196,7 +200,7 @@ private:
|
||||
// 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);
|
||||
int 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;
|
||||
|
@ -154,7 +154,11 @@ struct UTF8 {
|
||||
}
|
||||
|
||||
unsigned char type = GetRange(static_cast<unsigned char>(c));
|
||||
*codepoint = (0xFF >> type) & static_cast<unsigned char>(c);
|
||||
if (type >= 32) {
|
||||
*codepoint = 0;
|
||||
} else {
|
||||
*codepoint = (0xFFu >> type) & static_cast<unsigned char>(c);
|
||||
}
|
||||
bool result = true;
|
||||
switch (type) {
|
||||
case 2: TAIL(); return result;
|
||||
@ -279,7 +283,7 @@ struct UTF16 {
|
||||
RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
|
||||
unsigned v = codepoint - 0x10000;
|
||||
os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
|
||||
os.Put((v & 0x3FF) | 0xDC00);
|
||||
os.Put(static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00));
|
||||
}
|
||||
}
|
||||
|
||||
@ -295,7 +299,7 @@ struct UTF16 {
|
||||
RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
|
||||
unsigned v = codepoint - 0x10000;
|
||||
PutUnsafe(os, static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
|
||||
PutUnsafe(os, (v & 0x3FF) | 0xDC00);
|
||||
PutUnsafe(os, static_cast<typename OutputStream::Ch>((v & 0x3FF) | 0xDC00));
|
||||
}
|
||||
}
|
||||
|
||||
@ -380,7 +384,7 @@ struct UTF16BE : UTF16<CharType> {
|
||||
static CharType Take(InputByteStream& is) {
|
||||
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
|
||||
unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8;
|
||||
c |= static_cast<uint8_t>(is.Take());
|
||||
c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take()));
|
||||
return static_cast<CharType>(c);
|
||||
}
|
||||
|
||||
@ -616,28 +620,28 @@ struct AutoUTF {
|
||||
#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
|
||||
|
||||
template<typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) {
|
||||
static RAPIDJSON_FORCEINLINE 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<typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
|
||||
static RAPIDJSON_FORCEINLINE 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 <typename InputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) {
|
||||
static RAPIDJSON_FORCEINLINE 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 <typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE 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);
|
||||
@ -654,7 +658,7 @@ template<typename SourceEncoding, typename TargetEncoding>
|
||||
struct Transcoder {
|
||||
//! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream.
|
||||
template<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE bool Transcode(InputStream& is, OutputStream& os) {
|
||||
unsigned codepoint;
|
||||
if (!SourceEncoding::Decode(is, &codepoint))
|
||||
return false;
|
||||
@ -663,7 +667,7 @@ struct Transcoder {
|
||||
}
|
||||
|
||||
template<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE bool TranscodeUnsafe(InputStream& is, OutputStream& os) {
|
||||
unsigned codepoint;
|
||||
if (!SourceEncoding::Decode(is, &codepoint))
|
||||
return false;
|
||||
@ -673,7 +677,7 @@ struct Transcoder {
|
||||
|
||||
//! Validate one Unicode codepoint from an encoded stream.
|
||||
template<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) {
|
||||
return Transcode(is, os); // Since source/target encoding is different, must transcode.
|
||||
}
|
||||
};
|
||||
@ -686,19 +690,19 @@ inline void PutUnsafe(Stream& stream, typename Stream::Ch c);
|
||||
template<typename Encoding>
|
||||
struct Transcoder<Encoding, Encoding> {
|
||||
template<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE 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<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE 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<typename InputStream, typename OutputStream>
|
||||
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
|
||||
static RAPIDJSON_FORCEINLINE bool Validate(InputStream& is, OutputStream& os) {
|
||||
return Encoding::Validate(is, os); // source/target encoding are the same
|
||||
}
|
||||
};
|
||||
|
@ -38,7 +38,7 @@ inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErro
|
||||
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 follow by other values.");
|
||||
case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values.");
|
||||
|
||||
case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value.");
|
||||
|
||||
|
@ -104,6 +104,8 @@ enum ParseErrorCode {
|
||||
\see GenericReader::Parse, GenericDocument::Parse
|
||||
*/
|
||||
struct ParseResult {
|
||||
//!! Unspecified boolean type
|
||||
typedef bool (ParseResult::*BooleanType)() const;
|
||||
public:
|
||||
//! Default constructor, no error.
|
||||
ParseResult() : code_(kParseErrorNone), offset_(0) {}
|
||||
@ -115,8 +117,8 @@ public:
|
||||
//! 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(); }
|
||||
//! Explicit conversion to \c bool, returns \c true, iff !\ref IsError().
|
||||
operator BooleanType() const { return !IsError() ? &ParseResult::IsError : NULL; }
|
||||
//! Whether the result is an error.
|
||||
bool IsError() const { return code_ != kParseErrorNone; }
|
||||
|
||||
@ -124,6 +126,10 @@ public:
|
||||
bool operator==(ParseErrorCode code) const { return code_ == code; }
|
||||
friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; }
|
||||
|
||||
bool operator!=(const ParseResult& that) const { return !(*this == that); }
|
||||
bool operator!=(ParseErrorCode code) const { return !(*this == code); }
|
||||
friend bool operator!=(ParseErrorCode code, const ParseResult & err) { return err != code; }
|
||||
|
||||
//! Reset error code.
|
||||
void Clear() { Set(kParseErrorNone); }
|
||||
//! Update error code and offset.
|
||||
|
@ -68,7 +68,7 @@ private:
|
||||
++current_;
|
||||
else if (!eof_) {
|
||||
count_ += readCount_;
|
||||
readCount_ = fread(buffer_, 1, bufferSize_, fp_);
|
||||
readCount_ = std::fread(buffer_, 1, bufferSize_, fp_);
|
||||
bufferLast_ = buffer_ + readCount_ - 1;
|
||||
current_ = buffer_;
|
||||
|
||||
|
@ -25,7 +25,7 @@ RAPIDJSON_DIAG_OFF(unreachable-code)
|
||||
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
|
||||
//! Wrapper of C file stream for input using fread().
|
||||
//! Wrapper of C file stream for output using fwrite().
|
||||
/*!
|
||||
\note implements Stream concept
|
||||
*/
|
||||
@ -62,7 +62,7 @@ public:
|
||||
|
||||
void Flush() {
|
||||
if (current_ != buffer_) {
|
||||
size_t result = fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
|
||||
size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
|
||||
if (result < static_cast<size_t>(current_ - buffer_)) {
|
||||
// failure deliberately ignored at this time
|
||||
// added to avoid warn_unused_result build errors
|
||||
|
0
include/rapidjson/internal/biginteger.h
Executable file → Normal file
0
include/rapidjson/internal/biginteger.h
Executable file → Normal file
@ -21,7 +21,7 @@
|
||||
|
||||
#include "../rapidjson.h"
|
||||
|
||||
#if defined(_MSC_VER) && defined(_M_AMD64)
|
||||
#if defined(_MSC_VER) && defined(_M_AMD64) && !defined(__INTEL_COMPILER)
|
||||
#include <intrin.h>
|
||||
#pragma intrinsic(_BitScanReverse64)
|
||||
#pragma intrinsic(_umul128)
|
||||
|
@ -41,7 +41,7 @@ inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uin
|
||||
}
|
||||
}
|
||||
|
||||
inline unsigned CountDecimalDigit32(uint32_t n) {
|
||||
inline int 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;
|
||||
@ -63,7 +63,7 @@ inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buff
|
||||
const DiyFp wp_w = Mp - W;
|
||||
uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e);
|
||||
uint64_t p2 = Mp.f & (one.f - 1);
|
||||
unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9]
|
||||
int kappa = CountDecimalDigit32(p1); // kappa in [0, 9]
|
||||
*len = 0;
|
||||
|
||||
while (kappa > 0) {
|
||||
@ -102,7 +102,8 @@ inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buff
|
||||
kappa--;
|
||||
if (p2 < delta) {
|
||||
*K += kappa;
|
||||
GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * kPow10[-static_cast<int>(kappa)]);
|
||||
int index = -kappa;
|
||||
GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[index] : 0));
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -180,7 +181,7 @@ inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) {
|
||||
buffer[1] = '.';
|
||||
for (int i = 2; i < offset; i++)
|
||||
buffer[i] = '0';
|
||||
if (length + offset > maxDecimalPlaces) {
|
||||
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--)
|
||||
|
@ -48,13 +48,13 @@ public:
|
||||
int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; }
|
||||
uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; }
|
||||
|
||||
static unsigned EffectiveSignificandSize(int order) {
|
||||
static int EffectiveSignificandSize(int order) {
|
||||
if (order >= -1021)
|
||||
return 53;
|
||||
else if (order <= -1074)
|
||||
return 0;
|
||||
else
|
||||
return static_cast<unsigned>(order) + 1074;
|
||||
return order + 1074;
|
||||
}
|
||||
|
||||
private:
|
||||
|
@ -29,6 +29,14 @@ RAPIDJSON_DIAG_OFF(implicit-fallthrough)
|
||||
#ifdef __GNUC__
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(effc++)
|
||||
#if __GNUC__ >= 7
|
||||
RAPIDJSON_DIAG_OFF(implicit-fallthrough)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
|
||||
#endif
|
||||
|
||||
#ifndef RAPIDJSON_REGEX_VERBOSE
|
||||
@ -38,12 +46,40 @@ RAPIDJSON_DIAG_OFF(effc++)
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
namespace internal {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// DecodedStream
|
||||
|
||||
template <typename SourceStream, typename Encoding>
|
||||
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_;
|
||||
};
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// GenericRegex
|
||||
|
||||
static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1
|
||||
static const SizeType kRegexInvalidRange = ~SizeType(0);
|
||||
|
||||
template <typename Encoding, typename Allocator>
|
||||
class GenericRegexSearch;
|
||||
|
||||
//! Regular expression engine with subset of ECMAscript grammar.
|
||||
/*!
|
||||
Supported regular expression syntax:
|
||||
@ -79,45 +115,25 @@ static const SizeType kRegexInvalidRange = ~SizeType(0);
|
||||
template <typename Encoding, typename Allocator = CrtAllocator>
|
||||
class GenericRegex {
|
||||
public:
|
||||
typedef Encoding EncodingType;
|
||||
typedef typename Encoding::Ch Ch;
|
||||
template <typename, typename> friend class GenericRegexSearch;
|
||||
|
||||
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_()
|
||||
anchorBegin_(), anchorEnd_()
|
||||
{
|
||||
GenericStringStream<Encoding> ss(source);
|
||||
DecodedStream<GenericStringStream<Encoding> > ds(ss);
|
||||
DecodedStream<GenericStringStream<Encoding>, Encoding> ds(ss);
|
||||
Parse(ds);
|
||||
}
|
||||
|
||||
~GenericRegex() {
|
||||
Allocator::Free(stateSet_);
|
||||
}
|
||||
~GenericRegex() {}
|
||||
|
||||
bool IsValid() const {
|
||||
return root_ != kRegexInvalidState;
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool Match(InputStream& is) const {
|
||||
return SearchWithAnchoring(is, true, true);
|
||||
}
|
||||
|
||||
bool Match(const Ch* s) const {
|
||||
GenericStringStream<Encoding> is(s);
|
||||
return Match(is);
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool Search(InputStream& is) const {
|
||||
return SearchWithAnchoring(is, anchorBegin_, anchorEnd_);
|
||||
}
|
||||
|
||||
bool Search(const Ch* s) const {
|
||||
GenericStringStream<Encoding> is(s);
|
||||
return Search(is);
|
||||
}
|
||||
|
||||
private:
|
||||
enum Operator {
|
||||
kZeroOrOne,
|
||||
@ -152,28 +168,6 @@ private:
|
||||
SizeType minIndex;
|
||||
};
|
||||
|
||||
template <typename SourceStream>
|
||||
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<State>()[index];
|
||||
@ -195,7 +189,7 @@ private:
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
void Parse(DecodedStream<InputStream>& ds) {
|
||||
void Parse(DecodedStream<InputStream, Encoding>& ds) {
|
||||
Allocator allocator;
|
||||
Stack<Allocator> operandStack(&allocator, 256); // Frag
|
||||
Stack<Allocator> operatorStack(&allocator, 256); // Operator
|
||||
@ -322,14 +316,6 @@ private:
|
||||
printf("\n");
|
||||
#endif
|
||||
}
|
||||
|
||||
// Preallocate buffer for SearchWithAnchoring()
|
||||
RAPIDJSON_ASSERT(stateSet_ == 0);
|
||||
if (stateCount_ > 0) {
|
||||
stateSet_ = static_cast<unsigned*>(states_.GetAllocator().Malloc(GetStateSetSize()));
|
||||
state0_.template Reserve<SizeType>(stateCount_);
|
||||
state1_.template Reserve<SizeType>(stateCount_);
|
||||
}
|
||||
}
|
||||
|
||||
SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) {
|
||||
@ -370,14 +356,14 @@ private:
|
||||
bool Eval(Stack<Allocator>& operandStack, Operator op) {
|
||||
switch (op) {
|
||||
case kConcatenation:
|
||||
if (operandStack.GetSize() >= sizeof(Frag) * 2) {
|
||||
RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2);
|
||||
{
|
||||
Frag e2 = *operandStack.template Pop<Frag>(1);
|
||||
Frag e1 = *operandStack.template Pop<Frag>(1);
|
||||
Patch(e1.out, e2.start);
|
||||
*operandStack.template Push<Frag>() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return true;
|
||||
|
||||
case kAlternation:
|
||||
if (operandStack.GetSize() >= sizeof(Frag) * 2) {
|
||||
@ -408,7 +394,8 @@ private:
|
||||
}
|
||||
return false;
|
||||
|
||||
case kOneOrMore:
|
||||
default:
|
||||
RAPIDJSON_ASSERT(op == kOneOrMore);
|
||||
if (operandStack.GetSize() >= sizeof(Frag)) {
|
||||
Frag e = *operandStack.template Pop<Frag>(1);
|
||||
SizeType s = NewState(kRegexInvalidState, e.start, 0);
|
||||
@ -417,16 +404,12 @@ private:
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool EvalQuantifier(Stack<Allocator>& operandStack, unsigned n, unsigned m) {
|
||||
RAPIDJSON_ASSERT(n <= m);
|
||||
if (operandStack.GetSize() < sizeof(Frag))
|
||||
return false;
|
||||
RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag));
|
||||
|
||||
if (n == 0) {
|
||||
if (m == 0) // a{0} not support
|
||||
@ -466,22 +449,22 @@ private:
|
||||
static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; }
|
||||
|
||||
void CloneTopOperand(Stack<Allocator>& operandStack) {
|
||||
const Frag *src = operandStack.template Top<Frag>();
|
||||
SizeType count = stateCount_ - src->minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_)
|
||||
const Frag src = *operandStack.template Top<Frag>(); // Copy constructor to prevent invalidation
|
||||
SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_)
|
||||
State* s = states_.template Push<State>(count);
|
||||
memcpy(s, &GetState(src->minIndex), count * sizeof(State));
|
||||
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>() = Frag(src->start + count, src->out + count, src->minIndex + count);
|
||||
*operandStack.template Push<Frag>() = Frag(src.start + count, src.out + count, src.minIndex + count);
|
||||
stateCount_ += count;
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool ParseUnsigned(DecodedStream<InputStream>& ds, unsigned* u) {
|
||||
bool ParseUnsigned(DecodedStream<InputStream, Encoding>& ds, unsigned* u) {
|
||||
unsigned r = 0;
|
||||
if (ds.Peek() < '0' || ds.Peek() > '9')
|
||||
return false;
|
||||
@ -495,7 +478,7 @@ private:
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool ParseRange(DecodedStream<InputStream>& ds, SizeType* range) {
|
||||
bool ParseRange(DecodedStream<InputStream, Encoding>& ds, SizeType* range) {
|
||||
bool isBegin = true;
|
||||
bool negate = false;
|
||||
int step = 0;
|
||||
@ -573,7 +556,7 @@ private:
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool CharacterEscape(DecodedStream<InputStream>& ds, unsigned* escapedCodepoint) {
|
||||
bool CharacterEscape(DecodedStream<InputStream, Encoding>& ds, unsigned* escapedCodepoint) {
|
||||
unsigned codepoint;
|
||||
switch (codepoint = ds.Take()) {
|
||||
case '^':
|
||||
@ -601,73 +584,6 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) const {
|
||||
RAPIDJSON_ASSERT(IsValid());
|
||||
DecodedStream<InputStream> ds(is);
|
||||
|
||||
state0_.Clear();
|
||||
Stack<Allocator> *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<SizeType>(); s != current->template End<SizeType>(); ++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<Allocator>& l, SizeType index) const {
|
||||
if (index == kRegexInvalidState)
|
||||
return true;
|
||||
|
||||
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<SizeType>() = 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<Allocator> states_;
|
||||
Stack<Allocator> ranges_;
|
||||
SizeType root_;
|
||||
@ -677,14 +593,132 @@ private:
|
||||
static const unsigned kInfinityQuantifier = ~0u;
|
||||
|
||||
// For SearchWithAnchoring()
|
||||
uint32_t* stateSet_; // allocated by states_.GetAllocator()
|
||||
mutable Stack<Allocator> state0_;
|
||||
mutable Stack<Allocator> state1_;
|
||||
bool anchorBegin_;
|
||||
bool anchorEnd_;
|
||||
};
|
||||
|
||||
template <typename RegexType, typename Allocator = CrtAllocator>
|
||||
class GenericRegexSearch {
|
||||
public:
|
||||
typedef typename RegexType::EncodingType Encoding;
|
||||
typedef typename Encoding::Ch Ch;
|
||||
|
||||
GenericRegexSearch(const RegexType& regex, Allocator* allocator = 0) :
|
||||
regex_(regex), allocator_(allocator), ownAllocator_(0),
|
||||
state0_(allocator, 0), state1_(allocator, 0), stateSet_()
|
||||
{
|
||||
RAPIDJSON_ASSERT(regex_.IsValid());
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
stateSet_ = static_cast<unsigned*>(allocator_->Malloc(GetStateSetSize()));
|
||||
state0_.template Reserve<SizeType>(regex_.stateCount_);
|
||||
state1_.template Reserve<SizeType>(regex_.stateCount_);
|
||||
}
|
||||
|
||||
~GenericRegexSearch() {
|
||||
Allocator::Free(stateSet_);
|
||||
RAPIDJSON_DELETE(ownAllocator_);
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool Match(InputStream& is) {
|
||||
return SearchWithAnchoring(is, true, true);
|
||||
}
|
||||
|
||||
bool Match(const Ch* s) {
|
||||
GenericStringStream<Encoding> is(s);
|
||||
return Match(is);
|
||||
}
|
||||
|
||||
template <typename InputStream>
|
||||
bool Search(InputStream& is) {
|
||||
return SearchWithAnchoring(is, regex_.anchorBegin_, regex_.anchorEnd_);
|
||||
}
|
||||
|
||||
bool Search(const Ch* s) {
|
||||
GenericStringStream<Encoding> is(s);
|
||||
return Search(is);
|
||||
}
|
||||
|
||||
private:
|
||||
typedef typename RegexType::State State;
|
||||
typedef typename RegexType::Range Range;
|
||||
|
||||
template <typename InputStream>
|
||||
bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) {
|
||||
DecodedStream<InputStream, Encoding> ds(is);
|
||||
|
||||
state0_.Clear();
|
||||
Stack<Allocator> *current = &state0_, *next = &state1_;
|
||||
const size_t stateSetSize = GetStateSetSize();
|
||||
std::memset(stateSet_, 0, stateSetSize);
|
||||
|
||||
bool matched = AddState(*current, regex_.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<SizeType>(); s != current->template End<SizeType>(); ++s) {
|
||||
const State& sr = regex_.GetState(*s);
|
||||
if (sr.codepoint == codepoint ||
|
||||
sr.codepoint == RegexType::kAnyCharacterClass ||
|
||||
(sr.codepoint == RegexType::kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint)))
|
||||
{
|
||||
matched = AddState(*next, sr.out) || matched;
|
||||
if (!anchorEnd && matched)
|
||||
return true;
|
||||
}
|
||||
if (!anchorBegin)
|
||||
AddState(*next, regex_.root_);
|
||||
}
|
||||
internal::Swap(current, next);
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
size_t GetStateSetSize() const {
|
||||
return (regex_.stateCount_ + 31) / 32 * 4;
|
||||
}
|
||||
|
||||
// Return whether the added states is a match state
|
||||
bool AddState(Stack<Allocator>& l, SizeType index) {
|
||||
RAPIDJSON_ASSERT(index != kRegexInvalidState);
|
||||
|
||||
const State& s = regex_.GetState(index);
|
||||
if (s.out1 != kRegexInvalidState) { // Split
|
||||
bool matched = AddState(l, s.out);
|
||||
return AddState(l, s.out1) || matched;
|
||||
}
|
||||
else if (!(stateSet_[index >> 5] & (1u << (index & 31)))) {
|
||||
stateSet_[index >> 5] |= (1u << (index & 31));
|
||||
*l.template PushUnsafe<SizeType>() = 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 = (regex_.GetRange(rangeIndex).start & RegexType::kRangeNegationFlag) == 0;
|
||||
while (rangeIndex != kRegexInvalidRange) {
|
||||
const Range& r = regex_.GetRange(rangeIndex);
|
||||
if (codepoint >= (r.start & ~RegexType::kRangeNegationFlag) && codepoint <= r.end)
|
||||
return yes;
|
||||
rangeIndex = r.next;
|
||||
}
|
||||
return !yes;
|
||||
}
|
||||
|
||||
const RegexType& regex_;
|
||||
Allocator* allocator_;
|
||||
Allocator* ownAllocator_;
|
||||
Stack<Allocator> state0_;
|
||||
Stack<Allocator> state1_;
|
||||
uint32_t* stateSet_;
|
||||
};
|
||||
|
||||
typedef GenericRegex<UTF8<> > Regex;
|
||||
typedef GenericRegexSearch<Regex> RegexSearch;
|
||||
|
||||
} // namespace internal
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
@ -693,4 +727,8 @@ RAPIDJSON_NAMESPACE_END
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#endif // RAPIDJSON_INTERNAL_REGEX_H_
|
||||
|
@ -126,6 +126,7 @@ public:
|
||||
|
||||
template<typename T>
|
||||
RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) {
|
||||
RAPIDJSON_ASSERT(stackTop_);
|
||||
RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_);
|
||||
T* ret = reinterpret_cast<T*>(stackTop_);
|
||||
stackTop_ += sizeof(T) * count;
|
||||
@ -183,7 +184,7 @@ private:
|
||||
size_t newCapacity;
|
||||
if (stack_ == 0) {
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
newCapacity = initialCapacity_;
|
||||
} else {
|
||||
newCapacity = GetCapacity();
|
||||
|
@ -16,6 +16,7 @@
|
||||
#define RAPIDJSON_INTERNAL_STRFUNC_H_
|
||||
|
||||
#include "../stream.h"
|
||||
#include <cwchar>
|
||||
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
namespace internal {
|
||||
@ -28,14 +29,27 @@ namespace internal {
|
||||
*/
|
||||
template <typename Ch>
|
||||
inline SizeType StrLen(const Ch* s) {
|
||||
RAPIDJSON_ASSERT(s != 0);
|
||||
const Ch* p = s;
|
||||
while (*p) ++p;
|
||||
return SizeType(p - s);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline SizeType StrLen(const char* s) {
|
||||
return SizeType(std::strlen(s));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline SizeType StrLen(const wchar_t* s) {
|
||||
return SizeType(std::wcslen(s));
|
||||
}
|
||||
|
||||
//! Returns number of code points in a encoded string.
|
||||
template<typename Encoding>
|
||||
bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) {
|
||||
RAPIDJSON_ASSERT(s != 0);
|
||||
RAPIDJSON_ASSERT(outCount != 0);
|
||||
GenericStringStream<Encoding> is(s);
|
||||
const typename Encoding::Ch* end = s + length;
|
||||
SizeType count = 0;
|
||||
|
@ -140,9 +140,9 @@ inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosit
|
||||
significand++;
|
||||
|
||||
size_t remaining = length - i;
|
||||
const unsigned kUlpShift = 3;
|
||||
const unsigned kUlp = 1 << kUlpShift;
|
||||
int error = (remaining == 0) ? 0 : kUlp / 2;
|
||||
const int kUlpShift = 3;
|
||||
const int kUlp = 1 << kUlpShift;
|
||||
int64_t error = (remaining == 0) ? 0 : kUlp / 2;
|
||||
|
||||
DiyFp v(significand, 0);
|
||||
v = v.Normalize();
|
||||
@ -177,17 +177,17 @@ inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosit
|
||||
v = v.Normalize();
|
||||
error <<= oldExp - v.e;
|
||||
|
||||
const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
|
||||
unsigned precisionSize = 64 - effectiveSignificandSize;
|
||||
const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
|
||||
int precisionSize = 64 - effectiveSignificandSize;
|
||||
if (precisionSize + kUlpShift >= 64) {
|
||||
unsigned scaleExp = (precisionSize + kUlpShift) - 63;
|
||||
int scaleExp = (precisionSize + kUlpShift) - 63;
|
||||
v.f >>= scaleExp;
|
||||
v.e += scaleExp;
|
||||
error = (error >> scaleExp) + 1 + static_cast<int>(kUlp);
|
||||
error = (error >> scaleExp) + 1 + kUlp;
|
||||
precisionSize -= scaleExp;
|
||||
}
|
||||
|
||||
DiyFp rounded(v.f >> precisionSize, v.e + static_cast<int>(precisionSize));
|
||||
DiyFp rounded(v.f >> precisionSize, v.e + 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<unsigned>(error)) {
|
||||
|
@ -12,6 +12,9 @@
|
||||
// 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 <iosfwd>
|
||||
|
||||
@ -51,7 +54,7 @@ public:
|
||||
|
||||
Ch Peek() const {
|
||||
typename StreamType::int_type c = stream_.peek();
|
||||
return RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast<Ch>(c) : '\0';
|
||||
return RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast<Ch>(c) : static_cast<Ch>('\0');
|
||||
}
|
||||
|
||||
Ch Take() {
|
||||
@ -108,3 +111,5 @@ RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#endif // RAPIDJSON_ISTREAMWRAPPER_H_
|
||||
|
@ -12,6 +12,9 @@
|
||||
// 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 <iosfwd>
|
||||
|
||||
@ -74,3 +77,5 @@ RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#endif // RAPIDJSON_OSTREAMWRAPPER_H_
|
||||
|
@ -23,6 +23,11 @@ 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
|
||||
@ -235,7 +240,7 @@ public:
|
||||
template <typename T>
|
||||
RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer))
|
||||
Append(T* name, Allocator* allocator = 0) const {
|
||||
return Append(name, StrLen(name), allocator);
|
||||
return Append(name, internal::StrLen(name), allocator);
|
||||
}
|
||||
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
@ -269,7 +274,7 @@ public:
|
||||
else {
|
||||
Ch name[21];
|
||||
for (size_t i = 0; i <= length; i++)
|
||||
name[i] = buffer[i];
|
||||
name[i] = static_cast<Ch>(buffer[i]);
|
||||
Token token = { name, length, index };
|
||||
return Append(token, allocator);
|
||||
}
|
||||
@ -753,7 +758,7 @@ private:
|
||||
*/
|
||||
Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) {
|
||||
if (!allocator_) // allocator is independently owned.
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
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)
|
||||
@ -762,8 +767,12 @@ private:
|
||||
tokenCount_ = rhs.tokenCount_ + extraToken;
|
||||
tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch)));
|
||||
nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
|
||||
std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token));
|
||||
std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch));
|
||||
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_;
|
||||
@ -797,7 +806,7 @@ private:
|
||||
|
||||
// Create own allocator if user did not supply.
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
|
||||
// Count number of '/' as tokenCount
|
||||
tokenCount_ = 0;
|
||||
@ -987,11 +996,11 @@ private:
|
||||
src_++;
|
||||
Ch c = 0;
|
||||
for (int j = 0; j < 2; j++) {
|
||||
c <<= 4;
|
||||
c = static_cast<Ch>(c << 4);
|
||||
Ch h = *src_;
|
||||
if (h >= '0' && h <= '9') c += h - '0';
|
||||
else if (h >= 'A' && h <= 'F') c += h - 'A' + 10;
|
||||
else if (h >= 'a' && h <= 'f') c += h - 'a' + 10;
|
||||
if (h >= '0' && h <= '9') c = static_cast<Ch>(c + h - '0');
|
||||
else if (h >= 'A' && h <= 'F') c = static_cast<Ch>(c + h - 'A' + 10);
|
||||
else if (h >= 'a' && h <= 'f') c = static_cast<Ch>(c + h - 'a' + 10);
|
||||
else {
|
||||
valid_ = false;
|
||||
return 0;
|
||||
@ -1020,8 +1029,8 @@ private:
|
||||
unsigned char u = static_cast<unsigned char>(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]);
|
||||
os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u >> 4]));
|
||||
os_.Put(static_cast<typename OutputStream::Ch>(hexDigits[u & 15]));
|
||||
}
|
||||
private:
|
||||
OutputStream& os_;
|
||||
@ -1342,4 +1351,8 @@ RAPIDJSON_NAMESPACE_END
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#endif // RAPIDJSON_POINTER_H_
|
||||
|
@ -22,8 +22,21 @@ RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(effc++)
|
||||
#endif
|
||||
|
||||
#if defined(__clang__)
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(c++98-compat)
|
||||
#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.
|
||||
@ -34,7 +47,7 @@ RAPIDJSON_NAMESPACE_BEGIN
|
||||
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
|
||||
class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {
|
||||
public:
|
||||
typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base;
|
||||
typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> Base;
|
||||
typedef typename Base::Ch Ch;
|
||||
|
||||
//! Constructor
|
||||
@ -43,12 +56,17 @@ public:
|
||||
\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) {}
|
||||
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) {}
|
||||
|
||||
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
||||
PrettyWriter(PrettyWriter&& rhs) :
|
||||
Base(std::forward<PrettyWriter>(rhs)), indentChar_(rhs.indentChar_), indentCharCount_(rhs.indentCharCount_), formatOptions_(rhs.formatOptions_) {}
|
||||
#endif
|
||||
|
||||
//! 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.
|
||||
@ -61,6 +79,14 @@ public:
|
||||
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
|
||||
*/
|
||||
@ -75,12 +101,14 @@ public:
|
||||
bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); }
|
||||
|
||||
bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
|
||||
RAPIDJSON_ASSERT(str != 0);
|
||||
(void)copy;
|
||||
PrettyPrefix(kNumberType);
|
||||
return Base::WriteString(str, length);
|
||||
}
|
||||
|
||||
bool String(const Ch* str, SizeType length, bool copy = false) {
|
||||
RAPIDJSON_ASSERT(str != 0);
|
||||
(void)copy;
|
||||
PrettyPrefix(kStringType);
|
||||
return Base::WriteString(str, length);
|
||||
@ -99,11 +127,19 @@ public:
|
||||
}
|
||||
|
||||
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<Ch>& 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<typename Base::Level>()->inArray);
|
||||
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level)); // not inside an Object
|
||||
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray); // currently inside an Array, not Object
|
||||
RAPIDJSON_ASSERT(0 == Base::level_stack_.template Top<typename Base::Level>()->valueCount % 2); // Object has a Key without a Value
|
||||
|
||||
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
|
||||
|
||||
if (!empty) {
|
||||
@ -114,7 +150,7 @@ public:
|
||||
(void)ret;
|
||||
RAPIDJSON_ASSERT(ret == true);
|
||||
if (Base::level_stack_.Empty()) // end of json text
|
||||
Base::os_->Flush();
|
||||
Base::Flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -130,7 +166,7 @@ public:
|
||||
RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
|
||||
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
|
||||
|
||||
if (!empty) {
|
||||
if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
|
||||
Base::os_->Put('\n');
|
||||
WriteIndent();
|
||||
}
|
||||
@ -138,7 +174,7 @@ public:
|
||||
(void)ret;
|
||||
RAPIDJSON_ASSERT(ret == true);
|
||||
if (Base::level_stack_.Empty()) // end of json text
|
||||
Base::os_->Flush();
|
||||
Base::Flush();
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -162,7 +198,11 @@ public:
|
||||
\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); }
|
||||
bool RawValue(const Ch* json, size_t length, Type type) {
|
||||
RAPIDJSON_ASSERT(json != 0);
|
||||
PrettyPrefix(type);
|
||||
return Base::WriteRawValue(json, length);
|
||||
}
|
||||
|
||||
protected:
|
||||
void PrettyPrefix(Type type) {
|
||||
@ -173,11 +213,14 @@ protected:
|
||||
if (level->inArray) {
|
||||
if (level->valueCount > 0) {
|
||||
Base::os_->Put(','); // add comma if it is not the first element in array
|
||||
Base::os_->Put('\n');
|
||||
if (formatOptions_ & kFormatSingleLineArray)
|
||||
Base::os_->Put(' ');
|
||||
}
|
||||
else
|
||||
|
||||
if (!(formatOptions_ & kFormatSingleLineArray)) {
|
||||
Base::os_->Put('\n');
|
||||
WriteIndent();
|
||||
WriteIndent();
|
||||
}
|
||||
}
|
||||
else { // in object
|
||||
if (level->valueCount > 0) {
|
||||
@ -208,11 +251,12 @@ protected:
|
||||
|
||||
void WriteIndent() {
|
||||
size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
|
||||
PutN(*Base::os_, static_cast<typename TargetEncoding::Ch>(indentChar_), count);
|
||||
PutN(*Base::os_, static_cast<typename OutputStream::Ch>(indentChar_), count);
|
||||
}
|
||||
|
||||
Ch indentChar_;
|
||||
unsigned indentCharCount_;
|
||||
PrettyFormatOptions formatOptions_;
|
||||
|
||||
private:
|
||||
// Prohibit copy constructor & assignment operator.
|
||||
@ -222,6 +266,10 @@ private:
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#if defined(__clang__)
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef __GNUC__
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
@ -49,6 +49,11 @@
|
||||
// token stringification
|
||||
#define RAPIDJSON_STRINGIFY(x) RAPIDJSON_DO_STRINGIFY(x)
|
||||
#define RAPIDJSON_DO_STRINGIFY(x) #x
|
||||
|
||||
// token concatenation
|
||||
#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
|
||||
//!@endcond
|
||||
|
||||
/*! \def RAPIDJSON_MAJOR_VERSION
|
||||
@ -68,8 +73,8 @@
|
||||
\brief Version of RapidJSON in "<major>.<minor>.<patch>" string format.
|
||||
*/
|
||||
#define RAPIDJSON_MAJOR_VERSION 1
|
||||
#define RAPIDJSON_MINOR_VERSION 0
|
||||
#define RAPIDJSON_PATCH_VERSION 2
|
||||
#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)
|
||||
|
||||
@ -236,7 +241,7 @@
|
||||
# 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)
|
||||
# elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64))
|
||||
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
|
||||
# elif defined(RAPIDJSON_DOXYGEN_RUNNING)
|
||||
# define RAPIDJSON_ENDIAN
|
||||
@ -250,7 +255,7 @@
|
||||
|
||||
//! Whether using 64-bit architecture
|
||||
#ifndef RAPIDJSON_64BIT
|
||||
#if defined(__LP64__) || defined(_WIN64) || defined(__EMSCRIPTEN__)
|
||||
#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || defined(_WIN64) || defined(__EMSCRIPTEN__)
|
||||
#define RAPIDJSON_64BIT 1
|
||||
#else
|
||||
#define RAPIDJSON_64BIT 0
|
||||
@ -320,17 +325,17 @@
|
||||
#endif
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD
|
||||
// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_NEON/RAPIDJSON_SIMD
|
||||
|
||||
/*! \def RAPIDJSON_SIMD
|
||||
\ingroup RAPIDJSON_CONFIG
|
||||
\brief Enable SSE2/SSE4.2 optimization.
|
||||
\brief Enable SSE2/SSE4.2/Neon optimization.
|
||||
|
||||
RapidJSON supports optimized implementations for some parsing operations
|
||||
based on the SSE2 or SSE4.2 SIMD extensions on modern Intel-compatible
|
||||
processors.
|
||||
based on the SSE2, SSE4.2 or NEon SIMD extensions on modern Intel
|
||||
or ARM compatible processors.
|
||||
|
||||
To enable these optimizations, two different symbols can be defined;
|
||||
To enable these optimizations, three different symbols can be defined;
|
||||
\code
|
||||
// Enable SSE2 optimization.
|
||||
#define RAPIDJSON_SSE2
|
||||
@ -339,13 +344,17 @@
|
||||
#define RAPIDJSON_SSE42
|
||||
\endcode
|
||||
|
||||
\c RAPIDJSON_SSE42 takes precedence, if both are defined.
|
||||
// Enable ARM Neon optimization.
|
||||
#define RAPIDJSON_NEON
|
||||
\endcode
|
||||
|
||||
\c RAPIDJSON_SSE42 takes precedence over SSE2, 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)
|
||||
|| defined(RAPIDJSON_NEON) || defined(RAPIDJSON_DOXYGEN_RUNNING)
|
||||
#define RAPIDJSON_SIMD
|
||||
#endif
|
||||
|
||||
@ -405,7 +414,15 @@ RAPIDJSON_NAMESPACE_END
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// RAPIDJSON_STATIC_ASSERT
|
||||
|
||||
// Adopt from boost
|
||||
// Prefer C++11 static_assert, if available
|
||||
#ifndef RAPIDJSON_STATIC_ASSERT
|
||||
#if __cplusplus >= 201103L || ( defined(_MSC_VER) && _MSC_VER >= 1800 )
|
||||
#define RAPIDJSON_STATIC_ASSERT(x) \
|
||||
static_assert(x, RAPIDJSON_STRINGIFY(x))
|
||||
#endif // C++11
|
||||
#endif // RAPIDJSON_STATIC_ASSERT
|
||||
|
||||
// Adopt C++03 implementation from boost
|
||||
#ifndef RAPIDJSON_STATIC_ASSERT
|
||||
#ifndef __clang__
|
||||
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
|
||||
@ -413,13 +430,9 @@ RAPIDJSON_NAMESPACE_END
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
template <bool x> struct STATIC_ASSERTION_FAILURE;
|
||||
template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
|
||||
template<int x> struct StaticAssertTest {};
|
||||
template <size_t x> 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
|
||||
@ -438,7 +451,7 @@ RAPIDJSON_NAMESPACE_END
|
||||
typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest< \
|
||||
sizeof(::RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE<bool(x) >)> \
|
||||
RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
|
||||
#endif
|
||||
#endif // RAPIDJSON_STATIC_ASSERT
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY
|
||||
@ -529,8 +542,12 @@ RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
||||
#if defined(__clang__)
|
||||
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS __has_feature(cxx_rvalue_references) && \
|
||||
#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)
|
||||
|
||||
@ -564,7 +581,7 @@ RAPIDJSON_NAMESPACE_END
|
||||
#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__)) || \
|
||||
#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
|
||||
(defined(_MSC_VER) && _MSC_VER >= 1700)
|
||||
#define RAPIDJSON_HAS_CXX11_RANGE_FOR 1
|
||||
#else
|
||||
@ -579,7 +596,7 @@ RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#ifndef RAPIDJSON_NEW
|
||||
///! customization point for global \c new
|
||||
#define RAPIDJSON_NEW(x) new x
|
||||
#define RAPIDJSON_NEW(TypeName) new TypeName
|
||||
#endif
|
||||
#ifndef RAPIDJSON_DELETE
|
||||
///! customization point for global \c delete
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -19,13 +19,6 @@
|
||||
#include "pointer.h"
|
||||
#include <cmath> // abs, floor
|
||||
|
||||
#ifdef __clang__
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(weak-vtables)
|
||||
RAPIDJSON_DIAG_OFF(exit-time-destructors)
|
||||
RAPIDJSON_DIAG_OFF(c++98-compat-pedantic)
|
||||
#endif
|
||||
|
||||
#if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX)
|
||||
#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1
|
||||
#else
|
||||
@ -58,16 +51,23 @@ RAPIDJSON_DIAG_OFF(c++98-compat-pedantic)
|
||||
#include "stringbuffer.h"
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__)
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
|
||||
#if defined(__GNUC__)
|
||||
RAPIDJSON_DIAG_OFF(effc++)
|
||||
#endif
|
||||
|
||||
#ifdef __clang__
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
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
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@ -154,7 +154,6 @@ public:
|
||||
virtual uint64_t GetHashCode(void* hasher) = 0;
|
||||
virtual void DestroryHasher(void* hasher) = 0;
|
||||
virtual void* MallocState(size_t size) = 0;
|
||||
virtual void* ReallocState(void* originalPtr, size_t originalSize, size_t newSize) = 0;
|
||||
virtual void FreeState(void* p) = 0;
|
||||
};
|
||||
|
||||
@ -285,7 +284,7 @@ struct SchemaValidationContext {
|
||||
patternPropertiesSchemas(),
|
||||
patternPropertiesSchemaCount(),
|
||||
valuePatternValidatorType(kPatternValidatorOnly),
|
||||
objectDependencies(),
|
||||
propertyExist(),
|
||||
inArray(false),
|
||||
valueUniqueness(false),
|
||||
arrayUniqueness(false)
|
||||
@ -307,8 +306,8 @@ struct SchemaValidationContext {
|
||||
}
|
||||
if (patternPropertiesSchemas)
|
||||
factory.FreeState(patternPropertiesSchemas);
|
||||
if (objectDependencies)
|
||||
factory.FreeState(objectDependencies);
|
||||
if (propertyExist)
|
||||
factory.FreeState(propertyExist);
|
||||
}
|
||||
|
||||
SchemaValidatorFactoryType& factory;
|
||||
@ -325,9 +324,8 @@ struct SchemaValidationContext {
|
||||
SizeType patternPropertiesSchemaCount;
|
||||
PatternValidatorType valuePatternValidatorType;
|
||||
PatternValidatorType objectPatternValidatorType;
|
||||
SizeType objectRequiredCount;
|
||||
SizeType arrayElementIndex;
|
||||
bool* objectDependencies;
|
||||
bool* propertyExist;
|
||||
bool inArray;
|
||||
bool valueUniqueness;
|
||||
bool arrayUniqueness;
|
||||
@ -351,21 +349,23 @@ public:
|
||||
|
||||
Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) :
|
||||
allocator_(allocator),
|
||||
typeless_(schemaDocument->GetTypeless()),
|
||||
enum_(),
|
||||
enumCount_(),
|
||||
not_(),
|
||||
type_((1 << kTotalSchemaType) - 1), // typeless
|
||||
validatorCount_(),
|
||||
notValidatorIndex_(),
|
||||
properties_(),
|
||||
additionalPropertiesSchema_(),
|
||||
patternProperties_(),
|
||||
patternPropertyCount_(),
|
||||
propertyCount_(),
|
||||
requiredCount_(),
|
||||
minProperties_(),
|
||||
maxProperties_(SizeType(~0)),
|
||||
additionalProperties_(true),
|
||||
hasDependencies_(),
|
||||
hasRequired_(),
|
||||
hasSchemaDependencies_(),
|
||||
additionalItemsSchema_(),
|
||||
itemsList_(),
|
||||
@ -410,9 +410,11 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
AssignIfExist(allOf_, *schemaDocument, p, value, GetAllOfString(), document);
|
||||
AssignIfExist(anyOf_, *schemaDocument, p, value, GetAnyOfString(), document);
|
||||
AssignIfExist(oneOf_, *schemaDocument, p, value, GetOneOfString(), document);
|
||||
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);
|
||||
@ -453,7 +455,7 @@ public:
|
||||
for (SizeType i = 0; i < propertyCount_; i++) {
|
||||
new (&properties_[i]) Property();
|
||||
properties_[i].name = allProperties[i];
|
||||
properties_[i].schema = GetTypeless();
|
||||
properties_[i].schema = typeless_;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -486,7 +488,7 @@ public:
|
||||
SizeType index;
|
||||
if (FindPropertyIndex(*itr, &index)) {
|
||||
properties_[index].required = true;
|
||||
requiredCount_++;
|
||||
hasRequired_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -575,7 +577,7 @@ public:
|
||||
}
|
||||
|
||||
~Schema() {
|
||||
allocator_->Free(enum_);
|
||||
AllocatorType::Free(enum_);
|
||||
if (properties_) {
|
||||
for (SizeType i = 0; i < propertyCount_; i++)
|
||||
properties_[i].~Property();
|
||||
@ -590,7 +592,7 @@ public:
|
||||
#if RAPIDJSON_SCHEMA_HAS_REGEX
|
||||
if (pattern_) {
|
||||
pattern_->~RegexType();
|
||||
allocator_->Free(pattern_);
|
||||
AllocatorType::Free(pattern_);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@ -608,12 +610,12 @@ public:
|
||||
else if (additionalItemsSchema_)
|
||||
context.valueSchema = additionalItemsSchema_;
|
||||
else if (additionalItems_)
|
||||
context.valueSchema = GetTypeless();
|
||||
context.valueSchema = typeless_;
|
||||
else
|
||||
RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString());
|
||||
}
|
||||
else
|
||||
context.valueSchema = GetTypeless();
|
||||
context.valueSchema = typeless_;
|
||||
|
||||
context.arrayElementIndex++;
|
||||
}
|
||||
@ -763,10 +765,9 @@ public:
|
||||
if (!(type_ & (1 << kObjectSchemaType)))
|
||||
RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
|
||||
|
||||
context.objectRequiredCount = 0;
|
||||
if (hasDependencies_) {
|
||||
context.objectDependencies = static_cast<bool*>(context.factory.MallocState(sizeof(bool) * propertyCount_));
|
||||
std::memset(context.objectDependencies, 0, sizeof(bool) * propertyCount_);
|
||||
if (hasDependencies_ || hasRequired_) {
|
||||
context.propertyExist = static_cast<bool*>(context.factory.MallocState(sizeof(bool) * propertyCount_));
|
||||
std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_);
|
||||
}
|
||||
|
||||
if (patternProperties_) { // pre-allocate schema array
|
||||
@ -783,25 +784,24 @@ public:
|
||||
if (patternProperties_) {
|
||||
context.patternPropertiesSchemaCount = 0;
|
||||
for (SizeType i = 0; i < patternPropertyCount_; i++)
|
||||
if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len))
|
||||
if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len)) {
|
||||
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema;
|
||||
context.valueSchema = typeless_;
|
||||
}
|
||||
}
|
||||
|
||||
SizeType index;
|
||||
if (FindPropertyIndex(ValueType(str, len).Move(), &index)) {
|
||||
if (context.patternPropertiesSchemaCount > 0) {
|
||||
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema;
|
||||
context.valueSchema = GetTypeless();
|
||||
context.valueSchema = typeless_;
|
||||
context.valuePatternValidatorType = Context::kPatternValidatorWithProperty;
|
||||
}
|
||||
else
|
||||
context.valueSchema = properties_[index].schema;
|
||||
|
||||
if (properties_[index].required)
|
||||
context.objectRequiredCount++;
|
||||
|
||||
if (hasDependencies_)
|
||||
context.objectDependencies[index] = true;
|
||||
if (context.propertyExist)
|
||||
context.propertyExist[index] = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
@ -809,7 +809,7 @@ public:
|
||||
if (additionalPropertiesSchema_) {
|
||||
if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) {
|
||||
context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_;
|
||||
context.valueSchema = GetTypeless();
|
||||
context.valueSchema = typeless_;
|
||||
context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty;
|
||||
}
|
||||
else
|
||||
@ -817,7 +817,7 @@ public:
|
||||
return true;
|
||||
}
|
||||
else if (additionalProperties_) {
|
||||
context.valueSchema = GetTypeless();
|
||||
context.valueSchema = typeless_;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -828,8 +828,11 @@ public:
|
||||
}
|
||||
|
||||
bool EndObject(Context& context, SizeType memberCount) const {
|
||||
if (context.objectRequiredCount != requiredCount_)
|
||||
RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString());
|
||||
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());
|
||||
@ -839,10 +842,10 @@ public:
|
||||
|
||||
if (hasDependencies_) {
|
||||
for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++)
|
||||
if (context.objectDependencies[sourceIndex]) {
|
||||
if (context.propertyExist[sourceIndex]) {
|
||||
if (properties_[sourceIndex].dependencies) {
|
||||
for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++)
|
||||
if (properties_[sourceIndex].dependencies[targetIndex] && !context.objectDependencies[targetIndex])
|
||||
if (properties_[sourceIndex].dependencies[targetIndex] && !context.propertyExist[targetIndex])
|
||||
RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString());
|
||||
}
|
||||
else if (properties_[sourceIndex].dependenciesSchema)
|
||||
@ -880,7 +883,7 @@ public:
|
||||
#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);\
|
||||
static const ValueType v(s, static_cast<SizeType>(sizeof(s) / sizeof(Ch) - 1));\
|
||||
return v;\
|
||||
}
|
||||
|
||||
@ -933,7 +936,7 @@ private:
|
||||
};
|
||||
|
||||
#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
|
||||
typedef internal::GenericRegex<EncodingType> RegexType;
|
||||
typedef internal::GenericRegex<EncodingType, AllocatorType> RegexType;
|
||||
#elif RAPIDJSON_SCHEMA_USE_STDREGEX
|
||||
typedef std::basic_regex<Ch> RegexType;
|
||||
#else
|
||||
@ -948,11 +951,6 @@ private:
|
||||
SizeType count;
|
||||
};
|
||||
|
||||
static const SchemaType* GetTypeless() {
|
||||
static SchemaType typeless(0, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0);
|
||||
return &typeless;
|
||||
}
|
||||
|
||||
template <typename V1, typename V2>
|
||||
void AddUniqueElement(V1& a, const V2& v) {
|
||||
for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
|
||||
@ -998,9 +996,10 @@ private:
|
||||
template <typename ValueType>
|
||||
RegexType* CreatePattern(const ValueType& value) {
|
||||
if (value.IsString()) {
|
||||
RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString());
|
||||
RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), allocator_);
|
||||
if (!r->IsValid()) {
|
||||
r->~RegexType();
|
||||
AllocatorType::Free(r);
|
||||
r = 0;
|
||||
}
|
||||
return r;
|
||||
@ -1009,7 +1008,8 @@ private:
|
||||
}
|
||||
|
||||
static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) {
|
||||
return pattern->Search(str);
|
||||
GenericRegexSearch<RegexType> rs(*pattern);
|
||||
return rs.Search(str);
|
||||
}
|
||||
#elif RAPIDJSON_SCHEMA_USE_STDREGEX
|
||||
template <typename ValueType>
|
||||
@ -1103,6 +1103,9 @@ private:
|
||||
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<double>(i)))
|
||||
return false;
|
||||
}
|
||||
@ -1112,6 +1115,8 @@ private:
|
||||
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<double>(i)))
|
||||
return false;
|
||||
}
|
||||
@ -1137,6 +1142,8 @@ private:
|
||||
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<double>(i)))
|
||||
return false;
|
||||
}
|
||||
@ -1146,6 +1153,8 @@ private:
|
||||
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<double>(i)))
|
||||
return false;
|
||||
}
|
||||
@ -1207,6 +1216,7 @@ private:
|
||||
};
|
||||
|
||||
AllocatorType* allocator_;
|
||||
const SchemaType* typeless_;
|
||||
uint64_t* enum_;
|
||||
SizeType enumCount_;
|
||||
SchemaArray allOf_;
|
||||
@ -1222,11 +1232,11 @@ private:
|
||||
PatternProperty* patternProperties_;
|
||||
SizeType patternPropertyCount_;
|
||||
SizeType propertyCount_;
|
||||
SizeType requiredCount_;
|
||||
SizeType minProperties_;
|
||||
SizeType maxProperties_;
|
||||
bool additionalProperties_;
|
||||
bool hasDependencies_;
|
||||
bool hasRequired_;
|
||||
bool hasSchemaDependencies_;
|
||||
|
||||
const SchemaType* additionalItemsSchema_;
|
||||
@ -1256,7 +1266,7 @@ struct TokenHelper {
|
||||
char buffer[21];
|
||||
size_t length = static_cast<size_t>((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer);
|
||||
for (size_t i = 0; i < length; i++)
|
||||
*documentStack.template Push<Ch>() = buffer[i];
|
||||
*documentStack.template Push<Ch>() = static_cast<Ch>(buffer[i]);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1327,16 +1337,20 @@ public:
|
||||
\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.
|
||||
*/
|
||||
GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) RAPIDJSON_NOEXCEPT :
|
||||
explicit GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) :
|
||||
remoteProvider_(remoteProvider),
|
||||
allocator_(allocator),
|
||||
ownAllocator_(),
|
||||
root_(),
|
||||
typeless_(),
|
||||
schemaMap_(allocator, kInitialSchemaMapSize),
|
||||
schemaRef_(allocator, kInitialSchemaRefSize)
|
||||
{
|
||||
if (!allocator_)
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
|
||||
ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator)();
|
||||
|
||||
typeless_ = static_cast<SchemaType*>(allocator_->Malloc(sizeof(SchemaType)));
|
||||
new (typeless_) SchemaType(this, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0);
|
||||
|
||||
// Generate root schema, it will call CreateSchema() to create sub-schemas,
|
||||
// And call AddRefSchema() if there are $ref.
|
||||
@ -1354,6 +1368,9 @@ public:
|
||||
new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(refEntry->source, const_cast<SchemaType*>(s), false, allocator_);
|
||||
}
|
||||
}
|
||||
else if (refEntry->schema)
|
||||
*refEntry->schema = typeless_;
|
||||
|
||||
refEntry->~SchemaRefEntry();
|
||||
}
|
||||
|
||||
@ -1369,12 +1386,14 @@ public:
|
||||
allocator_(rhs.allocator_),
|
||||
ownAllocator_(rhs.ownAllocator_),
|
||||
root_(rhs.root_),
|
||||
typeless_(rhs.typeless_),
|
||||
schemaMap_(std::move(rhs.schemaMap_)),
|
||||
schemaRef_(std::move(rhs.schemaRef_))
|
||||
{
|
||||
rhs.remoteProvider_ = 0;
|
||||
rhs.allocator_ = 0;
|
||||
rhs.ownAllocator_ = 0;
|
||||
rhs.typeless_ = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -1383,6 +1402,11 @@ public:
|
||||
while (!schemaMap_.Empty())
|
||||
schemaMap_.template Pop<SchemaEntry>(1)->~SchemaEntry();
|
||||
|
||||
if (typeless_) {
|
||||
typeless_->~SchemaType();
|
||||
Allocator::Free(typeless_);
|
||||
}
|
||||
|
||||
RAPIDJSON_DELETE(ownAllocator_);
|
||||
}
|
||||
|
||||
@ -1417,14 +1441,12 @@ private:
|
||||
|
||||
void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) {
|
||||
if (schema)
|
||||
*schema = SchemaType::GetTypeless();
|
||||
*schema = typeless_;
|
||||
|
||||
if (v.GetType() == kObjectType) {
|
||||
const SchemaType* s = GetSchema(pointer);
|
||||
if (!s)
|
||||
CreateSchema(schema, pointer, v, document);
|
||||
else if (schema)
|
||||
*schema = s;
|
||||
|
||||
for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr)
|
||||
CreateSchemaRecursive(0, pointer.Append(itr->name, allocator_), itr->value, document);
|
||||
@ -1464,7 +1486,7 @@ private:
|
||||
|
||||
if (i > 0) { // Remote reference, resolve immediately
|
||||
if (remoteProvider_) {
|
||||
if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i - 1)) {
|
||||
if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i)) {
|
||||
PointerType pointer(&s[i], len - i, allocator_);
|
||||
if (pointer.IsValid()) {
|
||||
if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) {
|
||||
@ -1506,6 +1528,8 @@ private:
|
||||
return PointerType();
|
||||
}
|
||||
|
||||
const SchemaType* GetTypeless() const { return typeless_; }
|
||||
|
||||
static const size_t kInitialSchemaMapSize = 64;
|
||||
static const size_t kInitialSchemaRefSize = 64;
|
||||
|
||||
@ -1513,6 +1537,7 @@ private:
|
||||
Allocator *allocator_;
|
||||
Allocator *ownAllocator_;
|
||||
const SchemaType* root_; //!< Root schema.
|
||||
SchemaType* typeless_;
|
||||
internal::Stack<Allocator> schemaMap_; // Stores created Pointer -> Schemas
|
||||
internal::Stack<Allocator> schemaRef_; // Stores Pointer from $ref and schema which holds the $ref
|
||||
};
|
||||
@ -1566,11 +1591,11 @@ public:
|
||||
:
|
||||
schemaDocument_(&schemaDocument),
|
||||
root_(schemaDocument.GetRoot()),
|
||||
outputHandler_(GetNullHandler()),
|
||||
stateAllocator_(allocator),
|
||||
ownStateAllocator_(0),
|
||||
schemaStack_(allocator, schemaStackCapacity),
|
||||
documentStack_(allocator, documentStackCapacity),
|
||||
outputHandler_(0),
|
||||
valid_(true)
|
||||
#if RAPIDJSON_SCHEMA_VERBOSE
|
||||
, depth_(0)
|
||||
@ -1594,11 +1619,11 @@ public:
|
||||
:
|
||||
schemaDocument_(&schemaDocument),
|
||||
root_(schemaDocument.GetRoot()),
|
||||
outputHandler_(outputHandler),
|
||||
stateAllocator_(allocator),
|
||||
ownStateAllocator_(0),
|
||||
schemaStack_(allocator, schemaStackCapacity),
|
||||
documentStack_(allocator, documentStackCapacity),
|
||||
outputHandler_(&outputHandler),
|
||||
valid_(true)
|
||||
#if RAPIDJSON_SCHEMA_VERBOSE
|
||||
, depth_(0)
|
||||
@ -1670,7 +1695,7 @@ RAPIDJSON_MULTILINEMACRO_END
|
||||
}
|
||||
|
||||
#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\
|
||||
return valid_ = EndValue() && outputHandler_.method arg2
|
||||
return valid_ = EndValue() && (!outputHandler_ || outputHandler_->method arg2)
|
||||
|
||||
#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \
|
||||
RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\
|
||||
@ -1692,7 +1717,7 @@ RAPIDJSON_MULTILINEMACRO_END
|
||||
bool StartObject() {
|
||||
RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext()));
|
||||
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ());
|
||||
return valid_ = outputHandler_.StartObject();
|
||||
return valid_ = !outputHandler_ || outputHandler_->StartObject();
|
||||
}
|
||||
|
||||
bool Key(const Ch* str, SizeType len, bool copy) {
|
||||
@ -1700,7 +1725,7 @@ RAPIDJSON_MULTILINEMACRO_END
|
||||
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);
|
||||
return valid_ = !outputHandler_ || outputHandler_->Key(str, len, copy);
|
||||
}
|
||||
|
||||
bool EndObject(SizeType memberCount) {
|
||||
@ -1713,7 +1738,7 @@ RAPIDJSON_MULTILINEMACRO_END
|
||||
bool StartArray() {
|
||||
RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext()));
|
||||
RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ());
|
||||
return valid_ = outputHandler_.StartArray();
|
||||
return valid_ = !outputHandler_ || outputHandler_->StartArray();
|
||||
}
|
||||
|
||||
bool EndArray(SizeType elementCount) {
|
||||
@ -1761,12 +1786,8 @@ RAPIDJSON_MULTILINEMACRO_END
|
||||
return GetStateAllocator().Malloc(size);
|
||||
}
|
||||
|
||||
virtual void* ReallocState(void* originalPtr, size_t originalSize, size_t newSize) {
|
||||
return GetStateAllocator().Realloc(originalPtr, originalSize, newSize);
|
||||
}
|
||||
|
||||
virtual void FreeState(void* p) {
|
||||
return StateAllocator::Free(p);
|
||||
StateAllocator::Free(p);
|
||||
}
|
||||
|
||||
private:
|
||||
@ -1786,11 +1807,11 @@ private:
|
||||
:
|
||||
schemaDocument_(&schemaDocument),
|
||||
root_(root),
|
||||
outputHandler_(GetNullHandler()),
|
||||
stateAllocator_(allocator),
|
||||
ownStateAllocator_(0),
|
||||
schemaStack_(allocator, schemaStackCapacity),
|
||||
documentStack_(allocator, documentStackCapacity),
|
||||
outputHandler_(0),
|
||||
valid_(true)
|
||||
#if RAPIDJSON_SCHEMA_VERBOSE
|
||||
, depth_(depth)
|
||||
@ -1800,7 +1821,7 @@ private:
|
||||
|
||||
StateAllocator& GetStateAllocator() {
|
||||
if (!stateAllocator_)
|
||||
stateAllocator_ = ownStateAllocator_ = RAPIDJSON_NEW(StateAllocator());
|
||||
stateAllocator_ = ownStateAllocator_ = RAPIDJSON_NEW(StateAllocator)();
|
||||
return *stateAllocator_;
|
||||
}
|
||||
|
||||
@ -1818,8 +1839,8 @@ private:
|
||||
const SchemaType** sa = CurrentContext().patternPropertiesSchemas;
|
||||
typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType;
|
||||
bool valueUniqueness = CurrentContext().valueUniqueness;
|
||||
if (CurrentContext().valueSchema)
|
||||
PushSchema(*CurrentContext().valueSchema);
|
||||
RAPIDJSON_ASSERT(CurrentContext().valueSchema);
|
||||
PushSchema(*CurrentContext().valueSchema);
|
||||
|
||||
if (count > 0) {
|
||||
CurrentContext().objectPatternValidatorType = patternValidatorType;
|
||||
@ -1904,20 +1925,15 @@ private:
|
||||
Context& CurrentContext() { return *schemaStack_.template Top<Context>(); }
|
||||
const Context& CurrentContext() const { return *schemaStack_.template Top<Context>(); }
|
||||
|
||||
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<StateAllocator> schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *)
|
||||
internal::Stack<StateAllocator> documentStack_; //!< stack to store the current path of validating document (Ch)
|
||||
OutputHandler* outputHandler_;
|
||||
bool valid_;
|
||||
#if RAPIDJSON_SCHEMA_VERBOSE
|
||||
unsigned depth_;
|
||||
@ -1963,7 +1979,8 @@ public:
|
||||
GenericSchemaValidator<SchemaDocumentType, Handler> validator(sd_, handler);
|
||||
parseResult_ = reader.template Parse<parseFlags>(is_, validator);
|
||||
|
||||
if ((isValid_ = validator.IsValid())) {
|
||||
isValid_ = validator.IsValid();
|
||||
if (isValid_) {
|
||||
invalidSchemaPointer_ = PointerType();
|
||||
invalidSchemaKeyword_ = 0;
|
||||
invalidDocumentPointer_ = PointerType();
|
||||
@ -1995,13 +2012,6 @@ private:
|
||||
};
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
#if defined(__GNUC__)
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#ifdef __clang__
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
#endif // RAPIDJSON_SCHEMA_H_
|
||||
|
@ -1,5 +1,5 @@
|
||||
// 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
|
||||
@ -7,9 +7,9 @@
|
||||
//
|
||||
// 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
|
||||
// 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"
|
||||
@ -95,11 +95,55 @@ inline void PutUnsafe(Stream& stream, typename Stream::Ch c) {
|
||||
//! Put N copies of a character to a stream.
|
||||
template<typename Stream, typename Ch>
|
||||
inline void PutN(Stream& stream, Ch c, size_t n) {
|
||||
PutReserve<Stream>(stream, n);
|
||||
PutReserve(stream, n);
|
||||
for (size_t i = 0; i < n; i++)
|
||||
PutUnsafe(stream, c);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// GenericStreamWrapper
|
||||
|
||||
//! A Stream Wrapper
|
||||
/*! \tThis string stream is a wrapper for any stream by just forwarding any
|
||||
\treceived message to the origin stream.
|
||||
\note implements Stream concept
|
||||
*/
|
||||
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1800
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(4702) // unreachable code
|
||||
RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
|
||||
#endif
|
||||
|
||||
template <typename InputStream, typename Encoding = UTF8<> >
|
||||
class GenericStreamWrapper {
|
||||
public:
|
||||
typedef typename Encoding::Ch Ch;
|
||||
GenericStreamWrapper(InputStream& is): is_(is) {}
|
||||
|
||||
Ch Peek() const { return is_.Peek(); }
|
||||
Ch Take() { return is_.Take(); }
|
||||
size_t Tell() { return is_.Tell(); }
|
||||
Ch* PutBegin() { return is_.PutBegin(); }
|
||||
void Put(Ch ch) { is_.Put(ch); }
|
||||
void Flush() { is_.Flush(); }
|
||||
size_t PutEnd(Ch* ch) { return is_.PutEnd(ch); }
|
||||
|
||||
// wrapper for MemoryStream
|
||||
const Ch* Peek4() const { return is_.Peek4(); }
|
||||
|
||||
// wrapper for AutoUTFInputStream
|
||||
UTFType GetType() const { return is_.GetType(); }
|
||||
bool HasBOM() const { return is_.HasBOM(); }
|
||||
|
||||
protected:
|
||||
InputStream& is_;
|
||||
};
|
||||
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1800
|
||||
RAPIDJSON_DIAG_POP
|
||||
#endif
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// StringStream
|
||||
|
||||
|
@ -78,8 +78,12 @@ public:
|
||||
return stack_.template Bottom<Ch>();
|
||||
}
|
||||
|
||||
//! Get the size of string in bytes in the string buffer.
|
||||
size_t GetSize() const { return stack_.GetSize(); }
|
||||
|
||||
//! Get the length of string in Ch in the string buffer.
|
||||
size_t GetLength() const { return stack_.GetSize() / sizeof(Ch); }
|
||||
|
||||
static const size_t kDefaultCapacity = 256;
|
||||
mutable internal::Stack<Allocator> stack_;
|
||||
|
||||
|
@ -16,6 +16,7 @@
|
||||
#define RAPIDJSON_WRITER_H_
|
||||
|
||||
#include "stream.h"
|
||||
#include "internal/meta.h"
|
||||
#include "internal/stack.h"
|
||||
#include "internal/strfunc.h"
|
||||
#include "internal/dtoa.h"
|
||||
@ -31,6 +32,8 @@
|
||||
#include <nmmintrin.h>
|
||||
#elif defined(RAPIDJSON_SSE2)
|
||||
#include <emmintrin.h>
|
||||
#elif defined(RAPIDJSON_NEON)
|
||||
#include <arm_neon.h>
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
@ -41,6 +44,8 @@ RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
|
||||
#ifdef __clang__
|
||||
RAPIDJSON_DIAG_PUSH
|
||||
RAPIDJSON_DIAG_OFF(padded)
|
||||
RAPIDJSON_DIAG_OFF(unreachable-code)
|
||||
RAPIDJSON_DIAG_OFF(c++98-compat)
|
||||
#endif
|
||||
|
||||
RAPIDJSON_NAMESPACE_BEGIN
|
||||
@ -62,6 +67,7 @@ RAPIDJSON_NAMESPACE_BEGIN
|
||||
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
|
||||
};
|
||||
|
||||
@ -101,6 +107,13 @@ public:
|
||||
Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
|
||||
os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}
|
||||
|
||||
#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
|
||||
Writer(Writer&& rhs) :
|
||||
os_(rhs.os_), level_stack_(std::move(rhs.level_stack_)), maxDecimalPlaces_(rhs.maxDecimalPlaces_), hasRoot_(rhs.hasRoot_) {
|
||||
rhs.os_ = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
//! Reset the writer with a new stream.
|
||||
/*!
|
||||
This function reset the writer with a new stream and default settings,
|
||||
@ -167,30 +180,32 @@ public:
|
||||
*/
|
||||
//@{
|
||||
|
||||
bool Null() { Prefix(kNullType); return WriteNull(); }
|
||||
bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return WriteBool(b); }
|
||||
bool Int(int i) { Prefix(kNumberType); return WriteInt(i); }
|
||||
bool Uint(unsigned u) { Prefix(kNumberType); return WriteUint(u); }
|
||||
bool Int64(int64_t i64) { Prefix(kNumberType); return WriteInt64(i64); }
|
||||
bool Uint64(uint64_t u64) { Prefix(kNumberType); return WriteUint64(u64); }
|
||||
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 WriteDouble(d); }
|
||||
bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); }
|
||||
|
||||
bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
|
||||
RAPIDJSON_ASSERT(str != 0);
|
||||
(void)copy;
|
||||
Prefix(kNumberType);
|
||||
return WriteString(str, length);
|
||||
return EndValue(WriteString(str, length));
|
||||
}
|
||||
|
||||
bool String(const Ch* str, SizeType length, bool copy = false) {
|
||||
RAPIDJSON_ASSERT(str != 0);
|
||||
(void)copy;
|
||||
Prefix(kStringType);
|
||||
return WriteString(str, length);
|
||||
return EndValue(WriteString(str, length));
|
||||
}
|
||||
|
||||
#if RAPIDJSON_HAS_STDSTRING
|
||||
@ -207,15 +222,20 @@ public:
|
||||
|
||||
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<Ch>& str)
|
||||
{
|
||||
return Key(str.data(), SizeType(str.size()));
|
||||
}
|
||||
#endif
|
||||
|
||||
bool EndObject(SizeType memberCount = 0) {
|
||||
(void)memberCount;
|
||||
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
|
||||
RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
|
||||
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level)); // not inside an Object
|
||||
RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray); // currently inside an Array, not Object
|
||||
RAPIDJSON_ASSERT(0 == level_stack_.template Top<Level>()->valueCount % 2); // Object has a Key without a Value
|
||||
level_stack_.template Pop<Level>(1);
|
||||
bool ret = WriteEndObject();
|
||||
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
|
||||
os_->Flush();
|
||||
return ret;
|
||||
return EndValue(WriteEndObject());
|
||||
}
|
||||
|
||||
bool StartArray() {
|
||||
@ -229,10 +249,7 @@ public:
|
||||
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
|
||||
RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
|
||||
level_stack_.template Pop<Level>(1);
|
||||
bool ret = WriteEndArray();
|
||||
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
|
||||
os_->Flush();
|
||||
return ret;
|
||||
return EndValue(WriteEndArray());
|
||||
}
|
||||
//@}
|
||||
|
||||
@ -240,9 +257,9 @@ public:
|
||||
//@{
|
||||
|
||||
//! 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)); }
|
||||
|
||||
bool String(const Ch* const& str) { return String(str, internal::StrLen(str)); }
|
||||
bool Key(const Ch* const& str) { return Key(str, internal::StrLen(str)); }
|
||||
|
||||
//@}
|
||||
|
||||
//! Write a raw JSON value.
|
||||
@ -253,7 +270,19 @@ public:
|
||||
\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 WriteRawValue(json, length); }
|
||||
bool RawValue(const Ch* json, size_t length, Type type) {
|
||||
RAPIDJSON_ASSERT(json != 0);
|
||||
Prefix(type);
|
||||
return EndValue(WriteRawValue(json, length));
|
||||
}
|
||||
|
||||
//! Flush the output stream.
|
||||
/*!
|
||||
Allows the user to flush the output stream immediately.
|
||||
*/
|
||||
void Flush() {
|
||||
os_->Flush();
|
||||
}
|
||||
|
||||
protected:
|
||||
//! Information for each nested level
|
||||
@ -287,7 +316,7 @@ protected:
|
||||
const char* end = internal::i32toa(i, buffer);
|
||||
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
||||
for (const char* p = buffer; p != end; ++p)
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -296,7 +325,7 @@ protected:
|
||||
const char* end = internal::u32toa(u, buffer);
|
||||
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
||||
for (const char* p = buffer; p != end; ++p)
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -305,7 +334,7 @@ protected:
|
||||
const char* end = internal::i64toa(i64, buffer);
|
||||
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
||||
for (const char* p = buffer; p != end; ++p)
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -314,24 +343,40 @@ protected:
|
||||
char* end = internal::u64toa(u64, buffer);
|
||||
PutReserve(*os_, static_cast<size_t>(end - buffer));
|
||||
for (char* p = buffer; p != end; ++p)
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*p));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WriteDouble(double d) {
|
||||
if (internal::Double(d).IsNanOrInf())
|
||||
return false;
|
||||
|
||||
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<size_t>(end - buffer));
|
||||
for (char* p = buffer; p != end; ++p)
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(*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 typename OutputStream::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
|
||||
@ -387,7 +432,7 @@ protected:
|
||||
else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) {
|
||||
is.Take();
|
||||
PutUnsafe(*os_, '\\');
|
||||
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(escape[static_cast<unsigned char>(c)]));
|
||||
PutUnsafe(*os_, static_cast<typename OutputStream::Ch>(escape[static_cast<unsigned char>(c)]));
|
||||
if (escape[static_cast<unsigned char>(c)] == 'u') {
|
||||
PutUnsafe(*os_, '0');
|
||||
PutUnsafe(*os_, '0');
|
||||
@ -442,6 +487,13 @@ protected:
|
||||
}
|
||||
}
|
||||
|
||||
// Flush the value if it is the top level one.
|
||||
bool EndValue(bool ret) {
|
||||
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
|
||||
Flush();
|
||||
return ret;
|
||||
}
|
||||
|
||||
OutputStream* os_;
|
||||
internal::Stack<StackAllocator> level_stack_;
|
||||
int maxDecimalPlaces_;
|
||||
@ -489,8 +541,25 @@ inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
|
||||
|
||||
template<>
|
||||
inline bool Writer<StringBuffer>::WriteDouble(double d) {
|
||||
if (internal::Double(d).IsNanOrInf())
|
||||
return false;
|
||||
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_);
|
||||
@ -525,7 +594,7 @@ inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, siz
|
||||
// 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 };
|
||||
static const char space[16] = { 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F };
|
||||
const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
|
||||
const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
|
||||
const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
|
||||
@ -534,7 +603,7 @@ inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, siz
|
||||
const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(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 t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x1F) == 0x1F
|
||||
const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
|
||||
unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
|
||||
if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
|
||||
@ -559,7 +628,75 @@ inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, siz
|
||||
is.src_ = p;
|
||||
return RAPIDJSON_LIKELY(is.Tell() < length);
|
||||
}
|
||||
#endif // defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
|
||||
#elif defined(RAPIDJSON_NEON)
|
||||
template<>
|
||||
inline bool Writer<StringBuffer>::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<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
|
||||
const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~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
|
||||
const uint8x16_t s0 = vmovq_n_u8('"');
|
||||
const uint8x16_t s1 = vmovq_n_u8('\\');
|
||||
const uint8x16_t s2 = vmovq_n_u8('\b');
|
||||
const uint8x16_t s3 = vmovq_n_u8(32);
|
||||
|
||||
for (; p != endAligned; p += 16) {
|
||||
const uint8x16_t s = vld1q_u8(reinterpret_cast<const uint8_t *>(p));
|
||||
uint8x16_t x = vceqq_u8(s, s0);
|
||||
x = vorrq_u8(x, vceqq_u8(s, s1));
|
||||
x = vorrq_u8(x, vceqq_u8(s, s2));
|
||||
x = vorrq_u8(x, vcltq_u8(s, s3));
|
||||
|
||||
x = vrev64q_u8(x); // Rev in 64
|
||||
uint64_t low = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 0); // extract
|
||||
uint64_t high = vgetq_lane_u64(reinterpret_cast<uint64x2_t>(x), 1); // extract
|
||||
|
||||
SizeType len = 0;
|
||||
bool escaped = false;
|
||||
if (low == 0) {
|
||||
if (high != 0) {
|
||||
unsigned lz = (unsigned)__builtin_clzll(high);
|
||||
len = 8 + (lz >> 3);
|
||||
escaped = true;
|
||||
}
|
||||
} else {
|
||||
unsigned lz = (unsigned)__builtin_clzll(low);
|
||||
len = lz >> 3;
|
||||
escaped = true;
|
||||
}
|
||||
if (RAPIDJSON_UNLIKELY(escaped)) { // some of characters is escaped
|
||||
char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
|
||||
for (size_t i = 0; i < len; i++)
|
||||
q[i] = p[i];
|
||||
|
||||
p += len;
|
||||
break;
|
||||
}
|
||||
vst1q_u8(reinterpret_cast<uint8_t *>(os_->PushUnsafe(16)), s);
|
||||
}
|
||||
|
||||
is.src_ = p;
|
||||
return RAPIDJSON_LIKELY(is.Tell() < length);
|
||||
}
|
||||
#endif // RAPIDJSON_NEON
|
||||
|
||||
RAPIDJSON_NAMESPACE_END
|
||||
|
||||
|
2
include_dirs.js
Normal file
2
include_dirs.js
Normal file
@ -0,0 +1,2 @@
|
||||
var path = require('path');
|
||||
console.log(path.join(path.relative('.', __dirname), 'include'));
|
BIN
library.json
BIN
library.json
Binary file not shown.
BIN
package.json
Normal file
BIN
package.json
Normal file
Binary file not shown.
@ -1,14 +1,14 @@
|
||||
nuget {
|
||||
//Usage: Write-NuGetPackage rapidjson.autopkg -defines:MYVERSION=1.0.2
|
||||
//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.0.2"};
|
||||
authors: {"https://github.com/Tencent/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/";
|
||||
licenseUrl: "https://github.com/Tencent/rapidjson/blob/master/license.txt";
|
||||
projectUrl: "https://github.com/Tencent/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";
|
||||
@ -71,5 +71,7 @@ Changed
|
||||
targets {
|
||||
// We're trying to be standard about these sorts of thing. (Will help with config.h later :D)
|
||||
//Defines += HAS_EQCORE;
|
||||
// Fix creating the package with Raggles' fork of CoApp
|
||||
Includes += "$(MSBuildThisFileDirectory)../..${d_include}";
|
||||
};
|
||||
}
|
67
readme.md
67
readme.md
@ -1,14 +1,14 @@
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
## A fast JSON parser/generator for C++ with both SAX/DOM style API
|
||||
## 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 GitHub](https://github.com/Tencent/rapidjson/)
|
||||
* RapidJSON Documentation
|
||||
* [English](http://rapidjson.org/)
|
||||
* [简体中文](http://rapidjson.org/zh-cn/)
|
||||
@ -20,12 +20,12 @@ Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights
|
||||
| :---------------: | :-----------------: | :-------------------: |
|
||||
| ![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
|
||||
[lin-badge]: https://travis-ci.org/Tencent/rapidjson.svg?branch=master "Travis build status"
|
||||
[lin-link]: https://travis-ci.org/Tencent/rapidjson "Travis build status"
|
||||
[win-badge]: https://ci.appveyor.com/api/projects/status/l6qulgqahcayidrf/branch/master?svg=true "AppVeyor build status"
|
||||
[win-link]: https://ci.appveyor.com/project/miloyip/rapidjson-0fdqj/branch/master "AppVeyor build status"
|
||||
[cov-badge]: https://coveralls.io/repos/Tencent/rapidjson/badge.svg?branch=master "Coveralls coverage"
|
||||
[cov-link]: https://coveralls.io/r/Tencent/rapidjson?branch=master "Coveralls coverage"
|
||||
|
||||
## Introduction
|
||||
|
||||
@ -37,16 +37,26 @@ RapidJSON is a JSON parser and generator for C++. It was inspired by [RapidXml](
|
||||
|
||||
* 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/20 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 **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. More information about JSON can be obtained at
|
||||
JSON(JavaScript Object Notation) is a light-weight data exchange format. RapidJSON should be in full 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)
|
||||
* [RFC7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159)
|
||||
* [Standard ECMA-404: The JSON Data Interchange Format](https://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
|
||||
|
||||
@ -64,8 +74,8 @@ RapidJSON is a header-only C++ library. Just copy the `include/rapidjson` folder
|
||||
|
||||
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
|
||||
* (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:
|
||||
|
||||
@ -74,7 +84,7 @@ To generate user documentation and run tests please proceed with the steps below
|
||||
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`
|
||||
On successful 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
|
||||
@ -126,4 +136,25 @@ The following diagram shows the process.
|
||||
|
||||

|
||||
|
||||
More [examples](https://github.com/miloyip/rapidjson/tree/master/example) are available.
|
||||
More [examples](https://github.com/Tencent/rapidjson/tree/master/example) are available:
|
||||
|
||||
* DOM API
|
||||
* [tutorial](https://github.com/Tencent/rapidjson/blob/master/example/tutorial/tutorial.cpp): Basic usage of DOM API.
|
||||
|
||||
* SAX API
|
||||
* [simplereader](https://github.com/Tencent/rapidjson/blob/master/example/simplereader/simplereader.cpp): Dumps all SAX events while parsing a JSON by `Reader`.
|
||||
* [condense](https://github.com/Tencent/rapidjson/blob/master/example/condense/condense.cpp): A command line tool to rewrite a JSON, with all whitespaces removed.
|
||||
* [pretty](https://github.com/Tencent/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/Tencent/rapidjson/blob/master/example/capitalize/capitalize.cpp): A command line tool to capitalize strings in JSON.
|
||||
* [messagereader](https://github.com/Tencent/rapidjson/blob/master/example/messagereader/messagereader.cpp): Parse a JSON message with SAX API.
|
||||
* [serialize](https://github.com/Tencent/rapidjson/blob/master/example/serialize/serialize.cpp): Serialize a C++ object into JSON with SAX API.
|
||||
* [jsonx](https://github.com/Tencent/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/Tencent/rapidjson/blob/master/example/schemavalidator/schemavalidator.cpp) : A command line tool to validate a JSON with a JSON schema.
|
||||
|
||||
* Advanced
|
||||
* [prettyauto](https://github.com/Tencent/rapidjson/blob/master/example/prettyauto/prettyauto.cpp): A modified version of [pretty](https://github.com/Tencent/rapidjson/blob/master/example/pretty/pretty.cpp) to automatically handle JSON with any UTF encodings.
|
||||
* [parsebyparts](https://github.com/Tencent/rapidjson/blob/master/example/parsebyparts/parsebyparts.cpp): Implements an `AsyncDocumentParser` which can parse JSON in parts, using C++11 thread.
|
||||
* [filterkey](https://github.com/Tencent/rapidjson/blob/master/example/filterkey/filterkey.cpp): A command line tool to remove all values with user-specified key.
|
||||
* [filterkeydom](https://github.com/Tencent/rapidjson/blob/master/example/filterkeydom/filterkeydom.cpp): Same tool as above, but it demonstrates how to use a generator to populate a `Document`.
|
||||
|
105
readme.zh-cn.md
105
readme.zh-cn.md
@ -1,18 +1,18 @@
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
## 高效的C++ JSON解析/生成器,提供SAX及DOM风格API
|
||||
## 高效的 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 GitHub](https://github.com/Tencent/rapidjson/)
|
||||
* RapidJSON 文档
|
||||
* [English](http://rapidjson.org/)
|
||||
* [简体中文](http://rapidjson.org/zh-cn/)
|
||||
* [GitBook](https://www.gitbook.com/book/miloyip/rapidjson/)可下载PDF/EPUB/MOBI,但不含API参考手册。
|
||||
* [GitBook](https://www.gitbook.com/book/miloyip/rapidjson/details/zh-cn) 可下载 PDF/EPUB/MOBI,但不含 API 参考手册。
|
||||
|
||||
## Build 状态
|
||||
|
||||
@ -20,37 +20,47 @@ Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights
|
||||
| :---------------: | :-----------------: | :-------------------: |
|
||||
| ![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
|
||||
[lin-badge]: https://travis-ci.org/Tencent/rapidjson.svg?branch=master "Travis build status"
|
||||
[lin-link]: https://travis-ci.org/Tencent/rapidjson "Travis build status"
|
||||
[win-badge]: https://ci.appveyor.com/api/projects/status/l6qulgqahcayidrf/branch/master?svg=true "AppVeyor build status"
|
||||
[win-link]: https://ci.appveyor.com/project/miloyip/rapidjson-0fdqj/branch/master "AppVeyor build status"
|
||||
[cov-badge]: https://coveralls.io/repos/Tencent/rapidjson/badge.svg?branch=master "Coveralls coverage"
|
||||
[cov-link]: https://coveralls.io/r/Tencent/rapidjson?branch=master "Coveralls coverage"
|
||||
|
||||
## 简介
|
||||
|
||||
RapidJSON是一个C++的JSON解析器及生成器。它的灵感来自[RapidXml](http://rapidxml.sourceforge.net/)。
|
||||
RapidJSON 是一个 C++ 的 JSON 解析器及生成器。它的灵感来自 [RapidXml](http://rapidxml.sourceforge.net/)。
|
||||
|
||||
* RapidJSON小而全。它同时支持SAX和DOM风格的API。SAX解析器只有约500行代码。
|
||||
* RapidJSON 小而全。它同时支持 SAX 和 DOM 风格的 API。SAX 解析器只有约 500 行代码。
|
||||
|
||||
* RapidJSON快。它的性能可与`strlen()`相比。可支持SSE2/SSE4.2加速。
|
||||
* RapidJSON 快。它的性能可与 `strlen()` 相比。可支持 SSE2/SSE4.2 加速。
|
||||
|
||||
* RapidJSON独立。它不依赖于BOOST等外部库。它甚至不依赖于STL。
|
||||
* RapidJSON 独立。它不依赖于 BOOST 等外部库。它甚至不依赖于 STL。
|
||||
|
||||
* RapidJSON对内存友好。在大部分32/64位机器上,每个JSON值只占16或20字节(除字符串外)。它预设使用一个快速的内存分配器,令分析器可以紧凑地分配内存。
|
||||
* RapidJSON 对内存友好。在大部分 32/64 位机器上,每个 JSON 值只占 16 字节(除字符串外)。它预设使用一个快速的内存分配器,令分析器可以紧凑地分配内存。
|
||||
|
||||
* RapidJSON对Unicode友好。它支持UTF-8、UTF-16、UTF-32 (大端序/小端序),并内部支持这些编码的检测、校验及转码。例如,RapidJSON可以在分析一个UTF-8文件至DOM时,把当中的JSON字符串转码至UTF-16。它也支持代理对(surrogate pair)及`"\u0000"`(空字符)。
|
||||
* RapidJSON 对 Unicode 友好。它支持 UTF-8、UTF-16、UTF-32 (大端序/小端序),并内部支持这些编码的检测、校验及转码。例如,RapidJSON 可以在分析一个 UTF-8 文件至 DOM 时,把当中的 JSON 字符串转码至 UTF-16。它也支持代理对(surrogate pair)及 `"\u0000"`(空字符)。
|
||||
|
||||
在[这里](doc/features.md)可读取更多特点。
|
||||
在 [这里](doc/features.zh-cn.md) 可读取更多特点。
|
||||
|
||||
JSON(JavaScript Object Notation)是一个轻量的数据交换格式。RapidJSON应该完全遵从RFC7159/ECMA-404。 关于JSON的更多信息可参考:
|
||||
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)
|
||||
* [RFC7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159)
|
||||
* [Standard ECMA-404: The JSON Data Interchange Format](https://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是跨平台的。以下是一些曾测试的平台/编译器组合:
|
||||
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
|
||||
@ -60,27 +70,27 @@ RapidJSON是跨平台的。以下是一些曾测试的平台/编译器组合
|
||||
|
||||
## 安装
|
||||
|
||||
RapidJSON是只有头文件的C++库。只需把`include/rapidjson`目录复制至系统或项目的include目录中。
|
||||
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/)用于单元及性能测试
|
||||
RapidJSON 依赖于以下软件:
|
||||
* [CMake](https://cmake.org/) 作为通用生成工具
|
||||
* (optional) [Doxygen](http://www.doxygen.org) 用于生成文档
|
||||
* (optional) [googletest](https://github.com/google/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`。
|
||||
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`命令可获取详细的输出。
|
||||
成功生成后,你会在 `bin` 的目录下找到编译后的测试及例子可执行文件。而生成的文档将位于 build 下的 `doc/html` 目录。要执行测试,请在 build 下执行 `make test` 或 `ctest`。使用 `ctest -V` 命令可获取详细的输出。
|
||||
|
||||
我们也可以把程序库安装至全系统中,只要在具管理權限下从build目录执行`make install`命令。这样会按系统的偏好设置安装所有文件。当安装RapidJSON后,其他的CMake项目需要使用它时,可以通过在`CMakeLists.txt`加入一句`find_package(RapidJSON)`。
|
||||
我们也可以把程序库安装至全系统中,只要在具管理权限下从 build 目录执行 `make install` 命令。这样会按系统的偏好设置安装所有文件。当安装 RapidJSON 后,其他的 CMake 项目需要使用它时,可以通过在 `CMakeLists.txt` 加入一句 `find_package(RapidJSON)`。
|
||||
|
||||
## 用法一览
|
||||
|
||||
此简单例子解析一个JSON字符串至一个document (DOM),对DOM作出简单修改,最终把DOM转换(stringify)至JSON字符串。
|
||||
此简单例子解析一个 JSON 字符串至一个 document (DOM),对 DOM 作出简单修改,最终把 DOM 转换(stringify)至 JSON 字符串。
|
||||
|
||||
~~~~~~~~~~cpp
|
||||
// rapidjson/example/simpledom/simpledom.cpp`
|
||||
@ -92,16 +102,16 @@ RapidJSON依赖于以下软件:
|
||||
using namespace rapidjson;
|
||||
|
||||
int main() {
|
||||
// 1. 把JSON解析至DOM。
|
||||
// 1. 把 JSON 解析至 DOM。
|
||||
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
|
||||
Document d;
|
||||
d.Parse(json);
|
||||
|
||||
// 2. 利用DOM作出修改。
|
||||
// 2. 利用 DOM 作出修改。
|
||||
Value& s = d["stars"];
|
||||
s.SetInt(s.GetInt() + 1);
|
||||
|
||||
// 3. 把DOM转换(stringify)成JSON。
|
||||
// 3. 把 DOM 转换(stringify)成 JSON。
|
||||
StringBuffer buffer;
|
||||
Writer<StringBuffer> writer(buffer);
|
||||
d.Accept(writer);
|
||||
@ -118,4 +128,25 @@ int main() {
|
||||
|
||||

|
||||
|
||||
还有许多[例子](https://github.com/miloyip/rapidjson/tree/master/example)可供参考。
|
||||
还有许多 [例子](https://github.com/Tencent/rapidjson/tree/master/example) 可供参考:
|
||||
|
||||
* DOM API
|
||||
* [tutorial](https://github.com/Tencent/rapidjson/blob/master/example/tutorial/tutorial.cpp): DOM API 的基本使用方法。
|
||||
|
||||
* SAX API
|
||||
* [simplereader](https://github.com/Tencent/rapidjson/blob/master/example/simplereader/simplereader.cpp): 使用 `Reader` 解析 JSON 时,打印所有 SAX 事件。
|
||||
* [condense](https://github.com/Tencent/rapidjson/blob/master/example/condense/condense.cpp): 移除 JSON 中所有空白符的命令行工具。
|
||||
* [pretty](https://github.com/Tencent/rapidjson/blob/master/example/pretty/pretty.cpp): 为 JSON 加入缩进与换行的命令行工具,当中使用了 `PrettyWriter`。
|
||||
* [capitalize](https://github.com/Tencent/rapidjson/blob/master/example/capitalize/capitalize.cpp): 把 JSON 中所有字符串改为大写的命令行工具。
|
||||
* [messagereader](https://github.com/Tencent/rapidjson/blob/master/example/messagereader/messagereader.cpp): 使用 SAX API 去解析一个 JSON 报文。
|
||||
* [serialize](https://github.com/Tencent/rapidjson/blob/master/example/serialize/serialize.cpp): 使用 SAX API 去序列化 C++ 对象,生成 JSON。
|
||||
* [jsonx](https://github.com/Tencent/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/Tencent/rapidjson/blob/master/example/schemavalidator/schemavalidator.cpp): 使用 JSON Schema 去校验 JSON 的命令行工具。
|
||||
|
||||
* 进阶
|
||||
* [prettyauto](https://github.com/Tencent/rapidjson/blob/master/example/prettyauto/prettyauto.cpp): [pretty](https://github.com/Tencent/rapidjson/blob/master/example/pretty/pretty.cpp) 的修改版本,可自动处理任何 UTF 编码的 JSON。
|
||||
* [parsebyparts](https://github.com/Tencent/rapidjson/blob/master/example/parsebyparts/parsebyparts.cpp): 这例子中的 `AsyncDocumentParser` 类使用 C++ 线程来逐段解析 JSON。
|
||||
* [filterkey](https://github.com/Tencent/rapidjson/blob/master/example/filterkey/filterkey.cpp): 移取使用者指定的键值的命令行工具。
|
||||
* [filterkeydom](https://github.com/Tencent/rapidjson/blob/master/example/filterkey/filterkey.cpp): 如上的工具,但展示如何使用生成器(generator)去填充一个 `Document`。
|
@ -19,6 +19,8 @@ if(CCACHE_FOUND)
|
||||
endif()
|
||||
endif(CCACHE_FOUND)
|
||||
|
||||
set_property(DIRECTORY PROPERTY COMPILE_OPTIONS ${EXTRA_CXX_FLAGS})
|
||||
|
||||
IF(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug"))
|
||||
add_test(NAME perftest
|
||||
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/perftest
|
||||
|
@ -24,10 +24,13 @@
|
||||
|
||||
// __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.
|
||||
// Likewise, __ARM_NEON is used to detect Neon.
|
||||
#if defined(__SSE4_2__)
|
||||
# define RAPIDJSON_SSE42
|
||||
#elif defined(__SSE2__)
|
||||
# define RAPIDJSON_SSE2
|
||||
#elif defined(__ARM_NEON)
|
||||
# define RAPIDJSON_NEON
|
||||
#endif
|
||||
|
||||
#define RAPIDJSON_HAS_STDSTRING 1
|
||||
|
@ -28,6 +28,8 @@
|
||||
#define SIMD_SUFFIX(name) name##_SSE2
|
||||
#elif defined(RAPIDJSON_SSE42)
|
||||
#define SIMD_SUFFIX(name) name##_SSE42
|
||||
#elif defined(RAPIDJSON_NEON)
|
||||
#define SIMD_SUFFIX(name) name##_NEON
|
||||
#else
|
||||
#define SIMD_SUFFIX(name) name
|
||||
#endif
|
||||
@ -152,6 +154,35 @@ TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativeInsitu_DummyHandler)) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativePull_DummyHandler)) {
|
||||
for (size_t i = 0; i < kTrialCount; i++) {
|
||||
StringStream s(json_);
|
||||
BaseReaderHandler<> h;
|
||||
Reader reader;
|
||||
reader.IterativeParseInit();
|
||||
while (!reader.IterativeParseComplete()) {
|
||||
if (!reader.IterativeParseNext<kParseDefaultFlags>(s, h))
|
||||
break;
|
||||
}
|
||||
EXPECT_FALSE(reader.HasParseError());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseIterativePullInsitu_DummyHandler)) {
|
||||
for (size_t i = 0; i < kTrialCount; i++) {
|
||||
memcpy(temp_, json_, length_ + 1);
|
||||
InsituStringStream s(temp_);
|
||||
BaseReaderHandler<> h;
|
||||
Reader reader;
|
||||
reader.IterativeParseInit();
|
||||
while (!reader.IterativeParseComplete()) {
|
||||
if (!reader.IterativeParseNext<kParseDefaultFlags|kParseInsituFlag>(s, h))
|
||||
break;
|
||||
}
|
||||
EXPECT_FALSE(reader.HasParseError());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_ValidateEncoding)) {
|
||||
for (size_t i = 0; i < kTrialCount; i++) {
|
||||
StringStream s(json_);
|
||||
|
@ -1,6 +1,9 @@
|
||||
include(CheckCXXCompilerFlag)
|
||||
|
||||
set(UNITTEST_SOURCES
|
||||
allocatorstest.cpp
|
||||
bigintegertest.cpp
|
||||
cursorstreamwrappertest.cpp
|
||||
documenttest.cpp
|
||||
dtoatest.cpp
|
||||
encodedstreamtest.cpp
|
||||
@ -34,12 +37,31 @@ if(CCACHE_FOUND)
|
||||
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")
|
||||
set_property(DIRECTORY PROPERTY COMPILE_OPTIONS ${EXTRA_CXX_FLAGS})
|
||||
|
||||
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
# 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")
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS=1)
|
||||
# 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")
|
||||
@ -58,7 +80,7 @@ add_test(NAME unittest
|
||||
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.*
|
||||
COMMAND valgrind --suppressions=${CMAKE_SOURCE_DIR}/test/valgrind.supp --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")
|
||||
|
115
test/unittest/cursorstreamwrappertest.cpp
Normal file
115
test/unittest/cursorstreamwrappertest.cpp
Normal file
@ -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.
|
||||
|
||||
#include "unittest.h"
|
||||
#include "rapidjson/document.h"
|
||||
#include "rapidjson/cursorstreamwrapper.h"
|
||||
|
||||
using namespace rapidjson;
|
||||
|
||||
// static const char json[] = "{\"string\"\n\n:\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
|
||||
bool testJson(const char *json, size_t &line, size_t &col) {
|
||||
StringStream ss(json);
|
||||
CursorStreamWrapper<StringStream> csw(ss);
|
||||
Document document;
|
||||
document.ParseStream(csw);
|
||||
bool ret = document.HasParseError();
|
||||
if (ret) {
|
||||
col = csw.GetColumn();
|
||||
line = csw.GetLine();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingFirstBracket) {
|
||||
const char json[] = "\"string\"\n\n:\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 3);
|
||||
EXPECT_EQ(col, 0);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingQuotes) {
|
||||
const char json[] = "{\"string\n\n:\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 1);
|
||||
EXPECT_EQ(col, 8);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingColon) {
|
||||
const char json[] = "{\"string\"\n\n\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 3);
|
||||
EXPECT_EQ(col, 0);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingSecondQuotes) {
|
||||
const char json[] = "{\"string\"\n\n:my string\",\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 3);
|
||||
EXPECT_EQ(col, 1);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingComma) {
|
||||
const char json[] = "{\"string\"\n\n:\"my string\"\"array\"\n:[\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 3);
|
||||
EXPECT_EQ(col, 12);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingArrayBracket) {
|
||||
const char json[] = "{\"string\"\n\n:\"my string\",\"array\"\n:\"1\", \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 4);
|
||||
EXPECT_EQ(col, 9);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingArrayComma) {
|
||||
const char json[] = "{\"string\"\n\n:\"my string\",\"array\"\n:[\"1\" \"2\", \"3\"]}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 4);
|
||||
EXPECT_EQ(col, 6);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingLastArrayBracket) {
|
||||
const char json8[] = "{\"string\"\n\n:\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"}";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json8, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 4);
|
||||
EXPECT_EQ(col, 15);
|
||||
}
|
||||
|
||||
TEST(CursorStreamWrapper, MissingLastBracket) {
|
||||
const char json9[] = "{\"string\"\n\n:\"my string\",\"array\"\n:[\"1\", \"2\", \"3\"]";
|
||||
size_t col, line;
|
||||
bool ret = testJson(json9, line, col);
|
||||
EXPECT_TRUE(ret);
|
||||
EXPECT_EQ(line, 4);
|
||||
EXPECT_EQ(col, 16);
|
||||
}
|
@ -128,8 +128,14 @@ TEST(Document, UnchangedOnParseError) {
|
||||
Document doc;
|
||||
doc.SetArray().PushBack(0, doc.GetAllocator());
|
||||
|
||||
ParseResult noError;
|
||||
EXPECT_TRUE(noError);
|
||||
|
||||
ParseResult err = doc.Parse("{]");
|
||||
EXPECT_TRUE(doc.HasParseError());
|
||||
EXPECT_NE(err, noError);
|
||||
EXPECT_NE(err.Code(), noError);
|
||||
EXPECT_NE(noError, doc.GetParseError());
|
||||
EXPECT_EQ(err.Code(), doc.GetParseError());
|
||||
EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
|
||||
EXPECT_TRUE(doc.IsArray());
|
||||
@ -138,6 +144,9 @@ TEST(Document, UnchangedOnParseError) {
|
||||
err = doc.Parse("{}");
|
||||
EXPECT_FALSE(doc.HasParseError());
|
||||
EXPECT_FALSE(err.IsError());
|
||||
EXPECT_TRUE(err);
|
||||
EXPECT_EQ(err, noError);
|
||||
EXPECT_EQ(err.Code(), noError);
|
||||
EXPECT_EQ(err.Code(), doc.GetParseError());
|
||||
EXPECT_EQ(err.Offset(), doc.GetErrorOffset());
|
||||
EXPECT_TRUE(doc.IsObject());
|
||||
@ -291,7 +300,14 @@ TEST(Document, Swap) {
|
||||
o.SetObject().AddMember("a", 1, a);
|
||||
|
||||
// Swap between Document and Value
|
||||
// d1.Swap(o); // doesn't compile
|
||||
d1.Swap(o);
|
||||
EXPECT_TRUE(d1.IsObject());
|
||||
EXPECT_TRUE(o.IsArray());
|
||||
|
||||
d1.Swap(o);
|
||||
EXPECT_TRUE(d1.IsArray());
|
||||
EXPECT_TRUE(o.IsObject());
|
||||
|
||||
o.Swap(d1);
|
||||
EXPECT_TRUE(d1.IsObject());
|
||||
EXPECT_TRUE(o.IsArray());
|
||||
@ -447,10 +463,10 @@ TYPED_TEST_CASE(DocumentMove, MoveAllocatorTypes);
|
||||
|
||||
TYPED_TEST(DocumentMove, MoveConstructor) {
|
||||
typedef TypeParam Allocator;
|
||||
typedef GenericDocument<UTF8<>, Allocator> Document;
|
||||
typedef GenericDocument<UTF8<>, Allocator> D;
|
||||
Allocator allocator;
|
||||
|
||||
Document a(&allocator);
|
||||
D a(&allocator);
|
||||
a.Parse("[\"one\", \"two\", \"three\"]");
|
||||
EXPECT_FALSE(a.HasParseError());
|
||||
EXPECT_TRUE(a.IsArray());
|
||||
@ -458,7 +474,7 @@ TYPED_TEST(DocumentMove, MoveConstructor) {
|
||||
EXPECT_EQ(&a.GetAllocator(), &allocator);
|
||||
|
||||
// Document b(a); // does not compile (!is_copy_constructible)
|
||||
Document b(std::move(a));
|
||||
D b(std::move(a));
|
||||
EXPECT_TRUE(a.IsNull());
|
||||
EXPECT_TRUE(b.IsArray());
|
||||
EXPECT_EQ(3u, b.Size());
|
||||
@ -471,7 +487,7 @@ TYPED_TEST(DocumentMove, MoveConstructor) {
|
||||
EXPECT_EQ(2u, b.MemberCount());
|
||||
|
||||
// Document c = a; // does not compile (!is_copy_constructible)
|
||||
Document c = std::move(b);
|
||||
D c = std::move(b);
|
||||
EXPECT_TRUE(b.IsNull());
|
||||
EXPECT_TRUE(c.IsObject());
|
||||
EXPECT_EQ(2u, c.MemberCount());
|
||||
@ -481,25 +497,29 @@ TYPED_TEST(DocumentMove, MoveConstructor) {
|
||||
|
||||
TYPED_TEST(DocumentMove, MoveConstructorParseError) {
|
||||
typedef TypeParam Allocator;
|
||||
typedef GenericDocument<UTF8<>, Allocator> Document;
|
||||
typedef GenericDocument<UTF8<>, Allocator> D;
|
||||
|
||||
ParseResult noError;
|
||||
Document a;
|
||||
D a;
|
||||
a.Parse("{ 4 = 4]");
|
||||
ParseResult error(a.GetParseError(), a.GetErrorOffset());
|
||||
EXPECT_TRUE(a.HasParseError());
|
||||
EXPECT_NE(error, noError);
|
||||
EXPECT_NE(error.Code(), noError);
|
||||
EXPECT_NE(error.Code(), noError.Code());
|
||||
EXPECT_NE(error.Offset(), noError.Offset());
|
||||
|
||||
Document b(std::move(a));
|
||||
D b(std::move(a));
|
||||
EXPECT_FALSE(a.HasParseError());
|
||||
EXPECT_TRUE(b.HasParseError());
|
||||
EXPECT_EQ(a.GetParseError(), noError);
|
||||
EXPECT_EQ(a.GetParseError(), noError.Code());
|
||||
EXPECT_EQ(b.GetParseError(), error.Code());
|
||||
EXPECT_EQ(a.GetErrorOffset(), noError.Offset());
|
||||
EXPECT_EQ(b.GetParseError(), error);
|
||||
EXPECT_EQ(b.GetParseError(), error.Code());
|
||||
EXPECT_EQ(b.GetErrorOffset(), error.Offset());
|
||||
|
||||
Document c(std::move(b));
|
||||
D c(std::move(b));
|
||||
EXPECT_FALSE(b.HasParseError());
|
||||
EXPECT_TRUE(c.HasParseError());
|
||||
EXPECT_EQ(b.GetParseError(), noError.Code());
|
||||
@ -540,10 +560,10 @@ TYPED_TEST(DocumentMove, MoveConstructorStack) {
|
||||
|
||||
TYPED_TEST(DocumentMove, MoveAssignment) {
|
||||
typedef TypeParam Allocator;
|
||||
typedef GenericDocument<UTF8<>, Allocator> Document;
|
||||
typedef GenericDocument<UTF8<>, Allocator> D;
|
||||
Allocator allocator;
|
||||
|
||||
Document a(&allocator);
|
||||
D a(&allocator);
|
||||
a.Parse("[\"one\", \"two\", \"three\"]");
|
||||
EXPECT_FALSE(a.HasParseError());
|
||||
EXPECT_TRUE(a.IsArray());
|
||||
@ -551,7 +571,7 @@ TYPED_TEST(DocumentMove, MoveAssignment) {
|
||||
EXPECT_EQ(&a.GetAllocator(), &allocator);
|
||||
|
||||
// Document b; b = a; // does not compile (!is_copy_assignable)
|
||||
Document b;
|
||||
D b;
|
||||
b = std::move(a);
|
||||
EXPECT_TRUE(a.IsNull());
|
||||
EXPECT_TRUE(b.IsArray());
|
||||
@ -565,7 +585,7 @@ TYPED_TEST(DocumentMove, MoveAssignment) {
|
||||
EXPECT_EQ(2u, b.MemberCount());
|
||||
|
||||
// Document c; c = a; // does not compile (see static_assert)
|
||||
Document c;
|
||||
D c;
|
||||
c = std::move(b);
|
||||
EXPECT_TRUE(b.IsNull());
|
||||
EXPECT_TRUE(c.IsObject());
|
||||
@ -576,17 +596,17 @@ TYPED_TEST(DocumentMove, MoveAssignment) {
|
||||
|
||||
TYPED_TEST(DocumentMove, MoveAssignmentParseError) {
|
||||
typedef TypeParam Allocator;
|
||||
typedef GenericDocument<UTF8<>, Allocator> Document;
|
||||
typedef GenericDocument<UTF8<>, Allocator> D;
|
||||
|
||||
ParseResult noError;
|
||||
Document a;
|
||||
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());
|
||||
|
||||
Document b;
|
||||
D b;
|
||||
b = std::move(a);
|
||||
EXPECT_FALSE(a.HasParseError());
|
||||
EXPECT_TRUE(b.HasParseError());
|
||||
@ -595,7 +615,7 @@ TYPED_TEST(DocumentMove, MoveAssignmentParseError) {
|
||||
EXPECT_EQ(a.GetErrorOffset(), noError.Offset());
|
||||
EXPECT_EQ(b.GetErrorOffset(), error.Offset());
|
||||
|
||||
Document c;
|
||||
D c;
|
||||
c = std::move(b);
|
||||
EXPECT_FALSE(b.HasParseError());
|
||||
EXPECT_TRUE(c.HasParseError());
|
||||
@ -612,9 +632,9 @@ TYPED_TEST(DocumentMove, MoveAssignmentParseError) {
|
||||
TYPED_TEST(DocumentMove, MoveAssignmentStack) {
|
||||
typedef TypeParam Allocator;
|
||||
typedef UTF8<> Encoding;
|
||||
typedef GenericDocument<Encoding, Allocator> Document;
|
||||
typedef GenericDocument<Encoding, Allocator> D;
|
||||
|
||||
Document a;
|
||||
D a;
|
||||
size_t defaultCapacity = a.GetStackCapacity();
|
||||
|
||||
// Trick Document into getting GetStackCapacity() to return non-zero
|
||||
@ -625,12 +645,12 @@ TYPED_TEST(DocumentMove, MoveAssignmentStack) {
|
||||
size_t capacity = a.GetStackCapacity();
|
||||
EXPECT_GT(capacity, 0u);
|
||||
|
||||
Document b;
|
||||
D b;
|
||||
b = std::move(a);
|
||||
EXPECT_EQ(a.GetStackCapacity(), defaultCapacity);
|
||||
EXPECT_EQ(b.GetStackCapacity(), capacity);
|
||||
|
||||
Document c;
|
||||
D c;
|
||||
c = std::move(b);
|
||||
EXPECT_EQ(b.GetStackCapacity(), defaultCapacity);
|
||||
EXPECT_EQ(c.GetStackCapacity(), capacity);
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user