mt-libcouchbase 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (707) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +22 -0
  3. data/.gitmodules +3 -0
  4. data/.rspec +1 -0
  5. data/.travis.yml +38 -0
  6. data/Gemfile +4 -0
  7. data/LICENSE +24 -0
  8. data/README.md +445 -0
  9. data/Rakefile +76 -0
  10. data/ext/README.md +6 -0
  11. data/ext/Rakefile +19 -0
  12. data/ext/libcouchbase/.gitignore +132 -0
  13. data/ext/libcouchbase/CMakeLists.txt +455 -0
  14. data/ext/libcouchbase/CONTRIBUTING.md +105 -0
  15. data/ext/libcouchbase/LICENSE +202 -0
  16. data/ext/libcouchbase/README.markdown +195 -0
  17. data/ext/libcouchbase/RELEASE_NOTES.markdown +3523 -0
  18. data/ext/libcouchbase/cmake/Modules/ConfigureDtrace.cmake +52 -0
  19. data/ext/libcouchbase/cmake/Modules/CopyPDB.cmake +42 -0
  20. data/ext/libcouchbase/cmake/Modules/DistScript.cmake +17 -0
  21. data/ext/libcouchbase/cmake/Modules/DownloadLcbDep.cmake +18 -0
  22. data/ext/libcouchbase/cmake/Modules/FindCouchbaseHdrHistogram.cmake +15 -0
  23. data/ext/libcouchbase/cmake/Modules/FindCouchbaseLibev.cmake +73 -0
  24. data/ext/libcouchbase/cmake/Modules/FindCouchbaseLibevent.cmake +54 -0
  25. data/ext/libcouchbase/cmake/Modules/FindCouchbaseLibuv.cmake +57 -0
  26. data/ext/libcouchbase/cmake/Modules/FindProfiler.cmake +16 -0
  27. data/ext/libcouchbase/cmake/Modules/GenerateConfigDotH.cmake +49 -0
  28. data/ext/libcouchbase/cmake/Modules/GetLibcouchbaseFlags.cmake +142 -0
  29. data/ext/libcouchbase/cmake/Modules/GetPlatformCCInfo.cmake +45 -0
  30. data/ext/libcouchbase/cmake/Modules/GetVersionInfo.cmake +70 -0
  31. data/ext/libcouchbase/cmake/config-cmake.h.in +80 -0
  32. data/ext/libcouchbase/cmake/configure +355 -0
  33. data/ext/libcouchbase/cmake/defs.mk.in +6 -0
  34. data/ext/libcouchbase/cmake/dtrace-instr-link.pl +51 -0
  35. data/ext/libcouchbase/cmake/libcouchbase.stp.in +829 -0
  36. data/ext/libcouchbase/cmake/source_files.cmake +104 -0
  37. data/ext/libcouchbase/contrib/cJSON/cJSON.c +1022 -0
  38. data/ext/libcouchbase/contrib/cJSON/cJSON.h +158 -0
  39. data/ext/libcouchbase/contrib/cbsasl/CMakeLists.txt +25 -0
  40. data/ext/libcouchbase/contrib/cbsasl/COPYING +202 -0
  41. data/ext/libcouchbase/contrib/cbsasl/include/cbsasl/cbsasl.h +259 -0
  42. data/ext/libcouchbase/contrib/cbsasl/src/client.c +419 -0
  43. data/ext/libcouchbase/contrib/cbsasl/src/common.c +50 -0
  44. data/ext/libcouchbase/contrib/cbsasl/src/cram-md5/hmac.c +67 -0
  45. data/ext/libcouchbase/contrib/cbsasl/src/cram-md5/hmac.h +33 -0
  46. data/ext/libcouchbase/contrib/cbsasl/src/cram-md5/md5.c +296 -0
  47. data/ext/libcouchbase/contrib/cbsasl/src/cram-md5/md5.h +45 -0
  48. data/ext/libcouchbase/contrib/cbsasl/src/hash.c +573 -0
  49. data/ext/libcouchbase/contrib/cbsasl/src/hash.h +15 -0
  50. data/ext/libcouchbase/contrib/cbsasl/src/scram-sha/scram_utils.c +500 -0
  51. data/ext/libcouchbase/contrib/cbsasl/src/scram-sha/scram_utils.h +99 -0
  52. data/ext/libcouchbase/contrib/cbsasl/src/util.h +31 -0
  53. data/ext/libcouchbase/contrib/cliopts/CMakeLists.txt +2 -0
  54. data/ext/libcouchbase/contrib/cliopts/cliopts.c +938 -0
  55. data/ext/libcouchbase/contrib/cliopts/cliopts.h +610 -0
  56. data/ext/libcouchbase/contrib/genhash/genhash.c +371 -0
  57. data/ext/libcouchbase/contrib/genhash/genhash.h +241 -0
  58. data/ext/libcouchbase/contrib/gtest-1.7.0/CHANGES +157 -0
  59. data/ext/libcouchbase/contrib/gtest-1.7.0/CMakeLists.txt +252 -0
  60. data/ext/libcouchbase/contrib/gtest-1.7.0/CONTRIBUTORS +37 -0
  61. data/ext/libcouchbase/contrib/gtest-1.7.0/LICENSE +28 -0
  62. data/ext/libcouchbase/contrib/gtest-1.7.0/MINIFY.sh +15 -0
  63. data/ext/libcouchbase/contrib/gtest-1.7.0/README +435 -0
  64. data/ext/libcouchbase/contrib/gtest-1.7.0/cmake/internal_utils.cmake +227 -0
  65. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-death-test.h +294 -0
  66. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-message.h +250 -0
  67. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-param-test.h +1421 -0
  68. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-param-test.h.pump +487 -0
  69. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-printers.h +855 -0
  70. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-spi.h +232 -0
  71. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-test-part.h +179 -0
  72. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest-typed-test.h +259 -0
  73. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest.h +2291 -0
  74. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest_pred_impl.h +358 -0
  75. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/gtest_prod.h +58 -0
  76. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-death-test-internal.h +319 -0
  77. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-filepath.h +206 -0
  78. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-internal.h +1158 -0
  79. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-linked_ptr.h +233 -0
  80. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-param-util-generated.h +5143 -0
  81. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-param-util-generated.h.pump +301 -0
  82. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-param-util.h +619 -0
  83. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-port.h +1947 -0
  84. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-string.h +167 -0
  85. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-tuple.h +1012 -0
  86. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-tuple.h.pump +339 -0
  87. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-type-util.h +3331 -0
  88. data/ext/libcouchbase/contrib/gtest-1.7.0/include/gtest/internal/gtest-type-util.h.pump +297 -0
  89. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-all.cc +48 -0
  90. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-death-test.cc +1344 -0
  91. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-filepath.cc +382 -0
  92. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-internal-inl.h +1218 -0
  93. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-port.cc +805 -0
  94. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-printers.cc +363 -0
  95. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-test-part.cc +110 -0
  96. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest-typed-test.cc +110 -0
  97. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest.cc +5015 -0
  98. data/ext/libcouchbase/contrib/gtest-1.7.0/src/gtest_main.cc +38 -0
  99. data/ext/libcouchbase/contrib/http_parser/LICENSE-MIT +23 -0
  100. data/ext/libcouchbase/contrib/http_parser/README.md +178 -0
  101. data/ext/libcouchbase/contrib/http_parser/http_parser.c +2060 -0
  102. data/ext/libcouchbase/contrib/http_parser/http_parser.h +321 -0
  103. data/ext/libcouchbase/contrib/jsonsl/LICENSE +20 -0
  104. data/ext/libcouchbase/contrib/jsonsl/jsonsl.c +1452 -0
  105. data/ext/libcouchbase/contrib/jsonsl/jsonsl.h +971 -0
  106. data/ext/libcouchbase/contrib/lcb-jsoncpp/CMakeLists.txt +6 -0
  107. data/ext/libcouchbase/contrib/lcb-jsoncpp/LICENSE +55 -0
  108. data/ext/libcouchbase/contrib/lcb-jsoncpp/lcb-jsoncpp-forwards.h +255 -0
  109. data/ext/libcouchbase/contrib/lcb-jsoncpp/lcb-jsoncpp.cpp +4893 -0
  110. data/ext/libcouchbase/contrib/lcb-jsoncpp/lcb-jsoncpp.h +1961 -0
  111. data/ext/libcouchbase/contrib/snappy/CMakeLists.txt +7 -0
  112. data/ext/libcouchbase/contrib/snappy/COPYING +28 -0
  113. data/ext/libcouchbase/contrib/snappy/snappy-c.cc +90 -0
  114. data/ext/libcouchbase/contrib/snappy/snappy-c.h +138 -0
  115. data/ext/libcouchbase/contrib/snappy/snappy-internal.h +150 -0
  116. data/ext/libcouchbase/contrib/snappy/snappy-lcb-msvc.h +5 -0
  117. data/ext/libcouchbase/contrib/snappy/snappy-sinksource.cc +75 -0
  118. data/ext/libcouchbase/contrib/snappy/snappy-sinksource.h +137 -0
  119. data/ext/libcouchbase/contrib/snappy/snappy-stubs-internal.cc +42 -0
  120. data/ext/libcouchbase/contrib/snappy/snappy-stubs-internal.h +491 -0
  121. data/ext/libcouchbase/contrib/snappy/snappy-stubs-public.h +100 -0
  122. data/ext/libcouchbase/contrib/snappy/snappy.cc +1312 -0
  123. data/ext/libcouchbase/contrib/snappy/snappy.h +184 -0
  124. data/ext/libcouchbase/contrib/win32-defs/iocpdefs.h +133 -0
  125. data/ext/libcouchbase/contrib/win32-defs/mingwdefs.h +4396 -0
  126. data/ext/libcouchbase/contrib/win32-defs/win_stdint.h +258 -0
  127. data/ext/libcouchbase/doc/Doxyfile +2495 -0
  128. data/ext/libcouchbase/doc/DoxygenLayout.xml +109 -0
  129. data/ext/libcouchbase/doc/Makefile +44 -0
  130. data/ext/libcouchbase/doc/apiattr.h +117 -0
  131. data/ext/libcouchbase/doc/cbc-n1qlback.markdown +88 -0
  132. data/ext/libcouchbase/doc/cbc-pillowfight.markdown +296 -0
  133. data/ext/libcouchbase/doc/cbc-subdoc.markdown +299 -0
  134. data/ext/libcouchbase/doc/cbc.markdown +763 -0
  135. data/ext/libcouchbase/doc/cbcrc.markdown +52 -0
  136. data/ext/libcouchbase/doc/common-additional-options.markdown +82 -0
  137. data/ext/libcouchbase/doc/common-options.markdown +71 -0
  138. data/ext/libcouchbase/doc/environment.h +93 -0
  139. data/ext/libcouchbase/doc/example/threads.c +77 -0
  140. data/ext/libcouchbase/doc/footer.html +22 -0
  141. data/ext/libcouchbase/doc/genman.sh +25 -0
  142. data/ext/libcouchbase/doc/header.html +52 -0
  143. data/ext/libcouchbase/doc/intro.h +130 -0
  144. data/ext/libcouchbase/doc/mainpage.h +136 -0
  145. data/ext/libcouchbase/doc/man/cbc-admin.1 +1 -0
  146. data/ext/libcouchbase/doc/man/cbc-bucket-create.1 +1 -0
  147. data/ext/libcouchbase/doc/man/cbc-bucket-delete.1 +1 -0
  148. data/ext/libcouchbase/doc/man/cbc-cat.1 +1 -0
  149. data/ext/libcouchbase/doc/man/cbc-connstr.1 +1 -0
  150. data/ext/libcouchbase/doc/man/cbc-cp.1 +1 -0
  151. data/ext/libcouchbase/doc/man/cbc-create.1 +1 -0
  152. data/ext/libcouchbase/doc/man/cbc-decr.1 +1 -0
  153. data/ext/libcouchbase/doc/man/cbc-flush.1 +1 -0
  154. data/ext/libcouchbase/doc/man/cbc-hash.1 +1 -0
  155. data/ext/libcouchbase/doc/man/cbc-incr.1 +1 -0
  156. data/ext/libcouchbase/doc/man/cbc-lock.1 +1 -0
  157. data/ext/libcouchbase/doc/man/cbc-mcflush.1 +1 -0
  158. data/ext/libcouchbase/doc/man/cbc-mcversion.1 +1 -0
  159. data/ext/libcouchbase/doc/man/cbc-n1ql.1 +1 -0
  160. data/ext/libcouchbase/doc/man/cbc-n1qlback.1 +198 -0
  161. data/ext/libcouchbase/doc/man/cbc-observe.1 +1 -0
  162. data/ext/libcouchbase/doc/man/cbc-pillowfight.1 +499 -0
  163. data/ext/libcouchbase/doc/man/cbc-ping.1 +1 -0
  164. data/ext/libcouchbase/doc/man/cbc-rm.1 +1 -0
  165. data/ext/libcouchbase/doc/man/cbc-role-list.1 +1 -0
  166. data/ext/libcouchbase/doc/man/cbc-stats.1 +1 -0
  167. data/ext/libcouchbase/doc/man/cbc-subdoc.1 +494 -0
  168. data/ext/libcouchbase/doc/man/cbc-unlock.1 +1 -0
  169. data/ext/libcouchbase/doc/man/cbc-user-delete.1 +1 -0
  170. data/ext/libcouchbase/doc/man/cbc-user-list.1 +1 -0
  171. data/ext/libcouchbase/doc/man/cbc-user-upsert.1 +1 -0
  172. data/ext/libcouchbase/doc/man/cbc-verbosity.1 +1 -0
  173. data/ext/libcouchbase/doc/man/cbc-version.1 +1 -0
  174. data/ext/libcouchbase/doc/man/cbc-view.1 +1 -0
  175. data/ext/libcouchbase/doc/man/cbc-watch.1 +1 -0
  176. data/ext/libcouchbase/doc/man/cbc.1 +1035 -0
  177. data/ext/libcouchbase/doc/man/cbcrc.4 +71 -0
  178. data/ext/libcouchbase/doc/style.css +1162 -0
  179. data/ext/libcouchbase/example/CMakeLists.txt +52 -0
  180. data/ext/libcouchbase/example/README.markdown +47 -0
  181. data/ext/libcouchbase/example/analytics/.gitignore +1 -0
  182. data/ext/libcouchbase/example/analytics/analytics.c +158 -0
  183. data/ext/libcouchbase/example/analytics/build-queries.rb +34 -0
  184. data/ext/libcouchbase/example/analytics/cJSON.c +1 -0
  185. data/ext/libcouchbase/example/analytics/cJSON.h +1 -0
  186. data/ext/libcouchbase/example/analytics/queries/00-show-dataverse.json +5 -0
  187. data/ext/libcouchbase/example/analytics/queries/01-setup-dataset-breweries.json +6 -0
  188. data/ext/libcouchbase/example/analytics/queries/02-setup-dataset-beers.json +6 -0
  189. data/ext/libcouchbase/example/analytics/queries/03-initiate-shadow.json +6 -0
  190. data/ext/libcouchbase/example/analytics/queries/04-list-datasets.json +7 -0
  191. data/ext/libcouchbase/example/analytics/queries/05-count-breweries.json +5 -0
  192. data/ext/libcouchbase/example/analytics/queries/06-first-brewery.json +6 -0
  193. data/ext/libcouchbase/example/analytics/queries/07-key-based-lookup.json +6 -0
  194. data/ext/libcouchbase/example/analytics/queries/08-exact-match-lookup.json +7 -0
  195. data/ext/libcouchbase/example/analytics/queries/09-exact-match-lookup-different-shape.json +6 -0
  196. data/ext/libcouchbase/example/analytics/queries/10-other-query-filters.json +6 -0
  197. data/ext/libcouchbase/example/analytics/queries/11-equijoin.json +9 -0
  198. data/ext/libcouchbase/example/analytics/queries/12-equijoin-select-star.json +10 -0
  199. data/ext/libcouchbase/example/analytics/queries/13-ansi-join.json +8 -0
  200. data/ext/libcouchbase/example/analytics/queries/14-join-select-values.json +8 -0
  201. data/ext/libcouchbase/example/analytics/queries/15-nested-outer-join.json +7 -0
  202. data/ext/libcouchbase/example/analytics/queries/16-theta-join.json +8 -0
  203. data/ext/libcouchbase/example/analytics/queries/17-existential-quantification.json +9 -0
  204. data/ext/libcouchbase/example/analytics/queries/18-universal-quantification.json +7 -0
  205. data/ext/libcouchbase/example/analytics/queries/19-simple-aggregation.json +6 -0
  206. data/ext/libcouchbase/example/analytics/queries/20-simple-aggregation-unwrapped-value.json +6 -0
  207. data/ext/libcouchbase/example/analytics/queries/21-simple-aggregation-explicit.json +6 -0
  208. data/ext/libcouchbase/example/analytics/queries/22-grouping-and-aggregation.json +6 -0
  209. data/ext/libcouchbase/example/analytics/queries/23-grouping-and-aggregation-with-hint.json +7 -0
  210. data/ext/libcouchbase/example/analytics/queries/24-grouping-and-limits.json +7 -0
  211. data/ext/libcouchbase/example/analytics/queries/25-named-parameters.json +7 -0
  212. data/ext/libcouchbase/example/analytics/queries/26-positional-parameters.json +7 -0
  213. data/ext/libcouchbase/example/analytics/queries.h +113 -0
  214. data/ext/libcouchbase/example/crypto/.gitignore +2 -0
  215. data/ext/libcouchbase/example/crypto/Makefile +13 -0
  216. data/ext/libcouchbase/example/crypto/common_provider.c +26 -0
  217. data/ext/libcouchbase/example/crypto/common_provider.h +33 -0
  218. data/ext/libcouchbase/example/crypto/openssl_symmetric_decrypt.c +144 -0
  219. data/ext/libcouchbase/example/crypto/openssl_symmetric_encrypt.c +146 -0
  220. data/ext/libcouchbase/example/crypto/openssl_symmetric_provider.c +271 -0
  221. data/ext/libcouchbase/example/crypto/openssl_symmetric_provider.h +29 -0
  222. data/ext/libcouchbase/example/db/db.c +171 -0
  223. data/ext/libcouchbase/example/db/vb.c +227 -0
  224. data/ext/libcouchbase/example/fts/.gitignore +1 -0
  225. data/ext/libcouchbase/example/fts/build-queries.rb +33 -0
  226. data/ext/libcouchbase/example/fts/fts.c +142 -0
  227. data/ext/libcouchbase/example/fts/queries/00-simple-text-query.json +12 -0
  228. data/ext/libcouchbase/example/fts/queries/01-simple-text-query-on-non-default-index.json +9 -0
  229. data/ext/libcouchbase/example/fts/queries/02-simple-text-query-on-stored-field.json +13 -0
  230. data/ext/libcouchbase/example/fts/queries/03-match-query-with-facet.json +19 -0
  231. data/ext/libcouchbase/example/fts/queries/04-docid-query.json +11 -0
  232. data/ext/libcouchbase/example/fts/queries/05-unanalyzed-term-query-with-fuzziness-level-of-0.json +13 -0
  233. data/ext/libcouchbase/example/fts/queries/06-unanalyzed-term-query-with-fuzziness-level-of-2.json +14 -0
  234. data/ext/libcouchbase/example/fts/queries/07-match-phrase-query.json +13 -0
  235. data/ext/libcouchbase/example/fts/queries/08-phrase-query.json +16 -0
  236. data/ext/libcouchbase/example/fts/queries/09-query-string-query.json +9 -0
  237. data/ext/libcouchbase/example/fts/queries/10-conjunction-query.json +21 -0
  238. data/ext/libcouchbase/example/fts/queries/11-wild-card-query.json +13 -0
  239. data/ext/libcouchbase/example/fts/queries/12-numeric-range-query.json +11 -0
  240. data/ext/libcouchbase/example/fts/queries/13-regexp-query.json +13 -0
  241. data/ext/libcouchbase/example/fts/queries.h +61 -0
  242. data/ext/libcouchbase/example/instancepool/main.cc +112 -0
  243. data/ext/libcouchbase/example/instancepool/pool.cc +102 -0
  244. data/ext/libcouchbase/example/instancepool/pool.h +69 -0
  245. data/ext/libcouchbase/example/libeventdirect/main.c +222 -0
  246. data/ext/libcouchbase/example/mcc/mcc.cc +246 -0
  247. data/ext/libcouchbase/example/minimal/.gitignore +1 -0
  248. data/ext/libcouchbase/example/minimal/minimal.c +132 -0
  249. data/ext/libcouchbase/example/minimal/query.c +185 -0
  250. data/ext/libcouchbase/example/observe/durability.c +102 -0
  251. data/ext/libcouchbase/example/observe/observe.c +159 -0
  252. data/ext/libcouchbase/example/subdoc/subdoc-multi.cc +143 -0
  253. data/ext/libcouchbase/example/subdoc/subdoc-simple.cc +201 -0
  254. data/ext/libcouchbase/example/subdoc/subdoc-xattrs.c +286 -0
  255. data/ext/libcouchbase/example/tick/tick.c +119 -0
  256. data/ext/libcouchbase/example/tracing/.gitignore +2 -0
  257. data/ext/libcouchbase/example/tracing/Makefile +8 -0
  258. data/ext/libcouchbase/example/tracing/cJSON.c +1 -0
  259. data/ext/libcouchbase/example/tracing/cJSON.h +1 -0
  260. data/ext/libcouchbase/example/tracing/tracing.c +439 -0
  261. data/ext/libcouchbase/example/tracing/views.c +444 -0
  262. data/ext/libcouchbase/example/users/README +48 -0
  263. data/ext/libcouchbase/example/users/users.c +147 -0
  264. data/ext/libcouchbase/example/views/views-example.cc +83 -0
  265. data/ext/libcouchbase/include/libcouchbase/_cxxwrap.h +150 -0
  266. data/ext/libcouchbase/include/libcouchbase/api-legacy.h +1689 -0
  267. data/ext/libcouchbase/include/libcouchbase/api3.h +2 -0
  268. data/ext/libcouchbase/include/libcouchbase/assert.h +44 -0
  269. data/ext/libcouchbase/include/libcouchbase/auth.h +297 -0
  270. data/ext/libcouchbase/include/libcouchbase/cbft.h +151 -0
  271. data/ext/libcouchbase/include/libcouchbase/cntl-private.h +319 -0
  272. data/ext/libcouchbase/include/libcouchbase/cntl.h +1418 -0
  273. data/ext/libcouchbase/include/libcouchbase/configuration.h.in +29 -0
  274. data/ext/libcouchbase/include/libcouchbase/couchbase.h +4089 -0
  275. data/ext/libcouchbase/include/libcouchbase/crypto.h +306 -0
  276. data/ext/libcouchbase/include/libcouchbase/deprecated.h +312 -0
  277. data/ext/libcouchbase/include/libcouchbase/error.h +680 -0
  278. data/ext/libcouchbase/include/libcouchbase/http.h +1 -0
  279. data/ext/libcouchbase/include/libcouchbase/iops.h +1053 -0
  280. data/ext/libcouchbase/include/libcouchbase/ixmgmt.h +263 -0
  281. data/ext/libcouchbase/include/libcouchbase/kvbuf.h +137 -0
  282. data/ext/libcouchbase/include/libcouchbase/metrics.h +79 -0
  283. data/ext/libcouchbase/include/libcouchbase/n1ql.h +539 -0
  284. data/ext/libcouchbase/include/libcouchbase/pktfwd.h +270 -0
  285. data/ext/libcouchbase/include/libcouchbase/plugins/io/bsdio-inl.c +370 -0
  286. data/ext/libcouchbase/include/libcouchbase/plugins/io/wsaerr-inl.c +76 -0
  287. data/ext/libcouchbase/include/libcouchbase/plugins/io/wsaerr.h +199 -0
  288. data/ext/libcouchbase/include/libcouchbase/subdoc.h +347 -0
  289. data/ext/libcouchbase/include/libcouchbase/sysdefs.h +98 -0
  290. data/ext/libcouchbase/include/libcouchbase/tracing.h +437 -0
  291. data/ext/libcouchbase/include/libcouchbase/vbucket.h +680 -0
  292. data/ext/libcouchbase/include/libcouchbase/views.h +357 -0
  293. data/ext/libcouchbase/include/libcouchbase/visibility.h +66 -0
  294. data/ext/libcouchbase/include/memcached/COPYING +30 -0
  295. data/ext/libcouchbase/include/memcached/README +10 -0
  296. data/ext/libcouchbase/include/memcached/protocol_binary.h +885 -0
  297. data/ext/libcouchbase/packaging/README +7 -0
  298. data/ext/libcouchbase/packaging/abicheck/.gitignore +4 -0
  299. data/ext/libcouchbase/packaging/abicheck/Makefile +17 -0
  300. data/ext/libcouchbase/packaging/abicheck/README.md +27 -0
  301. data/ext/libcouchbase/packaging/abicheck/template.xml +3 -0
  302. data/ext/libcouchbase/packaging/deb/compat +1 -0
  303. data/ext/libcouchbase/packaging/deb/control +72 -0
  304. data/ext/libcouchbase/packaging/deb/copyright +10 -0
  305. data/ext/libcouchbase/packaging/deb/libcouchbase-dev.docs +3 -0
  306. data/ext/libcouchbase/packaging/deb/package.mk +31 -0
  307. data/ext/libcouchbase/packaging/deb/rules +46 -0
  308. data/ext/libcouchbase/packaging/deb/source/format +1 -0
  309. data/ext/libcouchbase/packaging/distinfo/README +1 -0
  310. data/ext/libcouchbase/packaging/distinfo/distinfo.cmake.in +4 -0
  311. data/ext/libcouchbase/packaging/dllversion.rc.in +39 -0
  312. data/ext/libcouchbase/packaging/libcouchbase.pc.in +10 -0
  313. data/ext/libcouchbase/packaging/nuget/libcouchbase.autopkg +76 -0
  314. data/ext/libcouchbase/packaging/parse-git-describe.pl +166 -0
  315. data/ext/libcouchbase/packaging/rpm/libcouchbase.spec.in +101 -0
  316. data/ext/libcouchbase/packaging/rpm/package.mk +40 -0
  317. data/ext/libcouchbase/plugins/io/iocp/CMakeLists.txt +9 -0
  318. data/ext/libcouchbase/plugins/io/iocp/iocp_iops.c +467 -0
  319. data/ext/libcouchbase/plugins/io/iocp/iocp_iops.h +217 -0
  320. data/ext/libcouchbase/plugins/io/iocp/iocp_loop.c +295 -0
  321. data/ext/libcouchbase/plugins/io/iocp/iocp_timer.c +79 -0
  322. data/ext/libcouchbase/plugins/io/iocp/iocp_util.c +229 -0
  323. data/ext/libcouchbase/plugins/io/libev/CMakeLists.txt +31 -0
  324. data/ext/libcouchbase/plugins/io/libev/libev_io_opts.h +66 -0
  325. data/ext/libcouchbase/plugins/io/libev/plugin-libev.c +289 -0
  326. data/ext/libcouchbase/plugins/io/libevent/CMakeLists.txt +31 -0
  327. data/ext/libcouchbase/plugins/io/libevent/libevent_io_opts.h +67 -0
  328. data/ext/libcouchbase/plugins/io/libevent/plugin-libevent.c +292 -0
  329. data/ext/libcouchbase/plugins/io/libuv/CMakeLists.txt +44 -0
  330. data/ext/libcouchbase/plugins/io/libuv/libuv_compat.h +218 -0
  331. data/ext/libcouchbase/plugins/io/libuv/libuv_io_opts.h +118 -0
  332. data/ext/libcouchbase/plugins/io/libuv/plugin-internal.h +155 -0
  333. data/ext/libcouchbase/plugins/io/libuv/plugin-libuv.c +709 -0
  334. data/ext/libcouchbase/plugins/io/select/CMakeLists.txt +13 -0
  335. data/ext/libcouchbase/plugins/io/select/plugin-select.c +451 -0
  336. data/ext/libcouchbase/plugins/io/select/select_io_opts.h +39 -0
  337. data/ext/libcouchbase/src/README.md +101 -0
  338. data/ext/libcouchbase/src/aspend.h +105 -0
  339. data/ext/libcouchbase/src/auth-priv.h +85 -0
  340. data/ext/libcouchbase/src/auth.cc +146 -0
  341. data/ext/libcouchbase/src/bootstrap.cc +263 -0
  342. data/ext/libcouchbase/src/bootstrap.h +149 -0
  343. data/ext/libcouchbase/src/bucketconfig/bc_cccp.cc +450 -0
  344. data/ext/libcouchbase/src/bucketconfig/bc_file.cc +281 -0
  345. data/ext/libcouchbase/src/bucketconfig/bc_http.cc +527 -0
  346. data/ext/libcouchbase/src/bucketconfig/bc_http.h +107 -0
  347. data/ext/libcouchbase/src/bucketconfig/bc_static.cc +150 -0
  348. data/ext/libcouchbase/src/bucketconfig/clconfig.h +700 -0
  349. data/ext/libcouchbase/src/bucketconfig/confmon.cc +403 -0
  350. data/ext/libcouchbase/src/callbacks.c +380 -0
  351. data/ext/libcouchbase/src/cbft.cc +253 -0
  352. data/ext/libcouchbase/src/cntl.cc +1057 -0
  353. data/ext/libcouchbase/src/config_static.h +176 -0
  354. data/ext/libcouchbase/src/connspec.cc +555 -0
  355. data/ext/libcouchbase/src/connspec.h +155 -0
  356. data/ext/libcouchbase/src/crypto.cc +399 -0
  357. data/ext/libcouchbase/src/ctx-log-inl.h +44 -0
  358. data/ext/libcouchbase/src/dns-srv.cc +146 -0
  359. data/ext/libcouchbase/src/dump.cc +103 -0
  360. data/ext/libcouchbase/src/errmap.cc +173 -0
  361. data/ext/libcouchbase/src/errmap.h +271 -0
  362. data/ext/libcouchbase/src/getconfig.cc +72 -0
  363. data/ext/libcouchbase/src/gethrtime.c +109 -0
  364. data/ext/libcouchbase/src/handler.cc +1101 -0
  365. data/ext/libcouchbase/src/hashtable.c +75 -0
  366. data/ext/libcouchbase/src/hdr_timings.c +92 -0
  367. data/ext/libcouchbase/src/hostlist.cc +293 -0
  368. data/ext/libcouchbase/src/hostlist.h +160 -0
  369. data/ext/libcouchbase/src/http/http-priv.h +326 -0
  370. data/ext/libcouchbase/src/http/http.cc +672 -0
  371. data/ext/libcouchbase/src/http/http.h +1 -0
  372. data/ext/libcouchbase/src/http/http_io.cc +316 -0
  373. data/ext/libcouchbase/src/instance.cc +917 -0
  374. data/ext/libcouchbase/src/internal.h +285 -0
  375. data/ext/libcouchbase/src/iofactory.c +575 -0
  376. data/ext/libcouchbase/src/jsparse/parser.cc +445 -0
  377. data/ext/libcouchbase/src/jsparse/parser.h +159 -0
  378. data/ext/libcouchbase/src/lcbht/lcbht.cc +177 -0
  379. data/ext/libcouchbase/src/lcbht/lcbht.h +210 -0
  380. data/ext/libcouchbase/src/lcbio/connect.cc +603 -0
  381. data/ext/libcouchbase/src/lcbio/connect.h +400 -0
  382. data/ext/libcouchbase/src/lcbio/ctx.c +658 -0
  383. data/ext/libcouchbase/src/lcbio/ctx.h +405 -0
  384. data/ext/libcouchbase/src/lcbio/iotable.c +290 -0
  385. data/ext/libcouchbase/src/lcbio/iotable.h +169 -0
  386. data/ext/libcouchbase/src/lcbio/ioutils.cc +356 -0
  387. data/ext/libcouchbase/src/lcbio/ioutils.h +144 -0
  388. data/ext/libcouchbase/src/lcbio/lcbio.h +51 -0
  389. data/ext/libcouchbase/src/lcbio/manager.cc +579 -0
  390. data/ext/libcouchbase/src/lcbio/manager.h +195 -0
  391. data/ext/libcouchbase/src/lcbio/protoctx.c +84 -0
  392. data/ext/libcouchbase/src/lcbio/rw-inl.h +137 -0
  393. data/ext/libcouchbase/src/lcbio/ssl.h +159 -0
  394. data/ext/libcouchbase/src/lcbio/timer-cxx.h +87 -0
  395. data/ext/libcouchbase/src/lcbio/timer-ng.h +179 -0
  396. data/ext/libcouchbase/src/lcbio/timer.c +132 -0
  397. data/ext/libcouchbase/src/legacy.c +431 -0
  398. data/ext/libcouchbase/src/list.c +144 -0
  399. data/ext/libcouchbase/src/list.h +127 -0
  400. data/ext/libcouchbase/src/logging.c +244 -0
  401. data/ext/libcouchbase/src/logging.h +88 -0
  402. data/ext/libcouchbase/src/mc/compress.cc +171 -0
  403. data/ext/libcouchbase/src/mc/compress.h +56 -0
  404. data/ext/libcouchbase/src/mc/forward.c +186 -0
  405. data/ext/libcouchbase/src/mc/forward.h +90 -0
  406. data/ext/libcouchbase/src/mc/iovcursor-inl.h +279 -0
  407. data/ext/libcouchbase/src/mc/iovcursor.h +66 -0
  408. data/ext/libcouchbase/src/mc/mcreq-flush-inl.h +115 -0
  409. data/ext/libcouchbase/src/mc/mcreq.c +983 -0
  410. data/ext/libcouchbase/src/mc/mcreq.h +1015 -0
  411. data/ext/libcouchbase/src/mcserver/mcserver.cc +1055 -0
  412. data/ext/libcouchbase/src/mcserver/mcserver.h +221 -0
  413. data/ext/libcouchbase/src/mcserver/negotiate.cc +757 -0
  414. data/ext/libcouchbase/src/mcserver/negotiate.h +128 -0
  415. data/ext/libcouchbase/src/mctx-helper.h +62 -0
  416. data/ext/libcouchbase/src/metrics.cc +132 -0
  417. data/ext/libcouchbase/src/n1ql/ixmgmt.cc +857 -0
  418. data/ext/libcouchbase/src/n1ql/n1ql-internal.h +22 -0
  419. data/ext/libcouchbase/src/n1ql/n1ql.cc +830 -0
  420. data/ext/libcouchbase/src/n1ql/params.cc +260 -0
  421. data/ext/libcouchbase/src/netbuf/netbuf-defs.h +89 -0
  422. data/ext/libcouchbase/src/netbuf/netbuf-mblock.h +235 -0
  423. data/ext/libcouchbase/src/netbuf/netbuf.c +929 -0
  424. data/ext/libcouchbase/src/netbuf/netbuf.h +452 -0
  425. data/ext/libcouchbase/src/newconfig.cc +365 -0
  426. data/ext/libcouchbase/src/nodeinfo.cc +184 -0
  427. data/ext/libcouchbase/src/operations/cbflush.cc +63 -0
  428. data/ext/libcouchbase/src/operations/counter.cc +117 -0
  429. data/ext/libcouchbase/src/operations/durability-cas.cc +251 -0
  430. data/ext/libcouchbase/src/operations/durability-seqno.cc +170 -0
  431. data/ext/libcouchbase/src/operations/durability.cc +668 -0
  432. data/ext/libcouchbase/src/operations/durability_internal.h +306 -0
  433. data/ext/libcouchbase/src/operations/get.cc +409 -0
  434. data/ext/libcouchbase/src/operations/observe-seqno.cc +94 -0
  435. data/ext/libcouchbase/src/operations/observe.cc +367 -0
  436. data/ext/libcouchbase/src/operations/ping.cc +496 -0
  437. data/ext/libcouchbase/src/operations/pktfwd.cc +86 -0
  438. data/ext/libcouchbase/src/operations/remove.cc +84 -0
  439. data/ext/libcouchbase/src/operations/stats.cc +459 -0
  440. data/ext/libcouchbase/src/operations/store.cc +358 -0
  441. data/ext/libcouchbase/src/operations/subdoc.cc +614 -0
  442. data/ext/libcouchbase/src/operations/touch.cc +84 -0
  443. data/ext/libcouchbase/src/packetutils.h +388 -0
  444. data/ext/libcouchbase/src/probes.d +182 -0
  445. data/ext/libcouchbase/src/rdb/bigalloc.c +225 -0
  446. data/ext/libcouchbase/src/rdb/bigalloc.h +73 -0
  447. data/ext/libcouchbase/src/rdb/chunkalloc.c +174 -0
  448. data/ext/libcouchbase/src/rdb/libcalloc.c +94 -0
  449. data/ext/libcouchbase/src/rdb/rope.c +419 -0
  450. data/ext/libcouchbase/src/rdb/rope.h +488 -0
  451. data/ext/libcouchbase/src/retrychk.cc +113 -0
  452. data/ext/libcouchbase/src/retryq.cc +458 -0
  453. data/ext/libcouchbase/src/retryq.h +170 -0
  454. data/ext/libcouchbase/src/ringbuffer.c +442 -0
  455. data/ext/libcouchbase/src/ringbuffer.h +100 -0
  456. data/ext/libcouchbase/src/rnd.cc +61 -0
  457. data/ext/libcouchbase/src/rnd.h +39 -0
  458. data/ext/libcouchbase/src/settings.c +125 -0
  459. data/ext/libcouchbase/src/settings.h +273 -0
  460. data/ext/libcouchbase/src/sllist-inl.h +197 -0
  461. data/ext/libcouchbase/src/sllist.h +76 -0
  462. data/ext/libcouchbase/src/ssl/CMakeLists.txt +11 -0
  463. data/ext/libcouchbase/src/ssl/ssl_c.c +442 -0
  464. data/ext/libcouchbase/src/ssl/ssl_common.c +478 -0
  465. data/ext/libcouchbase/src/ssl/ssl_e.c +421 -0
  466. data/ext/libcouchbase/src/ssl/ssl_iot_common.h +182 -0
  467. data/ext/libcouchbase/src/strcodecs/base64.c +307 -0
  468. data/ext/libcouchbase/src/strcodecs/strcodecs.h +302 -0
  469. data/ext/libcouchbase/src/timings.c +207 -0
  470. data/ext/libcouchbase/src/trace.h +117 -0
  471. data/ext/libcouchbase/src/tracing/span.cc +421 -0
  472. data/ext/libcouchbase/src/tracing/threshold_logging_tracer.cc +213 -0
  473. data/ext/libcouchbase/src/tracing/tracer.cc +53 -0
  474. data/ext/libcouchbase/src/tracing/tracing-internal.h +198 -0
  475. data/ext/libcouchbase/src/utilities.c +176 -0
  476. data/ext/libcouchbase/src/vbucket/CMakeLists.txt +2 -0
  477. data/ext/libcouchbase/src/vbucket/aliases.h +35 -0
  478. data/ext/libcouchbase/src/vbucket/crc32.h +83 -0
  479. data/ext/libcouchbase/src/vbucket/hash.h +30 -0
  480. data/ext/libcouchbase/src/vbucket/json-inl.h +112 -0
  481. data/ext/libcouchbase/src/vbucket/ketama.c +66 -0
  482. data/ext/libcouchbase/src/vbucket/rfc1321/global.h +32 -0
  483. data/ext/libcouchbase/src/vbucket/rfc1321/md5.h +35 -0
  484. data/ext/libcouchbase/src/vbucket/rfc1321/md5c-inl.h +335 -0
  485. data/ext/libcouchbase/src/vbucket/vbucket.c +1735 -0
  486. data/ext/libcouchbase/src/views/docreq.cc +213 -0
  487. data/ext/libcouchbase/src/views/docreq.h +94 -0
  488. data/ext/libcouchbase/src/views/viewreq.cc +381 -0
  489. data/ext/libcouchbase/src/views/viewreq.h +87 -0
  490. data/ext/libcouchbase/src/wait.cc +156 -0
  491. data/ext/libcouchbase/tests/CMakeLists.txt +149 -0
  492. data/ext/libcouchbase/tests/basic/t_base64.cc +109 -0
  493. data/ext/libcouchbase/tests/basic/t_ccbc103.cc +95 -0
  494. data/ext/libcouchbase/tests/basic/t_connstr.cc +456 -0
  495. data/ext/libcouchbase/tests/basic/t_creds.cc +96 -0
  496. data/ext/libcouchbase/tests/basic/t_ctlcodes.cc +92 -0
  497. data/ext/libcouchbase/tests/basic/t_host.cc +210 -0
  498. data/ext/libcouchbase/tests/basic/t_jsparse.cc +82 -0
  499. data/ext/libcouchbase/tests/basic/t_jsparse.h +589 -0
  500. data/ext/libcouchbase/tests/basic/t_list.cc +155 -0
  501. data/ext/libcouchbase/tests/basic/t_logger.cc +65 -0
  502. data/ext/libcouchbase/tests/basic/t_misc.cc +24 -0
  503. data/ext/libcouchbase/tests/basic/t_n1qlstrings.cc +17 -0
  504. data/ext/libcouchbase/tests/basic/t_netbuf.cc +446 -0
  505. data/ext/libcouchbase/tests/basic/t_packet.cc +215 -0
  506. data/ext/libcouchbase/tests/basic/t_ringbuffer.cc +278 -0
  507. data/ext/libcouchbase/tests/basic/t_scram.cc +514 -0
  508. data/ext/libcouchbase/tests/basic/t_slist.cc +429 -0
  509. data/ext/libcouchbase/tests/basic/t_strerror.cc +64 -0
  510. data/ext/libcouchbase/tests/basic/t_urlencode.cc +132 -0
  511. data/ext/libcouchbase/tests/check-all.cc +612 -0
  512. data/ext/libcouchbase/tests/htparse/t_basic.cc +173 -0
  513. data/ext/libcouchbase/tests/ioserver/connection.cc +166 -0
  514. data/ext/libcouchbase/tests/ioserver/future.cc +50 -0
  515. data/ext/libcouchbase/tests/ioserver/ioserver.cc +117 -0
  516. data/ext/libcouchbase/tests/ioserver/ioserver.h +478 -0
  517. data/ext/libcouchbase/tests/ioserver/socket.cc +88 -0
  518. data/ext/libcouchbase/tests/ioserver/ssl_connection.cc +145 -0
  519. data/ext/libcouchbase/tests/ioserver/threads-pthreads.cc +119 -0
  520. data/ext/libcouchbase/tests/ioserver/threads-win32.cc +117 -0
  521. data/ext/libcouchbase/tests/ioserver/threads.h +66 -0
  522. data/ext/libcouchbase/tests/iotests/iotests.h +15 -0
  523. data/ext/libcouchbase/tests/iotests/mock-environment.cc +632 -0
  524. data/ext/libcouchbase/tests/iotests/mock-environment.h +480 -0
  525. data/ext/libcouchbase/tests/iotests/mock-unit-test.cc +67 -0
  526. data/ext/libcouchbase/tests/iotests/mock-unit-test.h +61 -0
  527. data/ext/libcouchbase/tests/iotests/serverparams.h +76 -0
  528. data/ext/libcouchbase/tests/iotests/t_arithmetic.cc +143 -0
  529. data/ext/libcouchbase/tests/iotests/t_behavior.cc +220 -0
  530. data/ext/libcouchbase/tests/iotests/t_configcache.cc +117 -0
  531. data/ext/libcouchbase/tests/iotests/t_confmon.cc +223 -0
  532. data/ext/libcouchbase/tests/iotests/t_durability.cc +1108 -0
  533. data/ext/libcouchbase/tests/iotests/t_eerrs.cc +121 -0
  534. data/ext/libcouchbase/tests/iotests/t_errmap.cc +181 -0
  535. data/ext/libcouchbase/tests/iotests/t_forward.cc +118 -0
  536. data/ext/libcouchbase/tests/iotests/t_get.cc +512 -0
  537. data/ext/libcouchbase/tests/iotests/t_http.cc +438 -0
  538. data/ext/libcouchbase/tests/iotests/t_iops.cc +175 -0
  539. data/ext/libcouchbase/tests/iotests/t_lock.cc +274 -0
  540. data/ext/libcouchbase/tests/iotests/t_misc.cc +777 -0
  541. data/ext/libcouchbase/tests/iotests/t_mutate.cc +609 -0
  542. data/ext/libcouchbase/tests/iotests/t_n1ql.cc +270 -0
  543. data/ext/libcouchbase/tests/iotests/t_netfail.cc +778 -0
  544. data/ext/libcouchbase/tests/iotests/t_obseqno.cc +156 -0
  545. data/ext/libcouchbase/tests/iotests/t_regression.cc +321 -0
  546. data/ext/libcouchbase/tests/iotests/t_sched.cc +87 -0
  547. data/ext/libcouchbase/tests/iotests/t_serverops.cc +231 -0
  548. data/ext/libcouchbase/tests/iotests/t_smoke.cc +528 -0
  549. data/ext/libcouchbase/tests/iotests/t_snappy.cc +316 -0
  550. data/ext/libcouchbase/tests/iotests/t_subdoc.cc +857 -0
  551. data/ext/libcouchbase/tests/iotests/t_syncmode.cc +64 -0
  552. data/ext/libcouchbase/tests/iotests/t_views.cc +417 -0
  553. data/ext/libcouchbase/tests/iotests/testutil.cc +251 -0
  554. data/ext/libcouchbase/tests/iotests/testutil.h +163 -0
  555. data/ext/libcouchbase/tests/mc/mctest.h +119 -0
  556. data/ext/libcouchbase/tests/mc/pktmaker.h +101 -0
  557. data/ext/libcouchbase/tests/mc/t_alloc.cc +269 -0
  558. data/ext/libcouchbase/tests/mc/t_context.cc +100 -0
  559. data/ext/libcouchbase/tests/mc/t_flush.cc +185 -0
  560. data/ext/libcouchbase/tests/mc/t_forward.cc +239 -0
  561. data/ext/libcouchbase/tests/mc/t_ioflush.cc +102 -0
  562. data/ext/libcouchbase/tests/mc/t_iovcursor.cc +173 -0
  563. data/ext/libcouchbase/tests/mocksupport/procutil.c +305 -0
  564. data/ext/libcouchbase/tests/mocksupport/procutil.h +89 -0
  565. data/ext/libcouchbase/tests/mocksupport/server.c +391 -0
  566. data/ext/libcouchbase/tests/mocksupport/server.h +72 -0
  567. data/ext/libcouchbase/tests/mocksupport/timeout.c +69 -0
  568. data/ext/libcouchbase/tests/nonio_tests.cc +23 -0
  569. data/ext/libcouchbase/tests/rdb/rdbtest.h +133 -0
  570. data/ext/libcouchbase/tests/rdb/t_basic.cc +128 -0
  571. data/ext/libcouchbase/tests/rdb/t_bigalloc.cc +93 -0
  572. data/ext/libcouchbase/tests/rdb/t_refs.cc +112 -0
  573. data/ext/libcouchbase/tests/socktests/socktest.cc +344 -0
  574. data/ext/libcouchbase/tests/socktests/socktest.h +447 -0
  575. data/ext/libcouchbase/tests/socktests/t_basic.cc +143 -0
  576. data/ext/libcouchbase/tests/socktests/t_ctx.cc +73 -0
  577. data/ext/libcouchbase/tests/socktests/t_manager.cc +159 -0
  578. data/ext/libcouchbase/tests/socktests/t_putex.cc +256 -0
  579. data/ext/libcouchbase/tests/socktests/t_read.cc +187 -0
  580. data/ext/libcouchbase/tests/socktests/t_reentrant.cc +143 -0
  581. data/ext/libcouchbase/tests/socktests/t_ssl.cc +80 -0
  582. data/ext/libcouchbase/tests/socktests/t_write.cc +95 -0
  583. data/ext/libcouchbase/tests/start_mock.bat +15 -0
  584. data/ext/libcouchbase/tests/start_mock.sh +42 -0
  585. data/ext/libcouchbase/tests/unit_tests.cc +43 -0
  586. data/ext/libcouchbase/tests/vbucket/confdata/bad.json +101 -0
  587. data/ext/libcouchbase/tests/vbucket/confdata/full_25.json +363 -0
  588. data/ext/libcouchbase/tests/vbucket/confdata/ketama_expected.json +2562 -0
  589. data/ext/libcouchbase/tests/vbucket/confdata/map_node_present_nodesext_missing_nodes.json +94 -0
  590. data/ext/libcouchbase/tests/vbucket/confdata/memd_25.json +90 -0
  591. data/ext/libcouchbase/tests/vbucket/confdata/memd_30.json +1 -0
  592. data/ext/libcouchbase/tests/vbucket/confdata/memd_45.json +1 -0
  593. data/ext/libcouchbase/tests/vbucket/confdata/memd_ketama_config.json +31 -0
  594. data/ext/libcouchbase/tests/vbucket/confdata/terse_25.json +291 -0
  595. data/ext/libcouchbase/tests/vbucket/confdata/terse_30.json +1 -0
  596. data/ext/libcouchbase/tests/vbucket/t_config.cc +386 -0
  597. data/ext/libcouchbase/tools/CMakeLists.txt +80 -0
  598. data/ext/libcouchbase/tools/cbc-handlers.h +636 -0
  599. data/ext/libcouchbase/tools/cbc-n1qlback.cc +496 -0
  600. data/ext/libcouchbase/tools/cbc-pillowfight.cc +1230 -0
  601. data/ext/libcouchbase/tools/cbc-proxy.cc +534 -0
  602. data/ext/libcouchbase/tools/cbc-subdoc.cc +825 -0
  603. data/ext/libcouchbase/tools/cbc.cc +1928 -0
  604. data/ext/libcouchbase/tools/common/histogram.cc +44 -0
  605. data/ext/libcouchbase/tools/common/histogram.h +23 -0
  606. data/ext/libcouchbase/tools/common/options.cc +451 -0
  607. data/ext/libcouchbase/tools/common/options.h +90 -0
  608. data/ext/libcouchbase/tools/docgen/docgen.h +495 -0
  609. data/ext/libcouchbase/tools/docgen/loc.h +211 -0
  610. data/ext/libcouchbase/tools/docgen/placeholders.h +211 -0
  611. data/ext/libcouchbase/tools/docgen/seqgen.h +122 -0
  612. data/ext/libcouchbase/tools/extract-packets.rb +110 -0
  613. data/ext/libcouchbase/tools/linenoise/linenoise.c +1199 -0
  614. data/ext/libcouchbase/tools/linenoise/linenoise.h +73 -0
  615. data/lib/mt-libcouchbase/bucket.rb +825 -0
  616. data/lib/mt-libcouchbase/callbacks.rb +69 -0
  617. data/lib/mt-libcouchbase/connection.rb +896 -0
  618. data/lib/mt-libcouchbase/design_docs.rb +92 -0
  619. data/lib/mt-libcouchbase/error.rb +68 -0
  620. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdbase.rb +23 -0
  621. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdcounter.rb +36 -0
  622. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdendure.rb +26 -0
  623. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdfts.rb +24 -0
  624. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdget.rb +30 -0
  625. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdgetreplica.rb +49 -0
  626. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdhttp.rb +58 -0
  627. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdn1ql.rb +40 -0
  628. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdobseqno.rb +33 -0
  629. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdobserve.rb +30 -0
  630. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdstore.rb +40 -0
  631. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdstoredur.rb +45 -0
  632. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdsubdoc.rb +61 -0
  633. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdverbosity.rb +29 -0
  634. data/lib/mt-libcouchbase/ext/mt-libcouchbase/cmdviewquery.rb +61 -0
  635. data/lib/mt-libcouchbase/ext/mt-libcouchbase/contigbuf.rb +14 -0
  636. data/lib/mt-libcouchbase/ext/mt-libcouchbase/create_st.rb +15 -0
  637. data/lib/mt-libcouchbase/ext/mt-libcouchbase/create_st0.rb +23 -0
  638. data/lib/mt-libcouchbase/ext/mt-libcouchbase/create_st1.rb +26 -0
  639. data/lib/mt-libcouchbase/ext/mt-libcouchbase/create_st2.rb +32 -0
  640. data/lib/mt-libcouchbase/ext/mt-libcouchbase/create_st3.rb +26 -0
  641. data/lib/mt-libcouchbase/ext/mt-libcouchbase/crst_u.rb +20 -0
  642. data/lib/mt-libcouchbase/ext/mt-libcouchbase/durability_opts_st_v.rb +11 -0
  643. data/lib/mt-libcouchbase/ext/mt-libcouchbase/durability_opts_t.rb +14 -0
  644. data/lib/mt-libcouchbase/ext/mt-libcouchbase/durabilityopt_sv0.rb +63 -0
  645. data/lib/mt-libcouchbase/ext/mt-libcouchbase/enums.rb +1007 -0
  646. data/lib/mt-libcouchbase/ext/mt-libcouchbase/fragbuf.rb +18 -0
  647. data/lib/mt-libcouchbase/ext/mt-libcouchbase/ftshandle.rb +7 -0
  648. data/lib/mt-libcouchbase/ext/mt-libcouchbase/histogram.rb +34 -0
  649. data/lib/mt-libcouchbase/ext/mt-libcouchbase/http_request_t.rb +7 -0
  650. data/lib/mt-libcouchbase/ext/mt-libcouchbase/keybuf.rb +20 -0
  651. data/lib/mt-libcouchbase/ext/mt-libcouchbase/multicmd_ctx.rb +30 -0
  652. data/lib/mt-libcouchbase/ext/mt-libcouchbase/mutation_token.rb +17 -0
  653. data/lib/mt-libcouchbase/ext/mt-libcouchbase/n1qlhandle.rb +7 -0
  654. data/lib/mt-libcouchbase/ext/mt-libcouchbase/n1qlparams.rb +7 -0
  655. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respbase.rb +29 -0
  656. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respcounter.rb +32 -0
  657. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respendure.rb +49 -0
  658. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respfts.rb +40 -0
  659. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respget.rb +44 -0
  660. data/lib/mt-libcouchbase/ext/mt-libcouchbase/resphttp.rb +48 -0
  661. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respmcversion.rb +38 -0
  662. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respn1ql.rb +41 -0
  663. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respobseqno.rb +52 -0
  664. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respobserve.rb +41 -0
  665. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respserverbase.rb +32 -0
  666. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respstats.rb +38 -0
  667. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respstore.rb +32 -0
  668. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respstoredur.rb +38 -0
  669. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respsubdoc.rb +35 -0
  670. data/lib/mt-libcouchbase/ext/mt-libcouchbase/respviewquery.rb +67 -0
  671. data/lib/mt-libcouchbase/ext/mt-libcouchbase/sdentry.rb +22 -0
  672. data/lib/mt-libcouchbase/ext/mt-libcouchbase/sdspec.rb +31 -0
  673. data/lib/mt-libcouchbase/ext/mt-libcouchbase/t.rb +7 -0
  674. data/lib/mt-libcouchbase/ext/mt-libcouchbase/valbuf.rb +22 -0
  675. data/lib/mt-libcouchbase/ext/mt-libcouchbase/valbuf_u_buf.rb +14 -0
  676. data/lib/mt-libcouchbase/ext/mt-libcouchbase/viewhandle.rb +7 -0
  677. data/lib/mt-libcouchbase/ext/mt-libcouchbase.rb +1175 -0
  678. data/lib/mt-libcouchbase/ext/mt-libcouchbase_libuv.rb +22 -0
  679. data/lib/mt-libcouchbase/ext/tasks.rb +39 -0
  680. data/lib/mt-libcouchbase/n1ql.rb +80 -0
  681. data/lib/mt-libcouchbase/query_full_text.rb +147 -0
  682. data/lib/mt-libcouchbase/query_n1ql.rb +123 -0
  683. data/lib/mt-libcouchbase/query_view.rb +135 -0
  684. data/lib/mt-libcouchbase/results_fiber.rb +281 -0
  685. data/lib/mt-libcouchbase/results_native.rb +220 -0
  686. data/lib/mt-libcouchbase/subdoc_request.rb +139 -0
  687. data/lib/mt-libcouchbase/version.rb +5 -0
  688. data/lib/mt-libcouchbase.rb +40 -0
  689. data/mt-libcouchbase.gemspec +68 -0
  690. data/spec/bucket_spec.rb +290 -0
  691. data/spec/connection_spec.rb +257 -0
  692. data/spec/design_docs_spec.rb +31 -0
  693. data/spec/error_spec.rb +26 -0
  694. data/spec/fts_spec.rb +135 -0
  695. data/spec/n1ql_spec.rb +260 -0
  696. data/spec/results_libuv_spec.rb +244 -0
  697. data/spec/results_native_spec.rb +259 -0
  698. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/design.json +1 -0
  699. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/node-127.0.0.1%3A8091/data-0000.cbb +0 -0
  700. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/node-127.0.0.1%3A8091/failover.json +1 -0
  701. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/node-127.0.0.1%3A8091/meta.json +1 -0
  702. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/node-127.0.0.1%3A8091/seqno.json +1 -0
  703. data/spec/seed/2016-10-25T043505Z/2016-10-25T043505Z-full/bucket-default/node-127.0.0.1%3A8091/snapshot_markers.json +1 -0
  704. data/spec/subdoc_spec.rb +192 -0
  705. data/spec/view_spec.rb +201 -0
  706. data/windows_build.md +36 -0
  707. metadata +873 -0
@@ -0,0 +1,4893 @@
1
+ /// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
2
+ /// It is intended to be used with #include "lcb-jsoncpp.h"
3
+
4
+ // //////////////////////////////////////////////////////////////////////
5
+ // Beginning of content of file: LICENSE
6
+ // //////////////////////////////////////////////////////////////////////
7
+
8
+ /*
9
+ The JsonCpp library's source code, including accompanying documentation,
10
+ tests and demonstration applications, are licensed under the following
11
+ conditions...
12
+
13
+ The author (Baptiste Lepilleur) explicitly disclaims copyright in all
14
+ jurisdictions which recognize such a disclaimer. In such jurisdictions,
15
+ this software is released into the Public Domain.
16
+
17
+ In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
18
+ 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
19
+ released under the terms of the MIT License (see below).
20
+
21
+ In jurisdictions which recognize Public Domain property, the user of this
22
+ software may choose to accept it either as 1) Public Domain, 2) under the
23
+ conditions of the MIT License (see below), or 3) under the terms of dual
24
+ Public Domain/MIT License conditions described here, as they choose.
25
+
26
+ The MIT License is about as close to Public Domain as a license can get, and is
27
+ described in clear, concise terms at:
28
+
29
+ http://en.wikipedia.org/wiki/MIT_License
30
+
31
+ The full text of the MIT License follows:
32
+
33
+ ========================================================================
34
+ Copyright (c) 2007-2010 Baptiste Lepilleur
35
+
36
+ Permission is hereby granted, free of charge, to any person
37
+ obtaining a copy of this software and associated documentation
38
+ files (the "Software"), to deal in the Software without
39
+ restriction, including without limitation the rights to use, copy,
40
+ modify, merge, publish, distribute, sublicense, and/or sell copies
41
+ of the Software, and to permit persons to whom the Software is
42
+ furnished to do so, subject to the following conditions:
43
+
44
+ The above copyright notice and this permission notice shall be
45
+ included in all copies or substantial portions of the Software.
46
+
47
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
50
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
51
+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
52
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
53
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54
+ SOFTWARE.
55
+ ========================================================================
56
+ (END LICENSE TEXT)
57
+
58
+ The MIT license is compatible with both the GPL and commercial
59
+ software, affording one all of the rights of Public Domain with the
60
+ minor nuisance of being required to keep the above copyright notice
61
+ and license text in the source code. Note also that by accepting the
62
+ Public Domain "license" you can re-license your copy using whatever
63
+ license you like.
64
+
65
+ */
66
+
67
+ // //////////////////////////////////////////////////////////////////////
68
+ // End of content of file: LICENSE
69
+ // //////////////////////////////////////////////////////////////////////
70
+
71
+
72
+
73
+
74
+
75
+
76
+ #include "lcb-jsoncpp.h"
77
+
78
+ #ifndef JSON_IS_AMALGAMATION
79
+ #error "Compile with -I PATH_TO_JSON_DIRECTORY"
80
+ #endif
81
+
82
+
83
+ // //////////////////////////////////////////////////////////////////////
84
+ // Beginning of content of file: src/lib_json/json_tool.h
85
+ // //////////////////////////////////////////////////////////////////////
86
+
87
+ // Copyright 2007-2010 Baptiste Lepilleur
88
+ // Distributed under MIT license, or public domain if desired and
89
+ // recognized in your jurisdiction.
90
+ // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
91
+
92
+ #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
93
+ #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
94
+
95
+ /* This header provides common string manipulation support, such as UTF-8,
96
+ * portable conversion from/to string...
97
+ *
98
+ * It is an internal header that must not be exposed.
99
+ */
100
+
101
+ namespace Json {
102
+
103
+ /// Converts a unicode code-point to UTF-8.
104
+ static inline std::string codePointToUTF8(unsigned int cp) {
105
+ std::string result;
106
+
107
+ // based on description from http://en.wikipedia.org/wiki/UTF-8
108
+
109
+ if (cp <= 0x7f) {
110
+ result.resize(1);
111
+ result[0] = static_cast<char>(cp);
112
+ } else if (cp <= 0x7FF) {
113
+ result.resize(2);
114
+ result[1] = static_cast<char>(0x80 | (0x3f & cp));
115
+ result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
116
+ } else if (cp <= 0xFFFF) {
117
+ result.resize(3);
118
+ result[2] = static_cast<char>(0x80 | (0x3f & cp));
119
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
120
+ result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
121
+ } else if (cp <= 0x10FFFF) {
122
+ result.resize(4);
123
+ result[3] = static_cast<char>(0x80 | (0x3f & cp));
124
+ result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
125
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
126
+ result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
127
+ }
128
+
129
+ return result;
130
+ }
131
+
132
+ /// Returns true if ch is a control character (in range [1,31]).
133
+ static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
134
+
135
+ enum {
136
+ /// Constant that specify the size of the buffer that must be passed to
137
+ /// uintToString.
138
+ uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
139
+ };
140
+
141
+ // Defines a char buffer for use with uintToString().
142
+ typedef char UIntToStringBuffer[uintToStringBufferSize];
143
+
144
+ /** Converts an unsigned integer to string.
145
+ * @param value Unsigned interger to convert to string
146
+ * @param current Input/Output string buffer.
147
+ * Must have at least uintToStringBufferSize chars free.
148
+ */
149
+ static inline void uintToString(LargestUInt value, char*& current) {
150
+ *--current = 0;
151
+ do {
152
+ *--current = static_cast<signed char>(value % 10U + static_cast<unsigned>('0'));
153
+ value /= 10;
154
+ } while (value != 0);
155
+ }
156
+
157
+ /** Change ',' to '.' everywhere in buffer.
158
+ *
159
+ * We had a sophisticated way, but it did not work in WinCE.
160
+ * @see https://github.com/open-source-parsers/jsoncpp/pull/9
161
+ */
162
+ static inline void fixNumericLocale(char* begin, char* end) {
163
+ while (begin < end) {
164
+ if (*begin == ',') {
165
+ *begin = '.';
166
+ }
167
+ ++begin;
168
+ }
169
+ }
170
+
171
+ } // namespace Json {
172
+
173
+ #endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
174
+
175
+ // //////////////////////////////////////////////////////////////////////
176
+ // End of content of file: src/lib_json/json_tool.h
177
+ // //////////////////////////////////////////////////////////////////////
178
+
179
+
180
+
181
+
182
+
183
+
184
+ // //////////////////////////////////////////////////////////////////////
185
+ // Beginning of content of file: src/lib_json/json_reader.cpp
186
+ // //////////////////////////////////////////////////////////////////////
187
+
188
+ // Copyright 2007-2011 Baptiste Lepilleur
189
+ // Distributed under MIT license, or public domain if desired and
190
+ // recognized in your jurisdiction.
191
+ // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
192
+
193
+ #if !defined(JSON_IS_AMALGAMATION)
194
+ #include <json/assertions.h>
195
+ #include <json/reader.h>
196
+ #include <json/value.h>
197
+ #include "json_tool.h"
198
+ #endif // if !defined(JSON_IS_AMALGAMATION)
199
+ #include <utility>
200
+ #include <cstdio>
201
+ #include <cassert>
202
+ #include <cstring>
203
+ #include <istream>
204
+ #include <sstream>
205
+ #include <memory>
206
+ #include <set>
207
+
208
+ #if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
209
+ #define snprintf _snprintf
210
+ #endif
211
+
212
+ #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
213
+ // Disable warning about strdup being deprecated.
214
+ #pragma warning(disable : 4996)
215
+ #endif
216
+
217
+ static int const stackLimit_g = 1000;
218
+ static int stackDepth_g = 0; // see readValue()
219
+
220
+ namespace Json {
221
+
222
+ typedef std::auto_ptr<CharReader> CharReaderPtr;
223
+
224
+ // Implementation of class Features
225
+ // ////////////////////////////////
226
+
227
+ Features::Features()
228
+ : allowComments_(true), strictRoot_(false)
229
+ {}
230
+ Features Features::all() { return Features(); }
231
+
232
+ Features Features::strictMode() {
233
+ Features features;
234
+ features.allowComments_ = false;
235
+ features.strictRoot_ = true;
236
+ return features;
237
+ }
238
+
239
+ // Implementation of class Reader
240
+ // ////////////////////////////////
241
+
242
+ static bool containsNewLine(Reader::Location begin, Reader::Location end) {
243
+ for (; begin < end; ++begin)
244
+ if (*begin == '\n' || *begin == '\r')
245
+ return true;
246
+ return false;
247
+ }
248
+
249
+ // Class Reader
250
+ // //////////////////////////////////////////////////////////////////
251
+
252
+ Reader::Reader()
253
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
254
+ lastValue_(), commentsBefore_(), features_(Features::all()),
255
+ collectComments_() {}
256
+
257
+ Reader::Reader(const Features& features)
258
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
259
+ lastValue_(), commentsBefore_(), features_(features), collectComments_() {
260
+ }
261
+
262
+ bool
263
+ Reader::parse(const std::string& document, Value& root, bool collectComments) {
264
+ document_ = document;
265
+ const char* begin = document_.c_str();
266
+ const char* end = begin + document_.length();
267
+ return parse(begin, end, root, collectComments);
268
+ }
269
+
270
+ bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
271
+ // std::istream_iterator<char> begin(sin);
272
+ // std::istream_iterator<char> end;
273
+ // Those would allow streamed input from a file, if parse() were a
274
+ // template function.
275
+
276
+ // Since std::string is reference-counted, this at least does not
277
+ // create an extra copy.
278
+ std::string doc;
279
+ std::getline(sin, doc, (char)EOF);
280
+ return parse(doc, root, collectComments);
281
+ }
282
+
283
+ bool Reader::parse(const char* beginDoc,
284
+ const char* endDoc,
285
+ Value& root,
286
+ bool collectComments) {
287
+ if (!features_.allowComments_) {
288
+ collectComments = false;
289
+ }
290
+
291
+ begin_ = beginDoc;
292
+ end_ = endDoc;
293
+ collectComments_ = collectComments;
294
+ current_ = begin_;
295
+ lastValueEnd_ = 0;
296
+ lastValue_ = 0;
297
+ commentsBefore_ = "";
298
+ errors_.clear();
299
+ while (!nodes_.empty())
300
+ nodes_.pop();
301
+ nodes_.push(&root);
302
+
303
+ stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
304
+ bool successful = readValue();
305
+ Token token;
306
+ skipCommentTokens(token);
307
+ if (collectComments_ && !commentsBefore_.empty())
308
+ root.setComment(commentsBefore_, commentAfter);
309
+ if (features_.strictRoot_) {
310
+ if (!root.isArray() && !root.isObject()) {
311
+ // Set error location to start of doc, ideally should be first token found
312
+ // in doc
313
+ token.type_ = tokenError;
314
+ token.start_ = beginDoc;
315
+ token.end_ = endDoc;
316
+ addError(
317
+ "A valid JSON document must be either an array or an object value.",
318
+ token);
319
+ return false;
320
+ }
321
+ }
322
+ return successful;
323
+ }
324
+
325
+ bool Reader::readValue() {
326
+ // This is a non-reentrant way to support a stackLimit. Terrible!
327
+ // But this deprecated class has a security problem: Bad input can
328
+ // cause a seg-fault. This seems like a fair, binary-compatible way
329
+ // to prevent the problem.
330
+ if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
331
+ ++stackDepth_g;
332
+
333
+ Token token;
334
+ skipCommentTokens(token);
335
+ bool successful = true;
336
+
337
+ if (collectComments_ && !commentsBefore_.empty()) {
338
+ currentValue().setComment(commentsBefore_, commentBefore);
339
+ commentsBefore_ = "";
340
+ }
341
+
342
+ switch (token.type_) {
343
+ case tokenObjectBegin:
344
+ successful = readObject(token);
345
+ break;
346
+ case tokenArrayBegin:
347
+ successful = readArray(token);
348
+ break;
349
+ case tokenNumber:
350
+ successful = decodeNumber(token);
351
+ break;
352
+ case tokenString:
353
+ successful = decodeString(token);
354
+ break;
355
+ case tokenTrue:
356
+ {
357
+ Value v(true);
358
+ currentValue().swapPayload(v);
359
+ }
360
+ break;
361
+ case tokenFalse:
362
+ {
363
+ Value v(false);
364
+ currentValue().swapPayload(v);
365
+ }
366
+ break;
367
+ case tokenNull:
368
+ {
369
+ Value v;
370
+ currentValue().swapPayload(v);
371
+ }
372
+ break;
373
+ // Else, fall through...
374
+ default:
375
+ return addError("Syntax error: value, object or array expected.", token);
376
+ }
377
+
378
+ if (collectComments_) {
379
+ lastValueEnd_ = current_;
380
+ lastValue_ = &currentValue();
381
+ }
382
+
383
+ --stackDepth_g;
384
+ return successful;
385
+ }
386
+
387
+ void Reader::skipCommentTokens(Token& token) {
388
+ if (features_.allowComments_) {
389
+ do {
390
+ readToken(token);
391
+ } while (token.type_ == tokenComment);
392
+ } else {
393
+ readToken(token);
394
+ }
395
+ }
396
+
397
+ bool Reader::readToken(Token& token) {
398
+ skipSpaces();
399
+ token.start_ = current_;
400
+ Char c = getNextChar();
401
+ bool ok = true;
402
+ switch (c) {
403
+ case '{':
404
+ token.type_ = tokenObjectBegin;
405
+ break;
406
+ case '}':
407
+ token.type_ = tokenObjectEnd;
408
+ break;
409
+ case '[':
410
+ token.type_ = tokenArrayBegin;
411
+ break;
412
+ case ']':
413
+ token.type_ = tokenArrayEnd;
414
+ break;
415
+ case '"':
416
+ token.type_ = tokenString;
417
+ ok = readString();
418
+ break;
419
+ case '/':
420
+ token.type_ = tokenComment;
421
+ ok = readComment();
422
+ break;
423
+ case '0':
424
+ case '1':
425
+ case '2':
426
+ case '3':
427
+ case '4':
428
+ case '5':
429
+ case '6':
430
+ case '7':
431
+ case '8':
432
+ case '9':
433
+ case '-':
434
+ token.type_ = tokenNumber;
435
+ readNumber();
436
+ break;
437
+ case 't':
438
+ token.type_ = tokenTrue;
439
+ ok = match("rue", 3);
440
+ break;
441
+ case 'f':
442
+ token.type_ = tokenFalse;
443
+ ok = match("alse", 4);
444
+ break;
445
+ case 'n':
446
+ token.type_ = tokenNull;
447
+ ok = match("ull", 3);
448
+ break;
449
+ case ',':
450
+ token.type_ = tokenArraySeparator;
451
+ break;
452
+ case ':':
453
+ token.type_ = tokenMemberSeparator;
454
+ break;
455
+ case 0:
456
+ token.type_ = tokenEndOfStream;
457
+ break;
458
+ default:
459
+ ok = false;
460
+ break;
461
+ }
462
+ if (!ok)
463
+ token.type_ = tokenError;
464
+ token.end_ = current_;
465
+ return true;
466
+ }
467
+
468
+ void Reader::skipSpaces() {
469
+ while (current_ != end_) {
470
+ Char c = *current_;
471
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
472
+ ++current_;
473
+ else
474
+ break;
475
+ }
476
+ }
477
+
478
+ bool Reader::match(Location pattern, int patternLength) {
479
+ if (end_ - current_ < patternLength)
480
+ return false;
481
+ int index = patternLength;
482
+ while (index--)
483
+ if (current_[index] != pattern[index])
484
+ return false;
485
+ current_ += patternLength;
486
+ return true;
487
+ }
488
+
489
+ bool Reader::readComment() {
490
+ Location commentBegin = current_ - 1;
491
+ Char c = getNextChar();
492
+ bool successful = false;
493
+ if (c == '*')
494
+ successful = readCStyleComment();
495
+ else if (c == '/')
496
+ successful = readCppStyleComment();
497
+ if (!successful)
498
+ return false;
499
+
500
+ if (collectComments_) {
501
+ CommentPlacement placement = commentBefore;
502
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
503
+ if (c != '*' || !containsNewLine(commentBegin, current_))
504
+ placement = commentAfterOnSameLine;
505
+ }
506
+
507
+ addComment(commentBegin, current_, placement);
508
+ }
509
+ return true;
510
+ }
511
+
512
+ static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
513
+ std::string normalized;
514
+ normalized.reserve(end - begin);
515
+ Reader::Location current = begin;
516
+ while (current != end) {
517
+ char c = *current++;
518
+ if (c == '\r') {
519
+ if (current != end && *current == '\n')
520
+ // convert dos EOL
521
+ ++current;
522
+ // convert Mac EOL
523
+ normalized += '\n';
524
+ } else {
525
+ normalized += c;
526
+ }
527
+ }
528
+ return normalized;
529
+ }
530
+
531
+ void
532
+ Reader::addComment(Location begin, Location end, CommentPlacement placement) {
533
+ assert(collectComments_);
534
+ const std::string& normalized = normalizeEOL(begin, end);
535
+ if (placement == commentAfterOnSameLine) {
536
+ assert(lastValue_ != 0);
537
+ lastValue_->setComment(normalized, placement);
538
+ } else {
539
+ commentsBefore_ += normalized;
540
+ }
541
+ }
542
+
543
+ bool Reader::readCStyleComment() {
544
+ while (current_ != end_) {
545
+ Char c = getNextChar();
546
+ if (c == '*' && *current_ == '/')
547
+ break;
548
+ }
549
+ return getNextChar() == '/';
550
+ }
551
+
552
+ bool Reader::readCppStyleComment() {
553
+ while (current_ != end_) {
554
+ Char c = getNextChar();
555
+ if (c == '\n')
556
+ break;
557
+ if (c == '\r') {
558
+ // Consume DOS EOL. It will be normalized in addComment.
559
+ if (current_ != end_ && *current_ == '\n')
560
+ getNextChar();
561
+ // Break on Moc OS 9 EOL.
562
+ break;
563
+ }
564
+ }
565
+ return true;
566
+ }
567
+
568
+ void Reader::readNumber() {
569
+ const char *p = current_;
570
+ char c = '0'; // stopgap for already consumed character
571
+ // integral part
572
+ while (c >= '0' && c <= '9')
573
+ c = (current_ = p) < end_ ? *p++ : 0;
574
+ // fractional part
575
+ if (c == '.') {
576
+ c = (current_ = p) < end_ ? *p++ : 0;
577
+ while (c >= '0' && c <= '9')
578
+ c = (current_ = p) < end_ ? *p++ : 0;
579
+ }
580
+ // exponential part
581
+ if (c == 'e' || c == 'E') {
582
+ c = (current_ = p) < end_ ? *p++ : 0;
583
+ if (c == '+' || c == '-')
584
+ c = (current_ = p) < end_ ? *p++ : 0;
585
+ while (c >= '0' && c <= '9')
586
+ c = (current_ = p) < end_ ? *p++ : 0;
587
+ }
588
+ }
589
+
590
+ bool Reader::readString() {
591
+ Char c = 0;
592
+ while (current_ != end_) {
593
+ c = getNextChar();
594
+ if (c == '\\')
595
+ getNextChar();
596
+ else if (c == '"')
597
+ break;
598
+ }
599
+ return c == '"';
600
+ }
601
+
602
+ bool Reader::readObject(Token& /*tokenStart*/) {
603
+ Token tokenName;
604
+ std::string name;
605
+ Value init(objectValue);
606
+ currentValue().swapPayload(init);
607
+ while (readToken(tokenName)) {
608
+ bool initialTokenOk = true;
609
+ while (tokenName.type_ == tokenComment && initialTokenOk)
610
+ initialTokenOk = readToken(tokenName);
611
+ if (!initialTokenOk)
612
+ break;
613
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
614
+ return true;
615
+ name = "";
616
+ if (tokenName.type_ == tokenString) {
617
+ if (!decodeString(tokenName, name))
618
+ return recoverFromError(tokenObjectEnd);
619
+ } else {
620
+ break;
621
+ }
622
+
623
+ Token colon;
624
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
625
+ return addErrorAndRecover(
626
+ "Missing ':' after object member name", colon, tokenObjectEnd);
627
+ }
628
+ Value& value = currentValue()[name];
629
+ nodes_.push(&value);
630
+ bool ok = readValue();
631
+ nodes_.pop();
632
+ if (!ok) // error already set
633
+ return recoverFromError(tokenObjectEnd);
634
+
635
+ Token comma;
636
+ if (!readToken(comma) ||
637
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
638
+ comma.type_ != tokenComment)) {
639
+ return addErrorAndRecover(
640
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
641
+ }
642
+ bool finalizeTokenOk = true;
643
+ while (comma.type_ == tokenComment && finalizeTokenOk)
644
+ finalizeTokenOk = readToken(comma);
645
+ if (comma.type_ == tokenObjectEnd)
646
+ return true;
647
+ }
648
+ return addErrorAndRecover(
649
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
650
+ }
651
+
652
+ bool Reader::readArray(Token& /*tokenStart*/) {
653
+ Value init(arrayValue);
654
+ currentValue().swapPayload(init);
655
+ skipSpaces();
656
+ if (*current_ == ']') // empty array
657
+ {
658
+ Token endArray;
659
+ readToken(endArray);
660
+ return true;
661
+ }
662
+ int index = 0;
663
+ for (;;) {
664
+ Value& value = currentValue()[index++];
665
+ nodes_.push(&value);
666
+ bool ok = readValue();
667
+ nodes_.pop();
668
+ if (!ok) // error already set
669
+ return recoverFromError(tokenArrayEnd);
670
+
671
+ Token token;
672
+ // Accept Comment after last item in the array.
673
+ ok = readToken(token);
674
+ while (token.type_ == tokenComment && ok) {
675
+ ok = readToken(token);
676
+ }
677
+ bool badTokenType =
678
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
679
+ if (!ok || badTokenType) {
680
+ return addErrorAndRecover(
681
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
682
+ }
683
+ if (token.type_ == tokenArrayEnd)
684
+ break;
685
+ }
686
+ return true;
687
+ }
688
+
689
+ bool Reader::decodeNumber(Token& token) {
690
+ Value decoded;
691
+ if (!decodeNumber(token, decoded))
692
+ return false;
693
+ currentValue().swapPayload(decoded);
694
+ return true;
695
+ }
696
+
697
+ bool Reader::decodeNumber(Token& token, Value& decoded) {
698
+ // Attempts to parse the number as an integer. If the number is
699
+ // larger than the maximum supported value of an integer then
700
+ // we decode the number as a double.
701
+ Location current = token.start_;
702
+ bool isNegative = *current == '-';
703
+ if (isNegative)
704
+ ++current;
705
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
706
+ Value::LargestUInt maxIntegerValue =
707
+ isNegative ? Value::LargestUInt(-Value::minLargestInt)
708
+ : Value::maxLargestUInt;
709
+ Value::LargestUInt threshold = maxIntegerValue / 10;
710
+ Value::LargestUInt value = 0;
711
+ while (current < token.end_) {
712
+ Char c = *current++;
713
+ if (c < '0' || c > '9')
714
+ return decodeDouble(token, decoded);
715
+ Value::UInt digit(c - '0');
716
+ if (value >= threshold) {
717
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
718
+ // a) we've only just touched the limit, b) this is the last digit, and
719
+ // c) it's small enough to fit in that rounding delta, we're okay.
720
+ // Otherwise treat this number as a double to avoid overflow.
721
+ if (value > threshold || current != token.end_ ||
722
+ digit > maxIntegerValue % 10) {
723
+ return decodeDouble(token, decoded);
724
+ }
725
+ }
726
+ value = value * 10 + digit;
727
+ }
728
+ if (isNegative)
729
+ decoded = -Value::LargestInt(value);
730
+ else if (value <= Value::LargestUInt(Value::maxInt))
731
+ decoded = Value::LargestInt(value);
732
+ else
733
+ decoded = value;
734
+ return true;
735
+ }
736
+
737
+ bool Reader::decodeDouble(Token& token) {
738
+ Value decoded;
739
+ if (!decodeDouble(token, decoded))
740
+ return false;
741
+ currentValue().swapPayload(decoded);
742
+ return true;
743
+ }
744
+
745
+ bool Reader::decodeDouble(Token& token, Value& decoded) {
746
+ double value = 0;
747
+ std::string buffer(token.start_, token.end_);
748
+ std::istringstream is(buffer);
749
+ if (!(is >> value))
750
+ return addError("'" + std::string(token.start_, token.end_) +
751
+ "' is not a number.",
752
+ token);
753
+ decoded = value;
754
+ return true;
755
+ }
756
+
757
+ bool Reader::decodeString(Token& token) {
758
+ std::string decoded_string;
759
+ if (!decodeString(token, decoded_string))
760
+ return false;
761
+ Value decoded(decoded_string);
762
+ currentValue().swapPayload(decoded);
763
+ return true;
764
+ }
765
+
766
+ bool Reader::decodeString(Token& token, std::string& decoded) {
767
+ decoded.reserve(token.end_ - token.start_ - 2);
768
+ Location current = token.start_ + 1; // skip '"'
769
+ Location end = token.end_ - 1; // do not include '"'
770
+ while (current != end) {
771
+ Char c = *current++;
772
+ if (c == '"')
773
+ break;
774
+ else if (c == '\\') {
775
+ if (current == end)
776
+ return addError("Empty escape sequence in string", token, current);
777
+ Char escape = *current++;
778
+ switch (escape) {
779
+ case '"':
780
+ decoded += '"';
781
+ break;
782
+ case '/':
783
+ decoded += '/';
784
+ break;
785
+ case '\\':
786
+ decoded += '\\';
787
+ break;
788
+ case 'b':
789
+ decoded += '\b';
790
+ break;
791
+ case 'f':
792
+ decoded += '\f';
793
+ break;
794
+ case 'n':
795
+ decoded += '\n';
796
+ break;
797
+ case 'r':
798
+ decoded += '\r';
799
+ break;
800
+ case 't':
801
+ decoded += '\t';
802
+ break;
803
+ case 'u': {
804
+ unsigned int unicode;
805
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
806
+ return false;
807
+ decoded += codePointToUTF8(unicode);
808
+ } break;
809
+ default:
810
+ return addError("Bad escape sequence in string", token, current);
811
+ }
812
+ } else {
813
+ decoded += c;
814
+ }
815
+ }
816
+ return true;
817
+ }
818
+
819
+ bool Reader::decodeUnicodeCodePoint(Token& token,
820
+ Location& current,
821
+ Location end,
822
+ unsigned int& unicode) {
823
+
824
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
825
+ return false;
826
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
827
+ // surrogate pairs
828
+ if (end - current < 6)
829
+ return addError(
830
+ "additional six characters expected to parse unicode surrogate pair.",
831
+ token,
832
+ current);
833
+ unsigned int surrogatePair;
834
+ if (*(current++) == '\\' && *(current++) == 'u') {
835
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
836
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
837
+ } else
838
+ return false;
839
+ } else
840
+ return addError("expecting another \\u token to begin the second half of "
841
+ "a unicode surrogate pair",
842
+ token,
843
+ current);
844
+ }
845
+ return true;
846
+ }
847
+
848
+ bool Reader::decodeUnicodeEscapeSequence(Token& token,
849
+ Location& current,
850
+ Location end,
851
+ unsigned int& unicode) {
852
+ if (end - current < 4)
853
+ return addError(
854
+ "Bad unicode escape sequence in string: four digits expected.",
855
+ token,
856
+ current);
857
+ unicode = 0;
858
+ for (int index = 0; index < 4; ++index) {
859
+ Char c = *current++;
860
+ unicode *= 16;
861
+ if (c >= '0' && c <= '9')
862
+ unicode += c - '0';
863
+ else if (c >= 'a' && c <= 'f')
864
+ unicode += c - 'a' + 10;
865
+ else if (c >= 'A' && c <= 'F')
866
+ unicode += c - 'A' + 10;
867
+ else
868
+ return addError(
869
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
870
+ token,
871
+ current);
872
+ }
873
+ return true;
874
+ }
875
+
876
+ bool
877
+ Reader::addError(const std::string& message, Token& token, Location extra) {
878
+ ErrorInfo info;
879
+ info.token_ = token;
880
+ info.message_ = message;
881
+ info.extra_ = extra;
882
+ errors_.push_back(info);
883
+ return false;
884
+ }
885
+
886
+ bool Reader::recoverFromError(TokenType skipUntilToken) {
887
+ int errorCount = int(errors_.size());
888
+ Token skip;
889
+ for (;;) {
890
+ if (!readToken(skip))
891
+ errors_.resize(errorCount); // discard errors caused by recovery
892
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
893
+ break;
894
+ }
895
+ errors_.resize(errorCount);
896
+ return false;
897
+ }
898
+
899
+ bool Reader::addErrorAndRecover(const std::string& message,
900
+ Token& token,
901
+ TokenType skipUntilToken) {
902
+ addError(message, token);
903
+ return recoverFromError(skipUntilToken);
904
+ }
905
+
906
+ Value& Reader::currentValue() { return *(nodes_.top()); }
907
+
908
+ Reader::Char Reader::getNextChar() {
909
+ if (current_ == end_)
910
+ return 0;
911
+ return *current_++;
912
+ }
913
+
914
+ void Reader::getLocationLineAndColumn(Location location,
915
+ int& line,
916
+ int& column) const {
917
+ Location current = begin_;
918
+ Location lastLineStart = current;
919
+ line = 0;
920
+ while (current < location && current != end_) {
921
+ Char c = *current++;
922
+ if (c == '\r') {
923
+ if (*current == '\n')
924
+ ++current;
925
+ lastLineStart = current;
926
+ ++line;
927
+ } else if (c == '\n') {
928
+ lastLineStart = current;
929
+ ++line;
930
+ }
931
+ }
932
+ // column & line start at 1
933
+ column = int(location - lastLineStart) + 1;
934
+ ++line;
935
+ }
936
+
937
+ std::string Reader::getLocationLineAndColumn(Location location) const {
938
+ int line, column;
939
+ getLocationLineAndColumn(location, line, column);
940
+ char buffer[18 + 16 + 16 + 1];
941
+ #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
942
+ #if defined(WINCE)
943
+ _snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
944
+ #else
945
+ sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
946
+ #endif
947
+ #else
948
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
949
+ #endif
950
+ return buffer;
951
+ }
952
+
953
+ // Deprecated. Preserved for backward compatibility
954
+ std::string Reader::getFormatedErrorMessages() const {
955
+ return getFormattedErrorMessages();
956
+ }
957
+
958
+ std::string Reader::getFormattedErrorMessages() const {
959
+ std::string formattedMessage;
960
+ for (Errors::const_iterator itError = errors_.begin();
961
+ itError != errors_.end();
962
+ ++itError) {
963
+ const ErrorInfo& error = *itError;
964
+ formattedMessage +=
965
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
966
+ formattedMessage += " " + error.message_ + "\n";
967
+ if (error.extra_)
968
+ formattedMessage +=
969
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
970
+ }
971
+ return formattedMessage;
972
+ }
973
+
974
+ // Reader
975
+ /////////////////////////
976
+
977
+ // exact copy of Features
978
+ class OurFeatures {
979
+ public:
980
+ static OurFeatures all();
981
+ OurFeatures();
982
+ bool allowComments_;
983
+ bool strictRoot_;
984
+ bool allowDroppedNullPlaceholders_;
985
+ bool allowNumericKeys_;
986
+ bool allowSingleQuotes_;
987
+ bool failIfExtra_;
988
+ bool rejectDupKeys_;
989
+ int stackLimit_;
990
+ }; // OurFeatures
991
+
992
+ // exact copy of Implementation of class Features
993
+ // ////////////////////////////////
994
+
995
+ OurFeatures::OurFeatures()
996
+ : allowComments_(true), strictRoot_(false)
997
+ , allowDroppedNullPlaceholders_(false), allowNumericKeys_(false)
998
+ , allowSingleQuotes_(false)
999
+ , failIfExtra_(false)
1000
+ {
1001
+ }
1002
+
1003
+ OurFeatures OurFeatures::all() { return OurFeatures(); }
1004
+
1005
+ // Implementation of class Reader
1006
+ // ////////////////////////////////
1007
+
1008
+ // exact copy of Reader, renamed to OurReader
1009
+ class OurReader {
1010
+ public:
1011
+ typedef char Char;
1012
+ typedef const Char* Location;
1013
+ struct StructuredError {
1014
+ size_t offset_start;
1015
+ size_t offset_limit;
1016
+ std::string message;
1017
+ };
1018
+
1019
+ OurReader(OurFeatures const& features);
1020
+ bool parse(const char* beginDoc,
1021
+ const char* endDoc,
1022
+ Value& root,
1023
+ bool collectComments = true);
1024
+ std::string getFormattedErrorMessages() const;
1025
+
1026
+ private:
1027
+ OurReader(OurReader const&); // no impl
1028
+ void operator=(OurReader const&); // no impl
1029
+
1030
+ enum TokenType {
1031
+ tokenEndOfStream = 0,
1032
+ tokenObjectBegin,
1033
+ tokenObjectEnd,
1034
+ tokenArrayBegin,
1035
+ tokenArrayEnd,
1036
+ tokenString,
1037
+ tokenNumber,
1038
+ tokenTrue,
1039
+ tokenFalse,
1040
+ tokenNull,
1041
+ tokenArraySeparator,
1042
+ tokenMemberSeparator,
1043
+ tokenComment,
1044
+ tokenError
1045
+ };
1046
+
1047
+ class Token {
1048
+ public:
1049
+ TokenType type_;
1050
+ Location start_;
1051
+ Location end_;
1052
+ };
1053
+
1054
+ class ErrorInfo {
1055
+ public:
1056
+ Token token_;
1057
+ std::string message_;
1058
+ Location extra_;
1059
+ };
1060
+
1061
+ typedef std::deque<ErrorInfo> Errors;
1062
+
1063
+ bool readToken(Token& token);
1064
+ void skipSpaces();
1065
+ bool match(Location pattern, int patternLength);
1066
+ bool readComment();
1067
+ bool readCStyleComment();
1068
+ bool readCppStyleComment();
1069
+ bool readString();
1070
+ bool readStringSingleQuote();
1071
+ void readNumber();
1072
+ bool readValue();
1073
+ bool readObject(Token& token);
1074
+ bool readArray(Token& token);
1075
+ bool decodeNumber(Token& token);
1076
+ bool decodeNumber(Token& token, Value& decoded);
1077
+ bool decodeString(Token& token);
1078
+ bool decodeString(Token& token, std::string& decoded);
1079
+ bool decodeDouble(Token& token);
1080
+ bool decodeDouble(Token& token, Value& decoded);
1081
+ bool decodeUnicodeCodePoint(Token& token,
1082
+ Location& current,
1083
+ Location end,
1084
+ unsigned int& unicode);
1085
+ bool decodeUnicodeEscapeSequence(Token& token,
1086
+ Location& current,
1087
+ Location end,
1088
+ unsigned int& unicode);
1089
+ bool addError(const std::string& message, Token& token, Location extra = 0);
1090
+ bool recoverFromError(TokenType skipUntilToken);
1091
+ bool addErrorAndRecover(const std::string& message,
1092
+ Token& token,
1093
+ TokenType skipUntilToken);
1094
+ void skipUntilSpace();
1095
+ Value& currentValue();
1096
+ Char getNextChar();
1097
+ void
1098
+ getLocationLineAndColumn(Location location, int& line, int& column) const;
1099
+ std::string getLocationLineAndColumn(Location location) const;
1100
+ void addComment(Location begin, Location end, CommentPlacement placement);
1101
+ void skipCommentTokens(Token& token);
1102
+
1103
+ typedef std::stack<Value*> Nodes;
1104
+ Nodes nodes_;
1105
+ Errors errors_;
1106
+ std::string document_;
1107
+ Location begin_;
1108
+ Location end_;
1109
+ Location current_;
1110
+ Location lastValueEnd_;
1111
+ Value* lastValue_;
1112
+ std::string commentsBefore_;
1113
+ int stackDepth_;
1114
+
1115
+ OurFeatures const features_;
1116
+ bool collectComments_;
1117
+ }; // OurReader
1118
+
1119
+ // complete copy of Read impl, for OurReader
1120
+
1121
+ OurReader::OurReader(OurFeatures const& features)
1122
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
1123
+ lastValue_(), commentsBefore_(), features_(features), collectComments_() {
1124
+ }
1125
+
1126
+ bool OurReader::parse(const char* beginDoc,
1127
+ const char* endDoc,
1128
+ Value& root,
1129
+ bool collectComments) {
1130
+ if (!features_.allowComments_) {
1131
+ collectComments = false;
1132
+ }
1133
+
1134
+ begin_ = beginDoc;
1135
+ end_ = endDoc;
1136
+ collectComments_ = collectComments;
1137
+ current_ = begin_;
1138
+ lastValueEnd_ = 0;
1139
+ lastValue_ = 0;
1140
+ commentsBefore_ = "";
1141
+ errors_.clear();
1142
+ while (!nodes_.empty())
1143
+ nodes_.pop();
1144
+ nodes_.push(&root);
1145
+
1146
+ stackDepth_ = 0;
1147
+ bool successful = readValue();
1148
+ Token token;
1149
+ skipCommentTokens(token);
1150
+ if (features_.failIfExtra_) {
1151
+ if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
1152
+ addError("Extra non-whitespace after JSON value.", token);
1153
+ return false;
1154
+ }
1155
+ }
1156
+ if (collectComments_ && !commentsBefore_.empty())
1157
+ root.setComment(commentsBefore_, commentAfter);
1158
+ if (features_.strictRoot_) {
1159
+ if (!root.isArray() && !root.isObject()) {
1160
+ // Set error location to start of doc, ideally should be first token found
1161
+ // in doc
1162
+ token.type_ = tokenError;
1163
+ token.start_ = beginDoc;
1164
+ token.end_ = endDoc;
1165
+ addError(
1166
+ "A valid JSON document must be either an array or an object value.",
1167
+ token);
1168
+ return false;
1169
+ }
1170
+ }
1171
+ return successful;
1172
+ }
1173
+
1174
+ bool OurReader::readValue() {
1175
+ if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
1176
+ ++stackDepth_;
1177
+ Token token;
1178
+ skipCommentTokens(token);
1179
+ bool successful = true;
1180
+
1181
+ if (collectComments_ && !commentsBefore_.empty()) {
1182
+ currentValue().setComment(commentsBefore_, commentBefore);
1183
+ commentsBefore_ = "";
1184
+ }
1185
+
1186
+ switch (token.type_) {
1187
+ case tokenObjectBegin:
1188
+ successful = readObject(token);
1189
+ break;
1190
+ case tokenArrayBegin:
1191
+ successful = readArray(token);
1192
+ break;
1193
+ case tokenNumber:
1194
+ successful = decodeNumber(token);
1195
+ break;
1196
+ case tokenString:
1197
+ successful = decodeString(token);
1198
+ break;
1199
+ case tokenTrue:
1200
+ {
1201
+ Value v(true);
1202
+ currentValue().swapPayload(v);
1203
+ }
1204
+ break;
1205
+ case tokenFalse:
1206
+ {
1207
+ Value v(false);
1208
+ currentValue().swapPayload(v);
1209
+ }
1210
+ break;
1211
+ case tokenNull:
1212
+ {
1213
+ Value v;
1214
+ currentValue().swapPayload(v);
1215
+ }
1216
+ break;
1217
+ case tokenArraySeparator:
1218
+ case tokenObjectEnd:
1219
+ case tokenArrayEnd:
1220
+ if (features_.allowDroppedNullPlaceholders_) {
1221
+ // "Un-read" the current token and mark the current value as a null
1222
+ // token.
1223
+ current_--;
1224
+ Value v;
1225
+ currentValue().swapPayload(v);
1226
+ break;
1227
+ } // else, fall through ...
1228
+ default:
1229
+ return addError("Syntax error: value, object or array expected.", token);
1230
+ }
1231
+
1232
+ if (collectComments_) {
1233
+ lastValueEnd_ = current_;
1234
+ lastValue_ = &currentValue();
1235
+ }
1236
+
1237
+ --stackDepth_;
1238
+ return successful;
1239
+ }
1240
+
1241
+ void OurReader::skipCommentTokens(Token& token) {
1242
+ if (features_.allowComments_) {
1243
+ do {
1244
+ readToken(token);
1245
+ } while (token.type_ == tokenComment);
1246
+ } else {
1247
+ readToken(token);
1248
+ }
1249
+ }
1250
+
1251
+ bool OurReader::readToken(Token& token) {
1252
+ skipSpaces();
1253
+ token.start_ = current_;
1254
+ Char c = getNextChar();
1255
+ bool ok = true;
1256
+ switch (c) {
1257
+ case '{':
1258
+ token.type_ = tokenObjectBegin;
1259
+ break;
1260
+ case '}':
1261
+ token.type_ = tokenObjectEnd;
1262
+ break;
1263
+ case '[':
1264
+ token.type_ = tokenArrayBegin;
1265
+ break;
1266
+ case ']':
1267
+ token.type_ = tokenArrayEnd;
1268
+ break;
1269
+ case '"':
1270
+ token.type_ = tokenString;
1271
+ ok = readString();
1272
+ break;
1273
+ case '\'':
1274
+ if (features_.allowSingleQuotes_) {
1275
+ token.type_ = tokenString;
1276
+ ok = readStringSingleQuote();
1277
+ break;
1278
+ }
1279
+ /* falls through */
1280
+ case '/':
1281
+ token.type_ = tokenComment;
1282
+ ok = readComment();
1283
+ break;
1284
+ case '0':
1285
+ case '1':
1286
+ case '2':
1287
+ case '3':
1288
+ case '4':
1289
+ case '5':
1290
+ case '6':
1291
+ case '7':
1292
+ case '8':
1293
+ case '9':
1294
+ case '-':
1295
+ token.type_ = tokenNumber;
1296
+ readNumber();
1297
+ break;
1298
+ case 't':
1299
+ token.type_ = tokenTrue;
1300
+ ok = match("rue", 3);
1301
+ break;
1302
+ case 'f':
1303
+ token.type_ = tokenFalse;
1304
+ ok = match("alse", 4);
1305
+ break;
1306
+ case 'n':
1307
+ token.type_ = tokenNull;
1308
+ ok = match("ull", 3);
1309
+ break;
1310
+ case ',':
1311
+ token.type_ = tokenArraySeparator;
1312
+ break;
1313
+ case ':':
1314
+ token.type_ = tokenMemberSeparator;
1315
+ break;
1316
+ case 0:
1317
+ token.type_ = tokenEndOfStream;
1318
+ break;
1319
+ default:
1320
+ ok = false;
1321
+ break;
1322
+ }
1323
+ if (!ok)
1324
+ token.type_ = tokenError;
1325
+ token.end_ = current_;
1326
+ return true;
1327
+ }
1328
+
1329
+ void OurReader::skipSpaces() {
1330
+ while (current_ != end_) {
1331
+ Char c = *current_;
1332
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
1333
+ ++current_;
1334
+ else
1335
+ break;
1336
+ }
1337
+ }
1338
+
1339
+ bool OurReader::match(Location pattern, int patternLength) {
1340
+ if (end_ - current_ < patternLength)
1341
+ return false;
1342
+ int index = patternLength;
1343
+ while (index--)
1344
+ if (current_[index] != pattern[index])
1345
+ return false;
1346
+ current_ += patternLength;
1347
+ return true;
1348
+ }
1349
+
1350
+ bool OurReader::readComment() {
1351
+ Location commentBegin = current_ - 1;
1352
+ Char c = getNextChar();
1353
+ bool successful = false;
1354
+ if (c == '*')
1355
+ successful = readCStyleComment();
1356
+ else if (c == '/')
1357
+ successful = readCppStyleComment();
1358
+ if (!successful)
1359
+ return false;
1360
+
1361
+ if (collectComments_) {
1362
+ CommentPlacement placement = commentBefore;
1363
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
1364
+ if (c != '*' || !containsNewLine(commentBegin, current_))
1365
+ placement = commentAfterOnSameLine;
1366
+ }
1367
+
1368
+ addComment(commentBegin, current_, placement);
1369
+ }
1370
+ return true;
1371
+ }
1372
+
1373
+ void
1374
+ OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
1375
+ assert(collectComments_);
1376
+ const std::string& normalized = normalizeEOL(begin, end);
1377
+ if (placement == commentAfterOnSameLine) {
1378
+ assert(lastValue_ != 0);
1379
+ lastValue_->setComment(normalized, placement);
1380
+ } else {
1381
+ commentsBefore_ += normalized;
1382
+ }
1383
+ }
1384
+
1385
+ bool OurReader::readCStyleComment() {
1386
+ while (current_ != end_) {
1387
+ Char c = getNextChar();
1388
+ if (c == '*' && *current_ == '/')
1389
+ break;
1390
+ }
1391
+ return getNextChar() == '/';
1392
+ }
1393
+
1394
+ bool OurReader::readCppStyleComment() {
1395
+ while (current_ != end_) {
1396
+ Char c = getNextChar();
1397
+ if (c == '\n')
1398
+ break;
1399
+ if (c == '\r') {
1400
+ // Consume DOS EOL. It will be normalized in addComment.
1401
+ if (current_ != end_ && *current_ == '\n')
1402
+ getNextChar();
1403
+ // Break on Moc OS 9 EOL.
1404
+ break;
1405
+ }
1406
+ }
1407
+ return true;
1408
+ }
1409
+
1410
+ void OurReader::readNumber() {
1411
+ const char *p = current_;
1412
+ char c = '0'; // stopgap for already consumed character
1413
+ // integral part
1414
+ while (c >= '0' && c <= '9')
1415
+ c = (current_ = p) < end_ ? *p++ : 0;
1416
+ // fractional part
1417
+ if (c == '.') {
1418
+ c = (current_ = p) < end_ ? *p++ : 0;
1419
+ while (c >= '0' && c <= '9')
1420
+ c = (current_ = p) < end_ ? *p++ : 0;
1421
+ }
1422
+ // exponential part
1423
+ if (c == 'e' || c == 'E') {
1424
+ c = (current_ = p) < end_ ? *p++ : 0;
1425
+ if (c == '+' || c == '-')
1426
+ c = (current_ = p) < end_ ? *p++ : 0;
1427
+ while (c >= '0' && c <= '9')
1428
+ c = (current_ = p) < end_ ? *p++ : 0;
1429
+ }
1430
+ }
1431
+ bool OurReader::readString() {
1432
+ Char c = 0;
1433
+ while (current_ != end_) {
1434
+ c = getNextChar();
1435
+ if (c == '\\')
1436
+ getNextChar();
1437
+ else if (c == '"')
1438
+ break;
1439
+ }
1440
+ return c == '"';
1441
+ }
1442
+
1443
+
1444
+ bool OurReader::readStringSingleQuote() {
1445
+ Char c = 0;
1446
+ while (current_ != end_) {
1447
+ c = getNextChar();
1448
+ if (c == '\\')
1449
+ getNextChar();
1450
+ else if (c == '\'')
1451
+ break;
1452
+ }
1453
+ return c == '\'';
1454
+ }
1455
+
1456
+ bool OurReader::readObject(Token& /*tokenStart*/) {
1457
+ Token tokenName;
1458
+ std::string name;
1459
+ Value init(objectValue);
1460
+ currentValue().swapPayload(init);
1461
+ while (readToken(tokenName)) {
1462
+ bool initialTokenOk = true;
1463
+ while (tokenName.type_ == tokenComment && initialTokenOk)
1464
+ initialTokenOk = readToken(tokenName);
1465
+ if (!initialTokenOk)
1466
+ break;
1467
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
1468
+ return true;
1469
+ name = "";
1470
+ if (tokenName.type_ == tokenString) {
1471
+ if (!decodeString(tokenName, name))
1472
+ return recoverFromError(tokenObjectEnd);
1473
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
1474
+ Value numberName;
1475
+ if (!decodeNumber(tokenName, numberName))
1476
+ return recoverFromError(tokenObjectEnd);
1477
+ name = numberName.asString();
1478
+ } else {
1479
+ break;
1480
+ }
1481
+
1482
+ Token colon;
1483
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
1484
+ return addErrorAndRecover(
1485
+ "Missing ':' after object member name", colon, tokenObjectEnd);
1486
+ }
1487
+ if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
1488
+ if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
1489
+ std::string msg = "Duplicate key: '" + name + "'";
1490
+ return addErrorAndRecover(
1491
+ msg, tokenName, tokenObjectEnd);
1492
+ }
1493
+ Value& value = currentValue()[name];
1494
+ nodes_.push(&value);
1495
+ bool ok = readValue();
1496
+ nodes_.pop();
1497
+ if (!ok) // error already set
1498
+ return recoverFromError(tokenObjectEnd);
1499
+
1500
+ Token comma;
1501
+ if (!readToken(comma) ||
1502
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
1503
+ comma.type_ != tokenComment)) {
1504
+ return addErrorAndRecover(
1505
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
1506
+ }
1507
+ bool finalizeTokenOk = true;
1508
+ while (comma.type_ == tokenComment && finalizeTokenOk)
1509
+ finalizeTokenOk = readToken(comma);
1510
+ if (comma.type_ == tokenObjectEnd)
1511
+ return true;
1512
+ }
1513
+ return addErrorAndRecover(
1514
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
1515
+ }
1516
+
1517
+ bool OurReader::readArray(Token& /*tokenStart*/) {
1518
+ Value init(arrayValue);
1519
+ currentValue().swapPayload(init);
1520
+ skipSpaces();
1521
+ if (*current_ == ']') // empty array
1522
+ {
1523
+ Token endArray;
1524
+ readToken(endArray);
1525
+ return true;
1526
+ }
1527
+ int index = 0;
1528
+ for (;;) {
1529
+ Value& value = currentValue()[index++];
1530
+ nodes_.push(&value);
1531
+ bool ok = readValue();
1532
+ nodes_.pop();
1533
+ if (!ok) // error already set
1534
+ return recoverFromError(tokenArrayEnd);
1535
+
1536
+ Token token;
1537
+ // Accept Comment after last item in the array.
1538
+ ok = readToken(token);
1539
+ while (token.type_ == tokenComment && ok) {
1540
+ ok = readToken(token);
1541
+ }
1542
+ bool badTokenType =
1543
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
1544
+ if (!ok || badTokenType) {
1545
+ return addErrorAndRecover(
1546
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
1547
+ }
1548
+ if (token.type_ == tokenArrayEnd)
1549
+ break;
1550
+ }
1551
+ return true;
1552
+ }
1553
+
1554
+ bool OurReader::decodeNumber(Token& token) {
1555
+ Value decoded;
1556
+ if (!decodeNumber(token, decoded))
1557
+ return false;
1558
+ currentValue().swapPayload(decoded);
1559
+ return true;
1560
+ }
1561
+
1562
+ bool OurReader::decodeNumber(Token& token, Value& decoded) {
1563
+ // Attempts to parse the number as an integer. If the number is
1564
+ // larger than the maximum supported value of an integer then
1565
+ // we decode the number as a double.
1566
+ Location current = token.start_;
1567
+ bool isNegative = *current == '-';
1568
+ if (isNegative)
1569
+ ++current;
1570
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
1571
+ Value::LargestUInt maxIntegerValue =
1572
+ isNegative ? Value::LargestUInt(-Value::minLargestInt)
1573
+ : Value::maxLargestUInt;
1574
+ Value::LargestUInt threshold = maxIntegerValue / 10;
1575
+ Value::LargestUInt value = 0;
1576
+ while (current < token.end_) {
1577
+ Char c = *current++;
1578
+ if (c < '0' || c > '9')
1579
+ return decodeDouble(token, decoded);
1580
+ Value::UInt digit(c - '0');
1581
+ if (value >= threshold) {
1582
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
1583
+ // a) we've only just touched the limit, b) this is the last digit, and
1584
+ // c) it's small enough to fit in that rounding delta, we're okay.
1585
+ // Otherwise treat this number as a double to avoid overflow.
1586
+ if (value > threshold || current != token.end_ ||
1587
+ digit > maxIntegerValue % 10) {
1588
+ return decodeDouble(token, decoded);
1589
+ }
1590
+ }
1591
+ value = value * 10 + digit;
1592
+ }
1593
+ if (isNegative)
1594
+ decoded = -Value::LargestInt(value);
1595
+ else if (value <= Value::LargestUInt(Value::maxInt))
1596
+ decoded = Value::LargestInt(value);
1597
+ else
1598
+ decoded = value;
1599
+ return true;
1600
+ }
1601
+
1602
+ bool OurReader::decodeDouble(Token& token) {
1603
+ Value decoded;
1604
+ if (!decodeDouble(token, decoded))
1605
+ return false;
1606
+ currentValue().swapPayload(decoded);
1607
+ return true;
1608
+ }
1609
+
1610
+ bool OurReader::decodeDouble(Token& token, Value& decoded) {
1611
+ double value = 0;
1612
+ const int bufferSize = 32;
1613
+ int count;
1614
+ int length = int(token.end_ - token.start_);
1615
+
1616
+ // Sanity check to avoid buffer overflow exploits.
1617
+ if (length < 0) {
1618
+ return addError("Unable to parse token length", token);
1619
+ }
1620
+
1621
+ // Avoid using a string constant for the format control string given to
1622
+ // sscanf, as this can cause hard to debug crashes on OS X. See here for more
1623
+ // info:
1624
+ //
1625
+ // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
1626
+ char format[] = "%lf";
1627
+
1628
+ if (length <= bufferSize) {
1629
+ Char buffer[bufferSize + 1];
1630
+ memcpy(buffer, token.start_, length);
1631
+ buffer[length] = 0;
1632
+ count = sscanf(buffer, format, &value);
1633
+ } else {
1634
+ std::string buffer(token.start_, token.end_);
1635
+ count = sscanf(buffer.c_str(), format, &value);
1636
+ }
1637
+
1638
+ if (count != 1)
1639
+ return addError("'" + std::string(token.start_, token.end_) +
1640
+ "' is not a number.",
1641
+ token);
1642
+ decoded = value;
1643
+ return true;
1644
+ }
1645
+
1646
+ bool OurReader::decodeString(Token& token) {
1647
+ std::string decoded_string;
1648
+ if (!decodeString(token, decoded_string))
1649
+ return false;
1650
+ Value decoded(decoded_string);
1651
+ currentValue().swapPayload(decoded);
1652
+ return true;
1653
+ }
1654
+
1655
+ bool OurReader::decodeString(Token& token, std::string& decoded) {
1656
+ decoded.reserve(token.end_ - token.start_ - 2);
1657
+ Location current = token.start_ + 1; // skip '"'
1658
+ Location end = token.end_ - 1; // do not include '"'
1659
+ while (current != end) {
1660
+ Char c = *current++;
1661
+ if (c == '"')
1662
+ break;
1663
+ else if (c == '\\') {
1664
+ if (current == end)
1665
+ return addError("Empty escape sequence in string", token, current);
1666
+ Char escape = *current++;
1667
+ switch (escape) {
1668
+ case '"':
1669
+ decoded += '"';
1670
+ break;
1671
+ case '/':
1672
+ decoded += '/';
1673
+ break;
1674
+ case '\\':
1675
+ decoded += '\\';
1676
+ break;
1677
+ case 'b':
1678
+ decoded += '\b';
1679
+ break;
1680
+ case 'f':
1681
+ decoded += '\f';
1682
+ break;
1683
+ case 'n':
1684
+ decoded += '\n';
1685
+ break;
1686
+ case 'r':
1687
+ decoded += '\r';
1688
+ break;
1689
+ case 't':
1690
+ decoded += '\t';
1691
+ break;
1692
+ case 'u': {
1693
+ unsigned int unicode;
1694
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
1695
+ return false;
1696
+ decoded += codePointToUTF8(unicode);
1697
+ } break;
1698
+ default:
1699
+ return addError("Bad escape sequence in string", token, current);
1700
+ }
1701
+ } else {
1702
+ decoded += c;
1703
+ }
1704
+ }
1705
+ return true;
1706
+ }
1707
+
1708
+ bool OurReader::decodeUnicodeCodePoint(Token& token,
1709
+ Location& current,
1710
+ Location end,
1711
+ unsigned int& unicode) {
1712
+
1713
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
1714
+ return false;
1715
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
1716
+ // surrogate pairs
1717
+ if (end - current < 6)
1718
+ return addError(
1719
+ "additional six characters expected to parse unicode surrogate pair.",
1720
+ token,
1721
+ current);
1722
+ unsigned int surrogatePair;
1723
+ if (*(current++) == '\\' && *(current++) == 'u') {
1724
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
1725
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
1726
+ } else
1727
+ return false;
1728
+ } else
1729
+ return addError("expecting another \\u token to begin the second half of "
1730
+ "a unicode surrogate pair",
1731
+ token,
1732
+ current);
1733
+ }
1734
+ return true;
1735
+ }
1736
+
1737
+ bool OurReader::decodeUnicodeEscapeSequence(Token& token,
1738
+ Location& current,
1739
+ Location end,
1740
+ unsigned int& unicode) {
1741
+ if (end - current < 4)
1742
+ return addError(
1743
+ "Bad unicode escape sequence in string: four digits expected.",
1744
+ token,
1745
+ current);
1746
+ unicode = 0;
1747
+ for (int index = 0; index < 4; ++index) {
1748
+ Char c = *current++;
1749
+ unicode *= 16;
1750
+ if (c >= '0' && c <= '9')
1751
+ unicode += c - '0';
1752
+ else if (c >= 'a' && c <= 'f')
1753
+ unicode += c - 'a' + 10;
1754
+ else if (c >= 'A' && c <= 'F')
1755
+ unicode += c - 'A' + 10;
1756
+ else
1757
+ return addError(
1758
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
1759
+ token,
1760
+ current);
1761
+ }
1762
+ return true;
1763
+ }
1764
+
1765
+ bool
1766
+ OurReader::addError(const std::string& message, Token& token, Location extra) {
1767
+ ErrorInfo info;
1768
+ info.token_ = token;
1769
+ info.message_ = message;
1770
+ info.extra_ = extra;
1771
+ errors_.push_back(info);
1772
+ return false;
1773
+ }
1774
+
1775
+ bool OurReader::recoverFromError(TokenType skipUntilToken) {
1776
+ int errorCount = int(errors_.size());
1777
+ Token skip;
1778
+ for (;;) {
1779
+ if (!readToken(skip))
1780
+ errors_.resize(errorCount); // discard errors caused by recovery
1781
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
1782
+ break;
1783
+ }
1784
+ errors_.resize(errorCount);
1785
+ return false;
1786
+ }
1787
+
1788
+ bool OurReader::addErrorAndRecover(const std::string& message,
1789
+ Token& token,
1790
+ TokenType skipUntilToken) {
1791
+ addError(message, token);
1792
+ return recoverFromError(skipUntilToken);
1793
+ }
1794
+
1795
+ Value& OurReader::currentValue() { return *(nodes_.top()); }
1796
+
1797
+ OurReader::Char OurReader::getNextChar() {
1798
+ if (current_ == end_)
1799
+ return 0;
1800
+ return *current_++;
1801
+ }
1802
+
1803
+ void OurReader::getLocationLineAndColumn(Location location,
1804
+ int& line,
1805
+ int& column) const {
1806
+ Location current = begin_;
1807
+ Location lastLineStart = current;
1808
+ line = 0;
1809
+ while (current < location && current != end_) {
1810
+ Char c = *current++;
1811
+ if (c == '\r') {
1812
+ if (*current == '\n')
1813
+ ++current;
1814
+ lastLineStart = current;
1815
+ ++line;
1816
+ } else if (c == '\n') {
1817
+ lastLineStart = current;
1818
+ ++line;
1819
+ }
1820
+ }
1821
+ // column & line start at 1
1822
+ column = int(location - lastLineStart) + 1;
1823
+ ++line;
1824
+ }
1825
+
1826
+ std::string OurReader::getLocationLineAndColumn(Location location) const {
1827
+ int line, column;
1828
+ getLocationLineAndColumn(location, line, column);
1829
+ char buffer[18 + 16 + 16 + 1];
1830
+ #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
1831
+ #if defined(WINCE)
1832
+ _snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
1833
+ #else
1834
+ sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
1835
+ #endif
1836
+ #else
1837
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
1838
+ #endif
1839
+ return buffer;
1840
+ }
1841
+
1842
+ std::string OurReader::getFormattedErrorMessages() const {
1843
+ std::string formattedMessage;
1844
+ for (Errors::const_iterator itError = errors_.begin();
1845
+ itError != errors_.end();
1846
+ ++itError) {
1847
+ const ErrorInfo& error = *itError;
1848
+ formattedMessage +=
1849
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
1850
+ formattedMessage += " " + error.message_ + "\n";
1851
+ if (error.extra_)
1852
+ formattedMessage +=
1853
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
1854
+ }
1855
+ return formattedMessage;
1856
+ }
1857
+
1858
+
1859
+ class OurCharReader : public CharReader {
1860
+ bool const collectComments_;
1861
+ OurReader reader_;
1862
+ public:
1863
+ OurCharReader(
1864
+ bool collectComments,
1865
+ OurFeatures const& features)
1866
+ : collectComments_(collectComments)
1867
+ , reader_(features)
1868
+ {}
1869
+ virtual bool parse(
1870
+ char const* beginDoc, char const* endDoc,
1871
+ Value* root, std::string* errs) {
1872
+ bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
1873
+ if (errs) {
1874
+ *errs = reader_.getFormattedErrorMessages();
1875
+ }
1876
+ return ok;
1877
+ }
1878
+ };
1879
+
1880
+ CharReaderBuilder::CharReaderBuilder()
1881
+ {
1882
+ setDefaults(&settings_);
1883
+ }
1884
+ CharReaderBuilder::~CharReaderBuilder()
1885
+ {}
1886
+ CharReader* CharReaderBuilder::newCharReader() const
1887
+ {
1888
+ bool collectComments = settings_["collectComments"].asBool();
1889
+ OurFeatures features = OurFeatures::all();
1890
+ features.allowComments_ = settings_["allowComments"].asBool();
1891
+ features.strictRoot_ = settings_["strictRoot"].asBool();
1892
+ features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
1893
+ features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
1894
+ features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
1895
+ features.stackLimit_ = settings_["stackLimit"].asInt();
1896
+ features.failIfExtra_ = settings_["failIfExtra"].asBool();
1897
+ features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
1898
+ return new OurCharReader(collectComments, features);
1899
+ }
1900
+ static void getValidReaderKeys(std::set<std::string>* valid_keys)
1901
+ {
1902
+ valid_keys->clear();
1903
+ valid_keys->insert("collectComments");
1904
+ valid_keys->insert("allowComments");
1905
+ valid_keys->insert("strictRoot");
1906
+ valid_keys->insert("allowDroppedNullPlaceholders");
1907
+ valid_keys->insert("allowNumericKeys");
1908
+ valid_keys->insert("allowSingleQuotes");
1909
+ valid_keys->insert("stackLimit");
1910
+ valid_keys->insert("failIfExtra");
1911
+ valid_keys->insert("rejectDupKeys");
1912
+ }
1913
+ bool CharReaderBuilder::validate(Json::Value* invalid) const
1914
+ {
1915
+ Json::Value my_invalid;
1916
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
1917
+ Json::Value& inv = *invalid;
1918
+ std::set<std::string> valid_keys;
1919
+ getValidReaderKeys(&valid_keys);
1920
+ Value::Members keys = settings_.getMemberNames();
1921
+ size_t n = keys.size();
1922
+ for (size_t i = 0; i < n; ++i) {
1923
+ std::string const& key = keys[i];
1924
+ if (valid_keys.find(key) == valid_keys.end()) {
1925
+ inv[key] = settings_[key];
1926
+ }
1927
+ }
1928
+ return 0u == inv.size();
1929
+ }
1930
+ Value& CharReaderBuilder::operator[](std::string key)
1931
+ {
1932
+ return settings_[key];
1933
+ }
1934
+ // static
1935
+ void CharReaderBuilder::strictMode(Json::Value* settings)
1936
+ {
1937
+ //! [CharReaderBuilderStrictMode]
1938
+ (*settings)["allowComments"] = false;
1939
+ (*settings)["strictRoot"] = true;
1940
+ (*settings)["allowDroppedNullPlaceholders"] = false;
1941
+ (*settings)["allowNumericKeys"] = false;
1942
+ (*settings)["allowSingleQuotes"] = false;
1943
+ (*settings)["failIfExtra"] = true;
1944
+ (*settings)["rejectDupKeys"] = true;
1945
+ //! [CharReaderBuilderStrictMode]
1946
+ }
1947
+ // static
1948
+ void CharReaderBuilder::setDefaults(Json::Value* settings)
1949
+ {
1950
+ //! [CharReaderBuilderDefaults]
1951
+ (*settings)["collectComments"] = true;
1952
+ (*settings)["allowComments"] = true;
1953
+ (*settings)["strictRoot"] = false;
1954
+ (*settings)["allowDroppedNullPlaceholders"] = false;
1955
+ (*settings)["allowNumericKeys"] = false;
1956
+ (*settings)["allowSingleQuotes"] = false;
1957
+ (*settings)["stackLimit"] = 1000;
1958
+ (*settings)["failIfExtra"] = false;
1959
+ (*settings)["rejectDupKeys"] = false;
1960
+ //! [CharReaderBuilderDefaults]
1961
+ }
1962
+
1963
+ //////////////////////////////////
1964
+ // global functions
1965
+
1966
+ bool parseFromStream(
1967
+ CharReader::Factory const& fact, std::istream& sin,
1968
+ Value* root, std::string* errs)
1969
+ {
1970
+ std::ostringstream ssin;
1971
+ ssin << sin.rdbuf();
1972
+ std::string doc = ssin.str();
1973
+ char const* begin = doc.data();
1974
+ char const* end = begin + doc.size();
1975
+ // Note that we do not actually need a null-terminator.
1976
+ CharReaderPtr const reader(fact.newCharReader());
1977
+ return reader->parse(begin, end, root, errs);
1978
+ }
1979
+
1980
+ std::istream& operator>>(std::istream& sin, Value& root) {
1981
+ CharReaderBuilder b;
1982
+ std::string errs;
1983
+ bool ok = parseFromStream(b, sin, &root, &errs);
1984
+ if (!ok) {
1985
+ fprintf(stderr,
1986
+ "Error from reader: %s",
1987
+ errs.c_str());
1988
+
1989
+ throwRuntimeError("reader error");
1990
+ }
1991
+ return sin;
1992
+ }
1993
+
1994
+ } // namespace Json
1995
+
1996
+ // //////////////////////////////////////////////////////////////////////
1997
+ // End of content of file: src/lib_json/json_reader.cpp
1998
+ // //////////////////////////////////////////////////////////////////////
1999
+
2000
+
2001
+
2002
+
2003
+
2004
+
2005
+ // //////////////////////////////////////////////////////////////////////
2006
+ // Beginning of content of file: src/lib_json/json_valueiterator.inl
2007
+ // //////////////////////////////////////////////////////////////////////
2008
+
2009
+ // Copyright 2007-2010 Baptiste Lepilleur
2010
+ // Distributed under MIT license, or public domain if desired and
2011
+ // recognized in your jurisdiction.
2012
+ // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2013
+
2014
+ // included by json_value.cpp
2015
+
2016
+ namespace Json {
2017
+
2018
+ // //////////////////////////////////////////////////////////////////
2019
+ // //////////////////////////////////////////////////////////////////
2020
+ // //////////////////////////////////////////////////////////////////
2021
+ // class ValueIteratorBase
2022
+ // //////////////////////////////////////////////////////////////////
2023
+ // //////////////////////////////////////////////////////////////////
2024
+ // //////////////////////////////////////////////////////////////////
2025
+
2026
+ ValueIteratorBase::ValueIteratorBase()
2027
+ : current_(), isNull_(true) {
2028
+ }
2029
+
2030
+ ValueIteratorBase::ValueIteratorBase(
2031
+ const Value::ObjectValues::iterator& current)
2032
+ : current_(current), isNull_(false) {}
2033
+
2034
+ Value& ValueIteratorBase::deref() const {
2035
+ return current_->second;
2036
+ }
2037
+
2038
+ void ValueIteratorBase::increment() {
2039
+ ++current_;
2040
+ }
2041
+
2042
+ void ValueIteratorBase::decrement() {
2043
+ --current_;
2044
+ }
2045
+
2046
+ ValueIteratorBase::difference_type
2047
+ ValueIteratorBase::computeDistance(const SelfType& other) const {
2048
+ #ifdef JSON_USE_CPPTL_SMALLMAP
2049
+ return other.current_ - current_;
2050
+ #else
2051
+ // Iterator for null value are initialized using the default
2052
+ // constructor, which initialize current_ to the default
2053
+ // std::map::iterator. As begin() and end() are two instance
2054
+ // of the default std::map::iterator, they can not be compared.
2055
+ // To allow this, we handle this comparison specifically.
2056
+ if (isNull_ && other.isNull_) {
2057
+ return 0;
2058
+ }
2059
+
2060
+ // Usage of std::distance is not portable (does not compile with Sun Studio 12
2061
+ // RogueWave STL,
2062
+ // which is the one used by default).
2063
+ // Using a portable hand-made version for non random iterator instead:
2064
+ // return difference_type( std::distance( current_, other.current_ ) );
2065
+ difference_type myDistance = 0;
2066
+ for (Value::ObjectValues::iterator it = current_; it != other.current_;
2067
+ ++it) {
2068
+ ++myDistance;
2069
+ }
2070
+ return myDistance;
2071
+ #endif
2072
+ }
2073
+
2074
+ bool ValueIteratorBase::isEqual(const SelfType& other) const {
2075
+ if (isNull_) {
2076
+ return other.isNull_;
2077
+ }
2078
+ return current_ == other.current_;
2079
+ }
2080
+
2081
+ void ValueIteratorBase::copy(const SelfType& other) {
2082
+ current_ = other.current_;
2083
+ isNull_ = other.isNull_;
2084
+ }
2085
+
2086
+ Value ValueIteratorBase::key() const {
2087
+ const Value::CZString czstring = (*current_).first;
2088
+ if (czstring.data()) {
2089
+ if (czstring.isStaticString())
2090
+ return Value(StaticString(czstring.data()));
2091
+ return Value(czstring.data(), czstring.data() + czstring.length());
2092
+ }
2093
+ return Value(czstring.index());
2094
+ }
2095
+
2096
+ UInt ValueIteratorBase::index() const {
2097
+ const Value::CZString czstring = (*current_).first;
2098
+ if (!czstring.data())
2099
+ return czstring.index();
2100
+ return Value::UInt(-1);
2101
+ }
2102
+
2103
+ std::string ValueIteratorBase::name() const {
2104
+ char const* keey;
2105
+ char const* end;
2106
+ keey = memberName(&end);
2107
+ if (!keey) return std::string();
2108
+ return std::string(keey, end);
2109
+ }
2110
+
2111
+ char const* ValueIteratorBase::memberName() const {
2112
+ const char* cname = (*current_).first.data();
2113
+ return cname ? cname : "";
2114
+ }
2115
+
2116
+ char const* ValueIteratorBase::memberName(char const** end) const {
2117
+ const char* cname = (*current_).first.data();
2118
+ if (!cname) {
2119
+ *end = NULL;
2120
+ return NULL;
2121
+ }
2122
+ *end = cname + (*current_).first.length();
2123
+ return cname;
2124
+ }
2125
+
2126
+ // //////////////////////////////////////////////////////////////////
2127
+ // //////////////////////////////////////////////////////////////////
2128
+ // //////////////////////////////////////////////////////////////////
2129
+ // class ValueConstIterator
2130
+ // //////////////////////////////////////////////////////////////////
2131
+ // //////////////////////////////////////////////////////////////////
2132
+ // //////////////////////////////////////////////////////////////////
2133
+
2134
+ ValueConstIterator::ValueConstIterator() {}
2135
+
2136
+ ValueConstIterator::ValueConstIterator(
2137
+ const Value::ObjectValues::iterator& current)
2138
+ : ValueIteratorBase(current) {}
2139
+
2140
+ ValueConstIterator& ValueConstIterator::
2141
+ operator=(const ValueIteratorBase& other) {
2142
+ copy(other);
2143
+ return *this;
2144
+ }
2145
+
2146
+ // //////////////////////////////////////////////////////////////////
2147
+ // //////////////////////////////////////////////////////////////////
2148
+ // //////////////////////////////////////////////////////////////////
2149
+ // class ValueIterator
2150
+ // //////////////////////////////////////////////////////////////////
2151
+ // //////////////////////////////////////////////////////////////////
2152
+ // //////////////////////////////////////////////////////////////////
2153
+
2154
+ ValueIterator::ValueIterator() {}
2155
+
2156
+ ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
2157
+ : ValueIteratorBase(current) {}
2158
+
2159
+ ValueIterator::ValueIterator(const ValueConstIterator& other)
2160
+ : ValueIteratorBase(other) {}
2161
+
2162
+ ValueIterator::ValueIterator(const ValueIterator& other)
2163
+ : ValueIteratorBase(other) {}
2164
+
2165
+ ValueIterator& ValueIterator::operator=(const SelfType& other) {
2166
+ copy(other);
2167
+ return *this;
2168
+ }
2169
+
2170
+ } // namespace Json
2171
+
2172
+ // //////////////////////////////////////////////////////////////////////
2173
+ // End of content of file: src/lib_json/json_valueiterator.inl
2174
+ // //////////////////////////////////////////////////////////////////////
2175
+
2176
+
2177
+
2178
+
2179
+
2180
+
2181
+ // //////////////////////////////////////////////////////////////////////
2182
+ // Beginning of content of file: src/lib_json/json_value.cpp
2183
+ // //////////////////////////////////////////////////////////////////////
2184
+
2185
+ // Copyright 2011 Baptiste Lepilleur
2186
+ // Distributed under MIT license, or public domain if desired and
2187
+ // recognized in your jurisdiction.
2188
+ // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
2189
+
2190
+ #if !defined(JSON_IS_AMALGAMATION)
2191
+ #include <json/assertions.h>
2192
+ #include <json/value.h>
2193
+ #include <json/writer.h>
2194
+ #endif // if !defined(JSON_IS_AMALGAMATION)
2195
+ #include <math.h>
2196
+ #include <sstream>
2197
+ #include <utility>
2198
+ #include <cstring>
2199
+ #include <cassert>
2200
+ #ifdef JSON_USE_CPPTL
2201
+ #include <cpptl/conststring.h>
2202
+ #endif
2203
+ #include <cstddef> // size_t
2204
+ #include <algorithm> // min()
2205
+
2206
+ #define JSON_ASSERT_UNREACHABLE assert(false)
2207
+
2208
+ namespace Json {
2209
+
2210
+ // This is a walkaround to avoid the static initialization of Value::null.
2211
+ // kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
2212
+ // 8 (instead of 4) as a bit of future-proofing.
2213
+ #if defined(__ARMEL__)
2214
+ #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
2215
+ #else
2216
+ // This exists for binary compatibility only. Use nullRef.
2217
+ const Value Value::null;
2218
+ #define ALIGNAS(byte_alignment)
2219
+ #endif
2220
+ static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
2221
+ const unsigned char& kNullRef = kNull[0];
2222
+ const Value& Value::nullRef = reinterpret_cast<const Value&>(kNullRef);
2223
+
2224
+ const Int Value::minInt = Int(~(UInt(-1) / 2));
2225
+ const Int Value::maxInt = Int(UInt(-1) / 2);
2226
+ const UInt Value::maxUInt = UInt(-1);
2227
+ #if defined(JSON_HAS_INT64)
2228
+ const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
2229
+ const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
2230
+ const UInt64 Value::maxUInt64 = UInt64(-1);
2231
+ // The constant is hard-coded because some compiler have trouble
2232
+ // converting Value::maxUInt64 to a double correctly (AIX/xlC).
2233
+ // Assumes that UInt64 is a 64 bits integer.
2234
+ static const double maxUInt64AsDouble = 18446744073709551615.0;
2235
+ #endif // defined(JSON_HAS_INT64)
2236
+ const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
2237
+ const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
2238
+ const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
2239
+
2240
+ #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2241
+ template <typename T, typename U>
2242
+ static inline bool InRange(double d, T min, U max) {
2243
+ return d >= min && d <= max;
2244
+ }
2245
+ #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2246
+ static inline double integerToDouble(Json::UInt64 value) {
2247
+ return static_cast<double>(Int64(value / 2)) * 2.0 + Int64(value & 1);
2248
+ }
2249
+
2250
+ template <typename T> static inline double integerToDouble(T value) {
2251
+ return static_cast<double>(value);
2252
+ }
2253
+
2254
+ template <typename T, typename U>
2255
+ static inline bool InRange(double d, T min, U max) {
2256
+ return d >= integerToDouble(min) && d <= integerToDouble(max);
2257
+ }
2258
+ #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2259
+
2260
+ /** Duplicates the specified string value.
2261
+ * @param value Pointer to the string to duplicate. Must be zero-terminated if
2262
+ * length is "unknown".
2263
+ * @param length Length of the value. if equals to unknown, then it will be
2264
+ * computed using strlen(value).
2265
+ * @return Pointer on the duplicate instance of string.
2266
+ */
2267
+ static inline char* duplicateStringValue(const char* value,
2268
+ size_t length) {
2269
+ // Avoid an integer overflow in the call to malloc below by limiting length
2270
+ // to a sane value.
2271
+ if (length >= (size_t)Value::maxInt)
2272
+ length = Value::maxInt - 1;
2273
+
2274
+ char* newString = static_cast<char*>(malloc(length + 1));
2275
+ if (newString == NULL) {
2276
+ throwRuntimeError(
2277
+ "in Json::Value::duplicateStringValue(): "
2278
+ "Failed to allocate string value buffer");
2279
+ }
2280
+ memcpy(newString, value, length);
2281
+ newString[length] = 0;
2282
+ return newString;
2283
+ }
2284
+
2285
+ /* Record the length as a prefix.
2286
+ */
2287
+ static inline char* duplicateAndPrefixStringValue(
2288
+ const char* value,
2289
+ unsigned int length)
2290
+ {
2291
+ // Avoid an integer overflow in the call to malloc below by limiting length
2292
+ // to a sane value.
2293
+ JSON_ASSERT_MESSAGE(length <= (unsigned)Value::maxInt - sizeof(unsigned) - 1U,
2294
+ "in Json::Value::duplicateAndPrefixStringValue(): "
2295
+ "length too big for prefixing");
2296
+ unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
2297
+ char* newString = static_cast<char*>(malloc(actualLength));
2298
+ if (newString == 0) {
2299
+ throwRuntimeError(
2300
+ "in Json::Value::duplicateAndPrefixStringValue(): "
2301
+ "Failed to allocate string value buffer");
2302
+ }
2303
+ *reinterpret_cast<unsigned*>(newString) = length;
2304
+ memcpy(newString + sizeof(unsigned), value, length);
2305
+ newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
2306
+ return newString;
2307
+ }
2308
+ inline static void decodePrefixedString(
2309
+ bool isPrefixed, char const* prefixed,
2310
+ unsigned* length, char const** value)
2311
+ {
2312
+ if (!isPrefixed) {
2313
+ *length = static_cast<unsigned>(strlen(prefixed));
2314
+ *value = prefixed;
2315
+ } else {
2316
+ *length = *reinterpret_cast<unsigned const*>(prefixed);
2317
+ *value = prefixed + sizeof(unsigned);
2318
+ }
2319
+ }
2320
+ /** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
2321
+ */
2322
+ static inline void releaseStringValue(char* value) { free(value); }
2323
+
2324
+ } // namespace Json
2325
+
2326
+ // //////////////////////////////////////////////////////////////////
2327
+ // //////////////////////////////////////////////////////////////////
2328
+ // //////////////////////////////////////////////////////////////////
2329
+ // ValueInternals...
2330
+ // //////////////////////////////////////////////////////////////////
2331
+ // //////////////////////////////////////////////////////////////////
2332
+ // //////////////////////////////////////////////////////////////////
2333
+ #if !defined(JSON_IS_AMALGAMATION)
2334
+
2335
+ #include "json_valueiterator.inl"
2336
+ #endif // if !defined(JSON_IS_AMALGAMATION)
2337
+
2338
+ namespace Json {
2339
+
2340
+ Exception::Exception(std::string const& msg)
2341
+ : msg_(msg)
2342
+ {}
2343
+ Exception::~Exception() throw()
2344
+ {}
2345
+ char const* Exception::what() const throw()
2346
+ {
2347
+ return msg_.c_str();
2348
+ }
2349
+ RuntimeError::RuntimeError(std::string const& msg)
2350
+ : Exception(msg)
2351
+ {}
2352
+ LogicError::LogicError(std::string const& msg)
2353
+ : Exception(msg)
2354
+ {}
2355
+ void throwRuntimeError(std::string const& )
2356
+ {
2357
+ assert(false);
2358
+ // throw RuntimeError(msg);
2359
+ }
2360
+ void throwLogicError(std::string const&)
2361
+ {
2362
+ assert(false);
2363
+ // throw LogicError(msg);
2364
+ }
2365
+
2366
+ // //////////////////////////////////////////////////////////////////
2367
+ // //////////////////////////////////////////////////////////////////
2368
+ // //////////////////////////////////////////////////////////////////
2369
+ // class Value::CommentInfo
2370
+ // //////////////////////////////////////////////////////////////////
2371
+ // //////////////////////////////////////////////////////////////////
2372
+ // //////////////////////////////////////////////////////////////////
2373
+
2374
+ Value::CommentInfo::CommentInfo() : comment_(0) {}
2375
+
2376
+ Value::CommentInfo::~CommentInfo() {
2377
+ if (comment_)
2378
+ releaseStringValue(comment_);
2379
+ }
2380
+
2381
+ void Value::CommentInfo::setComment(const char* text, size_t len) {
2382
+ if (comment_) {
2383
+ releaseStringValue(comment_);
2384
+ comment_ = 0;
2385
+ }
2386
+ JSON_ASSERT(text != 0);
2387
+ JSON_ASSERT_MESSAGE(
2388
+ text[0] == '\0' || text[0] == '/',
2389
+ "in Json::Value::setComment(): Comments must start with /");
2390
+ // It seems that /**/ style comments are acceptable as well.
2391
+ comment_ = duplicateStringValue(text, len);
2392
+ }
2393
+
2394
+ // //////////////////////////////////////////////////////////////////
2395
+ // //////////////////////////////////////////////////////////////////
2396
+ // //////////////////////////////////////////////////////////////////
2397
+ // class Value::CZString
2398
+ // //////////////////////////////////////////////////////////////////
2399
+ // //////////////////////////////////////////////////////////////////
2400
+ // //////////////////////////////////////////////////////////////////
2401
+
2402
+ // Notes: policy_ indicates if the string was allocated when
2403
+ // a string is stored.
2404
+
2405
+ Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
2406
+
2407
+ Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
2408
+ : cstr_(str)
2409
+ {
2410
+ // allocate != duplicate
2411
+ storage_.policy_ = allocate & 0x3;
2412
+ storage_.length_ = ulength & 0x3FFFFFFF;
2413
+ }
2414
+
2415
+ Value::CZString::CZString(const CZString& other)
2416
+ : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0
2417
+ ? duplicateStringValue(other.cstr_, other.storage_.length_)
2418
+ : other.cstr_)
2419
+ {
2420
+ storage_.policy_ = (other.cstr_
2421
+ ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
2422
+ ? noDuplication : duplicate)
2423
+ : static_cast<DuplicationPolicy>(other.storage_.policy_));
2424
+ storage_.length_ = other.storage_.length_;
2425
+ }
2426
+
2427
+ Value::CZString::~CZString() {
2428
+ if (cstr_ && storage_.policy_ == duplicate)
2429
+ releaseStringValue(const_cast<char*>(cstr_));
2430
+ }
2431
+
2432
+ void Value::CZString::swap(CZString& other) {
2433
+ std::swap(cstr_, other.cstr_);
2434
+ std::swap(index_, other.index_);
2435
+ }
2436
+
2437
+ Value::CZString& Value::CZString::operator=(CZString other) {
2438
+ swap(other);
2439
+ return *this;
2440
+ }
2441
+
2442
+ bool Value::CZString::operator<(const CZString& other) const {
2443
+ if (!cstr_) return index_ < other.index_;
2444
+ //return strcmp(cstr_, other.cstr_) < 0;
2445
+ // Assume both are strings.
2446
+ unsigned this_len = this->storage_.length_;
2447
+ unsigned other_len = other.storage_.length_;
2448
+ unsigned min_len = std::min(this_len, other_len);
2449
+ int comp = memcmp(this->cstr_, other.cstr_, min_len);
2450
+ if (comp < 0) return true;
2451
+ if (comp > 0) return false;
2452
+ return (this_len < other_len);
2453
+ }
2454
+
2455
+ bool Value::CZString::operator==(const CZString& other) const {
2456
+ if (!cstr_) return index_ == other.index_;
2457
+ //return strcmp(cstr_, other.cstr_) == 0;
2458
+ // Assume both are strings.
2459
+ unsigned this_len = this->storage_.length_;
2460
+ unsigned other_len = other.storage_.length_;
2461
+ if (this_len != other_len) return false;
2462
+ int comp = memcmp(this->cstr_, other.cstr_, this_len);
2463
+ return comp == 0;
2464
+ }
2465
+
2466
+ ArrayIndex Value::CZString::index() const { return index_; }
2467
+
2468
+ //const char* Value::CZString::c_str() const { return cstr_; }
2469
+ const char* Value::CZString::data() const { return cstr_; }
2470
+ unsigned Value::CZString::length() const { return storage_.length_; }
2471
+ bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
2472
+
2473
+ // //////////////////////////////////////////////////////////////////
2474
+ // //////////////////////////////////////////////////////////////////
2475
+ // //////////////////////////////////////////////////////////////////
2476
+ // class Value::Value
2477
+ // //////////////////////////////////////////////////////////////////
2478
+ // //////////////////////////////////////////////////////////////////
2479
+ // //////////////////////////////////////////////////////////////////
2480
+
2481
+ /*! \internal Default constructor initialization must be equivalent to:
2482
+ * memset( this, 0, sizeof(Value) )
2483
+ * This optimization is used in ValueInternalMap fast allocator.
2484
+ */
2485
+ Value::Value(ValueType vtype) {
2486
+ initBasic(vtype);
2487
+ switch (vtype) {
2488
+ case nullValue:
2489
+ break;
2490
+ case intValue:
2491
+ case uintValue:
2492
+ value_.int_ = 0;
2493
+ break;
2494
+ case realValue:
2495
+ value_.real_ = 0.0;
2496
+ break;
2497
+ case stringValue:
2498
+ value_.string_ = 0;
2499
+ break;
2500
+ case arrayValue:
2501
+ case objectValue:
2502
+ value_.map_ = new ObjectValues();
2503
+ break;
2504
+ case booleanValue:
2505
+ value_.bool_ = false;
2506
+ break;
2507
+ default:
2508
+ JSON_ASSERT_UNREACHABLE;
2509
+ }
2510
+ }
2511
+
2512
+ Value::Value(Int value) {
2513
+ initBasic(intValue);
2514
+ value_.int_ = value;
2515
+ }
2516
+
2517
+ Value::Value(UInt value) {
2518
+ initBasic(uintValue);
2519
+ value_.uint_ = value;
2520
+ }
2521
+ #if defined(JSON_HAS_INT64)
2522
+ Value::Value(Int64 value) {
2523
+ initBasic(intValue);
2524
+ value_.int_ = value;
2525
+ }
2526
+ Value::Value(UInt64 value) {
2527
+ initBasic(uintValue);
2528
+ value_.uint_ = value;
2529
+ }
2530
+ #endif // defined(JSON_HAS_INT64)
2531
+
2532
+ Value::Value(double value) {
2533
+ initBasic(realValue);
2534
+ value_.real_ = value;
2535
+ }
2536
+
2537
+ Value::Value(const char* value) {
2538
+ initBasic(stringValue, true);
2539
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
2540
+ }
2541
+
2542
+ Value::Value(const char* beginValue, const char* endValue) {
2543
+ initBasic(stringValue, true);
2544
+ value_.string_ =
2545
+ duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
2546
+ }
2547
+
2548
+ Value::Value(const std::string& value) {
2549
+ initBasic(stringValue, true);
2550
+ value_.string_ =
2551
+ duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
2552
+ }
2553
+
2554
+ Value::Value(const StaticString& value) {
2555
+ initBasic(stringValue);
2556
+ value_.string_ = const_cast<char*>(value.c_str());
2557
+ }
2558
+
2559
+ #ifdef JSON_USE_CPPTL
2560
+ Value::Value(const CppTL::ConstString& value) {
2561
+ initBasic(stringValue, true);
2562
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
2563
+ }
2564
+ #endif
2565
+
2566
+ Value::Value(bool value) {
2567
+ initBasic(booleanValue);
2568
+ value_.bool_ = value;
2569
+ }
2570
+
2571
+ Value::Value(Value const& other)
2572
+ : type_(other.type_), allocated_(false)
2573
+ ,
2574
+ comments_(0)
2575
+ {
2576
+ switch (type_) {
2577
+ case nullValue:
2578
+ case intValue:
2579
+ case uintValue:
2580
+ case realValue:
2581
+ case booleanValue:
2582
+ value_ = other.value_;
2583
+ break;
2584
+ case stringValue:
2585
+ if (other.value_.string_ && other.allocated_) {
2586
+ unsigned len;
2587
+ char const* str;
2588
+ decodePrefixedString(other.allocated_, other.value_.string_,
2589
+ &len, &str);
2590
+ value_.string_ = duplicateAndPrefixStringValue(str, len);
2591
+ allocated_ = true;
2592
+ } else {
2593
+ value_.string_ = other.value_.string_;
2594
+ allocated_ = false;
2595
+ }
2596
+ break;
2597
+ case arrayValue:
2598
+ case objectValue:
2599
+ value_.map_ = new ObjectValues(*other.value_.map_);
2600
+ break;
2601
+ default:
2602
+ JSON_ASSERT_UNREACHABLE;
2603
+ }
2604
+ if (other.comments_) {
2605
+ comments_ = new CommentInfo[numberOfCommentPlacement];
2606
+ for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
2607
+ const CommentInfo& otherComment = other.comments_[comment];
2608
+ if (otherComment.comment_)
2609
+ comments_[comment].setComment(
2610
+ otherComment.comment_, strlen(otherComment.comment_));
2611
+ }
2612
+ }
2613
+ }
2614
+
2615
+ Value::~Value() {
2616
+ switch (type_) {
2617
+ case nullValue:
2618
+ case intValue:
2619
+ case uintValue:
2620
+ case realValue:
2621
+ case booleanValue:
2622
+ break;
2623
+ case stringValue:
2624
+ if (allocated_)
2625
+ releaseStringValue(value_.string_);
2626
+ break;
2627
+ case arrayValue:
2628
+ case objectValue:
2629
+ delete value_.map_;
2630
+ break;
2631
+ default:
2632
+ JSON_ASSERT_UNREACHABLE;
2633
+ }
2634
+
2635
+ if (comments_)
2636
+ delete[] comments_;
2637
+ }
2638
+
2639
+ Value &Value::operator=(const Value &other) {
2640
+ Value temp(other);
2641
+ swap(temp);
2642
+ return *this;
2643
+ }
2644
+
2645
+ void Value::swapPayload(Value& other) {
2646
+ ValueType temp = type_;
2647
+ type_ = other.type_;
2648
+ other.type_ = temp;
2649
+ std::swap(value_, other.value_);
2650
+ int temp2 = allocated_;
2651
+ allocated_ = other.allocated_;
2652
+ other.allocated_ = temp2 & 0x1;
2653
+ }
2654
+
2655
+ void Value::swap(Value& other) {
2656
+ swapPayload(other);
2657
+ std::swap(comments_, other.comments_);
2658
+ }
2659
+
2660
+ ValueType Value::type() const { return type_; }
2661
+
2662
+ int Value::compare(const Value& other) const {
2663
+ if (*this < other)
2664
+ return -1;
2665
+ if (*this > other)
2666
+ return 1;
2667
+ return 0;
2668
+ }
2669
+
2670
+ bool Value::operator<(const Value& other) const {
2671
+ int typeDelta = type_ - other.type_;
2672
+ if (typeDelta)
2673
+ return typeDelta < 0 ? true : false;
2674
+ switch (type_) {
2675
+ case nullValue:
2676
+ return false;
2677
+ case intValue:
2678
+ return value_.int_ < other.value_.int_;
2679
+ case uintValue:
2680
+ return value_.uint_ < other.value_.uint_;
2681
+ case realValue:
2682
+ return value_.real_ < other.value_.real_;
2683
+ case booleanValue:
2684
+ return value_.bool_ < other.value_.bool_;
2685
+ case stringValue:
2686
+ {
2687
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
2688
+ if (other.value_.string_) return true;
2689
+ else return false;
2690
+ }
2691
+ unsigned this_len;
2692
+ unsigned other_len;
2693
+ char const* this_str;
2694
+ char const* other_str;
2695
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
2696
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
2697
+ unsigned min_len = std::min(this_len, other_len);
2698
+ int comp = memcmp(this_str, other_str, min_len);
2699
+ if (comp < 0) return true;
2700
+ if (comp > 0) return false;
2701
+ return (this_len < other_len);
2702
+ }
2703
+ case arrayValue:
2704
+ case objectValue: {
2705
+ int delta = int(value_.map_->size() - other.value_.map_->size());
2706
+ if (delta)
2707
+ return delta < 0;
2708
+ return (*value_.map_) < (*other.value_.map_);
2709
+ }
2710
+ default:
2711
+ JSON_ASSERT_UNREACHABLE;
2712
+ }
2713
+ return false; // unreachable
2714
+ }
2715
+
2716
+ bool Value::operator<=(const Value& other) const { return !(other < *this); }
2717
+
2718
+ bool Value::operator>=(const Value& other) const { return !(*this < other); }
2719
+
2720
+ bool Value::operator>(const Value& other) const { return other < *this; }
2721
+
2722
+ bool Value::operator==(const Value& other) const {
2723
+ // if ( type_ != other.type_ )
2724
+ // GCC 2.95.3 says:
2725
+ // attempt to take address of bit-field structure member `Json::Value::type_'
2726
+ // Beats me, but a temp solves the problem.
2727
+ int temp = other.type_;
2728
+ if (type_ != temp)
2729
+ return false;
2730
+ switch (type_) {
2731
+ case nullValue:
2732
+ return true;
2733
+ case intValue:
2734
+ return value_.int_ == other.value_.int_;
2735
+ case uintValue:
2736
+ return value_.uint_ == other.value_.uint_;
2737
+ case realValue:
2738
+ return value_.real_ == other.value_.real_;
2739
+ case booleanValue:
2740
+ return value_.bool_ == other.value_.bool_;
2741
+ case stringValue:
2742
+ {
2743
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
2744
+ return (value_.string_ == other.value_.string_);
2745
+ }
2746
+ unsigned this_len;
2747
+ unsigned other_len;
2748
+ char const* this_str;
2749
+ char const* other_str;
2750
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
2751
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
2752
+ if (this_len != other_len) return false;
2753
+ int comp = memcmp(this_str, other_str, this_len);
2754
+ return comp == 0;
2755
+ }
2756
+ case arrayValue:
2757
+ case objectValue:
2758
+ return value_.map_->size() == other.value_.map_->size() &&
2759
+ (*value_.map_) == (*other.value_.map_);
2760
+ default:
2761
+ JSON_ASSERT_UNREACHABLE;
2762
+ }
2763
+ return false; // unreachable
2764
+ }
2765
+
2766
+ bool Value::operator!=(const Value& other) const { return !(*this == other); }
2767
+
2768
+ const char* Value::asCString() const {
2769
+ JSON_ASSERT_MESSAGE(type_ == stringValue,
2770
+ "in Json::Value::asCString(): requires stringValue");
2771
+ if (value_.string_ == 0) return 0;
2772
+ unsigned this_len;
2773
+ char const* this_str;
2774
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
2775
+ return this_str;
2776
+ }
2777
+
2778
+ bool Value::getString(char const** str, char const** cend) const {
2779
+ if (type_ != stringValue) return false;
2780
+ if (value_.string_ == 0) return false;
2781
+ unsigned length;
2782
+ decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
2783
+ *cend = *str + length;
2784
+ return true;
2785
+ }
2786
+
2787
+ std::string Value::asString() const {
2788
+ switch (type_) {
2789
+ case nullValue:
2790
+ return "";
2791
+ case stringValue:
2792
+ {
2793
+ if (value_.string_ == 0) return "";
2794
+ unsigned this_len;
2795
+ char const* this_str;
2796
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
2797
+ return std::string(this_str, this_len);
2798
+ }
2799
+ case booleanValue:
2800
+ return value_.bool_ ? "true" : "false";
2801
+ case intValue:
2802
+ return valueToString(value_.int_);
2803
+ case uintValue:
2804
+ return valueToString(value_.uint_);
2805
+ case realValue:
2806
+ return valueToString(value_.real_);
2807
+ default:
2808
+ JSON_FAIL_MESSAGE("Type is not convertible to string");
2809
+ }
2810
+ }
2811
+
2812
+ #ifdef JSON_USE_CPPTL
2813
+ CppTL::ConstString Value::asConstString() const {
2814
+ unsigned len;
2815
+ char const* str;
2816
+ decodePrefixedString(allocated_, value_.string_,
2817
+ &len, &str);
2818
+ return CppTL::ConstString(str, len);
2819
+ }
2820
+ #endif
2821
+
2822
+ Value::Int Value::asInt() const {
2823
+ switch (type_) {
2824
+ case intValue:
2825
+ JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
2826
+ return Int(value_.int_);
2827
+ case uintValue:
2828
+ JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
2829
+ return Int(value_.uint_);
2830
+ case realValue:
2831
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
2832
+ "double out of Int range");
2833
+ return Int(value_.real_);
2834
+ case nullValue:
2835
+ return 0;
2836
+ case booleanValue:
2837
+ return value_.bool_ ? 1 : 0;
2838
+ default:
2839
+ break;
2840
+ }
2841
+ JSON_FAIL_MESSAGE("Value is not convertible to Int.");
2842
+ }
2843
+
2844
+ Value::UInt Value::asUInt() const {
2845
+ switch (type_) {
2846
+ case intValue:
2847
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
2848
+ return UInt(value_.int_);
2849
+ case uintValue:
2850
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
2851
+ return UInt(value_.uint_);
2852
+ case realValue:
2853
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
2854
+ "double out of UInt range");
2855
+ return UInt(value_.real_);
2856
+ case nullValue:
2857
+ return 0;
2858
+ case booleanValue:
2859
+ return value_.bool_ ? 1 : 0;
2860
+ default:
2861
+ break;
2862
+ }
2863
+ JSON_FAIL_MESSAGE("Value is not convertible to UInt.");
2864
+ }
2865
+
2866
+ #if defined(JSON_HAS_INT64)
2867
+
2868
+ Value::Int64 Value::asInt64() const {
2869
+ switch (type_) {
2870
+ case intValue:
2871
+ return Int64(value_.int_);
2872
+ case uintValue:
2873
+ JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
2874
+ return Int64(value_.uint_);
2875
+ case realValue:
2876
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
2877
+ "double out of Int64 range");
2878
+ return Int64(value_.real_);
2879
+ case nullValue:
2880
+ return 0;
2881
+ case booleanValue:
2882
+ return value_.bool_ ? 1 : 0;
2883
+ default:
2884
+ break;
2885
+ }
2886
+ JSON_FAIL_MESSAGE("Value is not convertible to Int64.");
2887
+ }
2888
+
2889
+ Value::UInt64 Value::asUInt64() const {
2890
+ switch (type_) {
2891
+ case intValue:
2892
+ JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
2893
+ return UInt64(value_.int_);
2894
+ case uintValue:
2895
+ return UInt64(value_.uint_);
2896
+ case realValue:
2897
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
2898
+ "double out of UInt64 range");
2899
+ return UInt64(value_.real_);
2900
+ case nullValue:
2901
+ return 0;
2902
+ case booleanValue:
2903
+ return value_.bool_ ? 1 : 0;
2904
+ default:
2905
+ break;
2906
+ }
2907
+ JSON_FAIL_MESSAGE("Value is not convertible to UInt64.");
2908
+ }
2909
+ #endif // if defined(JSON_HAS_INT64)
2910
+
2911
+ LargestInt Value::asLargestInt() const {
2912
+ #if defined(JSON_NO_INT64)
2913
+ return asInt();
2914
+ #else
2915
+ return asInt64();
2916
+ #endif
2917
+ }
2918
+
2919
+ LargestUInt Value::asLargestUInt() const {
2920
+ #if defined(JSON_NO_INT64)
2921
+ return asUInt();
2922
+ #else
2923
+ return asUInt64();
2924
+ #endif
2925
+ }
2926
+
2927
+ double Value::asDouble() const {
2928
+ switch (type_) {
2929
+ case intValue:
2930
+ return static_cast<double>(value_.int_);
2931
+ case uintValue:
2932
+ #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2933
+ return static_cast<double>(value_.uint_);
2934
+ #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2935
+ return integerToDouble(value_.uint_);
2936
+ #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2937
+ case realValue:
2938
+ return value_.real_;
2939
+ case nullValue:
2940
+ return 0.0;
2941
+ case booleanValue:
2942
+ return value_.bool_ ? 1.0 : 0.0;
2943
+ default:
2944
+ break;
2945
+ }
2946
+ JSON_FAIL_MESSAGE("Value is not convertible to double.");
2947
+ }
2948
+
2949
+ float Value::asFloat() const {
2950
+ switch (type_) {
2951
+ case intValue:
2952
+ return static_cast<float>(value_.int_);
2953
+ case uintValue:
2954
+ #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2955
+ return static_cast<float>(value_.uint_);
2956
+ #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2957
+ return integerToDouble(value_.uint_);
2958
+ #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
2959
+ case realValue:
2960
+ return static_cast<float>(value_.real_);
2961
+ case nullValue:
2962
+ return 0.0;
2963
+ case booleanValue:
2964
+ return value_.bool_ ? 1.0f : 0.0f;
2965
+ default:
2966
+ break;
2967
+ }
2968
+ JSON_FAIL_MESSAGE("Value is not convertible to float.");
2969
+ }
2970
+
2971
+ bool Value::asBool() const {
2972
+ switch (type_) {
2973
+ case booleanValue:
2974
+ return value_.bool_;
2975
+ case nullValue:
2976
+ return false;
2977
+ case intValue:
2978
+ return value_.int_ ? true : false;
2979
+ case uintValue:
2980
+ return value_.uint_ ? true : false;
2981
+ case realValue:
2982
+ // This is kind of strange. Not recommended.
2983
+ return (value_.real_ != 0.0) ? true : false;
2984
+ default:
2985
+ break;
2986
+ }
2987
+ JSON_FAIL_MESSAGE("Value is not convertible to bool.");
2988
+ }
2989
+
2990
+ bool Value::isConvertibleTo(ValueType other) const {
2991
+ switch (other) {
2992
+ case nullValue:
2993
+ return (isNumeric() && asDouble() == 0.0) ||
2994
+ (type_ == booleanValue && value_.bool_ == false) ||
2995
+ (type_ == stringValue && asString() == "") ||
2996
+ (type_ == arrayValue && value_.map_->size() == 0) ||
2997
+ (type_ == objectValue && value_.map_->size() == 0) ||
2998
+ type_ == nullValue;
2999
+ case intValue:
3000
+ return isInt() ||
3001
+ (type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
3002
+ type_ == booleanValue || type_ == nullValue;
3003
+ case uintValue:
3004
+ return isUInt() ||
3005
+ (type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
3006
+ type_ == booleanValue || type_ == nullValue;
3007
+ case realValue:
3008
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
3009
+ case booleanValue:
3010
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
3011
+ case stringValue:
3012
+ return isNumeric() || type_ == booleanValue || type_ == stringValue ||
3013
+ type_ == nullValue;
3014
+ case arrayValue:
3015
+ return type_ == arrayValue || type_ == nullValue;
3016
+ case objectValue:
3017
+ return type_ == objectValue || type_ == nullValue;
3018
+ }
3019
+ JSON_ASSERT_UNREACHABLE;
3020
+ return false;
3021
+ }
3022
+
3023
+ /// Number of values in array or object
3024
+ ArrayIndex Value::size() const {
3025
+ switch (type_) {
3026
+ case nullValue:
3027
+ case intValue:
3028
+ case uintValue:
3029
+ case realValue:
3030
+ case booleanValue:
3031
+ case stringValue:
3032
+ return 0;
3033
+ case arrayValue: // size of the array is highest index + 1
3034
+ if (!value_.map_->empty()) {
3035
+ ObjectValues::const_iterator itLast = value_.map_->end();
3036
+ --itLast;
3037
+ return (*itLast).first.index() + 1;
3038
+ }
3039
+ return 0;
3040
+ case objectValue:
3041
+ return ArrayIndex(value_.map_->size());
3042
+ }
3043
+ JSON_ASSERT_UNREACHABLE;
3044
+ return 0; // unreachable;
3045
+ }
3046
+
3047
+ bool Value::empty() const {
3048
+ if (isNull() || isArray() || isObject())
3049
+ return size() == 0u;
3050
+ else
3051
+ return false;
3052
+ }
3053
+
3054
+ bool Value::operator!() const { return isNull(); }
3055
+
3056
+ void Value::clear() {
3057
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
3058
+ type_ == objectValue,
3059
+ "in Json::Value::clear(): requires complex value");
3060
+ switch (type_) {
3061
+ case arrayValue:
3062
+ case objectValue:
3063
+ value_.map_->clear();
3064
+ break;
3065
+ default:
3066
+ break;
3067
+ }
3068
+ }
3069
+
3070
+ void Value::resize(ArrayIndex newSize) {
3071
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
3072
+ "in Json::Value::resize(): requires arrayValue");
3073
+ if (type_ == nullValue)
3074
+ *this = Value(arrayValue);
3075
+ ArrayIndex oldSize = size();
3076
+ if (newSize == 0)
3077
+ clear();
3078
+ else if (newSize > oldSize)
3079
+ (*this)[newSize - 1];
3080
+ else {
3081
+ for (ArrayIndex index = newSize; index < oldSize; ++index) {
3082
+ value_.map_->erase(index);
3083
+ }
3084
+ assert(size() == newSize);
3085
+ }
3086
+ }
3087
+
3088
+ Value& Value::operator[](ArrayIndex index) {
3089
+ JSON_ASSERT_MESSAGE(
3090
+ type_ == nullValue || type_ == arrayValue,
3091
+ "in Json::Value::operator[](ArrayIndex): requires arrayValue");
3092
+ if (type_ == nullValue)
3093
+ *this = Value(arrayValue);
3094
+ CZString key(index);
3095
+ ObjectValues::iterator it = value_.map_->lower_bound(key);
3096
+ if (it != value_.map_->end() && (*it).first == key)
3097
+ return (*it).second;
3098
+
3099
+ ObjectValues::value_type defaultValue(key, nullRef);
3100
+ it = value_.map_->insert(it, defaultValue);
3101
+ return (*it).second;
3102
+ }
3103
+
3104
+ Value& Value::operator[](int index) {
3105
+ JSON_ASSERT_MESSAGE(
3106
+ index >= 0,
3107
+ "in Json::Value::operator[](int index): index cannot be negative");
3108
+ return (*this)[ArrayIndex(index)];
3109
+ }
3110
+
3111
+ const Value& Value::operator[](ArrayIndex index) const {
3112
+ JSON_ASSERT_MESSAGE(
3113
+ type_ == nullValue || type_ == arrayValue,
3114
+ "in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
3115
+ if (type_ == nullValue)
3116
+ return nullRef;
3117
+ CZString key(index);
3118
+ ObjectValues::const_iterator it = value_.map_->find(key);
3119
+ if (it == value_.map_->end())
3120
+ return nullRef;
3121
+ return (*it).second;
3122
+ }
3123
+
3124
+ const Value& Value::operator[](int index) const {
3125
+ JSON_ASSERT_MESSAGE(
3126
+ index >= 0,
3127
+ "in Json::Value::operator[](int index) const: index cannot be negative");
3128
+ return (*this)[ArrayIndex(index)];
3129
+ }
3130
+
3131
+ void Value::initBasic(ValueType vtype, bool allocated) {
3132
+ type_ = vtype;
3133
+ allocated_ = allocated;
3134
+ comments_ = 0;
3135
+ }
3136
+
3137
+ // Access an object value by name, create a null member if it does not exist.
3138
+ // @pre Type of '*this' is object or null.
3139
+ // @param key is null-terminated.
3140
+ Value& Value::resolveReference(const char* key) {
3141
+ JSON_ASSERT_MESSAGE(
3142
+ type_ == nullValue || type_ == objectValue,
3143
+ "in Json::Value::resolveReference(): requires objectValue");
3144
+ if (type_ == nullValue)
3145
+ *this = Value(objectValue);
3146
+ CZString actualKey(
3147
+ key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
3148
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
3149
+ if (it != value_.map_->end() && (*it).first == actualKey)
3150
+ return (*it).second;
3151
+
3152
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
3153
+ it = value_.map_->insert(it, defaultValue);
3154
+ Value& value = (*it).second;
3155
+ return value;
3156
+ }
3157
+
3158
+ // @param key is not null-terminated.
3159
+ Value& Value::resolveReference(char const* key, char const* cend)
3160
+ {
3161
+ JSON_ASSERT_MESSAGE(
3162
+ type_ == nullValue || type_ == objectValue,
3163
+ "in Json::Value::resolveReference(key, end): requires objectValue");
3164
+ if (type_ == nullValue)
3165
+ *this = Value(objectValue);
3166
+ CZString actualKey(
3167
+ key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
3168
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
3169
+ if (it != value_.map_->end() && (*it).first == actualKey)
3170
+ return (*it).second;
3171
+
3172
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
3173
+ it = value_.map_->insert(it, defaultValue);
3174
+ Value& value = (*it).second;
3175
+ return value;
3176
+ }
3177
+
3178
+ Value Value::get(ArrayIndex index, const Value& defaultValue) const {
3179
+ const Value* value = &((*this)[index]);
3180
+ return value == &nullRef ? defaultValue : *value;
3181
+ }
3182
+
3183
+ bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
3184
+
3185
+ Value const* Value::find(char const* key, char const* cend) const
3186
+ {
3187
+ JSON_ASSERT_MESSAGE(
3188
+ type_ == nullValue || type_ == objectValue,
3189
+ "in Json::Value::find(key, end, found): requires objectValue or nullValue");
3190
+ if (type_ == nullValue) return NULL;
3191
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
3192
+ ObjectValues::const_iterator it = value_.map_->find(actualKey);
3193
+ if (it == value_.map_->end()) return NULL;
3194
+ return &(*it).second;
3195
+ }
3196
+ const Value& Value::operator[](const char* key) const
3197
+ {
3198
+ Value const* found = find(key, key + strlen(key));
3199
+ if (!found) return nullRef;
3200
+ return *found;
3201
+ }
3202
+ Value const& Value::operator[](std::string const& key) const
3203
+ {
3204
+ Value const* found = find(key.data(), key.data() + key.length());
3205
+ if (!found) return nullRef;
3206
+ return *found;
3207
+ }
3208
+
3209
+ Value& Value::operator[](const char* key) {
3210
+ return resolveReference(key, key + strlen(key));
3211
+ }
3212
+
3213
+ Value& Value::operator[](const std::string& key) {
3214
+ return resolveReference(key.data(), key.data() + key.length());
3215
+ }
3216
+
3217
+ Value& Value::operator[](const StaticString& key) {
3218
+ return resolveReference(key.c_str());
3219
+ }
3220
+
3221
+ #ifdef JSON_USE_CPPTL
3222
+ Value& Value::operator[](const CppTL::ConstString& key) {
3223
+ return resolveReference(key.c_str(), key.end_c_str());
3224
+ }
3225
+ Value const& Value::operator[](CppTL::ConstString const& key) const
3226
+ {
3227
+ Value const* found = find(key.c_str(), key.end_c_str());
3228
+ if (!found) return nullRef;
3229
+ return *found;
3230
+ }
3231
+ #endif
3232
+
3233
+ Value& Value::append(const Value& value) { return (*this)[size()] = value; }
3234
+
3235
+ Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
3236
+ {
3237
+ Value const* found = find(key, cend);
3238
+ return !found ? defaultValue : *found;
3239
+ }
3240
+ Value Value::get(char const* key, Value const& defaultValue) const
3241
+ {
3242
+ return get(key, key + strlen(key), defaultValue);
3243
+ }
3244
+ Value Value::get(std::string const& key, Value const& defaultValue) const
3245
+ {
3246
+ return get(key.data(), key.data() + key.length(), defaultValue);
3247
+ }
3248
+
3249
+
3250
+ bool Value::removeMember(const char* key, const char* cend, Value* removed)
3251
+ {
3252
+ if (type_ != objectValue) {
3253
+ return false;
3254
+ }
3255
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
3256
+ ObjectValues::iterator it = value_.map_->find(actualKey);
3257
+ if (it == value_.map_->end())
3258
+ return false;
3259
+ *removed = it->second;
3260
+ value_.map_->erase(it);
3261
+ return true;
3262
+ }
3263
+ bool Value::removeMember(const char* key, Value* removed)
3264
+ {
3265
+ return removeMember(key, key + strlen(key), removed);
3266
+ }
3267
+ bool Value::removeMember(std::string const& key, Value* removed)
3268
+ {
3269
+ return removeMember(key.data(), key.data() + key.length(), removed);
3270
+ }
3271
+ Value Value::removeMember(const char* key)
3272
+ {
3273
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
3274
+ "in Json::Value::removeMember(): requires objectValue");
3275
+ if (type_ == nullValue)
3276
+ return nullRef;
3277
+
3278
+ Value removed; // null
3279
+ removeMember(key, key + strlen(key), &removed);
3280
+ return removed; // still null if removeMember() did nothing
3281
+ }
3282
+ Value Value::removeMember(const std::string& key)
3283
+ {
3284
+ return removeMember(key.c_str());
3285
+ }
3286
+
3287
+ bool Value::removeIndex(ArrayIndex index, Value* removed) {
3288
+ if (type_ != arrayValue) {
3289
+ return false;
3290
+ }
3291
+ CZString key(index);
3292
+ ObjectValues::iterator it = value_.map_->find(key);
3293
+ if (it == value_.map_->end()) {
3294
+ return false;
3295
+ }
3296
+ *removed = it->second;
3297
+ ArrayIndex oldSize = size();
3298
+ // shift left all items left, into the place of the "removed"
3299
+ for (ArrayIndex i = index; i < (oldSize - 1); ++i){
3300
+ CZString keey(i);
3301
+ (*value_.map_)[keey] = (*this)[i + 1];
3302
+ }
3303
+ // erase the last one ("leftover")
3304
+ CZString keyLast(oldSize - 1);
3305
+ ObjectValues::iterator itLast = value_.map_->find(keyLast);
3306
+ value_.map_->erase(itLast);
3307
+ return true;
3308
+ }
3309
+
3310
+ #ifdef JSON_USE_CPPTL
3311
+ Value Value::get(const CppTL::ConstString& key,
3312
+ const Value& defaultValue) const {
3313
+ return get(key.c_str(), key.end_c_str(), defaultValue);
3314
+ }
3315
+ #endif
3316
+
3317
+ bool Value::isMember(char const* key, char const* cend) const
3318
+ {
3319
+ Value const* value = find(key, cend);
3320
+ return NULL != value;
3321
+ }
3322
+ bool Value::isMember(char const* key) const
3323
+ {
3324
+ return isMember(key, key + strlen(key));
3325
+ }
3326
+ bool Value::isMember(std::string const& key) const
3327
+ {
3328
+ return isMember(key.data(), key.data() + key.length());
3329
+ }
3330
+
3331
+ #ifdef JSON_USE_CPPTL
3332
+ bool Value::isMember(const CppTL::ConstString& key) const {
3333
+ return isMember(key.c_str(), key.end_c_str());
3334
+ }
3335
+ #endif
3336
+
3337
+ Value::Members Value::getMemberNames() const {
3338
+ JSON_ASSERT_MESSAGE(
3339
+ type_ == nullValue || type_ == objectValue,
3340
+ "in Json::Value::getMemberNames(), value must be objectValue");
3341
+ if (type_ == nullValue)
3342
+ return Value::Members();
3343
+ Members members;
3344
+ members.reserve(value_.map_->size());
3345
+ ObjectValues::const_iterator it = value_.map_->begin();
3346
+ ObjectValues::const_iterator itEnd = value_.map_->end();
3347
+ for (; it != itEnd; ++it) {
3348
+ members.push_back(std::string((*it).first.data(),
3349
+ (*it).first.length()));
3350
+ }
3351
+ return members;
3352
+ }
3353
+ //
3354
+ //# ifdef JSON_USE_CPPTL
3355
+ // EnumMemberNames
3356
+ // Value::enumMemberNames() const
3357
+ //{
3358
+ // if ( type_ == objectValue )
3359
+ // {
3360
+ // return CppTL::Enum::any( CppTL::Enum::transform(
3361
+ // CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
3362
+ // MemberNamesTransform() ) );
3363
+ // }
3364
+ // return EnumMemberNames();
3365
+ //}
3366
+ //
3367
+ //
3368
+ // EnumValues
3369
+ // Value::enumValues() const
3370
+ //{
3371
+ // if ( type_ == objectValue || type_ == arrayValue )
3372
+ // return CppTL::Enum::anyValues( *(value_.map_),
3373
+ // CppTL::Type<const Value &>() );
3374
+ // return EnumValues();
3375
+ //}
3376
+ //
3377
+ //# endif
3378
+
3379
+ static bool IsIntegral(double d) {
3380
+ double integral_part;
3381
+ return modf(d, &integral_part) == 0.0;
3382
+ }
3383
+
3384
+ bool Value::isNull() const { return type_ == nullValue; }
3385
+
3386
+ bool Value::isBool() const { return type_ == booleanValue; }
3387
+
3388
+ bool Value::isInt() const {
3389
+ switch (type_) {
3390
+ case intValue:
3391
+ return value_.int_ >= minInt && value_.int_ <= maxInt;
3392
+ case uintValue:
3393
+ return value_.uint_ <= UInt(maxInt);
3394
+ case realValue:
3395
+ return value_.real_ >= minInt && value_.real_ <= maxInt &&
3396
+ IsIntegral(value_.real_);
3397
+ default:
3398
+ break;
3399
+ }
3400
+ return false;
3401
+ }
3402
+
3403
+ bool Value::isUInt() const {
3404
+ switch (type_) {
3405
+ case intValue:
3406
+ return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
3407
+ case uintValue:
3408
+ return value_.uint_ <= maxUInt;
3409
+ case realValue:
3410
+ return value_.real_ >= 0 && value_.real_ <= maxUInt &&
3411
+ IsIntegral(value_.real_);
3412
+ default:
3413
+ break;
3414
+ }
3415
+ return false;
3416
+ }
3417
+
3418
+ bool Value::isInt64() const {
3419
+ #if defined(JSON_HAS_INT64)
3420
+ switch (type_) {
3421
+ case intValue:
3422
+ return true;
3423
+ case uintValue:
3424
+ return value_.uint_ <= UInt64(maxInt64);
3425
+ case realValue:
3426
+ // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
3427
+ // double, so double(maxInt64) will be rounded up to 2^63. Therefore we
3428
+ // require the value to be strictly less than the limit.
3429
+ return value_.real_ >= double(minInt64) &&
3430
+ value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
3431
+ default:
3432
+ break;
3433
+ }
3434
+ #endif // JSON_HAS_INT64
3435
+ return false;
3436
+ }
3437
+
3438
+ bool Value::isUInt64() const {
3439
+ #if defined(JSON_HAS_INT64)
3440
+ switch (type_) {
3441
+ case intValue:
3442
+ return value_.int_ >= 0;
3443
+ case uintValue:
3444
+ return true;
3445
+ case realValue:
3446
+ // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
3447
+ // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
3448
+ // require the value to be strictly less than the limit.
3449
+ return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
3450
+ IsIntegral(value_.real_);
3451
+ default:
3452
+ break;
3453
+ }
3454
+ #endif // JSON_HAS_INT64
3455
+ return false;
3456
+ }
3457
+
3458
+ bool Value::isIntegral() const {
3459
+ #if defined(JSON_HAS_INT64)
3460
+ return isInt64() || isUInt64();
3461
+ #else
3462
+ return isInt() || isUInt();
3463
+ #endif
3464
+ }
3465
+
3466
+ bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
3467
+
3468
+ bool Value::isNumeric() const { return isIntegral() || isDouble(); }
3469
+
3470
+ bool Value::isString() const { return type_ == stringValue; }
3471
+
3472
+ bool Value::isArray() const { return type_ == arrayValue; }
3473
+
3474
+ bool Value::isObject() const { return type_ == objectValue; }
3475
+
3476
+ void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
3477
+ if (!comments_)
3478
+ comments_ = new CommentInfo[numberOfCommentPlacement];
3479
+ if ((len > 0) && (comment[len-1] == '\n')) {
3480
+ // Always discard trailing newline, to aid indentation.
3481
+ len -= 1;
3482
+ }
3483
+ comments_[placement].setComment(comment, len);
3484
+ }
3485
+
3486
+ void Value::setComment(const char* comment, CommentPlacement placement) {
3487
+ setComment(comment, strlen(comment), placement);
3488
+ }
3489
+
3490
+ void Value::setComment(const std::string& comment, CommentPlacement placement) {
3491
+ setComment(comment.c_str(), comment.length(), placement);
3492
+ }
3493
+
3494
+ bool Value::hasComment(CommentPlacement placement) const {
3495
+ return comments_ != 0 && comments_[placement].comment_ != 0;
3496
+ }
3497
+
3498
+ std::string Value::getComment(CommentPlacement placement) const {
3499
+ if (hasComment(placement))
3500
+ return comments_[placement].comment_;
3501
+ return "";
3502
+ }
3503
+
3504
+ std::string Value::toStyledString() const {
3505
+ StyledWriter writer;
3506
+ return writer.write(*this);
3507
+ }
3508
+
3509
+ Value::const_iterator Value::begin() const {
3510
+ switch (type_) {
3511
+ case arrayValue:
3512
+ case objectValue:
3513
+ if (value_.map_)
3514
+ return const_iterator(value_.map_->begin());
3515
+ break;
3516
+ default:
3517
+ break;
3518
+ }
3519
+ return const_iterator();
3520
+ }
3521
+
3522
+ Value::const_iterator Value::end() const {
3523
+ switch (type_) {
3524
+ case arrayValue:
3525
+ case objectValue:
3526
+ if (value_.map_)
3527
+ return const_iterator(value_.map_->end());
3528
+ break;
3529
+ default:
3530
+ break;
3531
+ }
3532
+ return const_iterator();
3533
+ }
3534
+
3535
+ Value::iterator Value::begin() {
3536
+ switch (type_) {
3537
+ case arrayValue:
3538
+ case objectValue:
3539
+ if (value_.map_)
3540
+ return iterator(value_.map_->begin());
3541
+ break;
3542
+ default:
3543
+ break;
3544
+ }
3545
+ return iterator();
3546
+ }
3547
+
3548
+ Value::iterator Value::end() {
3549
+ switch (type_) {
3550
+ case arrayValue:
3551
+ case objectValue:
3552
+ if (value_.map_)
3553
+ return iterator(value_.map_->end());
3554
+ break;
3555
+ default:
3556
+ break;
3557
+ }
3558
+ return iterator();
3559
+ }
3560
+
3561
+ // class PathArgument
3562
+ // //////////////////////////////////////////////////////////////////
3563
+
3564
+ PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
3565
+
3566
+ PathArgument::PathArgument(ArrayIndex index)
3567
+ : key_(), index_(index), kind_(kindIndex) {}
3568
+
3569
+ PathArgument::PathArgument(const char* key)
3570
+ : key_(key), index_(), kind_(kindKey) {}
3571
+
3572
+ PathArgument::PathArgument(const std::string& key)
3573
+ : key_(key.c_str()), index_(), kind_(kindKey) {}
3574
+
3575
+ // class Path
3576
+ // //////////////////////////////////////////////////////////////////
3577
+
3578
+ Path::Path(const std::string& path,
3579
+ const PathArgument& a1,
3580
+ const PathArgument& a2,
3581
+ const PathArgument& a3,
3582
+ const PathArgument& a4,
3583
+ const PathArgument& a5) {
3584
+ InArgs in;
3585
+ in.push_back(&a1);
3586
+ in.push_back(&a2);
3587
+ in.push_back(&a3);
3588
+ in.push_back(&a4);
3589
+ in.push_back(&a5);
3590
+ makePath(path, in);
3591
+ }
3592
+
3593
+ void Path::makePath(const std::string& path, const InArgs& in) {
3594
+ const char* current = path.c_str();
3595
+ const char* end = current + path.length();
3596
+ InArgs::const_iterator itInArg = in.begin();
3597
+ while (current != end) {
3598
+ if (*current == '[') {
3599
+ ++current;
3600
+ if (*current == '%')
3601
+ addPathInArg(path, in, itInArg, PathArgument::kindIndex);
3602
+ else {
3603
+ ArrayIndex index = 0;
3604
+ for (; current != end && *current >= '0' && *current <= '9'; ++current)
3605
+ index = index * 10 + ArrayIndex(*current - '0');
3606
+ args_.push_back(index);
3607
+ }
3608
+ if (current == end || *current++ != ']')
3609
+ invalidPath(path, int(current - path.c_str()));
3610
+ } else if (*current == '%') {
3611
+ addPathInArg(path, in, itInArg, PathArgument::kindKey);
3612
+ ++current;
3613
+ } else if (*current == '.') {
3614
+ ++current;
3615
+ } else {
3616
+ const char* beginName = current;
3617
+ while (current != end && !strchr("[.", *current))
3618
+ ++current;
3619
+ args_.push_back(std::string(beginName, current));
3620
+ }
3621
+ }
3622
+ }
3623
+
3624
+ void Path::addPathInArg(const std::string& /*path*/,
3625
+ const InArgs& in,
3626
+ InArgs::const_iterator& itInArg,
3627
+ PathArgument::Kind kind) {
3628
+ if (itInArg == in.end()) {
3629
+ // Error: missing argument %d
3630
+ } else if ((*itInArg)->kind_ != kind) {
3631
+ // Error: bad argument type
3632
+ } else {
3633
+ args_.push_back(**itInArg);
3634
+ }
3635
+ }
3636
+
3637
+ void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
3638
+ // Error: invalid path.
3639
+ }
3640
+
3641
+ const Value& Path::resolve(const Value& root) const {
3642
+ const Value* node = &root;
3643
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
3644
+ const PathArgument& arg = *it;
3645
+ if (arg.kind_ == PathArgument::kindIndex) {
3646
+ if (!node->isArray() || !node->isValidIndex(arg.index_)) {
3647
+ // Error: unable to resolve path (array value expected at position...
3648
+ }
3649
+ node = &((*node)[arg.index_]);
3650
+ } else if (arg.kind_ == PathArgument::kindKey) {
3651
+ if (!node->isObject()) {
3652
+ // Error: unable to resolve path (object value expected at position...)
3653
+ }
3654
+ node = &((*node)[arg.key_]);
3655
+ if (node == &Value::nullRef) {
3656
+ // Error: unable to resolve path (object has no member named '' at
3657
+ // position...)
3658
+ }
3659
+ }
3660
+ }
3661
+ return *node;
3662
+ }
3663
+
3664
+ Value Path::resolve(const Value& root, const Value& defaultValue) const {
3665
+ const Value* node = &root;
3666
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
3667
+ const PathArgument& arg = *it;
3668
+ if (arg.kind_ == PathArgument::kindIndex) {
3669
+ if (!node->isArray() || !node->isValidIndex(arg.index_))
3670
+ return defaultValue;
3671
+ node = &((*node)[arg.index_]);
3672
+ } else if (arg.kind_ == PathArgument::kindKey) {
3673
+ if (!node->isObject())
3674
+ return defaultValue;
3675
+ node = &((*node)[arg.key_]);
3676
+ if (node == &Value::nullRef)
3677
+ return defaultValue;
3678
+ }
3679
+ }
3680
+ return *node;
3681
+ }
3682
+
3683
+ Value& Path::make(Value& root) const {
3684
+ Value* node = &root;
3685
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
3686
+ const PathArgument& arg = *it;
3687
+ if (arg.kind_ == PathArgument::kindIndex) {
3688
+ if (!node->isArray()) {
3689
+ // Error: node is not an array at position ...
3690
+ }
3691
+ node = &((*node)[arg.index_]);
3692
+ } else if (arg.kind_ == PathArgument::kindKey) {
3693
+ if (!node->isObject()) {
3694
+ // Error: node is not an object at position...
3695
+ }
3696
+ node = &((*node)[arg.key_]);
3697
+ }
3698
+ }
3699
+ return *node;
3700
+ }
3701
+
3702
+ } // namespace Json
3703
+
3704
+ // //////////////////////////////////////////////////////////////////////
3705
+ // End of content of file: src/lib_json/json_value.cpp
3706
+ // //////////////////////////////////////////////////////////////////////
3707
+
3708
+
3709
+
3710
+
3711
+
3712
+
3713
+ // //////////////////////////////////////////////////////////////////////
3714
+ // Beginning of content of file: src/lib_json/json_writer.cpp
3715
+ // //////////////////////////////////////////////////////////////////////
3716
+
3717
+ // Copyright 2011 Baptiste Lepilleur
3718
+ // Distributed under MIT license, or public domain if desired and
3719
+ // recognized in your jurisdiction.
3720
+ // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
3721
+
3722
+ #if !defined(JSON_IS_AMALGAMATION)
3723
+ #include <json/writer.h>
3724
+ #include "json_tool.h"
3725
+ #endif // if !defined(JSON_IS_AMALGAMATION)
3726
+ #include <iomanip>
3727
+ #include <memory>
3728
+ #include <sstream>
3729
+ #include <utility>
3730
+ #include <set>
3731
+ #include <cassert>
3732
+ #include <cstring>
3733
+ #include <cstdio>
3734
+
3735
+ #if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
3736
+ #include <float.h>
3737
+ #define isfinite _finite
3738
+ #elif defined(__sun) && defined(__SVR4) //Solaris
3739
+ #include <ieeefp.h>
3740
+ #define isfinite finite
3741
+ #else
3742
+ #include <cmath>
3743
+ #define isfinite std::isfinite
3744
+ #endif
3745
+
3746
+ #if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
3747
+ #define snprintf _snprintf
3748
+ #elif defined(__ANDROID__)
3749
+ #define snprintf snprintf
3750
+ #elif __cplusplus >= 201103L
3751
+ #define snprintf std::snprintf
3752
+ #endif
3753
+
3754
+ #if defined(__BORLANDC__)
3755
+ #include <float.h>
3756
+ #define isfinite _finite
3757
+ #define snprintf _snprintf
3758
+ #endif
3759
+
3760
+ #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
3761
+ // Disable warning about strdup being deprecated.
3762
+ #pragma warning(disable : 4996)
3763
+ #endif
3764
+
3765
+ namespace Json {
3766
+
3767
+ typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
3768
+
3769
+ static bool containsControlCharacter(const char* str) {
3770
+ while (*str) {
3771
+ if (isControlCharacter(*(str++)))
3772
+ return true;
3773
+ }
3774
+ return false;
3775
+ }
3776
+
3777
+ static bool containsControlCharacter0(const char* str, unsigned len) {
3778
+ char const* end = str + len;
3779
+ while (end != str) {
3780
+ if (isControlCharacter(*str) || 0==*str)
3781
+ return true;
3782
+ ++str;
3783
+ }
3784
+ return false;
3785
+ }
3786
+
3787
+ std::string valueToString(LargestInt value) {
3788
+ UIntToStringBuffer buffer;
3789
+ char* current = buffer + sizeof(buffer);
3790
+ bool isNegative = value < 0;
3791
+ if (isNegative)
3792
+ value = -value;
3793
+ uintToString(LargestUInt(value), current);
3794
+ if (isNegative)
3795
+ *--current = '-';
3796
+ assert(current >= buffer);
3797
+ return current;
3798
+ }
3799
+
3800
+ std::string valueToString(LargestUInt value) {
3801
+ UIntToStringBuffer buffer;
3802
+ char* current = buffer + sizeof(buffer);
3803
+ uintToString(value, current);
3804
+ assert(current >= buffer);
3805
+ return current;
3806
+ }
3807
+
3808
+ #if defined(JSON_HAS_INT64)
3809
+
3810
+ std::string valueToString(Int value) {
3811
+ return valueToString(LargestInt(value));
3812
+ }
3813
+
3814
+ std::string valueToString(UInt value) {
3815
+ return valueToString(LargestUInt(value));
3816
+ }
3817
+
3818
+ #endif // # if defined(JSON_HAS_INT64)
3819
+
3820
+ std::string valueToString(double value) {
3821
+ // Allocate a buffer that is more than large enough to store the 16 digits of
3822
+ // precision requested below.
3823
+ char buffer[32];
3824
+ int len = -1;
3825
+
3826
+ // Print into the buffer. We need not request the alternative representation
3827
+ // that always has a decimal point because JSON doesn't distingish the
3828
+ // concepts of reals and integers.
3829
+ #if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with
3830
+ // visual studio 2005 to
3831
+ // avoid warning.
3832
+ #if defined(WINCE)
3833
+ len = _snprintf(buffer, sizeof(buffer), "%.17g", value);
3834
+ #else
3835
+ len = sprintf_s(buffer, sizeof(buffer), "%.17g", value);
3836
+ #endif
3837
+ #else
3838
+ if (isfinite(value)) {
3839
+ len = snprintf(buffer, sizeof(buffer), "%.17g", value);
3840
+ } else {
3841
+ // IEEE standard states that NaN values will not compare to themselves
3842
+ if (value != value) {
3843
+ len = snprintf(buffer, sizeof(buffer), "null");
3844
+ } else if (value < 0) {
3845
+ len = snprintf(buffer, sizeof(buffer), "-1e+9999");
3846
+ } else {
3847
+ len = snprintf(buffer, sizeof(buffer), "1e+9999");
3848
+ }
3849
+ // For those, we do not need to call fixNumLoc, but it is fast.
3850
+ }
3851
+ #endif
3852
+ assert(len >= 0);
3853
+ fixNumericLocale(buffer, buffer + len);
3854
+ return buffer;
3855
+ }
3856
+
3857
+ std::string valueToString(bool value) { return value ? "true" : "false"; }
3858
+
3859
+ std::string valueToQuotedString(const char* value) {
3860
+ if (value == NULL)
3861
+ return "";
3862
+ // Not sure how to handle unicode...
3863
+ if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
3864
+ !containsControlCharacter(value))
3865
+ return std::string("\"") + value + "\"";
3866
+ // We have to walk value and escape any special characters.
3867
+ // Appending to std::string is not efficient, but this should be rare.
3868
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
3869
+ std::string::size_type maxsize =
3870
+ strlen(value) * 2 + 3; // allescaped+quotes+NULL
3871
+ std::string result;
3872
+ result.reserve(maxsize); // to avoid lots of mallocs
3873
+ result += "\"";
3874
+ for (const char* c = value; *c != 0; ++c) {
3875
+ switch (*c) {
3876
+ case '\"':
3877
+ result += "\\\"";
3878
+ break;
3879
+ case '\\':
3880
+ result += "\\\\";
3881
+ break;
3882
+ case '\b':
3883
+ result += "\\b";
3884
+ break;
3885
+ case '\f':
3886
+ result += "\\f";
3887
+ break;
3888
+ case '\n':
3889
+ result += "\\n";
3890
+ break;
3891
+ case '\r':
3892
+ result += "\\r";
3893
+ break;
3894
+ case '\t':
3895
+ result += "\\t";
3896
+ break;
3897
+ // case '/':
3898
+ // Even though \/ is considered a legal escape in JSON, a bare
3899
+ // slash is also legal, so I see no reason to escape it.
3900
+ // (I hope I am not misunderstanding something.
3901
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
3902
+ // sequence.
3903
+ // Should add a flag to allow this compatibility mode and prevent this
3904
+ // sequence from occurring.
3905
+ default:
3906
+ if (isControlCharacter(*c)) {
3907
+ std::ostringstream oss;
3908
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
3909
+ << std::setw(4) << static_cast<int>(*c);
3910
+ result += oss.str();
3911
+ } else {
3912
+ result += *c;
3913
+ }
3914
+ break;
3915
+ }
3916
+ }
3917
+ result += "\"";
3918
+ return result;
3919
+ }
3920
+
3921
+ // https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
3922
+ static char const* strnpbrk(char const* s, char const* accept, size_t n) {
3923
+ assert((s || !n) && accept);
3924
+
3925
+ char const* const end = s + n;
3926
+ for (char const* cur = s; cur < end; ++cur) {
3927
+ int const c = *cur;
3928
+ for (char const* a = accept; *a; ++a) {
3929
+ if (*a == c) {
3930
+ return cur;
3931
+ }
3932
+ }
3933
+ }
3934
+ return NULL;
3935
+ }
3936
+ static std::string valueToQuotedStringN(const char* value, unsigned length) {
3937
+ if (value == NULL)
3938
+ return "";
3939
+ // Not sure how to handle unicode...
3940
+ if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
3941
+ !containsControlCharacter0(value, length))
3942
+ return std::string("\"") + value + "\"";
3943
+ // We have to walk value and escape any special characters.
3944
+ // Appending to std::string is not efficient, but this should be rare.
3945
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
3946
+ std::string::size_type maxsize =
3947
+ length * 2 + 3; // allescaped+quotes+NULL
3948
+ std::string result;
3949
+ result.reserve(maxsize); // to avoid lots of mallocs
3950
+ result += "\"";
3951
+ char const* end = value + length;
3952
+ for (const char* c = value; c != end; ++c) {
3953
+ switch (*c) {
3954
+ case '\"':
3955
+ result += "\\\"";
3956
+ break;
3957
+ case '\\':
3958
+ result += "\\\\";
3959
+ break;
3960
+ case '\b':
3961
+ result += "\\b";
3962
+ break;
3963
+ case '\f':
3964
+ result += "\\f";
3965
+ break;
3966
+ case '\n':
3967
+ result += "\\n";
3968
+ break;
3969
+ case '\r':
3970
+ result += "\\r";
3971
+ break;
3972
+ case '\t':
3973
+ result += "\\t";
3974
+ break;
3975
+ // case '/':
3976
+ // Even though \/ is considered a legal escape in JSON, a bare
3977
+ // slash is also legal, so I see no reason to escape it.
3978
+ // (I hope I am not misunderstanding something.)
3979
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
3980
+ // sequence.
3981
+ // Should add a flag to allow this compatibility mode and prevent this
3982
+ // sequence from occurring.
3983
+ default:
3984
+ if ((isControlCharacter(*c)) || (*c == 0)) {
3985
+ std::ostringstream oss;
3986
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
3987
+ << std::setw(4) << static_cast<int>(*c);
3988
+ result += oss.str();
3989
+ } else {
3990
+ result += *c;
3991
+ }
3992
+ break;
3993
+ }
3994
+ }
3995
+ result += "\"";
3996
+ return result;
3997
+ }
3998
+
3999
+ // Class Writer
4000
+ // //////////////////////////////////////////////////////////////////
4001
+ Writer::~Writer() {}
4002
+
4003
+ // Class FastWriter
4004
+ // //////////////////////////////////////////////////////////////////
4005
+
4006
+ FastWriter::FastWriter()
4007
+ : yamlCompatiblityEnabled_(false) {}
4008
+
4009
+ void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
4010
+
4011
+ std::string FastWriter::write(const Value& root) {
4012
+ document_ = "";
4013
+ writeValue(root);
4014
+ document_ += "\n";
4015
+ return document_;
4016
+ }
4017
+
4018
+ void FastWriter::writeValue(const Value& value) {
4019
+ switch (value.type()) {
4020
+ case nullValue:
4021
+ document_ += "null";
4022
+ break;
4023
+ case intValue:
4024
+ document_ += valueToString(value.asLargestInt());
4025
+ break;
4026
+ case uintValue:
4027
+ document_ += valueToString(value.asLargestUInt());
4028
+ break;
4029
+ case realValue:
4030
+ document_ += valueToString(value.asDouble());
4031
+ break;
4032
+ case stringValue:
4033
+ {
4034
+ // Is NULL possible for value.string_?
4035
+ char const* str;
4036
+ char const* end;
4037
+ bool ok = value.getString(&str, &end);
4038
+ if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
4039
+ break;
4040
+ }
4041
+ case booleanValue:
4042
+ document_ += valueToString(value.asBool());
4043
+ break;
4044
+ case arrayValue: {
4045
+ document_ += '[';
4046
+ int size = value.size();
4047
+ for (int index = 0; index < size; ++index) {
4048
+ if (index > 0)
4049
+ document_ += ',';
4050
+ writeValue(value[index]);
4051
+ }
4052
+ document_ += ']';
4053
+ } break;
4054
+ case objectValue: {
4055
+ Value::Members members(value.getMemberNames());
4056
+ document_ += '{';
4057
+ for (Value::Members::iterator it = members.begin(); it != members.end();
4058
+ ++it) {
4059
+ const std::string& name = *it;
4060
+ if (it != members.begin())
4061
+ document_ += ',';
4062
+ document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
4063
+ document_ += yamlCompatiblityEnabled_ ? ": " : ":";
4064
+ writeValue(value[name]);
4065
+ }
4066
+ document_ += '}';
4067
+ } break;
4068
+ }
4069
+ }
4070
+
4071
+ // Class StyledWriter
4072
+ // //////////////////////////////////////////////////////////////////
4073
+
4074
+ StyledWriter::StyledWriter()
4075
+ : rightMargin_(74), indentSize_(3), addChildValues_() {}
4076
+
4077
+ std::string StyledWriter::write(const Value& root) {
4078
+ document_ = "";
4079
+ addChildValues_ = false;
4080
+ indentString_ = "";
4081
+ writeCommentBeforeValue(root);
4082
+ writeValue(root);
4083
+ writeCommentAfterValueOnSameLine(root);
4084
+ document_ += "\n";
4085
+ return document_;
4086
+ }
4087
+
4088
+ void StyledWriter::writeValue(const Value& value) {
4089
+ switch (value.type()) {
4090
+ case nullValue:
4091
+ pushValue("null");
4092
+ break;
4093
+ case intValue:
4094
+ pushValue(valueToString(value.asLargestInt()));
4095
+ break;
4096
+ case uintValue:
4097
+ pushValue(valueToString(value.asLargestUInt()));
4098
+ break;
4099
+ case realValue:
4100
+ pushValue(valueToString(value.asDouble()));
4101
+ break;
4102
+ case stringValue:
4103
+ {
4104
+ // Is NULL possible for value.string_?
4105
+ char const* str;
4106
+ char const* end;
4107
+ bool ok = value.getString(&str, &end);
4108
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
4109
+ else pushValue("");
4110
+ break;
4111
+ }
4112
+ case booleanValue:
4113
+ pushValue(valueToString(value.asBool()));
4114
+ break;
4115
+ case arrayValue:
4116
+ writeArrayValue(value);
4117
+ break;
4118
+ case objectValue: {
4119
+ Value::Members members(value.getMemberNames());
4120
+ if (members.empty())
4121
+ pushValue("{}");
4122
+ else {
4123
+ writeWithIndent("{");
4124
+ indent();
4125
+ Value::Members::iterator it = members.begin();
4126
+ for (;;) {
4127
+ const std::string& name = *it;
4128
+ const Value& childValue = value[name];
4129
+ writeCommentBeforeValue(childValue);
4130
+ writeWithIndent(valueToQuotedString(name.c_str()));
4131
+ document_ += " : ";
4132
+ writeValue(childValue);
4133
+ if (++it == members.end()) {
4134
+ writeCommentAfterValueOnSameLine(childValue);
4135
+ break;
4136
+ }
4137
+ document_ += ',';
4138
+ writeCommentAfterValueOnSameLine(childValue);
4139
+ }
4140
+ unindent();
4141
+ writeWithIndent("}");
4142
+ }
4143
+ } break;
4144
+ }
4145
+ }
4146
+
4147
+ void StyledWriter::writeArrayValue(const Value& value) {
4148
+ unsigned size = value.size();
4149
+ if (size == 0)
4150
+ pushValue("[]");
4151
+ else {
4152
+ bool isArrayMultiLine = isMultineArray(value);
4153
+ if (isArrayMultiLine) {
4154
+ writeWithIndent("[");
4155
+ indent();
4156
+ bool hasChildValue = !childValues_.empty();
4157
+ unsigned index = 0;
4158
+ for (;;) {
4159
+ const Value& childValue = value[index];
4160
+ writeCommentBeforeValue(childValue);
4161
+ if (hasChildValue)
4162
+ writeWithIndent(childValues_[index]);
4163
+ else {
4164
+ writeIndent();
4165
+ writeValue(childValue);
4166
+ }
4167
+ if (++index == size) {
4168
+ writeCommentAfterValueOnSameLine(childValue);
4169
+ break;
4170
+ }
4171
+ document_ += ',';
4172
+ writeCommentAfterValueOnSameLine(childValue);
4173
+ }
4174
+ unindent();
4175
+ writeWithIndent("]");
4176
+ } else // output on a single line
4177
+ {
4178
+ assert(childValues_.size() == size);
4179
+ document_ += "[ ";
4180
+ for (unsigned index = 0; index < size; ++index) {
4181
+ if (index > 0)
4182
+ document_ += ", ";
4183
+ document_ += childValues_[index];
4184
+ }
4185
+ document_ += " ]";
4186
+ }
4187
+ }
4188
+ }
4189
+
4190
+ bool StyledWriter::isMultineArray(const Value& value) {
4191
+ int size = value.size();
4192
+ bool isMultiLine = size * 3 >= rightMargin_;
4193
+ childValues_.clear();
4194
+ for (int index = 0; index < size && !isMultiLine; ++index) {
4195
+ const Value& childValue = value[index];
4196
+ isMultiLine =
4197
+ isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
4198
+ childValue.size() > 0);
4199
+ }
4200
+ if (!isMultiLine) // check if line length > max line length
4201
+ {
4202
+ childValues_.reserve(size);
4203
+ addChildValues_ = true;
4204
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
4205
+ for (int index = 0; index < size; ++index) {
4206
+ if (hasCommentForValue(value[index])) {
4207
+ isMultiLine = true;
4208
+ }
4209
+ writeValue(value[index]);
4210
+ lineLength += int(childValues_[index].length());
4211
+ }
4212
+ addChildValues_ = false;
4213
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
4214
+ }
4215
+ return isMultiLine;
4216
+ }
4217
+
4218
+ void StyledWriter::pushValue(const std::string& value) {
4219
+ if (addChildValues_)
4220
+ childValues_.push_back(value);
4221
+ else
4222
+ document_ += value;
4223
+ }
4224
+
4225
+ void StyledWriter::writeIndent() {
4226
+ if (!document_.empty()) {
4227
+ char last = document_[document_.length() - 1];
4228
+ if (last == ' ') // already indented
4229
+ return;
4230
+ if (last != '\n') // Comments may add new-line
4231
+ document_ += '\n';
4232
+ }
4233
+ document_ += indentString_;
4234
+ }
4235
+
4236
+ void StyledWriter::writeWithIndent(const std::string& value) {
4237
+ writeIndent();
4238
+ document_ += value;
4239
+ }
4240
+
4241
+ void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
4242
+
4243
+ void StyledWriter::unindent() {
4244
+ assert(int(indentString_.size()) >= indentSize_);
4245
+ indentString_.resize(indentString_.size() - indentSize_);
4246
+ }
4247
+
4248
+ void StyledWriter::writeCommentBeforeValue(const Value& root) {
4249
+ if (!root.hasComment(commentBefore))
4250
+ return;
4251
+
4252
+ document_ += "\n";
4253
+ writeIndent();
4254
+ const std::string& comment = root.getComment(commentBefore);
4255
+ std::string::const_iterator iter = comment.begin();
4256
+ while (iter != comment.end()) {
4257
+ document_ += *iter;
4258
+ if (*iter == '\n' &&
4259
+ (iter != comment.end() && *(iter + 1) == '/'))
4260
+ writeIndent();
4261
+ ++iter;
4262
+ }
4263
+
4264
+ // Comments are stripped of trailing newlines, so add one here
4265
+ document_ += "\n";
4266
+ }
4267
+
4268
+ void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
4269
+ if (root.hasComment(commentAfterOnSameLine))
4270
+ document_ += " " + root.getComment(commentAfterOnSameLine);
4271
+
4272
+ if (root.hasComment(commentAfter)) {
4273
+ document_ += "\n";
4274
+ document_ += root.getComment(commentAfter);
4275
+ document_ += "\n";
4276
+ }
4277
+ }
4278
+
4279
+ bool StyledWriter::hasCommentForValue(const Value& value) {
4280
+ return value.hasComment(commentBefore) ||
4281
+ value.hasComment(commentAfterOnSameLine) ||
4282
+ value.hasComment(commentAfter);
4283
+ }
4284
+
4285
+ // Class StyledStreamWriter
4286
+ // //////////////////////////////////////////////////////////////////
4287
+
4288
+ StyledStreamWriter::StyledStreamWriter(std::string indentation)
4289
+ : document_(NULL), rightMargin_(74), indentation_(indentation),
4290
+ addChildValues_() {}
4291
+
4292
+ void StyledStreamWriter::write(std::ostream& out, const Value& root) {
4293
+ document_ = &out;
4294
+ addChildValues_ = false;
4295
+ indentString_ = "";
4296
+ indented_ = true;
4297
+ writeCommentBeforeValue(root);
4298
+ if (!indented_) writeIndent();
4299
+ indented_ = true;
4300
+ writeValue(root);
4301
+ writeCommentAfterValueOnSameLine(root);
4302
+ *document_ << "\n";
4303
+ document_ = NULL; // Forget the stream, for safety.
4304
+ }
4305
+
4306
+ void StyledStreamWriter::writeValue(const Value& value) {
4307
+ switch (value.type()) {
4308
+ case nullValue:
4309
+ pushValue("null");
4310
+ break;
4311
+ case intValue:
4312
+ pushValue(valueToString(value.asLargestInt()));
4313
+ break;
4314
+ case uintValue:
4315
+ pushValue(valueToString(value.asLargestUInt()));
4316
+ break;
4317
+ case realValue:
4318
+ pushValue(valueToString(value.asDouble()));
4319
+ break;
4320
+ case stringValue:
4321
+ {
4322
+ // Is NULL possible for value.string_?
4323
+ char const* str;
4324
+ char const* end;
4325
+ bool ok = value.getString(&str, &end);
4326
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
4327
+ else pushValue("");
4328
+ break;
4329
+ }
4330
+ case booleanValue:
4331
+ pushValue(valueToString(value.asBool()));
4332
+ break;
4333
+ case arrayValue:
4334
+ writeArrayValue(value);
4335
+ break;
4336
+ case objectValue: {
4337
+ Value::Members members(value.getMemberNames());
4338
+ if (members.empty())
4339
+ pushValue("{}");
4340
+ else {
4341
+ writeWithIndent("{");
4342
+ indent();
4343
+ Value::Members::iterator it = members.begin();
4344
+ for (;;) {
4345
+ const std::string& name = *it;
4346
+ const Value& childValue = value[name];
4347
+ writeCommentBeforeValue(childValue);
4348
+ writeWithIndent(valueToQuotedString(name.c_str()));
4349
+ *document_ << " : ";
4350
+ writeValue(childValue);
4351
+ if (++it == members.end()) {
4352
+ writeCommentAfterValueOnSameLine(childValue);
4353
+ break;
4354
+ }
4355
+ *document_ << ",";
4356
+ writeCommentAfterValueOnSameLine(childValue);
4357
+ }
4358
+ unindent();
4359
+ writeWithIndent("}");
4360
+ }
4361
+ } break;
4362
+ }
4363
+ }
4364
+
4365
+ void StyledStreamWriter::writeArrayValue(const Value& value) {
4366
+ unsigned size = value.size();
4367
+ if (size == 0)
4368
+ pushValue("[]");
4369
+ else {
4370
+ bool isArrayMultiLine = isMultineArray(value);
4371
+ if (isArrayMultiLine) {
4372
+ writeWithIndent("[");
4373
+ indent();
4374
+ bool hasChildValue = !childValues_.empty();
4375
+ unsigned index = 0;
4376
+ for (;;) {
4377
+ const Value& childValue = value[index];
4378
+ writeCommentBeforeValue(childValue);
4379
+ if (hasChildValue)
4380
+ writeWithIndent(childValues_[index]);
4381
+ else {
4382
+ if (!indented_) writeIndent();
4383
+ indented_ = true;
4384
+ writeValue(childValue);
4385
+ indented_ = false;
4386
+ }
4387
+ if (++index == size) {
4388
+ writeCommentAfterValueOnSameLine(childValue);
4389
+ break;
4390
+ }
4391
+ *document_ << ",";
4392
+ writeCommentAfterValueOnSameLine(childValue);
4393
+ }
4394
+ unindent();
4395
+ writeWithIndent("]");
4396
+ } else // output on a single line
4397
+ {
4398
+ assert(childValues_.size() == size);
4399
+ *document_ << "[ ";
4400
+ for (unsigned index = 0; index < size; ++index) {
4401
+ if (index > 0)
4402
+ *document_ << ", ";
4403
+ *document_ << childValues_[index];
4404
+ }
4405
+ *document_ << " ]";
4406
+ }
4407
+ }
4408
+ }
4409
+
4410
+ bool StyledStreamWriter::isMultineArray(const Value& value) {
4411
+ int size = value.size();
4412
+ bool isMultiLine = size * 3 >= rightMargin_;
4413
+ childValues_.clear();
4414
+ for (int index = 0; index < size && !isMultiLine; ++index) {
4415
+ const Value& childValue = value[index];
4416
+ isMultiLine =
4417
+ isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
4418
+ childValue.size() > 0);
4419
+ }
4420
+ if (!isMultiLine) // check if line length > max line length
4421
+ {
4422
+ childValues_.reserve(size);
4423
+ addChildValues_ = true;
4424
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
4425
+ for (int index = 0; index < size; ++index) {
4426
+ if (hasCommentForValue(value[index])) {
4427
+ isMultiLine = true;
4428
+ }
4429
+ writeValue(value[index]);
4430
+ lineLength += int(childValues_[index].length());
4431
+ }
4432
+ addChildValues_ = false;
4433
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
4434
+ }
4435
+ return isMultiLine;
4436
+ }
4437
+
4438
+ void StyledStreamWriter::pushValue(const std::string& value) {
4439
+ if (addChildValues_)
4440
+ childValues_.push_back(value);
4441
+ else
4442
+ *document_ << value;
4443
+ }
4444
+
4445
+ void StyledStreamWriter::writeIndent() {
4446
+ // blep intended this to look at the so-far-written string
4447
+ // to determine whether we are already indented, but
4448
+ // with a stream we cannot do that. So we rely on some saved state.
4449
+ // The caller checks indented_.
4450
+ *document_ << '\n' << indentString_;
4451
+ }
4452
+
4453
+ void StyledStreamWriter::writeWithIndent(const std::string& value) {
4454
+ if (!indented_) writeIndent();
4455
+ *document_ << value;
4456
+ indented_ = false;
4457
+ }
4458
+
4459
+ void StyledStreamWriter::indent() { indentString_ += indentation_; }
4460
+
4461
+ void StyledStreamWriter::unindent() {
4462
+ assert(indentString_.size() >= indentation_.size());
4463
+ indentString_.resize(indentString_.size() - indentation_.size());
4464
+ }
4465
+
4466
+ void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
4467
+ if (!root.hasComment(commentBefore))
4468
+ return;
4469
+
4470
+ if (!indented_) writeIndent();
4471
+ const std::string& comment = root.getComment(commentBefore);
4472
+ std::string::const_iterator iter = comment.begin();
4473
+ while (iter != comment.end()) {
4474
+ *document_ << *iter;
4475
+ if (*iter == '\n' &&
4476
+ (iter != comment.end() && *(iter + 1) == '/'))
4477
+ // writeIndent(); // would include newline
4478
+ *document_ << indentString_;
4479
+ ++iter;
4480
+ }
4481
+ indented_ = false;
4482
+ }
4483
+
4484
+ void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
4485
+ if (root.hasComment(commentAfterOnSameLine))
4486
+ *document_ << ' ' << root.getComment(commentAfterOnSameLine);
4487
+
4488
+ if (root.hasComment(commentAfter)) {
4489
+ writeIndent();
4490
+ *document_ << root.getComment(commentAfter);
4491
+ }
4492
+ indented_ = false;
4493
+ }
4494
+
4495
+ bool StyledStreamWriter::hasCommentForValue(const Value& value) {
4496
+ return value.hasComment(commentBefore) ||
4497
+ value.hasComment(commentAfterOnSameLine) ||
4498
+ value.hasComment(commentAfter);
4499
+ }
4500
+
4501
+ //////////////////////////
4502
+ // BuiltStyledStreamWriter
4503
+
4504
+ /// Scoped enums are not available until C++11.
4505
+ struct CommentStyle {
4506
+ /// Decide whether to write comments.
4507
+ enum Enum {
4508
+ None, ///< Drop all comments.
4509
+ Most, ///< Recover odd behavior of previous versions (not implemented yet).
4510
+ All ///< Keep all comments.
4511
+ };
4512
+ };
4513
+
4514
+ struct BuiltStyledStreamWriter : public StreamWriter
4515
+ {
4516
+ BuiltStyledStreamWriter(
4517
+ std::string const& indentation,
4518
+ CommentStyle::Enum cs,
4519
+ std::string const& colonSymbol,
4520
+ std::string const& nullSymbol,
4521
+ std::string const& endingLineFeedSymbol);
4522
+ virtual int write(Value const& root, std::ostream* sout);
4523
+ private:
4524
+ void writeValue(Value const& value);
4525
+ void writeArrayValue(Value const& value);
4526
+ bool isMultineArray(Value const& value);
4527
+ void pushValue(std::string const& value);
4528
+ void writeIndent();
4529
+ void writeWithIndent(std::string const& value);
4530
+ void indent();
4531
+ void unindent();
4532
+ void writeCommentBeforeValue(Value const& root);
4533
+ void writeCommentAfterValueOnSameLine(Value const& root);
4534
+ static bool hasCommentForValue(const Value& value);
4535
+
4536
+ typedef std::vector<std::string> ChildValues;
4537
+
4538
+ ChildValues childValues_;
4539
+ std::string indentString_;
4540
+ int rightMargin_;
4541
+ std::string indentation_;
4542
+ CommentStyle::Enum cs_;
4543
+ std::string colonSymbol_;
4544
+ std::string nullSymbol_;
4545
+ std::string endingLineFeedSymbol_;
4546
+ bool addChildValues_ : 1;
4547
+ bool indented_ : 1;
4548
+ };
4549
+ BuiltStyledStreamWriter::BuiltStyledStreamWriter(
4550
+ std::string const& indentation,
4551
+ CommentStyle::Enum cs,
4552
+ std::string const& colonSymbol,
4553
+ std::string const& nullSymbol,
4554
+ std::string const& endingLineFeedSymbol)
4555
+ : rightMargin_(74)
4556
+ , indentation_(indentation)
4557
+ , cs_(cs)
4558
+ , colonSymbol_(colonSymbol)
4559
+ , nullSymbol_(nullSymbol)
4560
+ , endingLineFeedSymbol_(endingLineFeedSymbol)
4561
+ , addChildValues_(false)
4562
+ , indented_(false)
4563
+ {
4564
+ }
4565
+ int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
4566
+ {
4567
+ sout_ = sout;
4568
+ addChildValues_ = false;
4569
+ indented_ = true;
4570
+ indentString_ = "";
4571
+ writeCommentBeforeValue(root);
4572
+ if (!indented_) writeIndent();
4573
+ indented_ = true;
4574
+ writeValue(root);
4575
+ writeCommentAfterValueOnSameLine(root);
4576
+ *sout_ << endingLineFeedSymbol_;
4577
+ sout_ = NULL;
4578
+ return 0;
4579
+ }
4580
+ void BuiltStyledStreamWriter::writeValue(Value const& value) {
4581
+ switch (value.type()) {
4582
+ case nullValue:
4583
+ pushValue(nullSymbol_);
4584
+ break;
4585
+ case intValue:
4586
+ pushValue(valueToString(value.asLargestInt()));
4587
+ break;
4588
+ case uintValue:
4589
+ pushValue(valueToString(value.asLargestUInt()));
4590
+ break;
4591
+ case realValue:
4592
+ pushValue(valueToString(value.asDouble()));
4593
+ break;
4594
+ case stringValue:
4595
+ {
4596
+ // Is NULL is possible for value.string_?
4597
+ char const* str;
4598
+ char const* end;
4599
+ bool ok = value.getString(&str, &end);
4600
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
4601
+ else pushValue("");
4602
+ break;
4603
+ }
4604
+ case booleanValue:
4605
+ pushValue(valueToString(value.asBool()));
4606
+ break;
4607
+ case arrayValue:
4608
+ writeArrayValue(value);
4609
+ break;
4610
+ case objectValue: {
4611
+ Value::Members members(value.getMemberNames());
4612
+ if (members.empty())
4613
+ pushValue("{}");
4614
+ else {
4615
+ writeWithIndent("{");
4616
+ indent();
4617
+ Value::Members::iterator it = members.begin();
4618
+ for (;;) {
4619
+ std::string const& name = *it;
4620
+ Value const& childValue = value[name];
4621
+ writeCommentBeforeValue(childValue);
4622
+ writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
4623
+ *sout_ << colonSymbol_;
4624
+ writeValue(childValue);
4625
+ if (++it == members.end()) {
4626
+ writeCommentAfterValueOnSameLine(childValue);
4627
+ break;
4628
+ }
4629
+ *sout_ << ",";
4630
+ writeCommentAfterValueOnSameLine(childValue);
4631
+ }
4632
+ unindent();
4633
+ writeWithIndent("}");
4634
+ }
4635
+ } break;
4636
+ }
4637
+ }
4638
+
4639
+ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
4640
+ unsigned size = value.size();
4641
+ if (size == 0)
4642
+ pushValue("[]");
4643
+ else {
4644
+ bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
4645
+ if (isMultiLine) {
4646
+ writeWithIndent("[");
4647
+ indent();
4648
+ bool hasChildValue = !childValues_.empty();
4649
+ unsigned index = 0;
4650
+ for (;;) {
4651
+ Value const& childValue = value[index];
4652
+ writeCommentBeforeValue(childValue);
4653
+ if (hasChildValue)
4654
+ writeWithIndent(childValues_[index]);
4655
+ else {
4656
+ if (!indented_) writeIndent();
4657
+ indented_ = true;
4658
+ writeValue(childValue);
4659
+ indented_ = false;
4660
+ }
4661
+ if (++index == size) {
4662
+ writeCommentAfterValueOnSameLine(childValue);
4663
+ break;
4664
+ }
4665
+ *sout_ << ",";
4666
+ writeCommentAfterValueOnSameLine(childValue);
4667
+ }
4668
+ unindent();
4669
+ writeWithIndent("]");
4670
+ } else // output on a single line
4671
+ {
4672
+ assert(childValues_.size() == size);
4673
+ *sout_ << "[";
4674
+ if (!indentation_.empty()) *sout_ << " ";
4675
+ for (unsigned index = 0; index < size; ++index) {
4676
+ if (index > 0)
4677
+ *sout_ << ", ";
4678
+ *sout_ << childValues_[index];
4679
+ }
4680
+ if (!indentation_.empty()) *sout_ << " ";
4681
+ *sout_ << "]";
4682
+ }
4683
+ }
4684
+ }
4685
+
4686
+ bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
4687
+ int size = value.size();
4688
+ bool isMultiLine = size * 3 >= rightMargin_;
4689
+ childValues_.clear();
4690
+ for (int index = 0; index < size && !isMultiLine; ++index) {
4691
+ Value const& childValue = value[index];
4692
+ isMultiLine =
4693
+ isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
4694
+ childValue.size() > 0);
4695
+ }
4696
+ if (!isMultiLine) // check if line length > max line length
4697
+ {
4698
+ childValues_.reserve(size);
4699
+ addChildValues_ = true;
4700
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
4701
+ for (int index = 0; index < size; ++index) {
4702
+ if (hasCommentForValue(value[index])) {
4703
+ isMultiLine = true;
4704
+ }
4705
+ writeValue(value[index]);
4706
+ lineLength += int(childValues_[index].length());
4707
+ }
4708
+ addChildValues_ = false;
4709
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
4710
+ }
4711
+ return isMultiLine;
4712
+ }
4713
+
4714
+ void BuiltStyledStreamWriter::pushValue(std::string const& value) {
4715
+ if (addChildValues_)
4716
+ childValues_.push_back(value);
4717
+ else
4718
+ *sout_ << value;
4719
+ }
4720
+
4721
+ void BuiltStyledStreamWriter::writeIndent() {
4722
+ // blep intended this to look at the so-far-written string
4723
+ // to determine whether we are already indented, but
4724
+ // with a stream we cannot do that. So we rely on some saved state.
4725
+ // The caller checks indented_.
4726
+
4727
+ if (!indentation_.empty()) {
4728
+ // In this case, drop newlines too.
4729
+ *sout_ << '\n' << indentString_;
4730
+ }
4731
+ }
4732
+
4733
+ void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
4734
+ if (!indented_) writeIndent();
4735
+ *sout_ << value;
4736
+ indented_ = false;
4737
+ }
4738
+
4739
+ void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
4740
+
4741
+ void BuiltStyledStreamWriter::unindent() {
4742
+ assert(indentString_.size() >= indentation_.size());
4743
+ indentString_.resize(indentString_.size() - indentation_.size());
4744
+ }
4745
+
4746
+ void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
4747
+ if (cs_ == CommentStyle::None) return;
4748
+ if (!root.hasComment(commentBefore))
4749
+ return;
4750
+
4751
+ if (!indented_) writeIndent();
4752
+ const std::string& comment = root.getComment(commentBefore);
4753
+ std::string::const_iterator iter = comment.begin();
4754
+ while (iter != comment.end()) {
4755
+ *sout_ << *iter;
4756
+ if (*iter == '\n' &&
4757
+ (iter != comment.end() && *(iter + 1) == '/'))
4758
+ // writeIndent(); // would write extra newline
4759
+ *sout_ << indentString_;
4760
+ ++iter;
4761
+ }
4762
+ indented_ = false;
4763
+ }
4764
+
4765
+ void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
4766
+ if (cs_ == CommentStyle::None) return;
4767
+ if (root.hasComment(commentAfterOnSameLine))
4768
+ *sout_ << " " + root.getComment(commentAfterOnSameLine);
4769
+
4770
+ if (root.hasComment(commentAfter)) {
4771
+ writeIndent();
4772
+ *sout_ << root.getComment(commentAfter);
4773
+ }
4774
+ }
4775
+
4776
+ // static
4777
+ bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
4778
+ return value.hasComment(commentBefore) ||
4779
+ value.hasComment(commentAfterOnSameLine) ||
4780
+ value.hasComment(commentAfter);
4781
+ }
4782
+
4783
+ ///////////////
4784
+ // StreamWriter
4785
+
4786
+ StreamWriter::StreamWriter()
4787
+ : sout_(NULL)
4788
+ {
4789
+ }
4790
+ StreamWriter::~StreamWriter()
4791
+ {
4792
+ }
4793
+ StreamWriter::Factory::~Factory()
4794
+ {}
4795
+ StreamWriterBuilder::StreamWriterBuilder()
4796
+ {
4797
+ setDefaults(&settings_);
4798
+ }
4799
+ StreamWriterBuilder::~StreamWriterBuilder()
4800
+ {}
4801
+ StreamWriter* StreamWriterBuilder::newStreamWriter() const
4802
+ {
4803
+ std::string indentation = settings_["indentation"].asString();
4804
+ std::string cs_str = settings_["commentStyle"].asString();
4805
+ bool eyc = settings_["enableYAMLCompatibility"].asBool();
4806
+ bool dnp = settings_["dropNullPlaceholders"].asBool();
4807
+ CommentStyle::Enum cs = CommentStyle::All;
4808
+ if (cs_str == "All") {
4809
+ cs = CommentStyle::All;
4810
+ } else if (cs_str == "None") {
4811
+ cs = CommentStyle::None;
4812
+ } else {
4813
+ throwRuntimeError("commentStyle must be 'All' or 'None'");
4814
+ }
4815
+ std::string colonSymbol = " : ";
4816
+ if (eyc) {
4817
+ colonSymbol = ": ";
4818
+ } else if (indentation.empty()) {
4819
+ colonSymbol = ":";
4820
+ }
4821
+ std::string nullSymbol = "null";
4822
+ if (dnp) {
4823
+ nullSymbol = "";
4824
+ }
4825
+ std::string endingLineFeedSymbol = "";
4826
+ return new BuiltStyledStreamWriter(
4827
+ indentation, cs,
4828
+ colonSymbol, nullSymbol, endingLineFeedSymbol);
4829
+ }
4830
+ static void getValidWriterKeys(std::set<std::string>* valid_keys)
4831
+ {
4832
+ valid_keys->clear();
4833
+ valid_keys->insert("indentation");
4834
+ valid_keys->insert("commentStyle");
4835
+ valid_keys->insert("enableYAMLCompatibility");
4836
+ valid_keys->insert("dropNullPlaceholders");
4837
+ }
4838
+ bool StreamWriterBuilder::validate(Json::Value* invalid) const
4839
+ {
4840
+ Json::Value my_invalid;
4841
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
4842
+ Json::Value& inv = *invalid;
4843
+ std::set<std::string> valid_keys;
4844
+ getValidWriterKeys(&valid_keys);
4845
+ Value::Members keys = settings_.getMemberNames();
4846
+ size_t n = keys.size();
4847
+ for (size_t i = 0; i < n; ++i) {
4848
+ std::string const& key = keys[i];
4849
+ if (valid_keys.find(key) == valid_keys.end()) {
4850
+ inv[key] = settings_[key];
4851
+ }
4852
+ }
4853
+ return 0u == inv.size();
4854
+ }
4855
+ Value& StreamWriterBuilder::operator[](std::string key)
4856
+ {
4857
+ return settings_[key];
4858
+ }
4859
+ // static
4860
+ void StreamWriterBuilder::setDefaults(Json::Value* settings)
4861
+ {
4862
+ //! [StreamWriterBuilderDefaults]
4863
+ (*settings)["commentStyle"] = "All";
4864
+ (*settings)["indentation"] = "\t";
4865
+ (*settings)["enableYAMLCompatibility"] = false;
4866
+ (*settings)["dropNullPlaceholders"] = false;
4867
+ //! [StreamWriterBuilderDefaults]
4868
+ }
4869
+
4870
+ std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
4871
+ std::ostringstream sout;
4872
+ StreamWriterPtr const writer(builder.newStreamWriter());
4873
+ writer->write(root, &sout);
4874
+ return sout.str();
4875
+ }
4876
+
4877
+ std::ostream& operator<<(std::ostream& sout, Value const& root) {
4878
+ StreamWriterBuilder builder;
4879
+ StreamWriterPtr const writer(builder.newStreamWriter());
4880
+ writer->write(root, &sout);
4881
+ return sout;
4882
+ }
4883
+
4884
+ } // namespace Json
4885
+
4886
+ // //////////////////////////////////////////////////////////////////////
4887
+ // End of content of file: src/lib_json/json_writer.cpp
4888
+ // //////////////////////////////////////////////////////////////////////
4889
+
4890
+
4891
+
4892
+
4893
+