Commit 7f9921fc authored by Milo Yip's avatar Milo Yip

Merge branch 'master' into schema

# Conflicts:
#	.gitignore
#	include/rapidjson/internal/stack.h
parents 74f0673d 4f20bdcf
<<<<<<< HEAD
=======
/bin/*
!/bin/data
!/bin/encodings
!/bin/jsonchecker
!/bin/types
>>>>>>> master
/build
/doc/html
/doc/doxygen_*.db
......@@ -16,3 +24,4 @@ Testing
install_manifest.txt
Doxyfile
DartConfiguration.tcl
*.nupkg
......@@ -6,10 +6,12 @@ compiler:
env:
matrix:
- CONF=debug ARCH=x86_64
- CONF=release ARCH=x86_64
- CONF=debug ARCH=x86
- CONF=release ARCH=x86
- CONF=debug ARCH=x86_64 CXX11=ON
- CONF=release ARCH=x86_64 CXX11=ON
- CONF=debug ARCH=x86 CXX11=ON
- CONF=release ARCH=x86 CXX11=ON
- CONF=debug ARCH=x86_64 CXX11=OFF
- CONF=debug ARCH=x86 CXX11=OFF
global:
- ARCH_FLAGS_x86='-m32' # #266: don't use SSE on 32-bit
- ARCH_FLAGS_x86_64='-msse4.2' # use SSE4.2 on 64-bit
......@@ -34,6 +36,7 @@ before_script:
eval "ARCH_FLAGS=\${ARCH_FLAGS_${ARCH}}" ;
(cd build && cmake
-DRAPIDJSON_HAS_STDSTRING=ON
-DRAPIDJSON_BUILD_CXX11=$CXX11
-DCMAKE_VERBOSE_MAKEFILE=ON
-DCMAKE_BUILD_TYPE=$CONF
-DCMAKE_CXX_FLAGS="$ARCH_FLAGS $GCOV_FLAGS"
......
......@@ -20,6 +20,8 @@ option(RAPIDJSON_BUILD_TESTS "Build rapidjson perftests and unittests." ON)
option(RAPIDJSON_BUILD_THIRDPARTY_GTEST
"Use gtest installation in `thirdparty/gtest` by default if available" OFF)
option(RAPIDJSON_BUILD_CXX11 "Build rapidjson with C++11 (gcc/clang)" ON)
option(RAPIDJSON_HAS_STDSTRING "" OFF)
if(RAPIDJSON_HAS_STDSTRING)
add_definitions(-DRAPIDJSON_HAS_STDSTRING)
......@@ -27,8 +29,18 @@ endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native -Wall -Wextra -Werror")
if (RAPIDJSON_BUILD_CXX11)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.7.0")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
endif()
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native -Wall -Wextra -Werror -Wno-missing-field-initializers")
if (RAPIDJSON_BUILD_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
add_definitions(-D_CRT_SECURE_NO_WARNINGS=1)
endif()
......
[
true,
true,
false,
false,
true,
true,
true,
false,
false,
true,
false,
false,
true,
false,
false,
false,
true,
false,
false,
true,
true,
false,
true,
true,
true,
false,
false,
false,
true,
false,
true,
false,
false,
true,
true,
true,
true,
true,
true,
false,
false,
true,
false,
false,
false,
true,
true,
false,
true,
true,
false,
true,
false,
true,
true,
true,
false,
false,
false,
true,
false,
false,
false,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
false,
false,
false,
false,
false,
true,
true,
true,
true,
true,
true,
true,
false,
false,
false,
true,
false,
false,
false,
true,
true,
true,
false,
false,
true,
false
]
\ No newline at end of file
[
135.747111636,
123.377054008,
140.527504552,
-72.299143906,
-23.851678949,
73.586193519,
-158.299382442,
177.477876032,
32.268518982,
-139.560009969,
115.203105183,
-106.025823607,
167.224138231,
103.378383732,
-97.498486285,
18.184723416,
69.137075711,
33.849002681,
-120.185228215,
-20.841408615,
-172.659492727,
-2.691464061,
22.426164066,
-98.416909437,
-31.603082708,
-85.072296561,
108.620987395,
-43.127078238,
-126.473562057,
-158.595489097,
-57.890678254,
-13.254016573,
-85.024504709,
171.663552644,
-146.495558248,
-10.606748276,
-118.786969354,
153.352057804,
-45.215545083,
37.038725288,
106.344071897,
-64.607402031,
85.148030911,
28.897784566,
39.51082061,
20.450382102,
-113.174943618,
71.60785784,
-168.202648062,
-157.338200017,
10.879588527,
-114.261694831,
-5.622927072,
-173.330830616,
-29.47002003,
-39.829034201,
50.031545162,
82.815735508,
-119.188760828,
-48.455928081,
163.964263034,
46.30378861,
-26.248889762,
-47.354615322,
155.388677633,
-166.710356904,
42.987233558,
144.275297374,
37.394383186,
-122.550388725,
177.469945914,
101.104677413,
109.429869885,
-104.919625624,
147.522756541,
-81.294703727,
122.744731363,
81.803603684,
26.321556167,
147.045441354,
147.256895816,
-174.211095908,
52.518769316,
-78.58250334,
-173.356685435,
-107.728209264,
-69.982325771,
-113.776095893,
-35.785267074,
-105.748545976,
-30.206523864,
-76.185311723,
-126.400112781,
-26.864958639,
56.840053629,
93.781553535,
-116.002949803,
-46.617140948,
176.846840093,
-144.24821335
]
[
"d35bf0d4-8d8f-4e17-a5c3-ad9bfd675266",
"db402774-eeb6-463b-9986-c458c44d8b5a",
"2a2e4101-b5f2-40b8-8750-e03f01661e60",
"76787cfa-f4eb-4d62-aaad-e1d588d00ad5",
"fd73894b-b500-4a7c-888c-06b5bd9cec65",
"cce1862a-cf31-4ef2-9e23-f1d23b4e6163",
"00a98bb0-2b6e-4368-8512-71c21aa87db7",
"ab9a8d69-cec7-4550-bd35-3ed678e22782",
"f18b48e1-5114-4fbe-9652-579e8d66950e",
"4efe3baa-7ac5-4d6a-a839-6b9cfe825764",
"b4aec119-5b0a-434c-b388-109816c482a5",
"e0ef0cbb-127a-4a28-9831-5741b4295275",
"d50286a5-cb7b-4c9e-be99-f214439bae8c",
"a981094c-f1ac-42ed-a9fa-86404c7210ff",
"2a34ee57-5815-4829-b77b-eeebaa8fe340",
"a0530d44-48f8-4eff-b9ea-8810c4308351",
"c6f91509-83e1-4ea1-9680-e667fbfd56ee",
"cab11402-dcdd-4454-b190-6da124947395",
"283d159c-2b18-4856-b4c7-5059252eaa15",
"146157c6-72a8-4051-9991-cb6ea6743d81",
"aef6f269-7306-4bd2-83f7-6d5605b5dc9a",
"37fe6027-d638-4017-80a9-e7b0567b278e",
"5003d731-33fb-4159-af61-d76348a44079",
"e0e06979-5f80-4713-9fe0-8a4d60dc89f8",
"7e85bdc3-0345-4cb6-9398-ccab06e79976",
"f2ebf5af-6568-4ffe-a46d-403863fd4b66",
"e0b5bb1c-b4dd-4535-9a9e-3c73f1167d46",
"c852d20b-6bcb-4b12-bd57-308296c64c5a",
"7ac3ae82-1818-49cd-a8a4-5ac77dfafd46",
"138004a9-76e2-4ad7-bd42-e74dabdbb803",
"ab25b5be-96be-45b0-b765-947b40ec36a6",
"08404734-fd57-499e-a4cf-71e9ec782ede",
"8dfdeb16-248b-4a21-bf89-2e22b11a4101",
"a0e44ef0-3b09-41e8-ad5d-ed8e6a1a2a67",
"a7981e49-188d-414a-9779-b1ad91e599d1",
"329186c0-bf27-4208-baf7-c0a0a5a2d5b7",
"cb5f3381-d33e-4b30-b1a9-f482623cad33",
"15031262-ca73-4e3c-bd0a-fcf89bdf0caf",
"6d7333d1-2e8c-4d78-bfde-5be47e70eb13",
"acaa160c-670a-4e8f-ac45-49416e77d5f9",
"228f87eb-cde4-4106-808b-2dbf3c7b6d2e",
"2ff830a3-5445-4d8e-b161-bddd30666697",
"f488bedd-ff6e-4108-b9a7-07f6da62f476",
"2e12b846-0a34-478e-adf7-a438493803e6",
"6686b8ef-7446-4d86-bd8c-df24119e3bfe",
"e474a5c5-5793-4d41-b4ab-5423acc56ef1",
"ac046573-e718-44dc-a0dc-9037eeaba6a9",
"6b0e9099-cf53-4d5a-8a71-977528628fcf",
"d51a3f22-0ff9-4087-ba9b-fcee2a2d8ade",
"bdc01286-3511-4d22-bfb8-76d01203d366",
"ca44eb84-17ff-4f27-8f1e-1bd25f4e8725",
"4e9a8c2f-be0b-4913-92d2-c801b9a50d04",
"7685d231-dadd-4041-9165-898397438ab7",
"86f0bf26-d66a-44d8-99f5-d6768addae3b",
"2ca1167c-72ba-45a0-aa42-faf033db0d0b",
"199a1182-ea55-49ff-ba51-71c29cdd0aac",
"be6a4dd2-c821-4aa0-8b83-d64d6644b5b2",
"4c5f4781-7f80-4daa-9c20-76b183000514",
"513b31bd-54fb-4d12-a427-42a7c13ff8e1",
"8e211bcb-d76c-4012-83ad-74dd7d23b687",
"44d5807e-0501-4f66-8779-e244d4fdca0a",
"db8cd555-0563-4b7b-b00c-eada300a7065",
"cb14d0c9-46cc-4797-bd3a-752b05629f07",
"4f68b3ef-ac9b-47a0-b6d7-57f398a5c6a5",
"77221aae-1bcf-471c-be45-7f31f733f9d6",
"42a7cac8-9e80-4c45-8c71-511d863c98ea",
"f9018d22-b82c-468c-bdb5-8864d5964801",
"75f4e9b8-62a2-4f21-ad8a-e19eff0419bc",
"9b7385c8-8653-4184-951c-b0ac1b36b42e",
"571018aa-ffbf-4b42-a16d-07b57a7f5f0e",
"35de4a2f-6bf1-45aa-b820-2a27ea833e44",
"0b8edb20-3bb4-4cb4-b089-31957466dbab",
"97da4778-9a7b-4140-a545-968148c81fb7",
"969f326c-8f2a-47c5-b41c-d9c2f06c9b9d",
"ae211037-8b53-4b17-bfc8-c06fc7774409",
"12c5c3c4-0bd5-45d3-bc1d-d04a3c65d3e6",
"ec02024f-ce43-4dd3-8169-a59f7baee043",
"5b6afe77-ce48-47ca-90a0-25cd10ca5ffd",
"2e3a61d4-6b8f-4d2f-ba86-878b4012efd8",
"19a88a67-a5d3-4647-898f-1cde07bce040",
"6db6f420-b5c8-48b9-bbb2-8864fe6fed65",
"5a45dbde-7b53-4f6b-b864-e3b63be3708a",
"c878321b-8a02-4239-9981-15760c2e7d15",
"4e36687f-8bf6-4b12-b496-3a8e382d067e",
"a59a63cd-43c0-4c6e-b208-6dbca86f8176",
"303308c4-2e4a-45b5-8bf3-3e66e9ad05a1",
"8b58fdf1-43a6-4c98-9547-6361b50791af",
"a3563591-72ed-42b5-8e41-bac1d76d70cf",
"38db8c78-3739-4f6e-8313-de4138082114",
"86615bea-7e73-4daf-95da-ae6b9eee1bbb",
"35d38e3e-076e-40dd-9aa8-05be2603bd59",
"9f84c62d-b454-4ba3-8c19-a01878985cdc",
"6721bbae-d765-4a06-8289-6fe46a1bf943",
"0837796f-d0dd-4e50-9b7c-1983e6cc7c48",
"021eb7d7-e869-49b9-80c3-9dd16ce2d981",
"819c56f8-e040-475d-aad5-c6d5e98b20aa",
"3a61ef02-735e-4229-937d-b3777a3f4e1f",
"79dfab84-12e6-4ec8-bfc8-460ae71e4eca",
"a106fabf-e149-476c-8053-b62388b6eb57",
"9a3900a5-bfb4-4de0-baa5-253a8bd0b634"
]
\ No newline at end of file
[
8125686,
8958709,
5976222,
1889524,
7968493,
1357486,
118415,
7081097,
4635968,
7555332,
2270233,
3428352,
8699968,
2087333,
7861337,
7554440,
2017031,
7981692,
6060687,
1877715,
3297474,
8373177,
6158629,
7853641,
3004441,
9650406,
2695251,
1180761,
4988426,
6043805,
8063373,
6103218,
2848339,
8188690,
9235573,
5949816,
6116081,
6471138,
3354531,
4787414,
9660600,
942529,
7278535,
7967399,
554292,
1436493,
267319,
2606657,
7900601,
4276634,
7996757,
8544466,
7266469,
3301373,
4005350,
6437652,
7717672,
7126292,
8588394,
2127902,
7410190,
1517806,
4583602,
3123440,
7747613,
5029464,
9834390,
3087227,
4913822,
7550487,
4518144,
5862588,
1778599,
9493290,
5588455,
3638706,
7394293,
4294719,
3837830,
6381878,
7175866,
8575492,
1415229,
1453733,
6972404,
9782571,
4234063,
7117418,
7293130,
8057071,
9345285,
7626648,
3358911,
4574537,
9371826,
7627107,
6154093,
5392367,
5398105,
6956377
]
\ No newline at end of file
This diff is collapsed.
[
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
\ No newline at end of file
This diff is collapsed.
Test data obtained from https://github.com/xpol/lua-rapidjson/tree/master/performance
......@@ -764,18 +764,19 @@ WARN_LOGFILE =
# spaces.
# Note: If this tag is empty the current directory is searched.
INPUT = ./readme.zh-cn.md \
./include/rapidjson/rapidjson.h \
./include/ \
./doc/features.zh-cn.md \
./doc/tutorial.zh-cn.md \
./doc/stream.zh-cn.md \
./doc/encoding.zh-cn.md \
./doc/dom.zh-cn.md \
./doc/sax.zh-cn.md \
./doc/performance.zh-cn.md \
./doc/internals.md \
./doc/faq.zh-cn.md
INPUT = readme.zh-cn.md \
include/rapidjson/rapidjson.h \
include/ \
doc/features.zh-cn.md \
doc/tutorial.zh-cn.md \
doc/pointer.zh-cn.md \
doc/stream.zh-cn.md \
doc/encoding.zh-cn.md \
doc/dom.zh-cn.md \
doc/sax.zh-cn.md \
doc/performance.zh-cn.md \
doc/internals.md \
doc/faq.zh-cn.md
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
......
......@@ -115,6 +115,7 @@ Parse flags | Meaning
`kParseIterativeFlag` | Iterative(constant complexity in terms of function call stack size) parsing.
`kParseStopWhenDoneFlag` | After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate `kParseErrorDocumentRootNotSingular` error. Using this flag for parsing multiple JSONs in the same stream.
`kParseFullPrecisionFlag` | Parse number in full precision (slower). If this flag is not set, the normal precision (faster) is used. Normal precision has maximum 3 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) error.
`kParseCommentsFlag` | Allow one-line `// ...` and multi-line `/* ... */` comments (relaxed JSON syntax).
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.
......
......@@ -115,6 +115,7 @@ GenericDocument& GenericDocument::Parse(const Ch* str);
`kParseIterativeFlag` | 迭代式(调用堆栈大小为常数复杂度)解析。
`kParseStopWhenDoneFlag` | 当从流解析了一个完整的JSON根节点之后,停止继续处理余下的流。当使用了此标志,解析器便不会产生`kParseErrorDocumentRootNotSingular`错误。可使用本标志去解析同一个流里的多个JSON。
`kParseFullPrecisionFlag` | 使用完整的精确度去解析数字(较慢)。如不设置此标节,则会使用正常的精确度(较快)。正常精确度会有最多3个[ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place)的误差。
`kParseCommentsFlag` | 容许单行 `// ...` 及多行 `/* ... */` 注释(放宽的JSON语法)。
由于使用了非类型模板参数,而不是函数参数,C++编译器能为个别组合生成代码,以改善性能及减少代码尺寸(当只用单种特化)。缺点是需要在编译期决定标志。
......
......@@ -106,59 +106,59 @@
Call one of the `SetXXX()` methods - they call destructor which deallocates DOM data:
```
~~~~~~~~~~cpp
Document d;
...
d.SetObject(); // clear and minimize
```
~~~~~~~~~~
Alternatively, use equivalent of the [C++ swap with temporary idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize):
```
~~~~~~~~~~cpp
Value(kObjectType).Swap(d);
```
~~~~~~~~~~
or equivalent, but sightly longer to type:
```
~~~~~~~~~~cpp
d.Swap(Value(kObjectType).Move());
```
~~~~~~~~~~
9. How to insert a document node into another document?
Let's take the following two DOM trees represented as JSON documents:
```
~~~~~~~~~~cpp
Document person;
person.Parse("{\"person\":{\"name\":{\"first\":\"Adam\",\"last\":\"Thomas\"}}}");
Document address;
address.Parse("{\"address\":{\"city\":\"Moscow\",\"street\":\"Quiet\"}}");
```
~~~~~~~~~~
Let's assume we want to merge them in such way that the whole `address` document becomes a node of the `person`:
```
~~~~~~~~~~js
{ "person": {
"name": { "first": "Adam", "last": "Thomas" },
"address": { "city": "Moscow", "street": "Quiet" }
}
}
```
~~~~~~~~~~
The most important requirement to take care of document and value life-cycle as well as consistent memory managent using the right allocator during the value transfer.
Simple yet most efficient way to achieve that is to modify the `address` definition above to initialize it with allocator of the `person` document, then we just add the root nenber of the value:
```
Simple yet most efficient way to achieve that is to modify the `address` definition above to initialize it with allocator of the `person` document, then we just add the root member of the value:
~~~~~~~~~~cpp
Documnet address(person.GetAllocator());
...
person["person"].AddMember("address", address["address"], person.GetAllocator());
```
~~~~~~~~~~
Alternatively, if we don't want to explicitly refer to the root value of `address` by name, we can refer to it via iterator:
```
~~~~~~~~~~cpp
auto addressRoot = address.MemberBegin();
person["person"].AddMember(addressRoot->name, addressRoot->value, person.GetAllocator());
```
~~~~~~~~~~
Second way is to deep-clone the value from the address document:
```
~~~~~~~~~~cpp
Value addressValue = Value(address["address"], person.GetAllocator());
person["person"].AddMember("address", addressValue, person.GetAllocator());
```
~~~~~~~~~~
## Document/Value (DOM)
......
......@@ -28,7 +28,7 @@
6. 怎样安装RapidJSON?
[安装一节](readme.zh-cn.md)
[安装一节](../readme.zh-cn.md#安装)
7. RapidJSON能否运行于我的平台?
......@@ -52,7 +52,7 @@
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
......@@ -98,10 +98,69 @@
错误信息存储在`ParseResult`,它包含错误代号及偏移值(从JSON开始至错误处的字符数目)。可以把错误代号翻译为人类可读的错误讯息。
7.不只使用`double`去表示JSON number?
7.不只使用`double`去表示JSON number?
一些应用需要使用64位无号/有号整数。这些整数不能无损地转换成`double`。因此解析器会检测一个JSON number是否能转换至各种整数类型及`double`
8. 如何清空并最小化`document``value`的容量?
调用 `SetXXX()` 方法 - 这些方法会调用析构函数,并重建空的Object或Array:
~~~~~~~~~~cpp
Document d;
...
d.SetObject(); // clear and minimize
~~~~~~~~~~
另外,也可以参考在 [C++ swap with temporary idiom](https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize)中的一种等价的方法:
~~~~~~~~~~cpp
Value(kObjectType).Swap(d);
~~~~~~~~~~
或者,使用这个稍微长一点的代码也能完成同样的事情:
~~~~~~~~~~cpp
d.Swap(Value(kObjectType).Move());
~~~~~~~~~~
9. 如何将一个`document`节点插入到另一个`document`中?
比如有以下两个document(DOM):
~~~~~~~~~~cpp
Document person;
person.Parse("{\"person\":{\"name\":{\"first\":\"Adam\",\"last\":\"Thomas\"}}}");
Document address;
address.Parse("{\"address\":{\"city\":\"Moscow\",\"street\":\"Quiet\"}}");
~~~~~~~~~~
假设我们希望将整个 `address` 插入到`person`中,作为其的一个子节点:
~~~~~~~~~~js
{ "person": {
"name": { "first": "Adam", "last": "Thomas" },
"address": { "city": "Moscow", "street": "Quiet" }
}
}
~~~~~~~~~~
在插入节点的过程中需要注意`document``value`的生命周期并且正确地使用allocator进行内存分配和管理。
一个简单有效的方法就是修改上述`address`变量的定义,让其使用`person`的allocator初始化,然后将其添加到根节点。
~~~~~~~~~~cpp
Documnet address(person.GetAllocator());
...
person["person"].AddMember("address", address["address"], person.GetAllocator());
~~~~~~~~~~
当然,如果你不想通过显式地写出`address`的key来得到其值,可以使用迭代器来实现:
~~~~~~~~~~cpp
auto addressRoot = address.MemberBegin();
person["person"].AddMember(addressRoot->name, addressRoot->value, person.GetAllocator());
~~~~~~~~~~
此外,还可以通过深拷贝address document来实现:
~~~~~~~~~~cpp
Value addressValue = Value(address["address"], person.GetAllocator());
person["person"].AddMember("address", addressValue, person.GetAllocator());
~~~~~~~~~~
## Document/Value (DOM)
1. 什么是转移语意?为什么?
......
......@@ -23,6 +23,8 @@
* 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.
## Unicode
......
......@@ -23,6 +23,8 @@
* 支持Unicod代理对(surrogate pair)。
* 支持空字符(`"\u0000"`)。
* 例如,可以优雅地解析及处理`["Hello\u0000World"]`。含读写字符串长度的API。
* 支持放宽的可选语法
* 单行(`// ...`)及多行(`/* ... */`) 注释。
## Unicode
......
......@@ -148,7 +148,7 @@ When using `p.Get(root)` or `GetValueByPointer(root, p)`, `root` is a (const) `V
The other functions have two groups of signature. One group uses `Document& document` as parameter, another one uses `Value& root`. The first group uses `document.GetAllocator()` for creating values. And the second group needs user to supply an allocator, like the functions in DOM.
All examples above do not require an allocator parameter, because the parameter is a `Document&`. But if you want to resolve a pointer to a subtree. You need to supply it as in the following example:
All examples above do not require an allocator parameter, because the first parameter is a `Document&`. But if you want to resolve a pointer to a subtree, you need to supply the allocator as in the following example:
~~~cpp
class Person {
......@@ -179,7 +179,7 @@ private:
# Error Handling {#ErrorHandling}
A `Pointer` parses a source string in its constructor. If there is parsing error, `Pointer::IsValid()` returns false. And you can use `Pointer::GetParseErrorCode()` and `GetParseErrorOffset()` to retrieve the error information.
A `Pointer` parses a source string in its constructor. If there is parsing error, `Pointer::IsValid()` returns `false`. And you can use `Pointer::GetParseErrorCode()` and `GetParseErrorOffset()` to retrieve the error information.
Note that, all resolving functions assumes valid pointer. Resolving with an invalid pointer causes assertion failure.
......@@ -215,7 +215,7 @@ It can also stringify to URI fragment reprsentation by `StringifyUriFragment()`.
# User-Supplied Tokens {#UserSuppliedTokens}
If a pointer will be resolved multiple times, it should be construct once, and then apply it to different DOMs or in different times. This reduce time and memory allocation for constructing `Pointer` multiple times.
If a pointer will be resolved multiple times, it should be constructed once, and then apply it to different DOMs or in different times. This reduce time and memory allocation for constructing `Pointer` multiple times.
We can go one step further, to completely eliminate the parsing process and dynamic memory allocation, we can establish the token array directly:
......
# Pointer
## 状态: 实验性,应该会合进 v1.1
JSON Pointer 是一个标准化([RFC6901])的方式去选取一个 JSON Document(DOM)中的值。这类似于 XML 的 XPath。然而,JSON Pointer 简单得多,而且每个 JSON Pointer 仅指向单个值。
使用 RapidJSON 的 JSON Pointer 实现能简化一些 DOM 的操作。
[TOC]
# JSON Pointer {#JsonPointer}
一个 JSON Pointer 由一串(零至多个)token 所组成,每个 token 都有 `/` 前缀。每个 token 可以是一个字符串或数字。例如,给定一个 JSON:
~~~javascript
{
"foo" : ["bar", "baz"],
"pi" : 3.1416
}
~~~
以下的 JSON Pointer 解析为:
1. `"/foo"``[ "bar", "baz" ]`
2. `"/foo/0"``"bar"`
3. `"/foo/1"``"baz"`
4. `"/pi"``3.1416`
要注意,一个空 JSON Pointer `""` (零个token)解析为整个 JSON。
# 基本使用方法 {#BasicUsage}
以下的代码范例不解自明。
~~~cpp
#include "rapidjson/pointer.h"
// ...
Document d;
// 使用 Set() 创建 DOM
Pointer("/project").Set(d, "RapidJSON");
Pointer("/stars").Set(d, 10);
// { "project" : "RapidJSON", "stars" : 10 }
// 使用 Get() 访问 DOM。若该值不存在则返回 nullptr。
if (Value* stars = Pointer("/stars").Get(d))
stars->SetInt(stars->GetInt() + 1);
// { "project" : "RapidJSON", "stars" : 11 }
// Set() 和 Create() 自动生成父值(如果它们不存在)。
Pointer("/a/b/0").Create(d);
// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] } }
// GetWithDefault() 返回引用。若该值不存在则会深拷贝缺省值。
Value& hello = Pointer("/hello").GetWithDefault(d, "world");
// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "world" }
// Swap() 和 Set() 相似
Value x("C++");
Pointer("/hello").Swap(d, x);
// { "project" : "RapidJSON", "stars" : 11, "a" : { "b" : [ null ] }, "hello" : "C++" }
// x 变成 "world"
// 删去一个成员或元素,若值存在返回 true
bool success = Pointer("/a").Erase(d);
assert(success);
// { "project" : "RapidJSON", "stars" : 10 }
~~~
# 辅助函数 {#HelperFunctions}
由于面向对象的调用习惯可能不符直觉,RapidJSON 也提供了一些辅助函数,它们把成员函数包装成自由函数。
以下的例子与上面例子所做的事情完全相同。
~~~cpp
Document d;
SetValueByPointer(d, "/project", "RapidJSON");
SetValueByPointer(d, "/stars", 10);
if (Value* stars = GetValueByPointer(d, "/stars"))
stars->SetInt(stars->GetInt() + 1);
CreateValueByPointer(d, "/a/b/0");
Value& hello = GetValueByPointerWithDefault(d, "/hello", "world");
Value x("C++");
SwapValueByPointer(d, "/hello", x);
bool success = EraseValueByPointer(d, "/a");
assert(success);
~~~
以下对比 3 种调用方式:
1. `Pointer(source).<Method>(root, ...)`
2. `<Method>ValueByPointer(root, Pointer(source), ...)`
3. `<Method>ValueByPointer(root, source, ...)`
# 解析 Pointer {#ResolvingPointer}
`Pointer::Get()``GetValueByPointer()` 函数并不修改 DOM。若那些 token 不能匹配 DOM 里的值,这些函数便返回 `nullptr`。使用者可利用这个方法来检查一个值是否存在。
注意,数值 token 可表示数组索引或成员名字。解析过程中会按值的类型来匹配。
~~~javascript
{
"0" : 123,
"1" : [456]
}
~~~
1. `"/0"``123`
2. `"/1/0"``456`
Token `"0"` 在第一个 pointer 中被当作成员名字。它在第二个 pointer 中被当作成数组索引。
其他函数会改变 DOM,包括`Create()``GetWithDefault()``Set()``Swap()`。这些函数总是成功的。若一些父值不存在,就会创建它们。若父值类型不匹配 token,也会强行改变其类型。改变类型也意味着完全移除其 DOM 子树的内容。
例如,把上面的 JSON 解译至 `d` 之后,
~~~cpp
SetValueByPointer(d, "1/a", 789); // { "0" : 123, "1" : { "a" : 789 } }
~~~
## 解析负号 token
另外,[RFC6901] 定义了一个特殊 token `-` (单个负号),用于表示数组最后元素的下一个元素。 `Get()` 只会把此 token 当作成员名字 '"-"'。而其他函数则会以此解析数组,等同于对数组调用 `Value::PushBack()`
~~~cpp
Document d;
d.Parse("{\"foo\":[123]}");
SetValueByPointer(d, "/foo/-", 456); // { "foo" : [123, 456] }
SetValueByPointer(d, "/-", 789); // { "foo" : [123, 456], "-" : 789 }
~~~
## 解析 Document 及 Value
当使用 `p.Get(root)``GetValueByPointer(root, p)``root` 是一个(常数) `Value&`。这意味着,它也可以是 DOM 里的一个子树。
其他函数有两组签名。一组使用 `Document& document` 作为参数,另一组使用 `Value& root`。第一组使用 `document.GetAllocator()` 去创建值,而第二组则需要使用者提供一个 allocator,如同 DOM 里的函数。
以上例子都不需要 allocator 参数,因为它的第一个参数是 `Document&`。但如果你需要对一个子树进行解析,就需要如下面的例子般提供 allocator:
~~~cpp
class Person {
public:
Person() {
document_ = new Document();
// CreateValueByPointer() here no need allocator
SetLocation(CreateValueByPointer(*document_, "/residence"), ...);
SetLocation(CreateValueByPointer(*document_, "/office"), ...);
};
private:
void SetLocation(Value& location, const char* country, const char* addresses[2]) {
Value::Allocator& a = document_->GetAllocator();
// SetValueByPointer() here need allocator
SetValueByPointer(location, "/country", country, a);
SetValueByPointer(location, "/address/0", address[0], a);
SetValueByPointer(location, "/address/1", address[1], a);
}
// ...
Document* document_;
};
~~~
`Erase()``EraseValueByPointer()` 不需要 allocator。而且它们成功删除值之后会返回 `true`
# 错误处理 {#ErrorHandling}
`Pointer` 在其建构函数里会解译源字符串。若有解析错误,`Pointer::IsValid()` 返回 `false`。你可使用 `Pointer::GetParseErrorCode()``GetParseErrorOffset()` 去获取错信息。
要注意的是,所有解析函数都假设 pointer 是合法的。对一个非法 pointer 解析会做成断言失败。
# URI 片段表示方式 {#URIFragment}
除了我们一直在使用的字符串方式表示 JSON pointer,[RFC6901]也定义了一个 JSON Pointer 的 URI 片段(fragment)表示方式。URI 片段是定义于 [RFC3986] "Uniform Resource Identifier (URI): Generic Syntax"。
URI 片段的主要分别是必然以 `#` (pound sign)开头,而一些字符也会以百分比编码成 UTF-8 序列。例如,以下的表展示了不同表示法下的 C/C++ 字符串常数。
字符串表示方式 | URI 片段表示方式 | Pointer Tokens (UTF-8)
----------------------|-----------------------------|------------------------
`"/foo/0"` | `"#/foo/0"` | `{"foo", 0}`
`"/a~1b"` | `"#/a~1b"` | `{"a/b"}`
`"/m~0n"` | `"#/m~0n"` | `{"m~n"}`
`"/ "` | `"#/%20"` | `{" "}`
`"/\0"` | `"#/%00"` | `{"\0"}`
`"/€"` | `"#/%E2%82%AC"` | `{"€"}`
RapidJSON 完全支持 URI 片段表示方式。它在解译时会自动检测 `#` 号。
# 字符串化
你也可以把一个 `Pointer` 字符串化,储存于字符串或其他输出流。例如:
~~~
Pointer p(...);
StringBuffer sb;
p.Stringify(sb);
std::cout << sb.GetString() << std::endl;
~~~
使用 `StringifyUriFragment()` 可以把 pointer 字符串化为 URI 片段表示法。
# 使用者提供的 tokens {#UserSuppliedTokens}
若一个 pointer 会用于多次解析,它应该只被创建一次,然后再施于不同的 DOM ,或在不同时间做解析。这样可以避免多次创键 `Pointer`,节省时间和内存分配。
我们甚至可以再更进一步,完全消去解析过程及动态内存分配。我们可以直接生成 token 数组:
~~~cpp
#define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex }
#define INDEX(i) { #i, sizeof(#i) - 1, i }
static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) };
static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0]));
// Equivalent to static const Pointer p("/foo/123");
~~~
这种做法可能适合内存受限的系统。
[RFC3986]: https://tools.ietf.org/html/rfc3986
[RFC6901]: https://tools.ietf.org/html/rfc6901
......@@ -175,7 +175,7 @@ bool Parse(InputStream& is, Handler& handler);
# Writer {#Writer}
`Reader`把JSON转换(解析)成为事件。`Writer`完全做相反的事情。它把事件转换成JSON。
`Reader`把JSON转换(解析)成为事件。`Writer`做完全相反的事情。它把事件转换成JSON。
`Writer`是非常容易使用的。若你的应用程序只需把一些数据转换成JSON,可能直接使用`Writer`,会比建立一个`Document`然后用`Writer`把它转换成JSON更加方便。
......@@ -265,7 +265,7 @@ public:
## PrettyWriter {#PrettyWriter}
`Writer`所输出的是没有空格字符的最紧凑JSON,适合网络传输或储存,但适合人类阅读。
`Writer`所输出的是没有空格字符的最紧凑JSON,适合网络传输或储存,但适合人类阅读。
因此,RapidJSON提供了一个`PrettyWriter`,它在输出中加入缩进及换行。
......@@ -386,13 +386,13 @@ 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}
如前面提及过,`Writer`可处理`Reader`发出的事件。`condense`例子简单地设置`Writer`作为一个`Reader`的处理器,因此它能移除JSON中的所有空白字符。`pretty`例子使用同样的关系,只是以`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改为大写。
......@@ -472,5 +472,5 @@ int main(int, char*[]) {
["HELLO\nWORLD"]
~~~~~~~~~~
我们还可以开发更复杂的过滤器。然而,由于SAX风格API在某一时间点只能提供单一事件的信息,使用者需要自行记录一些上下文信息(例如从根节点起的路径、储存其他相关值)。对些一些处理情况,用DOM会比SAX更容易实现。
我们还可以开发更复杂的过滤器。然而,由于SAX风格API在某一时间点只能提供单一事件的信息,使用者需要自行记录一些上下文信息(例如从根节点起的路径、储存其他相关值)。对于处理某些情况,用DOM会比SAX更容易实现。
......@@ -2,7 +2,7 @@
本教程简介文件对象模型(Document Object Model, DOM)API。
[用法一览](readme.zh-cn.md)中所示,可以解析一个JSON至DOM,然后就可以轻松查询及修改DOM,并最终转换回JSON。
[用法一览](../readme.zh-cn.md#用法一览)中所示,可以解析一个JSON至DOM,然后就可以轻松查询及修改DOM,并最终转换回JSON。
[TOC]
......@@ -123,7 +123,7 @@ a[3] = 4
你可以用整数字面量访问元素,如`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());
......@@ -461,7 +461,7 @@ contact.AddMember(key, val, document.GetAllocator());
* `bool RemoveMember(const Ch* name)`:使用键名来移除成员(线性时间复杂度)。
* `bool RemoveMember(const Value& name)`:除了`name`是一个Value,和上一行相同。
* `MemberIterator RemoveMember(MemberIterator)`:使用迭器移除成员(_常数_时间复杂度)。
* `MemberIterator RemoveMember(MemberIterator)`:使用迭器移除成员(_常数_时间复杂度)。
* `MemberIterator EraseMember(MemberIterator)`:和上行相似但维持成员次序(线性时间复杂度)。
* `MemberIterator EraseMember(MemberIterator first, MemberIterator last)`:移除一个范围内的成员,维持次序(线性时间复杂度)。
......
......@@ -20,7 +20,7 @@ include_directories("../include/")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -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")
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)
endif()
......
......@@ -27,7 +27,7 @@ struct CapitalizeFilter {
bool String(const char* str, SizeType length, bool) {
buffer_.clear();
for (SizeType i = 0; i < length; i++)
buffer_.push_back(std::toupper(str[i]));
buffer_.push_back(static_cast<char>(std::toupper(str[i])));
return out_.String(&buffer_.front(), length, true); // true = output handler need to copy the string
}
bool StartObject() { return out_.StartObject(); }
......@@ -58,7 +58,7 @@ int main(int, char*[]) {
// JSON reader parse from the input stream and let writer generate the output.
CapitalizeFilter<Writer<FileWriteStream> > filter(writer);
if (!reader.Parse(is, filter)) {
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
......
......@@ -24,7 +24,7 @@ int main(int, char*[]) {
// JSON reader parse from the input stream and let writer generate the output.
if (!reader.Parse(is, writer)) {
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
......
......@@ -17,6 +17,11 @@ RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch-enum)
#endif
struct MessageHandler
: public BaseReaderHandler<UTF8<>, MessageHandler> {
MessageHandler() : messages_(), state_(kExpectObjectStart), name_() {}
......@@ -63,7 +68,11 @@ struct MessageHandler
RAPIDJSON_DIAG_POP
#endif
void ParseMessages(const char* json, MessageMap& messages) {
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
static void ParseMessages(const char* json, MessageMap& messages) {
Reader reader;
MessageHandler handler;
StringStream ss(json);
......
......@@ -22,7 +22,7 @@ int main(int, char*[]) {
// JSON reader parse from the input stream and let writer generate the output.
if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
......
......@@ -48,7 +48,7 @@ int main(int, char*[]) {
// JSON reader parse from the input stream and let writer generate the output.
//if (!reader.Parse<kParseValidateEncodingFlag>(is, writer)) {
if (!reader.Parse<kParseValidateEncodingFlag>(eis, writer)) { // CHANGED
fprintf(stderr, "\nError(%u): %s\n", (unsigned)reader.GetErrorOffset(), GetParseError_En(reader.GetParseErrorCode()));
fprintf(stderr, "\nError(%u): %s\n", static_cast<unsigned>(reader.GetErrorOffset()), GetParseError_En(reader.GetParseErrorCode()));
return 1;
}
......
......@@ -11,17 +11,24 @@ using namespace rapidjson;
class Person {
public:
Person(const std::string& name, unsigned age) : name_(name), age_(age) {}
Person(const Person& rhs) : name_(rhs.name_), age_(rhs.age_) {}
virtual ~Person();
Person& operator=(const Person& rhs) {
name_ = rhs.name_;
age_ = rhs.age_;
return *this;
}
protected:
template <typename Writer>
void Serialize(Writer& writer) const {
// This base class just write out name-value pairs, without wrapping within an object.
writer.String("name");
#ifdef RAPIDJSON_HAS_STDSTRING
#if RAPIDJSON_HAS_STDSTRING
writer.String(name_);
#else
writer.String(name_.c_str(), (SizeType)name_.length()); // Supplying length of string is faster.
writer.String(name_.c_str(), static_cast<SizeType>(name_.length())); // Supplying length of string is faster.
#endif
writer.String("age");
writer.Uint(age_);
......@@ -38,16 +45,17 @@ Person::~Person() {
class Education {
public:
Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {}
Education(const Education& rhs) : school_(rhs.school_), GPA_(rhs.GPA_) {}
template <typename Writer>
void Serialize(Writer& writer) const {
writer.StartObject();
writer.String("school");
#ifdef RAPIDJSON_HAS_STDSTRING
#if RAPIDJSON_HAS_STDSTRING
writer.String(school_);
#else
writer.String(school_.c_str(), (SizeType)school_.length());
writer.String(school_.c_str(), static_cast<SizeType>(school_.length()));
#endif
writer.String("GPA");
......@@ -102,8 +110,16 @@ Dependent::~Dependent() {
class Employee : public Person {
public:
Employee(const std::string& name, unsigned age, bool married) : Person(name, age), dependents_(), married_(married) {}
Employee(const Employee& rhs) : Person(rhs), dependents_(rhs.dependents_), married_(rhs.married_) {}
virtual ~Employee();
Employee& operator=(const Employee& rhs) {
static_cast<Person&>(*this) = rhs;
dependents_ = rhs.dependents_;
married_ = rhs.married_;
return *this;
}
void AddDependent(const Dependent& dependent) {
dependents_.push_back(dependent);
}
......
......@@ -121,17 +121,17 @@ int main(int, char*[]) {
// This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer.
Value author;
{
char buffer[10];
int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string.
char buffer2[10];
int len = sprintf(buffer2, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string.
author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator());
author.SetString(buffer2, static_cast<SizeType>(len), document.GetAllocator());
// Shorter but slower version:
// document["hello"].SetString(buffer, document.GetAllocator());
// Constructor version:
// Value author(buffer, len, document.GetAllocator());
// Value author(buffer, document.GetAllocator());
memset(buffer, 0, sizeof(buffer)); // For demonstration purpose.
memset(buffer2, 0, sizeof(buffer2)); // For demonstration purpose.
}
// Variable 'buffer' is unusable now but 'author' has already made a copy.
document.AddMember("author", author, document.GetAllocator());
......
......@@ -199,7 +199,7 @@ public:
return originalPtr;
// Simply expand it if it is the last allocation and there is sufficient space
if (originalPtr == (char *)(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) {
if (originalPtr == reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) {
size_t increment = static_cast<size_t>(newSize - originalSize);
increment = RAPIDJSON_ALIGN(increment);
if (chunkHead_->size + increment <= chunkHead_->capacity) {
......
This diff is collapsed.
......@@ -22,6 +22,11 @@ RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Input byte stream wrapper with a statically bound encoding.
......@@ -60,7 +65,7 @@ private:
//! Output byte stream wrapper with statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
\tparam InputByteStream Type of input byte stream. For example, FileWriteStream.
\tparam OutputByteStream Type of input byte stream. For example, FileWriteStream.
*/
template <typename Encoding, typename OutputByteStream>
class EncodedOutputStream {
......@@ -77,8 +82,8 @@ public:
void Flush() { os_.Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); }
Ch Take() { RAPIDJSON_ASSERT(false); }
Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
......@@ -142,7 +147,7 @@ private:
// FF FE UTF-16LE
// EF BB BF UTF-8
const unsigned char* c = (const unsigned char *)is_->Peek4();
const unsigned char* c = reinterpret_cast<const unsigned char *>(is_->Peek4());
if (!c)
return;
......@@ -193,7 +198,7 @@ private:
//! Output stream wrapper with dynamically bound encoding and automatic encoding detection.
/*!
\tparam CharType Type of character for writing.
\tparam InputByteStream type of output byte stream to be wrapped.
\tparam OutputByteStream type of output byte stream to be wrapped.
*/
template <typename CharType, typename OutputByteStream>
class AutoUTFOutputStream {
......@@ -227,8 +232,8 @@ public:
void Flush() { os_->Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); }
Ch Take() { RAPIDJSON_ASSERT(false); }
Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
......@@ -254,6 +259,10 @@ private:
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#ifdef __GNUC__
RAPIDJSON_DIAG_POP
#endif
......
This diff is collapsed.
......@@ -12,11 +12,17 @@
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef RAPIDJSON_ERROR_EN_H__
#define RAPIDJSON_ERROR_EN_H__
#ifndef RAPIDJSON_ERROR_EN_H_
#define RAPIDJSON_ERROR_EN_H_
#include "error.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch-enum)
RAPIDJSON_DIAG_OFF(covered-switch-default)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Maps error code of parsing into error message.
......@@ -55,11 +61,14 @@ inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErro
case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error.");
case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error.");
default:
return RAPIDJSON_ERROR_STRING("Unknown error.");
default: return RAPIDJSON_ERROR_STRING("Unknown error.");
}
}
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_ERROR_EN_H__
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_ERROR_EN_H_
......@@ -12,11 +12,16 @@
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef RAPIDJSON_ERROR_ERROR_H__
#define RAPIDJSON_ERROR_ERROR_H__
#ifndef RAPIDJSON_ERROR_ERROR_H_
#define RAPIDJSON_ERROR_ERROR_H_
#include "../rapidjson.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
/*! \file error.h */
/*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */
......@@ -99,7 +104,7 @@ enum ParseErrorCode {
\see GenericReader::Parse, GenericDocument::Parse
*/
struct ParseResult {
public:
//! Default constructor, no error.
ParseResult() : code_(kParseErrorNone), offset_(0) {}
//! Constructor to set an error.
......@@ -143,4 +148,8 @@ typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode);
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_ERROR_ERROR_H__
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_ERROR_ERROR_H_
......@@ -18,6 +18,13 @@
#include "rapidjson.h"
#include <cstdio>
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
RAPIDJSON_DIAG_OFF(unreachable-code)
RAPIDJSON_DIAG_OFF(missing-noreturn)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! File byte stream for input using fread().
......@@ -85,4 +92,8 @@ private:
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_FILESTREAM_H_
......@@ -18,6 +18,11 @@
#include "rapidjson.h"
#include <cstdio>
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(unreachable-code)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Wrapper of C file stream for input using fread().
......@@ -57,7 +62,11 @@ public:
void Flush() {
if (current_ != buffer_) {
fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
size_t result = 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
}
current_ = buffer_;
}
}
......@@ -88,4 +97,8 @@ inline void PutN(FileWriteStream& stream, char c, size_t n) {
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_FILESTREAM_H_
......@@ -240,7 +240,7 @@ private:
uint64_t r = 0;
for (const char* p = begin; p != end; ++p) {
RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
r = r * 10u + (unsigned)(*p - '0');
r = r * 10u + static_cast<unsigned>(*p - '0');
}
return r;
}
......
......@@ -35,6 +35,11 @@ RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(effc++)
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
struct DiyFp {
DiyFp() {}
......@@ -242,6 +247,11 @@ inline DiyFp GetCachedPower10(int exp, int *outExp) {
RAPIDJSON_DIAG_POP
#endif
#ifdef __clang__
RAPIDJSON_DIAG_POP
RAPIDJSON_DIAG_OFF(padded)
#endif
} // namespace internal
RAPIDJSON_NAMESPACE_END
......
......@@ -53,7 +53,7 @@ public:
else if (order <= -1074)
return 0;
else
return (unsigned)order + 1074;
return static_cast<unsigned>(order) + 1074;
}
private:
......
......@@ -18,6 +18,11 @@
#include "../rapidjson.h"
#include "swap.h"
#if defined(__clang__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(c++98-compat)
#endif
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {
......@@ -108,11 +113,21 @@ public:
// Optimization note: try to minimize the size of this function for force inline.
// Expansion is run very infrequently, so it is moved to another (probably non-inline) function.
template<typename T>
RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) {
RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) {
// Expand the stack if needed
if (stackTop_ + sizeof(T) * count >= stackEnd_)
if (RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_))
Expand<T>(count);
}
template<typename T>
RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) {
Reserve<T>(count);
return PushUnsafe<T>(count);
}
template<typename T>
RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) {
RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_);
T* ret = reinterpret_cast<T*>(stackTop_);
stackTop_ += sizeof(T) * count;
return ret;
......@@ -132,6 +147,7 @@ public:
}
template<typename T>
<<<<<<< HEAD
const T* Top() const {
RAPIDJSON_ASSERT(GetSize() >= sizeof(T));
return reinterpret_cast<T*>(stackTop_ - sizeof(T));
......@@ -150,6 +166,18 @@ public:
const T* Bottom() const { return (T*)stack_; }
Allocator& GetAllocator() { return *allocator_; }
=======
T* Bottom() { return reinterpret_cast<T*>(stack_); }
bool HasAllocator() const {
return allocator_ != 0;
}
Allocator& GetAllocator() {
RAPIDJSON_ASSERT(allocator_);
return *allocator_;
}
>>>>>>> master
bool Empty() const { return stackTop_ == stack_; }
size_t GetSize() const { return static_cast<size_t>(stackTop_ - stack_); }
size_t GetCapacity() const { return static_cast<size_t>(stackEnd_ - stack_); }
......@@ -176,7 +204,7 @@ private:
void Resize(size_t newCapacity) {
const size_t size = GetSize(); // Backup the current size
stack_ = (char*)allocator_->Realloc(stack_, GetCapacity(), newCapacity);
stack_ = static_cast<char*>(allocator_->Realloc(stack_, GetCapacity(), newCapacity));
stackTop_ = stack_ + size;
stackEnd_ = stack_ + newCapacity;
}
......@@ -201,4 +229,8 @@ private:
} // namespace internal
RAPIDJSON_NAMESPACE_END
#if defined(__clang__)
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_STACK_H_
......@@ -149,7 +149,7 @@ inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosit
v = v.Normalize();
error <<= -v.e;
const int dExp = (int)decimalPosition - (int)i + exp;
const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(i) + exp;
int actualExp;
DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
......@@ -206,7 +206,7 @@ inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosit
inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) {
const BigInteger dInt(decimals, length);
const int dExp = (int)decimalPosition - (int)length + exp;
const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(length) + exp;
Double a(approx);
int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
if (cmp < 0)
......@@ -246,8 +246,8 @@ inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t
// Trim right-most digits
const int kMaxDecimalDigit = 780;
if ((int)length > kMaxDecimalDigit) {
int delta = (int(length) - kMaxDecimalDigit);
if (static_cast<int>(length) > kMaxDecimalDigit) {
int delta = (static_cast<int>(length) - kMaxDecimalDigit);
exp += delta;
decimalPosition -= static_cast<unsigned>(delta);
length = kMaxDecimalDigit;
......
......@@ -17,10 +17,15 @@
#include "../rapidjson.h"
#if defined(__clang__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(c++98-compat)
#endif
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {
//! Custom swap() to avoid dependency on C++ <algorith> header
//! Custom swap() to avoid dependency on C++ <algorithm> header
/*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only.
\note This has the same semantics as std::swap().
*/
......@@ -34,4 +39,8 @@ inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT {
} // namespace internal
RAPIDJSON_NAMESPACE_END
#if defined(__clang__)
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_INTERNAL_SWAP_H_
......@@ -17,6 +17,12 @@
#include "rapidjson.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(unreachable-code)
RAPIDJSON_DIAG_OFF(missing-noreturn)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Represents an in-memory input byte stream.
......@@ -58,4 +64,8 @@ struct MemoryStream {
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_MEMORYBUFFER_H_
......@@ -89,14 +89,14 @@
#include <limits.h>
// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
// or compiler give many errors like this:
// compiling for ARM we have to wrap <wchar.h> include with 'extern "C++" {}'
// or compiler would give many errors like this:
// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
#ifdef __cplusplus
#if defined(__cplusplus) && !defined(_M_ARM)
extern "C" {
#endif
# include <wchar.h>
#ifdef __cplusplus
#if defined(__cplusplus) && !defined(_M_ARM)
}
#endif
......
......@@ -18,6 +18,11 @@
#include "document.h"
#include "internal/itoa.h"
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(switch-enum)
#endif
RAPIDJSON_NAMESPACE_BEGIN
static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token
......@@ -71,7 +76,7 @@ template <typename ValueType, typename Allocator = CrtAllocator>
class GenericPointer {
public:
typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value
typedef typename EncodingType::Ch Ch; //!< Character type from Value
typedef typename ValueType::Ch Ch; //!< Character type from Value
//! A token is the basic units of internal representation.
/*!
......@@ -253,11 +258,12 @@ public:
*/
GenericPointer Append(SizeType index, Allocator* allocator = 0) const {
char buffer[21];
SizeType length = (sizeof(SizeType) == 4 ? internal::u32toa(index, buffer): internal::u64toa(index, buffer)) - buffer;
char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer);
SizeType length = static_cast<SizeType>(end - buffer);
buffer[length] = '\0';
if (sizeof(Ch) == 1) {
Token token = { (Ch*)buffer, length, index };
Token token = { reinterpret_cast<Ch*>(buffer), length, index };
return Append(token, allocator);
}
else {
......@@ -271,7 +277,7 @@ public:
//! Append a token by value, and return a new Pointer
/*!
\param value Value (either Uint or String) to be appended.
\param token token to be appended.
\param allocator Allocator for the newly return Pointer.
\return A new Pointer with appended token.
*/
......@@ -393,7 +399,7 @@ public:
bool exist = true;
for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
if (v->IsArray() && t->name[0] == '-' && t->length == 1) {
v->PushBack(Value().Move(), allocator);
v->PushBack(ValueType().Move(), allocator);
v = &((*v)[v->Size() - 1]);
exist = false;
}
......@@ -411,7 +417,7 @@ public:
if (t->index >= v->Size()) {
v->Reserve(t->index + 1, allocator);
while (t->index >= v->Size())
v->PushBack(Value().Move(), allocator);
v->PushBack(ValueType().Move(), allocator);
exist = false;
}
v = &((*v)[t->index]);
......@@ -419,7 +425,7 @@ public:
else {
typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
if (m == v->MemberEnd()) {
v->AddMember(Value(t->name, t->length, allocator).Move(), Value().Move(), allocator);
v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator);
v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end
exist = false;
}
......@@ -438,7 +444,6 @@ public:
//! Creates a value in a document.
/*!
\param document A document to be resolved.
\param allocator Allocator for creating the values if the specified value or its parents are not exist.
\param alreadyExist If non-null, it stores whether the resolved value is already exist.
\return The resolved newly created, or already exists value.
*/
......@@ -528,7 +533,7 @@ public:
//! Query a value in a subtree with default primitive value.
/*!
\tparam T \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
\tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
*/
template <typename T>
RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
......@@ -558,7 +563,7 @@ public:
//! Query a value in a document with default primitive value.
/*!
\tparam T \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
\tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
*/
template <typename T, typename stackAllocator>
RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
......@@ -604,7 +609,7 @@ public:
//! Set a primitive value in a subtree.
/*!
\tparam T \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
\tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
*/
template <typename T>
RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
......@@ -640,7 +645,7 @@ public:
//! Set a primitive value in a document.
/*!
\tparam T \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
\tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
*/
template <typename T, typename stackAllocator>
RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
......@@ -762,11 +767,13 @@ private:
}
//! Parse a JSON String or its URI fragment representation into tokens.
#ifndef __clang__ // -Wdocumentation
/*!
\param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated.
\param length Length of the source string.
\note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped.
*/
#endif
void Parse(const Ch* source, size_t length) {
RAPIDJSON_ASSERT(source != NULL);
RAPIDJSON_ASSERT(nameBuffer_ == 0);
......@@ -860,7 +867,7 @@ private:
*name++ = c;
}
token->length = name - token->name;
token->length = static_cast<SizeType>(name - token->name);
if (token->length == 0)
isNumber = false;
*name++ = '\0'; // Null terminator
......@@ -947,6 +954,8 @@ private:
*/
class PercentDecodeStream {
public:
typedef typename ValueType::Ch Ch;
//! Constructor
/*!
\param source Start of the stream
......@@ -976,7 +985,7 @@ private:
return c;
}
size_t Tell() const { return src_ - head_; }
size_t Tell() const { return static_cast<size_t>(src_ - head_); }
bool IsValid() const { return valid_; }
private:
......@@ -1313,4 +1322,8 @@ bool EraseValueByPointer(T& root, const CharType(&source)[N]) {
RAPIDJSON_NAMESPACE_END
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_POINTER_H_
......@@ -186,7 +186,7 @@ protected:
void WriteIndent() {
size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
PutN(*Base::os_, indentChar_, count);
PutN(*Base::os_, static_cast<typename TargetEncoding::Ch>(indentChar_), count);
}
Ch indentChar_;
......
......@@ -119,6 +119,31 @@
#define RAPIDJSON_NAMESPACE_END }
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_HAS_STDSTRING
#ifndef RAPIDJSON_HAS_STDSTRING
#ifdef RAPIDJSON_DOXYGEN_RUNNING
#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation
#else
#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default
#endif
/*! \def RAPIDJSON_HAS_STDSTRING
\ingroup RAPIDJSON_CONFIG
\brief Enable RapidJSON support for \c std::string
By defining this preprocessor symbol to \c 1, several convenience functions for using
\ref rapidjson::GenericValue with \c std::string are enabled, especially
for construction and comparison.
\hideinitializer
*/
#endif // !defined(RAPIDJSON_HAS_STDSTRING)
#if RAPIDJSON_HAS_STDSTRING
#include <string>
#endif // RAPIDJSON_HAS_STDSTRING
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NO_INT64DEFINE
......@@ -153,9 +178,9 @@
#ifndef RAPIDJSON_FORCEINLINE
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#if defined(_MSC_VER) && !defined(NDEBUG)
#if defined(_MSC_VER) && defined(NDEBUG)
#define RAPIDJSON_FORCEINLINE __forceinline
#elif defined(__GNUC__) && __GNUC__ >= 4 && !defined(NDEBUG)
#elif defined(__GNUC__) && __GNUC__ >= 4 && defined(NDEBUG)
#define RAPIDJSON_FORCEINLINE __attribute__((always_inline))
#else
#define RAPIDJSON_FORCEINLINE
......@@ -211,6 +236,8 @@
# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
# elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__)
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif defined(_MSC_VER) && defined(_M_ARM)
# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
# elif defined(RAPIDJSON_DOXYGEN_RUNNING)
# define RAPIDJSON_ENDIAN
# else
......@@ -238,13 +265,13 @@
\param x pointer to align
Some machines require strict data alignment. Currently the default uses 4 bytes
alignment. User can customize by defining the RAPIDJSON_ALIGN function macro.,
alignment. User can customize by defining the RAPIDJSON_ALIGN function macro.
*/
#ifndef RAPIDJSON_ALIGN
#if RAPIDJSON_64BIT == 1
#define RAPIDJSON_ALIGN(x) ((x + 7u) & ~7u)
#define RAPIDJSON_ALIGN(x) (((x) + static_cast<uint64_t>(7u)) & ~static_cast<uint64_t>(7u))
#else
#define RAPIDJSON_ALIGN(x) ((x + 3u) & ~3u)
#define RAPIDJSON_ALIGN(x) (((x) + 3u) & ~3u)
#endif
#endif
......@@ -349,7 +376,9 @@ RAPIDJSON_NAMESPACE_END
// Adopt from boost
#ifndef RAPIDJSON_STATIC_ASSERT
#ifndef __clang__
//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
#endif
RAPIDJSON_NAMESPACE_BEGIN
template <bool x> struct STATIC_ASSERTION_FAILURE;
template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
......@@ -365,7 +394,9 @@ RAPIDJSON_NAMESPACE_END
#else
#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
#endif
#ifndef __clang__
//!@endcond
#endif
/*! \def RAPIDJSON_STATIC_ASSERT
\brief (Internal) macro to check for conditions at compile-time
......@@ -378,6 +409,35 @@ RAPIDJSON_NAMESPACE_END
RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY
//! Compiler branching hint for expression with high probability to be true.
/*!
\ingroup RAPIDJSON_CONFIG
\param x Boolean expression likely to be true.
*/
#ifndef RAPIDJSON_LIKELY
#if defined(__GNUC__) || defined(__clang__)
#define RAPIDJSON_LIKELY(x) __builtin_expect(!!(x), 1)
#else
#define RAPIDJSON_LIKELY(x) x
#endif
#endif
//! Compiler branching hint for expression with low probability to be true.
/*!
\ingroup RAPIDJSON_CONFIG
\param x Boolean expression unlikely to be true.
*/
#ifndef RAPIDJSON_UNLIKELY
#if defined(__GNUC__) || defined(__clang__)
#define RAPIDJSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define RAPIDJSON_UNLIKELY(x) x
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
// Helpers
......@@ -554,11 +614,25 @@ struct StreamTraits {
enum { copyOptimization = 0 };
};
//! Reserve n characters for writing to a stream.
template<typename Stream>
inline void PutReserve(Stream& stream, size_t count) {
(void)stream;
(void)count;
}
//! Write character to a stream, presuming buffer is reserved.
template<typename Stream>
inline void PutUnsafe(Stream& stream, typename Stream::Ch c) {
stream.Put(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);
for (size_t i = 0; i < n; i++)
stream.Put(c);
PutUnsafe(stream, c);
}
///////////////////////////////////////////////////////////////////////////////
......
This diff is collapsed.
......@@ -23,6 +23,11 @@
#include "internal/stack.h"
#if defined(__clang__)
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(c++98-compat)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! Represents an in-memory output stream.
......@@ -48,6 +53,7 @@ public:
#endif
void Put(Ch c) { *stack_.template Push<Ch>() = c; }
void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; }
void Flush() {}
void Clear() { stack_.Clear(); }
......@@ -57,6 +63,8 @@ public:
stack_.ShrinkToFit();
stack_.template Pop<Ch>(1);
}
void Reserve(size_t count) { stack_.template Reserve<Ch>(count); }
Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
void Pop(size_t count) { stack_.template Pop<Ch>(count); }
......@@ -82,6 +90,16 @@ private:
//! String buffer with UTF8 encoding
typedef GenericStringBuffer<UTF8<> > StringBuffer;
template<typename Encoding, typename Allocator>
inline void PutReserve(GenericStringBuffer<Encoding, Allocator>& stream, size_t count) {
stream.Reserve(count);
}
template<typename Encoding, typename Allocator>
inline void PutUnsafe(GenericStringBuffer<Encoding, Allocator>& stream, typename Encoding::Ch c) {
stream.PutUnsafe(c);
}
//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
......@@ -90,4 +108,8 @@ inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
RAPIDJSON_NAMESPACE_END
#if defined(__clang__)
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_STRINGBUFFER_H_
......@@ -23,15 +23,16 @@
#include "stringbuffer.h"
#include <new> // placement new
#if RAPIDJSON_HAS_STDSTRING
#include <string>
#endif
#ifdef _MSC_VER
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
#endif
#ifdef __clang__
RAPIDJSON_DIAG_PUSH
RAPIDJSON_DIAG_OFF(padded)
#endif
RAPIDJSON_NAMESPACE_BEGIN
//! JSON writer
......@@ -145,7 +146,7 @@ public:
RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
level_stack_.template Pop<Level>(1);
bool ret = WriteEndObject();
if (level_stack_.Empty()) // end of json text
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
os_->Flush();
return ret;
}
......@@ -162,7 +163,7 @@ public:
RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
level_stack_.template Pop<Level>(1);
bool ret = WriteEndArray();
if (level_stack_.Empty()) // end of json text
if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
os_->Flush();
return ret;
}
......@@ -188,15 +189,18 @@ protected:
static const size_t kDefaultLevelDepth = 32;
bool WriteNull() {
os_->Put('n'); os_->Put('u'); os_->Put('l'); os_->Put('l'); return true;
PutReserve(*os_, 4);
PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true;
}
bool WriteBool(bool b) {
if (b) {
os_->Put('t'); os_->Put('r'); os_->Put('u'); os_->Put('e');
PutReserve(*os_, 4);
PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e');
}
else {
os_->Put('f'); os_->Put('a'); os_->Put('l'); os_->Put('s'); os_->Put('e');
PutReserve(*os_, 5);
PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e');
}
return true;
}
......@@ -204,45 +208,50 @@ protected:
bool WriteInt(int i) {
char buffer[11];
const char* end = internal::i32toa(i, buffer);
PutReserve(*os_, static_cast<size_t>(end - buffer));
for (const char* p = buffer; p != end; ++p)
os_->Put(*p);
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
return true;
}
bool WriteUint(unsigned u) {
char buffer[10];
const char* end = internal::u32toa(u, buffer);
PutReserve(*os_, static_cast<size_t>(end - buffer));
for (const char* p = buffer; p != end; ++p)
os_->Put(*p);
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
return true;
}
bool WriteInt64(int64_t i64) {
char buffer[21];
const char* end = internal::i64toa(i64, buffer);
PutReserve(*os_, static_cast<size_t>(end - buffer));
for (const char* p = buffer; p != end; ++p)
os_->Put(*p);
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
return true;
}
bool WriteUint64(uint64_t u64) {
char buffer[20];
char* end = internal::u64toa(u64, buffer);
PutReserve(*os_, static_cast<size_t>(end - buffer));
for (char* p = buffer; p != end; ++p)
os_->Put(*p);
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
return true;
}
bool WriteDouble(double d) {
char buffer[25];
char* end = internal::dtoa(d, buffer);
PutReserve(*os_, static_cast<size_t>(end - buffer));
for (char* p = buffer; p != end; ++p)
os_->Put(*p);
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
return true;
}
bool WriteString(const Ch* str, SizeType length) {
static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static const typename TargetEncoding::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static const char escape[256] = {
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
//0 1 2 3 4 5 6 7 8 9 A B C D E F
......@@ -255,22 +264,27 @@ protected:
#undef Z16
};
os_->Put('\"');
if (TargetEncoding::supportUnicode)
PutReserve(*os_, 2 + length * 6); // "\uxxxx..."
else
PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..."
PutUnsafe(*os_, '\"');
GenericStringStream<SourceEncoding> is(str);
while (is.Tell() < length) {
while (RAPIDJSON_LIKELY(is.Tell() < length)) {
const Ch c = is.Peek();
if (!TargetEncoding::supportUnicode && (unsigned)c >= 0x80) {
if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) {
// Unicode escaping
unsigned codepoint;
if (!SourceEncoding::Decode(is, &codepoint))
if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint)))
return false;
os_->Put('\\');
os_->Put('u');
PutUnsafe(*os_, '\\');
PutUnsafe(*os_, 'u');
if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
os_->Put(hexDigits[(codepoint >> 12) & 15]);
os_->Put(hexDigits[(codepoint >> 8) & 15]);
os_->Put(hexDigits[(codepoint >> 4) & 15]);
os_->Put(hexDigits[(codepoint ) & 15]);
PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]);
PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]);
PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]);
PutUnsafe(*os_, hexDigits[(codepoint ) & 15]);
}
else {
RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
......@@ -278,34 +292,34 @@ protected:
unsigned s = codepoint - 0x010000;
unsigned lead = (s >> 10) + 0xD800;
unsigned trail = (s & 0x3FF) + 0xDC00;
os_->Put(hexDigits[(lead >> 12) & 15]);
os_->Put(hexDigits[(lead >> 8) & 15]);
os_->Put(hexDigits[(lead >> 4) & 15]);
os_->Put(hexDigits[(lead ) & 15]);
os_->Put('\\');
os_->Put('u');
os_->Put(hexDigits[(trail >> 12) & 15]);
os_->Put(hexDigits[(trail >> 8) & 15]);
os_->Put(hexDigits[(trail >> 4) & 15]);
os_->Put(hexDigits[(trail ) & 15]);
PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]);
PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]);
PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]);
PutUnsafe(*os_, hexDigits[(lead ) & 15]);
PutUnsafe(*os_, '\\');
PutUnsafe(*os_, 'u');
PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]);
PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]);
PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]);
PutUnsafe(*os_, hexDigits[(trail ) & 15]);
}
}
else if ((sizeof(Ch) == 1 || (unsigned)c < 256) && escape[(unsigned char)c]) {
else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) {
is.Take();
os_->Put('\\');
os_->Put(escape[(unsigned char)c]);
if (escape[(unsigned char)c] == 'u') {
os_->Put('0');
os_->Put('0');
os_->Put(hexDigits[(unsigned char)c >> 4]);
os_->Put(hexDigits[(unsigned char)c & 0xF]);
PutUnsafe(*os_, '\\');
PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(escape[static_cast<unsigned char>(c)]));
if (escape[static_cast<unsigned char>(c)] == 'u') {
PutUnsafe(*os_, '0');
PutUnsafe(*os_, '0');
PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]);
PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]);
}
}
else
if (!Transcoder<SourceEncoding, TargetEncoding>::Transcode(is, *os_))
if (RAPIDJSON_UNLIKELY(!(Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
return false;
}
os_->Put('\"');
PutUnsafe(*os_, '\"');
return true;
}
......@@ -316,7 +330,7 @@ protected:
void Prefix(Type type) {
(void)type;
if (level_stack_.GetSize() != 0) { // this value is not at root
if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root
Level* level = level_stack_.template Top<Level>();
if (level->valueCount > 0) {
if (level->inArray)
......@@ -392,4 +406,8 @@ RAPIDJSON_NAMESPACE_END
RAPIDJSON_DIAG_POP
#endif
#ifdef __clang__
RAPIDJSON_DIAG_POP
#endif
#endif // RAPIDJSON_RAPIDJSON_H_
nuget {
//Usage: Write-NuGetPackage rapidjson.autopkg -defines:MYVERSION=1.0.2
//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"};
owners: {"@lsantos (github)"};
licenseUrl: "https://github.com/miloyip/rapidjson/blob/master/license.txt";
projectUrl: "https://github.com/miloyip/rapidjson/";
iconUrl: "https://cdn1.iconfinder.com/data/icons/fatcow/32x32/json.png";
requireLicenseAcceptance:false;
summary: @"A fast JSON parser/generator for C++ with both SAX/DOM style API";
// if you need to span several lines you can prefix a string with an @ symbol (exactly like c# does).
description: @"Rapidjson is an attempt to create the fastest JSON parser and generator.
- Small but complete. Supports both SAX and DOM style API. SAX parser only a few hundred lines of code.
- Fast. In the order of magnitude of strlen(). Optionally supports SSE2/SSE4.2 for acceleration.
- Self-contained. Minimal dependency on standard libraries. No BOOST, not even STL.
- Compact. Each JSON value is 16 or 20 bytes for 32 or 64-bit machines respectively (excluding text string storage). With the custom memory allocator, parser allocates memory compactly during parsing.
- Full RFC4627 compliance. Supports UTF-8, UTF-16 and UTF-32.
- Support both in-situ parsing (directly decode strings into the source JSON text) and non-destructive parsing (decode strings into new buffers).
- Parse number to int/unsigned/int64_t/uint64_t/double depending on input
- Support custom memory allocation. Also, the default memory pool allocator can also be supplied with a user buffer (such as a buffer allocated on user's heap or - programme stack) to minimize allocation.
As the name implies, rapidjson is inspired by rapidxml.";
releaseNotes: @"
Added
Add Value::XXXMember(...) overloads for std::string (#335)
Fixed
Include rapidjson.h for all internal/error headers.
Parsing some numbers incorrectly in full-precision mode (kFullPrecisionParseFlag) (#342)
Fix alignment of 64bit platforms (#328)
Fix MemoryPoolAllocator::Clear() to clear user-buffer (0691502)
Changed
CMakeLists for include as a thirdparty in projects (#334, #337)
Change Document::ParseStream() to use stack allocator for Reader (ffbe386)";
copyright: "Copyright 2015";
tags: { native, coapp, JSON, nativepackage };
language: en-US;
};
dependencies {
packages : {
//TODO: Add dependecies here in [pkg.name]/[version] form per newline
//zlib/[1.2.8],
};
}
// the files that go into the content folders
files {
#defines {
SDK_ROOT = .\;
}
// grab all the files in the include folder
// the folder that contains all the .h files will
// automatically get added to the Includes path.
nestedinclude += {
#destination = ${d_include}rapidjson;
"${SDK_ROOT}include\rapidjson\**\*.h"
};
};
targets {
// We're trying to be standard about these sorts of thing. (Will help with config.h later :D)
//Defines += HAS_EQCORE;
};
}
\ No newline at end of file
......@@ -31,15 +31,15 @@ Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights
RapidJSON is a JSON parser and generator for C++. It was inspired by [RapidXml](http://rapidxml.sourceforge.net/).
* RapidJSON is small but complete. It supports both SAX and DOM style API. The SAX parser is only a half thousand lines of code.
* RapidJSON is **small** but **complete**. It supports both SAX and DOM style API. The SAX parser is only a half thousand lines of code.
* RapidJSON is fast. Its performance can be comparable to `strlen()`. It also optionally supports SSE2/SSE4.2 for acceleration.
* RapidJSON is **fast**. Its performance can be comparable to `strlen()`. It also optionally supports SSE2/SSE4.2 for acceleration.
* RapidJSON is self-contained. It does not depend on external libraries such as BOOST. It even does not depend on STL.
* 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/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 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).
* 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).
......@@ -63,9 +63,9 @@ Users can build and run the unit tests on their platform/compiler.
RapidJSON is a header-only C++ library. Just copy the `include/rapidjson` folder to system or project's include path.
RapidJSON uses following software as its dependencies:
* [CMake](http://www.cmake.org) as a general build tool
* [CMake](https://cmake.org/) as a general build tool
* (optional)[Doxygen](http://www.doxygen.org) to build documentation
* (optional)[googletest](https://code.google.com/p/googletest/) for unit and performance testing
* (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:
......
......@@ -9,7 +9,7 @@ IF(GTESTSRC_FOUND)
endif()
add_subdirectory(${GTEST_SOURCE_DIR} ${CMAKE_BINARY_DIR}/googletest)
include_directories(${GTEST_INCLUDE_DIR})
include_directories(SYSTEM ${GTEST_INCLUDE_DIR})
set(TEST_LIBRARIES gtest gtest_main)
......
......@@ -65,44 +65,87 @@ public:
PerfTest() : filename_(), json_(), length_(), whitespace_(), whitespace_length_() {}
virtual void SetUp() {
const char *paths[] = {
"data/sample.json",
"bin/data/sample.json",
"../bin/data/sample.json",
"../../bin/data/sample.json",
"../../../bin/data/sample.json"
};
FILE *fp = 0;
for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) {
fp = fopen(filename_ = paths[i], "rb");
if (fp)
break;
{
const char *paths[] = {
"data/sample.json",
"bin/data/sample.json",
"../bin/data/sample.json",
"../../bin/data/sample.json",
"../../../bin/data/sample.json"
};
FILE *fp = 0;
for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) {
fp = fopen(filename_ = paths[i], "rb");
if (fp)
break;
}
ASSERT_TRUE(fp != 0);
fseek(fp, 0, SEEK_END);
length_ = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
json_ = (char*)malloc(length_ + 1);
ASSERT_EQ(length_, fread(json_, 1, length_, fp));
json_[length_] = '\0';
fclose(fp);
}
ASSERT_TRUE(fp != 0);
fseek(fp, 0, SEEK_END);
length_ = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
json_ = (char*)malloc(length_ + 1);
ASSERT_EQ(length_, fread(json_, 1, length_, fp));
json_[length_] = '\0';
fclose(fp);
// whitespace test
whitespace_length_ = 1024 * 1024;
whitespace_ = (char *)malloc(whitespace_length_ + 4);
char *p = whitespace_;
for (size_t i = 0; i < whitespace_length_; i += 4) {
*p++ = ' ';
*p++ = '\n';
*p++ = '\r';
*p++ = '\t';
{
whitespace_length_ = 1024 * 1024;
whitespace_ = (char *)malloc(whitespace_length_ + 4);
char *p = whitespace_;
for (size_t i = 0; i < whitespace_length_; i += 4) {
*p++ = ' ';
*p++ = '\n';
*p++ = '\r';
*p++ = '\t';
}
*p++ = '[';
*p++ = '0';
*p++ = ']';
*p++ = '\0';
}
// types test
{
const char *typespaths[] = {
"data/types",
"bin/types",
"../bin/types",
"../../bin/types/",
"../../../bin/types"
};
const char* typesfilenames[] = {
"booleans.json",
"floats.json",
"guids.json",
"integers.json",
"mixed.json",
"nulls.json",
"paragraphs.json"
};
for (size_t j = 0; j < sizeof(typesfilenames) / sizeof(typesfilenames[0]); j++) {
types_[j] = 0;
for (size_t i = 0; i < sizeof(typespaths) / sizeof(typespaths[0]); i++) {
char filename[256];
sprintf(filename, "%s/%s", typespaths[i], typesfilenames[j]);
if (FILE* fp = fopen(filename, "rb")) {
fseek(fp, 0, SEEK_END);
typesLength_[j] = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
types_[j] = (char*)malloc(typesLength_[j] + 1);
ASSERT_EQ(typesLength_[j], fread(types_[j], 1, typesLength_[j], fp));
types_[j][typesLength_[j]] = '\0';
fclose(fp);
break;
}
}
}
}
*p++ = '[';
*p++ = '0';
*p++ = ']';
*p++ = '\0';
}
virtual void TearDown() {
......@@ -110,6 +153,10 @@ public:
free(whitespace_);
json_ = 0;
whitespace_ = 0;
for (size_t i = 0; i < 7; i++) {
free(types_[i]);
types_[i] = 0;
}
}
private:
......@@ -122,6 +169,8 @@ protected:
size_t length_;
char *whitespace_;
size_t whitespace_length_;
char *types_[7];
size_t typesLength_[7];
static const size_t kTrialCount = 1000;
};
......
......@@ -45,7 +45,10 @@ public:
temp_ = (char *)malloc(length_ + 1);
// Parse as a document
EXPECT_FALSE(doc_.Parse(json_).IsNull());
EXPECT_FALSE(doc_.Parse(json_).HasParseError());
for (size_t i = 0; i < 7; i++)
EXPECT_FALSE(typesDoc_[i].Parse(types_[i]).HasParseError());
}
virtual void TearDown() {
......@@ -60,6 +63,7 @@ private:
protected:
char *temp_;
Document doc_;
Document typesDoc_[7];
};
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler)) {
......@@ -91,6 +95,35 @@ TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler)) {
}
}
#define TEST_TYPED(index, Name)\
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_##Name)) {\
for (size_t i = 0; i < kTrialCount * 10; i++) {\
StringStream s(types_[index]);\
BaseReaderHandler<> h;\
Reader reader;\
EXPECT_TRUE(reader.Parse(s, h));\
}\
}\
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParseInsitu_DummyHandler_##Name)) {\
for (size_t i = 0; i < kTrialCount * 10; i++) {\
memcpy(temp_, types_[index], typesLength_[index] + 1);\
InsituStringStream s(temp_);\
BaseReaderHandler<> h;\
Reader reader;\
EXPECT_TRUE(reader.Parse<kParseInsituFlag>(s, h));\
}\
}
TEST_TYPED(0, Booleans)
TEST_TYPED(1, Floats)
TEST_TYPED(2, Guids)
TEST_TYPED(3, Integers)
TEST_TYPED(4, Mixed)
TEST_TYPED(5, Nulls)
TEST_TYPED(6, Paragraphs)
#undef TEST_TYPED
TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FullPrecision)) {
for (size_t i = 0; i < kTrialCount; i++) {
StringStream s(json_);
......@@ -250,8 +283,10 @@ TEST_F(RapidJson, DocumentAccept) {
}
struct NullStream {
typedef char Ch;
NullStream() /*: length_(0)*/ {}
void Put(char) { /*++length_;*/ }
void Put(Ch) { /*++length_;*/ }
void Flush() {}
//size_t length_;
};
......@@ -278,6 +313,27 @@ TEST_F(RapidJson, Writer_StringBuffer) {
}
}
#define TEST_TYPED(index, Name)\
TEST_F(RapidJson, Writer_StringBuffer_##Name) {\
for (size_t i = 0; i < kTrialCount * 10; i++) {\
StringBuffer s(0, 1024 * 1024);\
Writer<StringBuffer> writer(s);\
typesDoc_[index].Accept(writer);\
const char* str = s.GetString();\
(void)str;\
}\
}
TEST_TYPED(0, Booleans)
TEST_TYPED(1, Floats)
TEST_TYPED(2, Guids)
TEST_TYPED(3, Integers)
TEST_TYPED(4, Mixed)
TEST_TYPED(5, Nulls)
TEST_TYPED(6, Paragraphs)
#undef TEST_TYPED
TEST_F(RapidJson, PrettyWriter_StringBuffer) {
for (size_t i = 0; i < kTrialCount; i++) {
StringBuffer s(0, 2048 * 1024);
......@@ -357,4 +413,10 @@ TEST_F(RapidJson, SIMD_SUFFIX(ReaderParse_DummyHandler_FileReadStream)) {
}
}
TEST_F(RapidJson, StringBuffer) {
StringBuffer sb;
for (int i = 0; i < 32 * 1024 * 1024; i++)
sb.Put(i & 0x7f);
}
#endif // TEST_RAPIDJSON
......@@ -24,7 +24,7 @@ set(UNITTEST_SOURCES
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")
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)
endif()
......
......@@ -22,21 +22,21 @@ template <typename Allocator>
void TestAllocator(Allocator& a) {
EXPECT_TRUE(a.Malloc(0) == 0);
uint8_t* p = (uint8_t*)a.Malloc(100);
uint8_t* p = static_cast<uint8_t*>(a.Malloc(100));
EXPECT_TRUE(p != 0);
for (size_t i = 0; i < 100; i++)
p[i] = (uint8_t)i;
p[i] = static_cast<uint8_t>(i);
// Expand
uint8_t* q = (uint8_t*)a.Realloc(p, 100, 200);
uint8_t* q = static_cast<uint8_t*>(a.Realloc(p, 100, 200));
EXPECT_TRUE(q != 0);
for (size_t i = 0; i < 100; i++)
EXPECT_EQ(i, q[i]);
for (size_t i = 100; i < 200; i++)
q[i] = (uint8_t)i;
q[i] = static_cast<uint8_t>(i);
// Shrink
uint8_t *r = (uint8_t*)a.Realloc(q, 200, 150);
uint8_t *r = static_cast<uint8_t*>(a.Realloc(q, 200, 150));
EXPECT_TRUE(r != 0);
for (size_t i = 0; i < 150; i++)
EXPECT_EQ(i, r[i]);
......@@ -56,8 +56,28 @@ TEST(Allocator, MemoryPoolAllocator) {
MemoryPoolAllocator<> a;
TestAllocator(a);
for (int i = 1; i < 1000; i++) {
for (size_t i = 1; i < 1000; i++) {
EXPECT_TRUE(a.Malloc(i) != 0);
EXPECT_LE(a.Size(), a.Capacity());
}
}
TEST(Allocator, Alignment) {
#if RAPIDJSON_64BIT == 1
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000000), RAPIDJSON_ALIGN(0));
for (uint64_t i = 1; i < 8; i++) {
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008), RAPIDJSON_ALIGN(i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000000, 0x00000010), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0x00000008) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0x00000001, 0x00000000), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0x00000000, 0xFFFFFFF8) + i));
EXPECT_EQ(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF8), RAPIDJSON_ALIGN(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0xFFFFFFF0) + i));
}
#else
EXPECT_EQ(0u, RAPIDJSON_ALIGN(0u));
for (uint32_t i = 1; i < 4; i++) {
EXPECT_EQ(4u, RAPIDJSON_ALIGN(i));
EXPECT_EQ(8u, RAPIDJSON_ALIGN(4u + i));
EXPECT_EQ(0xFFFFFFF8u, RAPIDJSON_ALIGN(0xFFFFFFF4u + i));
EXPECT_EQ(0xFFFFFFFCu, RAPIDJSON_ALIGN(0xFFFFFFF8u + i));
}
#endif
}
This diff is collapsed.
......@@ -25,6 +25,7 @@ using namespace rapidjson;
class EncodedStreamTest : public ::testing::Test {
public:
EncodedStreamTest() : json_(), length_() {}
virtual ~EncodedStreamTest();
virtual void SetUp() {
json_ = ReadFile("utf8.json", true, &length_);
......@@ -42,15 +43,15 @@ private:
protected:
static FILE* Open(const char* filename) {
const char *paths[] = {
"encodings/%s",
"bin/encodings/%s",
"../bin/encodings/%s",
"../../bin/encodings/%s",
"../../../bin/encodings/%s"
"encodings",
"bin/encodings",
"../bin/encodings",
"../../bin/encodings",
"../../../bin/encodings"
};
char buffer[1024];
for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) {
sprintf(buffer, paths[i], filename);
sprintf(buffer, "%s/%s", paths[i], filename);
FILE *fp = fopen(buffer, "rb");
if (fp)
return fp;
......@@ -67,9 +68,9 @@ protected:
}
fseek(fp, 0, SEEK_END);
*outLength = (size_t)ftell(fp);
*outLength = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
char* buffer = (char*)malloc(*outLength + 1);
char* buffer = static_cast<char*>(malloc(*outLength + 1));
size_t readLength = fread(buffer, 1, *outLength, fp);
buffer[readLength] = '\0';
fclose(fp);
......@@ -248,6 +249,8 @@ protected:
size_t length_;
};
EncodedStreamTest::~EncodedStreamTest() {}
TEST_F(EncodedStreamTest, EncodedInputStream) {
TestEncodedInputStream<UTF8<>, UTF8<> >("utf8.json");
TestEncodedInputStream<UTF8<>, UTF8<> >("utf8bom.json");
......
......@@ -240,7 +240,6 @@ static const unsigned kCodepointRanges[] = {
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
#define UTF8_ACCEPT 0u
#define UTF8_REJECT 12u
static const unsigned char utf8d[] = {
// The first part of the table maps bytes to character classes that
......@@ -298,7 +297,7 @@ TEST(EncodingsTest, UTF8) {
unsigned decodedCount = 0;
for (const char* s = encodedStr; *s; ++s)
if (!decode(&state, &decodedCodepoint, (unsigned char)*s)) {
if (!decode(&state, &decodedCodepoint, static_cast<unsigned char>(*s))) {
EXPECT_EQ(codepoint, decodedCodepoint);
decodedCount++;
}
......@@ -355,7 +354,7 @@ TEST(EncodingsTest, UTF16) {
unsigned state = 0;
UTF16<>::Ch buffer[3], *p = &buffer[0];
for (const char* s = utf8os.GetString(); *s; ++s) {
if (!decode(&state, &decodedCodepoint, (unsigned char)*s))
if (!decode(&state, &decodedCodepoint, static_cast<unsigned char>(*s)))
break;
}
......
......@@ -22,6 +22,7 @@ using namespace rapidjson;
class FileStreamTest : public ::testing::Test {
public:
FileStreamTest() : filename_(), json_(), length_() {}
virtual ~FileStreamTest();
virtual void SetUp() {
const char *paths[] = {
......@@ -42,9 +43,9 @@ public:
ASSERT_TRUE(fp != 0);
fseek(fp, 0, SEEK_END);
length_ = (size_t)ftell(fp);
length_ = static_cast<size_t>(ftell(fp));
fseek(fp, 0, SEEK_SET);
json_ = (char*)malloc(length_ + 1);
json_ = static_cast<char*>(malloc(length_ + 1));
size_t readLength = fread(json_, 1, length_, fp);
json_[readLength] = '\0';
fclose(fp);
......@@ -65,6 +66,8 @@ protected:
size_t length_;
};
FileStreamTest::~FileStreamTest() {}
TEST_F(FileStreamTest, FileReadStream) {
FILE *fp = fopen(filename_, "rb");
ASSERT_TRUE(fp != 0);
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -41,7 +41,7 @@ using namespace rapidjson_simd;
template <typename StreamType>
void TestSkipWhitespace() {
for (int step = 1; step < 32; step++) {
for (size_t step = 1; step < 32; step++) {
char buffer[1025];
for (size_t i = 0; i < 1024; i++)
buffer[i] = " \t\r\n"[i % 4];
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -66,7 +66,7 @@ gh_pages_prepare()
[ ! -d "html" ] || \
abort "Doxygen target directory already exists."
git --version
git clone --single-branch -b gh-pages "${GITHUB_CLONE}" html
git clone -b gh-pages "${GITHUB_CLONE}" html
cd html
# setup git config (with defaults)
git config user.name "${GIT_NAME-travis}"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment