Compare commits

..

331 Commits
1.4.3 ... 1.7.5

Author SHA1 Message Date
Christopher Dunn
a304d61a7b 1.7.5 <- 1.7.4 2016-09-01 02:45:08 -05:00
Christopher Dunn
0a97e38ea5 Merge pull request #523 from prezi/fix-android-lconv
Workaround for missing lconv::decimal_point on android
2016-09-01 02:36:34 -05:00
Gida Pataki
894e78bff1 Workaround for missing lconv::decimal_point on android 2016-08-26 23:30:18 +02:00
Christopher Dunn
126bdc2b05 Reject extra chars if strictRoot
resolves #511
2016-08-21 20:32:16 -05:00
Christopher Dunn
094a7d8564 Fix locale for decimal points
resolves #514
2016-08-21 20:13:58 -05:00
Christopher Dunn
b9afdf190d Use int64_t for 64bit ints
resolves #509
2016-08-21 19:58:43 -05:00
Christopher Dunn
80a82ea269 Optional space after comma
resolves #513
2016-08-21 16:35:19 -05:00
Christopher Dunn
f78f685bab Remove needless if.
resolves #516
2016-08-21 16:31:14 -05:00
Christopher Dunn
7d8eddb98c Merge pull request #519 from open-source-parsers/fix-517
Avoid null for stringValue
2016-08-21 16:30:28 -05:00
Christopher Dunn
7e0571b444 Avoid null for stringValue
fixes #517
2016-08-21 16:25:29 -05:00
Christopher Dunn
b14c8c1423 Merge pull request #502 from open-source-parsers/null-object
Allow dtor for nullSingleton
2016-07-20 22:28:44 -07:00
Christopher Dunn
b299d3581f Allow dtor for nullSingleton
re #488 and #490
2016-07-20 11:31:41 -07:00
Christopher Dunn
48d2a69d47 1.7.4 <- 1.7.3 2016-07-09 13:27:28 -05:00
Christopher Dunn
772e257fc9 Merge pull request #493 from zorun/master
Fix compilation errors for downstream projects caused by incorrect pkconfig paths
2016-07-08 17:02:30 -05:00
Baptiste Jonglez
101fcf0806 Fix compilation errors for downstream projects caused by incorrect pkgconfig paths
Recent commit 911e2b0fea ("By default use <prefix> relative paths when
installing") introduced relative install paths in CMake.  But this
interacts badly with commit e6f1cffdd3 from a year ago: now, the paths in
`pkgconfig/jsoncpp.pc` are relative, which is incorrect.

Before 911e2b0fea (1.7.2 on Archlinux), this was correct:

    $ head -4 /usr/lib/pkgconfig/jsoncpp.pc
    prefix=/usr
    exec_prefix=${prefix}
    libdir=/usr/lib
    includedir=/usr/include

After 911e2b0fea (1.7.3 on Archlinux), this is now incorrect:

    $ head -4 /usr/lib/pkgconfig/jsoncpp.pc
    prefix=/usr
    exec_prefix=${prefix}
    libdir=lib
    includedir=include

This change causes hard-to-debug compilation errors for projects that
depend on jsoncpp, for instance:

    CXXLD    libring.la
    /tmp/ring-daemon/src/ring-daemon/src/../libtool: line 7486: cd: lib: No such file or directory
    libtool:   error: cannot determine absolute directory name of 'lib'
    make[3]: *** [Makefile:679: libring.la] Error 1

This is because jsoncpp contributes `-Llib -ljsoncpp` to the LDFLAGS, via
the pkg-config machinery.  Notice the relative path in `-Llib`.

To fix this, simply revert commit e6f1cffdd3 ("Fix custom includedir &
libdir substitution in pkg-config").  The change in 911e2b0fea should have
the same effect.

See #279, #470 for references.
2016-07-08 00:46:04 +02:00
Christopher Dunn
7e4df50d17 Merge pull request #490 from open-source-parsers/null-singleton
Use a Myers Singleton for null
2016-06-27 00:12:23 -05:00
Christopher Dunn
318f30357c 1.7.3 2016-06-26 19:40:43 -05:00
Christopher Dunn
0f288aecdd Use a Myers Singleton for null
Avoid some static initialization problems.

From @marklakata
See #488
2016-06-26 19:36:40 -05:00
Christopher Dunn
e0f9aab0bf Make internal func anon
fixes #489
2016-06-26 17:54:15 -05:00
Christopher Dunn
43203f1d09 Merge pull request #478 from quantumsteve/msvc_override
Use override keyword with Visual Studio.
2016-05-28 10:01:46 -05:00
Steven Hahn
55176b2bdd Use override keyword with Visual Studio. 2016-05-25 18:29:34 -04:00
Christopher Dunn
4356d9bba1 Merge pull request #474 from cdunn2001/fix-warning
Fix some warnings
2016-05-15 23:35:02 -05:00
Christopher Dunn
ea4af18317 Fix int->char conv warn
resolves #473
2016-05-15 23:13:56 -05:00
Christopher Dunn
b999616df8 fix warning 2016-05-15 23:13:47 -05:00
Christopher Dunn
660307d357 Merge pull request #470 from aboseley/relative_install_paths
By default use <prefix> relative paths when installing
2016-05-05 13:59:20 -05:00
Adam Boseley
911e2b0fea By default use <prefix> relative paths when installing
This allows the config file to keep working
when it is installed to a non-standard location
from a make DESTDIR=<location> install
2016-05-04 23:41:18 -07:00
Christopher Dunn
d4a49cf511 Merge pull request #466 from bkuhls/buildroot
CMakeLists.txt: Treat conversion warning as error only with JSONCPP_W…
2016-05-02 20:40:08 -05:00
Christopher Dunn
8bd4f943da Merge pull request #467 from jcfr/generalize-setting-of-JSONCPP_OVERRIDE
json/config.h: Generalize setting of JSONCPP_OVERRIDE to all compilers
2016-04-27 02:45:32 -05:00
Christopher Dunn
4018422a05 Merge pull request #465 from ds283/intel-compiler
Add CMAKE_CXX_FLAGS for Intel compiler
2016-04-27 02:28:41 -05:00
Jean-Christophe Fillion-Robin
ba6fa48d31 json/config.h: Generalize setting of JSONCPP_OVERRIDE to all compilers
This commit has been adapted from InsightSoftwareConsortium/ITK@1c86090
2016-04-25 17:35:12 -04:00
Bernd Kuhls
17fc9b1a80 CMakeLists.txt: Treat conversion warning as error only with JSONCPP_WITH_WARNING_AS_ERROR=On
Fixes errors when building with buildroot:
http://autobuild.buildroot.net/?reason=jsoncpp-1.7.2

Signed-off-by: Bernd Kuhls <bernd.kuhls@t-online.de>
2016-04-25 19:47:13 +02:00
ds283
6f22b0e076 Add CMAKE_CXX_FLAGS for Intel compiler 2016-04-25 14:47:05 +01:00
Christopher Dunn
980cdf0fb5 Exclude allocator.h from amalgamated header
Nobody using SecureAllocator really needs the amalgamated header.

resolves #461
2016-04-22 00:45:18 -05:00
Christopher Dunn
45da594e71 Merge pull request #454 from cbeiraod/master
Small fix for strict compilers (using the flag -Werror for instance)
2016-03-26 15:07:55 -05:00
Cristóvão B da Cruz e Silva
c8a7b445ea Small fix for strict compilers (using the flag -Werror for instance) 2016-03-26 18:41:46 +00:00
Christopher Dunn
c8054483f8 1.7.2 <- 1.7.1
This only fixes a clang warning, but we have already
seen more than one report for it.
2016-03-25 15:09:15 -05:00
Christopher Dunn
96d32b37ea Merge pull request #452 from cdunn2001/fix-451
Fix a clang warning
2016-03-24 00:27:13 -05:00
Christopher Dunn
ef2ff8754a Fix a clang warning
Resolves #451.
2016-03-23 22:33:18 -05:00
Christopher Dunn
b58c844579 1.7.1 <- 1.7.0
And 1.7.0 is recalled b/c we accidentally
had SecureAlloc by default.
2016-03-21 21:17:56 -05:00
Christopher Dunn
b803b92d11 Merge pull request #449 from cdunn2001/override-keyword
Use macro for `override`
2016-03-21 21:16:00 -05:00
Christopher Dunn
98e981dff9 Use macro for override
b/c MS VS2010 is supposed to be C++11 but does not fulfull
the entire standard.

Resolves #410.
Re: #430.
2016-03-21 21:00:24 -05:00
Christopher Dunn
1c47796479 JSONCPP_USING_SECURE_MEMORY default is 0
Re: #410
2016-03-21 20:44:16 -05:00
Christopher Dunn
12c67e810d Fix amalgamate.py
Fixes #448.
2016-03-21 20:33:34 -05:00
Christopher Dunn
c018d9fc3a Merge pull request #442 from open-source-parsers/JSONCPP_STRING
Secure allocator available for wiping memory.

Resolves #437.
Resolves #152.
2016-03-19 19:30:30 -05:00
dawesc
ae564653c4 -DJSONCPP_USE_SECURE_MEMORY=1 for cmake
Add allocator.h to amalgamated header
Test JSONCPP_USE_SECURE_MEMORY in Travis
2016-03-19 19:21:15 -05:00
dawesc
f8674c63b1 allocator.h 2016-03-19 14:37:30 -05:00
dawesc
b50a124fa6 .gitignore for eclipse 2016-03-19 14:37:30 -05:00
Christopher Dunn
59e327f50b Merge pull request #445 from ya1gaurav/patch-36
Added NORETURN for throw functions.
2016-03-17 20:54:26 -05:00
Gaurav
0b597b4b48 Added NORETURN for throw functions.
Fix in definition also.
2016-03-16 11:17:21 +05:30
Gaurav
d97ea5bf8d Added NORETURN for throw functions.
Resolve Issue - https://github.com/open-source-parsers/jsoncpp/issues/389
2016-03-16 11:15:09 +05:30
Christopher Dunn
e29b671ed5 Merge pull request #444 from ya1gaurav/patch-35
Supporting GCC 6.0

Resolves #411.
2016-03-15 19:23:17 -05:00
Gaurav
fbe1cf3916 Supporting GCC 6.0
Fixes test with GCC-6.0
2016-03-15 18:33:34 +05:30
Gaurav
cf86c473a5 Supporting GCC 6.0
This patch is also needed to build success for GCC 6.0.
Refer issue - https://github.com/open-source-parsers/jsoncpp/issues/411
2016-03-15 18:31:44 +05:30
Christopher Dawes
75570d7068 Fixing up for #define instead of typedef in secure allocators 2016-03-14 19:15:17 -05:00
Christopher Dunn
5da29e2707 Another shot at #411 2016-03-14 18:35:53 -05:00
Christopher Dunn
c80faa400c Merge pull request #438 from ya1gaurav/patch-34
MinGW support while building as DLL

Fixed #434.
2016-03-12 14:40:19 -06:00
Gaurav
8aabf93cc1 MinGW support while building as DLL
__MINGW32__ is appropriate to support for MinGW
2016-03-08 17:34:22 +05:30
Gaurav
3e51598176 MinGW support while building as DLL
This is PR for https://github.com/open-source-parsers/jsoncpp/issues/434
It will fix reported build error.
2016-03-08 17:17:42 +05:30
Christopher Dunn
1b5e61d008 Merge pull request #435 from cdunn2001/JSONCPP_STRING
JSONCPP_STRING etc.
2016-03-06 12:43:47 -06:00
Christopher Dunn
b84e0c159d JSONCPP_ISTREAM 2016-03-06 11:56:39 -06:00
Christopher Dunn
1e990640a9 JSONCPP_ISTRINGSTREAM 2016-03-06 11:56:39 -06:00
Christopher Dunn
38bb491400 JSONCPP_OSTRINGSTREAM 2016-03-06 11:56:38 -06:00
Christopher Dunn
724ba29bd3 JSONCPP_OSTREAM 2016-03-06 11:56:38 -06:00
Christopher Dunn
de5b792168 JSONCPP_STRING 2016-03-06 11:56:38 -06:00
Christopher Dunn
1b8e3b7f4d Merge pull request #432 from ya1gaurav/patch-33
Avoid passing Null to memcmp

hopefully resolves #404
2016-03-02 14:27:03 -06:00
Gaurav
4878913143 Avoid passing Null to memcmp
As per discussion in - https://github.com/open-source-parsers/jsoncpp/issues/404
Null should not be pass to memcmp, it may show undesired behaviour, so avoid doing that using assertion.
Also, changed one direct "assert" to JSON_ASSERT - it will be decided if exceptions are used or not.
2016-03-01 14:13:28 +05:30
Christopher Dunn
d179e24c14 Merge pull request #429 from tmaciejewski/remove_c_style_casting
remove C-style casting
2016-02-29 23:20:07 -06:00
Tomasz Maciejewski
ccd70540e3 remove C-style casting 2016-02-28 12:56:04 +01:00
Christopher Dunn
b4d2b65841 Merge pull request #418 from Techwolfy/master
std::snprintf fix for Cygwin
2016-02-10 21:17:31 -06:00
Techwolf
7e46bf76e8 std::snprintf fix for Cygwin 2016-02-10 17:09:32 -08:00
Christopher Dunn
da0c50f7b2 Merge pull request #416 from cdunn2001/fix-gcc6-errors
Fix gcc6 errors
2016-02-07 11:40:50 -06:00
Christopher Dunn
02bc3d77de This *might* fix the last gcc-6 error.
See https://github.com/open-source-parsers/jsoncpp/issues/411#issuecomment-180974558

I was unable to produce a warning in Clang, so I am not certain. But based on a [SO answer](http://stackoverflow.com/questions/25480059/gcc-conversion-warning-when-assigning-to-a-bitfield), I think I've fixed the following:
```
/tmp/jsoncpp/src/lib_json/json_value.cpp: In copy constructor 'Json::Value::CZString::CZString(const Json::Value::CZString&)':
/tmp/jsoncpp/src/lib_json/json_value.cpp:235:18: error: conversion to 'unsigned char:2' from 'unsigned int' may alter its value [-Werror=conversion]
   storage_.policy_ = (other.cstr_
                      ~~~~~~~~~~~~
                  ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                      ? noDuplication : duplicate)
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                  : static_cast<DuplicationPolicy>(other.storage_.policy_));
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
2016-02-07 11:28:50 -06:00
Christopher Dunn
6b562c850d Drop -Wno-sign-conversion suppression 2016-02-07 11:19:04 -06:00
Christopher Dunn
2713f4f456 Fix a sign-compare 2016-02-07 11:17:28 -06:00
Christopher Dunn
83bc9c7cf6 Errors for sign-compare, since gcc6 is stricter 2016-02-07 11:12:25 -06:00
Christopher Dunn
95f120f68e For gcc>=6 JSON_USE_INT64_DOUBLE_CONVERSION 2016-02-07 11:09:41 -06:00
Christopher Dunn
9a4b1e39bf 1.7.0 < 1.6.5 2016-02-06 10:27:39 -06:00
Christopher Dunn
2c872ec997 Merge pull request #406 from magnific0/master
std::snprintf not part of std for MinGW32 using c++11
2016-02-06 10:21:45 -06:00
Christopher Dunn
b860cc38e8 Merge pull request #414 from cdunn2001/conversion-errors
Fix conversion warnings/errors
2016-02-06 10:19:23 -06:00
Christopher Dunn
fef4b75796 More conversion fixes for gcc 2016-02-06 10:10:49 -06:00
Christopher Dunn
779d8a33fc Try to find ptrdiff_t for GNUC 4.9.2
https://travis-ci.org/open-source-parsers/jsoncpp/jobs/107452667
2016-02-06 09:49:29 -06:00
Christopher Dunn
d4513fcf45 Fix conversion warnings/errors
See #411.
  http://paste.debian.net/378673/
2016-02-06 09:25:20 -06:00
Christopher Dunn
baefec773c In case cmake is run in root-dir 2016-02-06 08:29:12 -06:00
Christopher Dunn
bc72070f43 Merge pull request #393 from ds283/cmake-binary-dir
Change ${CMAKE_BINARY_DIR} to ${CMAKE_CURRENT_BINARY_DIR}
2016-02-04 15:05:02 -06:00
Jacco
bc9b445fee std::snprintf fix for MinGW32 c++11 2016-01-25 11:39:36 +01:00
Jacco
2646ac5fa5 std::snprintf fix for MinGW32 c++11 2016-01-25 11:38:49 +01:00
ds283
2cca1cd239 Change ${CMAKE_BINARY_DIR} to ${CMAKE_CURRENT_BINARY_DIR}
- if building as a submodule of another repository, installation of pkg-config files can fail because they may not be in the top-level binary directory

- changing ${CMAKE_BINARY_DIR} to ${CMAKE_CURRENT_BINARY_DIR} allow CMake to find the files for installation
2015-12-05 12:18:12 +00:00
Christopher Dunn
9234cbbc90 Merge pull request #387 from joerg-krause/cmake-option-strict-iso
Disable -pedantic conditionally; add -pedantic-errors and -Werror conditionally
2015-10-30 01:16:49 -05:00
Jörg Krause
7c93031c9b Enable -Werror with JSONCPP_WITH_WARNING_AS_ERROR
Commit 912d55094d disabled '-Werror'. Enable it
if jsoncpp is build with JSONCPP_WITH_WARNING_AS_ERROR=ON.
2015-10-29 09:21:01 +01:00
Jörg Krause
48bfe91062 Add option JSONCPP_WITH_STRICT_ISO
'-pedantic' issues all warnings demanded by strict ISO C/C++; rejecting
extensions that do not follow ISO C/C++. Without this option, certain GNU
extensions and traditional C/C++ features are supported as well.

With this option enabled building jsoncpp fails with the musl toolchain on
x86 because of an incompatible posix_memalign declaration [1]. Without
'-pedantic' there is no error anymore and jsoncpp builds fine.

Add an option JSONCPP_WITH_STRICT_ISO to disable compilation with '-pedantic'
with GCC. If jsoncpp is build with the JSONCPP_WITH_WARNING_AS_ERROR option
'-pedantic-errors' is used instead.

[1] https://gcc.gnu.org/ml/gcc-patches/2015-05/msg01425.html
2015-10-29 09:16:21 +01:00
Christopher Dunn
0cce773019 Merge pull request #384 from EvinceMoi/master
json_reader throwRuntimeError return error details
2015-10-27 15:48:05 -05:00
Evince
6b10ce8c0d json_reader throwRuntimeError return error details instead of hard-coded message
Signed-off-by: Evince <baneyue@gmail.com>
2015-10-28 00:22:46 +08:00
Christopher Dunn
34bdbb58b4 Merge pull request #267 from cdunn2001/moveSemantics
move ctors
2015-10-21 01:13:59 -05:00
Christopher Dunn
527965cbde Minor
adjustments, based on comments in PR.
2015-10-19 23:49:07 -05:00
Motti
2b00891a86 move ctors
* Add move constructor to Value::CZString
* Add unit test for Value move constructor
* Allow includer to specify in advance the value for
JSON_HAS_RVALUE_REFERENCES
2015-10-19 23:42:52 -05:00
Christopher Dunn
a4ce2829dc Some indentation
in anticipation of another change.
2015-10-19 23:40:47 -05:00
Christopher Dunn
69e7f1c858 Merge pull request #382 from cdunn2001/ccache
Support ccache
2015-10-19 22:50:41 -05:00
Christopher Dunn
d1a2b94d5b Support ccache
http://stackoverflow.com/a/24305849/263998
2015-10-19 12:10:58 -05:00
Christopher Dunn
772f634548 Merge pull request #381 from bknecht/precision
Resolves #284
2015-10-15 16:15:15 -05:00
Benjamin Knecht
9fd1ca8d68 Add test code for precision 2015-10-15 18:32:24 +02:00
Benjamin Knecht
38022157b2 making precision unsigned int
adding precision as settings value for StreamBuilder
2015-10-15 18:00:42 +02:00
Benjamin Knecht
039a6e3b61 Create format string with sprintf.
For now use hardcoded precision '17' for now
2015-10-15 17:28:56 +02:00
Christopher Dunn
9c17e61bd0 Merge pull request #379 from cdunn2001/issue-377
Iterator conversions
2015-10-10 17:20:37 -05:00
ycqiu
c8a8cfcd4b fix
In value.h, ValueConstIterator can convert to ValueIterator, I think that is a bug. the correct way is ValueIterator can convert to ValueConstIterator.
2015-10-10 17:17:20 -05:00
ycqiu
4994c77d09 add test code
does not compile
2015-10-10 16:22:14 -05:00
Christopher Dunn
beae99924f Merge pull request #373 from antonindrawan/QNX_support
Compiles jsoncpp with QNX 6.6
2015-10-04 14:54:09 -05:00
Christopher Dunn
8b9940fd24 Merge pull request #375 from Dani-Hub/issue-374-remove-defaulted-ctor
Remove defaulted default constructor
2015-10-03 16:03:27 -05:00
drgler
b96d90efbd Remove defaulted default constructor 2015-10-03 19:40:23 +02:00
Anton Indrawan
e375b8c89e Compiles jsoncpp with QNX 6.6 2015-10-03 11:48:19 +02:00
Christopher Dunn
49393ead06 Merge pull request #371 from mathstuf/more-platform-support
json_writer: improve isfinite support on *nix
2015-10-03 03:58:20 -05:00
Ben Boeckel
8df11d518b json_writer: improve isfinite support on *nix
Based on a patches to CMake by:

Ådne Hovda <ahovda@openit.com>:

    commit 7b1cdb00279908cacabada92f8a53e4986465423

    jsoncpp: Provide 'isfinite' implementation on older AIX and HP-UX

    Newer AIX and HP-UX platforms provide 'isfinite' as a <math.h> macro.
    Older versions do not, so add the definition if it is not provided.

Michael Scott <michael.scott@gbgplc.com>:

    commit 9217b678b305d7df7471ba476a81bf28961fdfa3

    jsoncpp: Provide 'isfinite' impl on more HP-UX versions (#15576)

    Some versions of HP-UX do not define 'isfinite' or 'finite' in math.h
    for Itanium when preprocessing with C++, so we have to add the
    definition ourselves instead to map to the internal version.

Joerg Sonnenberger <joerg@bec.de>:

    commit 75644dafe54c21902f14cfe58cb8338b553b69d8

    jsoncpp: Fix compilation as C99 on Solaris

    In C99 mode, Solaris variants may already define isfinite, so check for
    the existence first.
2015-10-01 13:27:19 -04:00
Christopher Dunn
8e400e9be7 Merge pull request #368 from mathstuf/export-factory-inner-class
reader: export CharReader::Factory
2015-09-28 17:06:34 -05:00
Christopher Dunn
dc5aa4ad7f Fix VS warnings
These don't really need to be const.

resolves #369
2015-09-28 17:05:57 -05:00
Ben Boeckel
80def66fa5 reader: export CharReader::Factory 2015-09-28 15:45:11 -04:00
Christopher Dunn
6992831c1c Merge pull request #367 from Dani-Hub/issue-350-unique_ptr-2
__cplusplus value should not be used to decide for std::unique_ptr

resolves #350
2015-09-28 11:27:29 -05:00
drgler
7e4875a239 __cplusplus value should not be used to decide for std::unique_ptr #350:
In addition to the C++ language version define __cplusplus also check _CPPLIB_VER for better Dinkumware support.
2015-09-27 14:03:35 +02:00
Christopher Dunn
979cbec237 Fully init OurReader
See #363, similar to #364.
2015-09-23 09:44:58 -05:00
Christopher Dunn
2e625dd9af Merge pull request #364 from ya1gaurav/patch-28
Have default ctor for OurFeatures
2015-09-23 09:41:17 -05:00
Gaurav
83ea25e5e2 Make OurFeatures ctor as default.
Please review suggested changes.
2015-09-23 09:42:26 +05:30
Christopher Dunn
5721f1ca57 Merge pull request #366 from ya1gaurav/patch-30
parseCommandLine also throws
2015-09-22 05:09:33 -05:00
Christopher Dunn
9942f6a1c7 Merge pull request #365 from ya1gaurav/patch-29
Remove conditional check for isMultiLine
2015-09-22 05:08:56 -05:00
Gaurav
6c14548293 parseCommandLine also throws
Catching exceptions thrown by parseCommandLine (std::bad_alloc & std::length_error) also.
2015-09-22 13:53:19 +05:30
Gaurav
6ee0bff822 Remove conditional check for isMultiLine
At all 3 places isMultiLine is checked in for loop :
for (int index = 0; index < size && !isMultiLine; ++index) {
It means !isMultiLine is always true (otherwise do not enter loop), so || condition does not depend on isMultiLine, so removed that.
2015-09-22 09:48:54 +05:30
Gaurav
e3b35992f8 Add default value of stackLimit couple of places
stackLimit default value is missing at two places.Adding them.
2015-09-21 18:05:15 +05:30
Christopher Dunn
cc5cdb565c Merge pull request #348 from cdunn2001/override-keyword
C++11: override keyword
2015-09-05 12:12:37 -05:00
Gaurav
aadd0b1b63 C++11: override keyword
Source : http://en.cppreference.com/w/cpp/language/override
2015-09-05 12:03:38 -05:00
Christopher Dunn
3ee15b7bcc Merge pull request #339 from Dani-Hub/master
Floating-point NaN or Infinity values should be allowed as a feature …
2015-09-05 11:59:54 -05:00
drgler
68509e6161 Fix number reading in the presence of Infinity: Only check for infinity if we have a leading sign character. 2015-09-05 14:49:33 +02:00
drgler
4cea1f6f6c Adjust whitespace formatting 2015-09-05 14:48:29 +02:00
Daniel Krügler
6f9ed421d0 Merge pull request #2 from BillyDonahue/billy_danihub_fix
Billy danihub fix
2015-09-05 13:38:04 +02:00
Billy Donahue
7f7bbeff76 don't need out field of TestData 2015-09-05 04:22:18 -04:00
Billy Donahue
bfffe8cec7 prettier test 2015-09-05 04:07:56 -04:00
Billy Donahue
73154fb546 expanded Infinity test 2015-09-05 03:48:38 -04:00
drgler
63c747218b Floating-point NaN or Infinity values should be allowed as a feature #209
Introduce 'allowSpecialFloats' for readers and 'useSpecialFloats' for writers, use consistent macro snprintf definition for writers and readers, provide new unit tests for #209
2015-09-03 22:50:03 +02:00
drgler
2084563efb Floating-point NaN or Infinity values should be allowed as a feature #209
Introduce 'allowSpecialFloats' for readers and 'useSpecialFloats' for writers, use consistent macro snprintf definition for writers and readers, provide new unit tests for #209
2015-09-03 22:19:22 +02:00
Christopher Dunn
6329975e6d Merge pull request #337 from AMDmi3/patch-1
Specify float constant as float
2015-08-21 20:45:37 -05:00
Dmitry Marakasov
7acfd599f0 Specify float constant as float
Otherwise, on some 32 bit platforms this may not fit into long and compilation will fail:

    src/test_lib_json/main.cpp:1260: error: integer constant is too large for 'long' type
2015-08-21 21:19:26 +03:00
Robert Dailey
63a961a752 Clean up cmake END* (again)
(I missed a couple. ~cd)
2015-08-14 14:47:46 -07:00
Christopher Dunn
cb2378fa41 Merge pull request #332 from cdunn2001/END
Clean up cmake END*
2015-08-14 14:40:42 -07:00
Robert Dailey
37aaaec70e Clean up cmake END*
* Clean up closing statements for if conditions, functions, macros,
  and other entities. Newer versions of CMake do not require you to
  redundantly respecify the parameters to the opening arguments.
2015-08-14 14:31:08 -07:00
Christopher Dunn
585446e6b3 Merge pull request #327 from cdunn2001/more-gitattributes
More gitattributes
2015-08-09 16:38:21 -07:00
Christopher Dunn
7f4be39e9f add .gitattributes
helps #325
2015-08-09 16:25:36 -07:00
Christopher Dunn
47595e922b normalized some windows VS stuff 2015-08-09 16:23:50 -07:00
Christopher Dunn
9f7dbcb19b Merge pull request #326 from rcdailey/git-attributes
Introduce .gitattributes file and normalize line endings
2015-08-09 16:23:20 -07:00
Robert Dailey
c1996256d6 Normalize line endings
This commit contains nothing but line ending normalization
changes. These changes were performed after the introduction
of .gitattributes into the repository.
2015-08-09 18:02:52 -05:00
Robert Dailey
25e4adc4e1 Add .gitattributes file 2015-08-09 18:02:37 -05:00
Aaron Jacobs
cc2c15c3eb Remove undefined behavior from a left shift of a negative value.
Fixed by shifting a positive value, then negating the result.

(Credit: Richard Trieu)
2015-08-03 10:58:29 +10:00
Christopher Dunn
912d55094d Merge pull request #323 from joerg-krause/master
Remove -Werror
2015-08-02 15:48:38 -05:00
Jörg Krause
d7b84f69c5 Remove Werror
-Werror shouldn't be used in released code since it can cause random build
failures on moderate warnings. It also depends on the used toolchain since
different toolchains may or may not print the same warnings.
2015-07-30 23:56:28 +02:00
Christopher Dunn
9dad198af6 Merge pull request #320 from shields/negation-overflow
Fix cases where the most negative signed integer was negated, causing undefined behavior.
2015-07-28 11:35:52 -05:00
Michael Shields
7f06e9dc28 Fix cases where the most negative signed integer was negated, causing
undefined behavior.
2015-07-27 16:35:19 -07:00
Christopher Dunn
d84702c903 1.6.5 2015-07-23 00:26:13 -05:00
Christopher Dunn
949babd7b0 Exceptions declared in header
resolves #272
2015-07-23 00:26:13 -05:00
Christopher Dunn
6ed877c77c correction for #316 2015-07-23 00:26:13 -05:00
Christopher Dunn
1c69568f8d Merge pull request #316 from filipjs/master
Update json_tool.h

typo in a comment
2015-07-17 06:44:33 -05:00
filipjs
770fdda28b Update json_tool.h
Fix a typo in comment.
2015-07-14 14:34:07 +02:00
Christopher Dunn
81cf237917 Merge pull request #314 from cdunn2001/master
-Werror

plus small bug-fix
2015-07-12 14:38:02 -05:00
Christopher Dunn
cac79543f8 1.6.4
minor bug-fix
2015-07-12 14:29:53 -05:00
Christopher Dunn
d8186f36a6 -Werror 2015-07-12 14:28:55 -05:00
Christopher Dunn
7f240623d3 fixed a bug found by -Wshadow 2015-07-12 14:28:55 -05:00
Christopher Dunn
784433ac72 fix some warnings 2015-07-12 14:28:37 -05:00
Christopher Dunn
7275e3ce3c drop -Wsign-conversion 2015-07-12 12:49:57 -05:00
Christopher Dunn
46aa9d75fa -Wconversion
* https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
* http://programmers.stackexchange.com/questions/122608/clang-warning-flags-for-objective-c-development/124574#124574

In clang: `-Wconversion` implies `-Wshorten-64-to-32`
2015-07-12 12:39:04 -05:00
Christopher Dunn
f94a0e8989 auto-generated file with minor update 2015-07-12 12:31:43 -05:00
Christopher Dunn
e22a2f36f7 Merge pull request #313 from cdunn2001/master
`-std=c++11` for gcc builds too

There was an issue with Travis, but we seem to be past that now.

We were using only -std=c++0x for gcc, as you can see in the diff.

resolves #134
2015-07-12 12:18:28 -05:00
Christopher Dunn
fac87108a4 -std=c++11 for gcc builds too 2015-07-12 12:08:34 -05:00
Christopher Dunn
14fc9f124e Merge pull request #312 from cdunn2001/master
gcc-4.9, clang (3.0)
2015-07-12 12:04:41 -05:00
Christopher Dunn
658fa37e63 gcc-4.9, clang (3.0) 2015-07-12 11:53:49 -05:00
Christopher Dunn
056e5f9b64 Merge pull request #309 from cdunn2001/master
dockerize the Travis build, and allow C++11
2015-07-11 14:19:02 -05:00
Christopher Dunn
d8e8c14ffc valgrind in Travis 2015-07-11 14:11:45 -05:00
Christopher Dunn
f4e6fccd46 dockerize the Travis build
Docker builds are *much* faster in Travis.

Also, we prepare to enable C++11.
2015-07-11 14:06:18 -05:00
Christopher Dunn
2428889813 1.6.3 2015-07-11 13:41:13 -05:00
Christopher Dunn
89704039a0 minor doc fix, for #302 2015-07-11 12:11:00 -05:00
Christopher Dunn
6ca8ffcb91 Merge pull request #305 from cdunn2001/fix-fixeol-undefined-name-sys
Fix undefined name "sys"

Same as #299 (bca0eff), but an earlier commit needed to be rebased.
2015-07-11 11:17:09 -05:00
Mike Naberezny
b5e70f950e Fix undefined name "sys"
Same as #299 (bca0eff81a1c5ef160d9858b8e89b1c919b71c1f), but an earlier
commit needed to be rebased.
2015-07-11 11:15:43 -05:00
Christopher Dunn
b26804d1c2 Merge pull request #304 from cdunn2001/297
Same as #297 (1c4f274ab3), but properly rebased
2015-07-11 11:08:47 -05:00
Stuart Eichert
702a539762 Fix #296: Explicitly cast size_t results to unsigned when needed
This is rebased from #297, where AppVeyor had been failing, and which
was not properly based on the master branch.
2015-07-11 11:00:18 -05:00
Stuart Eichert
81cb7e5c5b Warn about implicit 64 to 32 bit conversions when using clang 2015-07-11 10:59:56 -05:00
Christopher Dunn
d259f608fd Merge pull request #303 from cdunn2001/appveyor-14.0
fix appveyor 32-bit windows build

I've backed rebased under #297 because AppVeyor has been failing since there, and because that was not properly based on master anyway.
2015-07-11 10:58:59 -05:00
Christopher Dunn
4652f818fe fix appveyor 32-bit windows build
* http://help.appveyor.com/discussions/problems/2229-v140-not-found-on-vs2105rc
```
Done Building Project "C:\projects\jsoncpp\jsoncpp.sln" (default targets) -- FAILED.

Build FAILED.

"C:\projects\jsoncpp\jsoncpp.sln" (default target) (1) ->
"C:\projects\jsoncpp\ALL_BUILD.vcxproj.metaproj" (default target) (2) ->
"C:\projects\jsoncpp\ZERO_CHECK.vcxproj" (default target) (3) ->
(PlatformPrepareForBuild target) ->
  C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.Cpp.Platform.targets(64,5): error MSB8020: The build tools for v140 (Platform Toolset = 'v140') cannot be found. To build using the v140 build tools, please install v140 build tools.  Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting "Upgrade Solution...". [C:\projects\jsoncpp\ZERO_CHECK.vcxproj]
```
2015-07-11 10:53:13 -05:00
Christopher Dunn
ce32274ba5 Merge pull request #295 from martyngigg/master
Allow an optional suffix on the debug library name in CMake
2015-07-01 03:18:33 -05:00
Martyn Gigg
717c791d4e Allow an optional suffix on the debug library name in CMake. 2015-06-29 19:20:08 +01:00
Christopher Dunn
6e52e272da Merge pull request #294 from cdunn2001/master
fix ,/. problem in reader
2015-06-19 00:10:32 -05:00
Christopher Dunn
6416350438 fix ,/. problem in reader
fixes #293
2015-06-18 22:45:36 -05:00
Christopher Dunn
bcb83b921c fix doxybuild.py for Windows
issue #287 (tylerknott@)
2015-06-18 22:26:44 -05:00
Christopher Dunn
3f05b1a897 Merge pull request #276 from bmyerz/master
make the unix cmake example work
2015-05-21 00:47:35 -05:00
Christopher Dunn
de2c85f576 Merge pull request #282 from keithkml/patch-1
Clarify which parts of README for users vs devs
2015-05-20 20:33:31 -05:00
Christopher Dunn
b389d81bf9 Merge pull request #280 from mgorny/pkg-config-fix
Fix custom includedir & libdir substitution in pkg-config
2015-05-20 20:24:37 -05:00
Keith Lea
89c51f3457 Clarify which parts of README for users vs devs
When I arrived at the JsonCpp GitHub page, as an intermediate C++ developer, I could not figure out how to include JsonCpp into my project. The changes I propose to the README make this much clearer, and define a clear distinction between which instructions are for those developing and contributing to JsonCpp, and those who are just using it.
2015-05-20 09:43:47 -07:00
Michał Górny
e6f1cffdd3 Fix custom includedir & libdir substitution in pkg-config
Do not prepend ${prefix} to substituted includedir & libdir
in the pkg-config file -- if the paths are overriden by user, CMake puts
absolute paths there (even if user specifies a relative path). Instead,
use the absolute path provided by CMake and appropriately default
LIBRARY_INSTALL_DIR & INCLUDE_INSTALL_DIR to absolute paths with
${CMAKE_INSTALL_PREFIX} prepended.

Fixes: https://github.com/open-source-parsers/jsoncpp/issues/279
Signed-off-by: Michał Górny <mgorny@gentoo.org>
2015-05-19 17:32:31 +02:00
Christopher Dunn
64441486ac Merge pull request #275 from stefan-it/stefan/cmake-generator-fix
[Documentation][Markdown] Use correct help option for cmake.
2015-05-19 01:53:11 -05:00
Christopher Dunn
d5e54d2609 Merge pull request #277 from gogo40/master
fix compile error on android

But note that we do not have continuous integration testing for Android. This could break again.

`snprintf` drives me crazy. It should have been part of every C library 20 years ago.
2015-05-19 01:52:57 -05:00
Péricles Lopes Machado
97e093a361 fix compile error on android 2015-05-18 14:31:05 -03:00
Brandon Myers
d57ac97db8 make the unix make example work
...by setting the archive directory variable
2015-05-18 10:06:21 -07:00
Stefan Schweter
31e9962754 [Documentation][Markdown] Use correct help option for cmake. 2015-05-17 13:04:40 +02:00
Christopher Dunn
5256551b03 address compilation probs for C++ Builder
BORLANDC compiler strangeness. Thanks to:

* Dan Liu
* Victor Chen

close #269
close #252
2015-04-28 05:08:58 +01:00
Christopher Dunn
6649009ffa another fix for BORLANDC 2015-04-28 04:57:49 +01:00
Christopher Dunn
2a10f4a3b8 move ctors for BORLAND 2015-04-28 04:55:12 +01:00
Christopher Dunn
28d086e1d9 Merge pull request #266 from cdunn2001/issue-252
Use unsigned for DuplicationPolicy, to fix a problem with "C++ Builder"
IDE.

Fixes #252.

Thanks to:

* Dan Liu -- http://blog.csdn.net/gzliudan/article/details/45264201)
* Victor Chen -- http://www.cppfans.com/sdk/json/jsoncpp.asp
2015-04-27 18:28:06 -07:00
Christopher Dunn
a0a7c5f6de a little test for issue 252, but does not fail for me 2015-04-27 18:14:09 -07:00
Dan Liu
fcbab02e4a fix crash for "C++ Builder" IDE
http://blog.csdn.net/gzliudan/article/details/45264201
2015-04-27 18:10:12 -07:00
Christopher Dunn
f4ee48bc21 Merge pull request #265 from cdunn2001/valgrind
run valgrind in Travis CI
2015-04-26 20:08:17 -07:00
Christopher Dunn
88184d142b run valgrind in Travis CI
Because this runs apt-get, it will not work as-is for OSX. So when
we have OSX in Travis, we will have to wrap this somehow. See #250.

Closes #222.
2015-04-27 04:03:34 +01:00
Christopher Dunn
ae177fd901 Merge pull request #263 from cdunn2001/static-shared
Use standard **cmake** variables, to support superprojects better.

- `JSONCPP_LIB_BUILD_SHARED` -> `BUILD_SHARED_LIBS`
- `JSONCPP_LIB_BUILD_STATIC` -> `BUILD_STATIC_LIBS`
2015-04-23 08:58:38 -07:00
Gaurav
3f6345234f Use standard CMake variables - static/shared lib.
Replace JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
2015-04-23 07:32:19 -07:00
Gaurav
a53070c42b Use standard CMake variables - static/shared lib.
Replace JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
2015-04-23 07:32:19 -07:00
Gaurav
c09e121aeb Use standard CMake variables - static/shared lib.
Replace JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
2015-04-23 07:32:18 -07:00
Gaurav
4f8ec9d207 Use standard CMake variables - static/shared lib.
Replaced JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
Replaced JSONCPP_LIB_BUILD_STATIC => BUILD_STATIC_LIBS
2015-04-23 07:32:18 -07:00
Gaurav
0fe61a68f8 Use standard CMake variables - static/shared lib.
Replaced JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
2015-04-23 07:32:18 -07:00
Gaurav
43019088f0 Use standard CMake variables - static/shared lib.
Replaced JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
Moved flag JSON_DLL to line no 8.
2015-04-23 07:32:18 -07:00
Gaurav
0c1c076b7c Use standard CMake variables - static/shared lib.
Replaced JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
Moved definition DJSON_DLL to line 11.
2015-04-23 07:32:18 -07:00
Gaurav
11130997c3 Use standard CMake variables - static/shared lib.
Replace JSONCPP_LIB_BUILD_SHARED => BUILD_SHARED_LIBS
Replace JSONCPP_LIB_BUILD_STATIC => BUILD_STATIC_LIBS
Removed workaround  https://github.com/open-source-parsers/jsoncpp/issues/51
Removed OPTION for shared/static in this file.
2015-04-23 07:32:17 -07:00
Gaurav
30bb4ccb67 Use standard CMake variables - static/shared lib.
Currently JSONCPP_LIB_BUILD_SHARED variable is used as option to build static/shared libraries.
The current patch uses standard CMake variables for this.
Such a workaround is done in https://github.com/open-source-parsers/jsoncpp/issues/51
Current patch will make it generic.
2015-04-23 18:39:00 +05:30
Christopher Dunn
74143f39e7 fix leak in unit-tests 2015-04-22 19:33:41 -07:00
Christopher Dunn
56650e83c5 swap docs for default vs. strictMode 2015-04-20 13:10:31 -07:00
Christopher Dunn
441f8cdfa1 Merge pull request #244 from cdunn2001/appveyor
New `appveyor.yml`: All tests pass, in both Appveyor and Travis!

Henceforth, GitHub will run both for any pull-request, so this file will be needed in the `0.y.z` branch too.
2015-04-18 17:14:33 -07:00
Christopher Dunn
a658759039 maybe fix an error 2015-04-16 18:33:39 -07:00
Christopher Dunn
0eb0e502c8 add a comment, to force a build 2015-04-16 18:30:24 -07:00
Marek Kotewicz
e983204906 appveyor deploy init 2015-04-16 18:12:18 -07:00
Marek Kotewicz
fe06acb587 fixed version on appveyor build 2015-04-16 18:12:17 -07:00
Marek Kotewicz
1b49a55ea1 appveyor multiple platforms 2015-04-16 18:12:17 -07:00
Marek Kotewicz
13c36e9807 appveyor.yml 2015-04-16 18:12:17 -07:00
Christopher Dunn
50069d72da prefer std::string for setComment()
in case of embedded nulls
2015-04-11 14:49:28 -05:00
Christopher Dunn
24682e37bf 1.6.2 <- 1.6.1
Fix UTF-8 for old (deprecated) Writers.

* Do not truncate at embedded zeroes.
2015-04-11 14:45:33 -05:00
Christopher Dunn
c2b988ee74 Merge pull request #241 from cdunn2001/fix-more-utf8
support UTF-8 (specifically, embedded zeroes) in old Writers
2015-04-11 14:44:41 -05:00
Christopher Dunn
e255ce31a4 support UTF-8 in old Writers
We had already fixed Value to hold UTF-8 properly, but only the newer
StreamWriter was writing UTF-8 properly.

Old FasterWriter etc. were using asCString() instead of asString() in
Value::writeValue().

Hopefully this change does not break any existing code. Seems unlikely.

issue #240
2015-04-11 14:41:30 -05:00
Christopher Dunn
779b5bc5ba Merge pull request #239 from sbc100/copyright
Add copyright information to .py files
2015-04-11 14:41:03 -05:00
Sam Clegg
63860617b3 Add copyright information to .py files
This change adds explicit copyright information too python
files files.  The copyright year used in each case is the
date of the first git commit of each file.

The goal is to allow jsoncpp to be integrated into the
chromium source tree which requires license information in
each source file.

fixes #234
2015-04-09 18:05:47 -07:00
Christopher Dunn
9cb88d2ca6 1.6.1 <- 1.6.0 2015-03-31 15:07:14 -05:00
Christopher Dunn
363e51c0a9 Merge pull request #232 from cdunn2001/fix-snprintf
Fix snprintf

Well, it passes Travis. But when we have time, we should clean up how snprintf is used in both reader and writer.
2015-03-31 15:06:11 -05:00
Christopher Dunn
240ddb6a1b use std::snprintf for C++11 2015-03-31 15:04:24 -05:00
Baruch Siach
9dd77dc0ef Revert "Use std namespace for snprintf."
This reverts commit 1c58876185.

std::snprintf() is only available in C++11, which is not provided by
all compilers. Since the C library snprintf() can easily be used as a
replacement on Linux systems, this patch changes jsoncpp to use the C
library snprintf() instead of C++11 std::snprintf(), fixing the build error
below:

    src/lib_json/json_writer.cpp:33:18: error: 'snprintf' is not a member of 'std'

See #231, #224, and #218.
2015-03-31 15:04:24 -05:00
Christopher Dunn
244b1496e1 Merge pull request #225 from selaselah/master
fix find_program() bug: no result in not-win sys
2015-03-31 11:32:06 -05:00
selaselah
c083835261 fix find_program() bug: no result in not-win sys 2015-03-19 19:18:58 +08:00
Christopher Dunn
cbe7e7c9cb Merge pull request #221 from btolfa/forgotten-virtual-dtor
Added forgotten virtual dtor for `Json::CharReader::Factory`.

(Without this, the destructor of the derived `CharReaderBuilder` would not be called, which is a small memory leak.)
2015-03-15 13:49:24 -05:00
Tengiz Sharafiev
be183def8f Update reader.h 2015-03-14 21:30:00 +03:00
Christopher Dunn
951bd3d05d Merge pull request #219 from cdunn2001/c-std-headers
Close #218. Fix #214.
2015-03-11 21:36:51 -05:00
Connor Manning
1c58876185 Use std namespace for snprintf. 2015-03-11 21:33:08 -05:00
Connor Manning
2f2034629e Constrain MSVC _isfinite to before 2013, remove duplicate includes. 2015-03-11 21:33:08 -05:00
Dani-Hub
7020451b44 Fix isfinite for MSVC. 2015-03-11 21:32:59 -05:00
Connor Manning
80497f102e Use C++ standard headers. 2015-03-10 18:48:45 -05:00
Dani-Hub
f9feb66be2 Change exception data member
from "reference to string" to "string" (Resolves the most serious part of issue #216)
2015-03-09 18:42:16 -05:00
Christopher Dunn
ed495edcc1 prefer ValueIterator::name() to ::memberName()
in case of embedded nulls
2015-03-08 14:35:00 -05:00
Christopher Dunn
3c0a383877 Merge pull request #212 from cdunn2001/macro-deprec
close #210
2015-03-08 13:10:37 -05:00
Dani-Hub
5003983029 Make preprocessor query robust against older gcc versions 2015-03-08 13:07:27 -05:00
Dani-Hub
871b311e7e Provide JSONCPP_DEPRECATED definitions for clang and gcc 2015-03-08 13:07:27 -05:00
Christopher Dunn
cdbc35f6ac 1.6.0 2015-03-08 12:57:13 -05:00
Christopher Dunn
4e30c4fcdb comments 2015-03-08 12:56:32 -05:00
Christopher Dunn
0d33cb3639 Merge pull request #211 from cdunn2001/except
* Add Json::Exception and derivatives.
* Clarify when exceptions are thrown, to avoid crashes caused by malicious input.
* Use our own type (derived fro std::exception) so they are trappable.
2015-03-08 12:50:34 -05:00
Christopher Dunn
2250b3c29d use Json::RuntimeError 2015-03-08 12:44:55 -05:00
Christopher Dunn
9376368d86 use Json::LogicError in macros 2015-03-08 12:42:53 -05:00
Christopher Dunn
5383794cc9 Runtime/LogicError and throwers 2015-03-08 12:31:57 -05:00
Christopher Dunn
75279ccec2 base Json::Exception 2015-03-08 12:20:06 -05:00
Christopher Dunn
717b08695e clarify errors
* use macros for logic errors, not input errors
* throw on parsing failure in `operator>>()`, not assert
* throw on malloc, not assert
2015-03-08 12:06:22 -05:00
Christopher Dunn
ee4ea0ec3f delete debug code from test 2015-03-07 15:47:39 -06:00
Christopher Dunn
ce19001238 require length
Ugh! I meant to do this long ago. It would have caught my blunder.
2015-03-07 15:12:52 -06:00
Christopher Dunn
078f991c57 1.5.4 <- 1.5.3
important bug-fix (thx to datadiode@)
2015-03-07 14:52:01 -06:00
Christopher Dunn
72b5293695 Merge pull request #207 from cdunn2001/fix_CZString_copy_constructor
Fix czstring copy constructor
2015-03-07 14:49:54 -06:00
Christopher Dunn
a63d82d78a drop unused CString ctor case
`Value::CZString::CZString(char const* str, unsigned length, DuplicationPolicy allocate)` with `allocate == duplicate` does not happen.
2015-03-07 14:43:37 -06:00
datadiode
ee83f8891c Trivial fixes in CZString constructors. 2015-03-07 14:43:07 -06:00
Christopher Dunn
5c448687e1 fix ValueTest/zeroes* 2015-03-07 14:41:15 -06:00
Christopher Dunn
401e98269e old-style enum namespacing 2015-03-06 16:11:55 -06:00
Christopher Dunn
b2a7438d08 Merge pull request #205 from open-source-parsers/reject-dup-keys
[Shekhar (shakers007) wrote](https://sourceforge.net/p/jsoncpp/bugs/22/):

> As per RFC4627 (section 2.2), names within an object should be unique. When using JSONCPP's strict mode, parsing such an object should fail.
2015-03-06 12:58:55 -06:00
Christopher Dunn
62ad140d18 rejectDupKeys 2015-03-06 12:39:05 -06:00
Christopher Dunn
527332d5d5 add rejectDupKeys feature - not yet impld 2015-03-06 12:38:58 -06:00
Christopher Dunn
cada3b951f test for repeated key in strictMode
https://sourceforge.net/p/jsoncpp/bugs/22/
2015-03-06 12:38:00 -06:00
Christopher Dunn
ff61752444 change str_ for cross-compilation
https://sourceforge.net/p/jsoncpp/bugs/59/
2015-03-06 10:31:46 -06:00
Christopher Dunn
7f439f4276 clarify operator= 2015-03-06 09:22:57 -06:00
Christopher Dunn
3976f17ffd test assignment over-writes comments, but swapPayload() does not 2015-03-06 09:16:19 -06:00
Christopher Dunn
80ca11bb41 test commentBefore
for issue #203
2015-03-06 05:55:19 -06:00
Christopher Dunn
2fc08b4ebd clarify which versions work with old compilers 2015-03-05 21:45:42 -06:00
Christopher Dunn
239c733ab5 1.5.3 <- 1.5.2 2015-03-05 18:27:52 -06:00
Christopher Dunn
295e73ff3c generate both version.h and version from CMakelists.txt
This forces consistency, since they will be re-generated whenever
a git operation alters CMakelists.txt. They are still in the repo
because users might not actually run cmake.
2015-03-05 18:27:39 -06:00
Christopher Dunn
2a840c105c had trouble finding Python on Windows
With this change, `make jsoncpp_check` will still fail if Python
is missing, so our CI tests are unaffected.
2015-03-05 17:42:12 -06:00
Christopher Dunn
7ec98dc9fe Merge pull request #202 from open-source-parsers/get-with-zero
`Value::get(key, default)` with zero
2015-03-05 16:56:56 -06:00
Christopher Dunn
0fd2875a44 fix get() for embedded zeroes in key
This method had been overlooked.
2015-03-05 16:47:29 -06:00
Christopher Dunn
d31151d150 test get(key, default) 2015-03-05 16:44:50 -06:00
Christopher Dunn
f50145fbda Merge pull request #201 from open-source-parsers/vs
* Copy .dll for running unit-tests in VisualStudio.
* Stop using `do{}while(0)` idiom b/c VisualStudio warns.
* Fix a warning in a test.
2015-03-05 16:37:42 -06:00
Christopher Dunn
b3e6f3d70f drop do{}while(0) idiom
Rationale:
  * http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros/154138#154138

But Visual Studio issues a warning: `warning C4127: conditional expression is constant`
  * http://stackoverflow.com/questions/1946445/c-c-how-to-use-the-do-while0-construct-without-compiler-warnings-like-c412
2015-03-05 15:26:29 -06:00
Christopher Dunn
13e063c336 copy .dll for unit-test
Fix 2nd problem in issue #200.
* http://stackoverflow.com/questions/10671916/how-to-copy-dll-files-into-the-same-folder-as-the-executable-using-cmake

Q: What about the Python tests?
A: They are not normally run in Visual Studio. If desired, one can set PATH.
2015-03-05 15:23:20 -06:00
Christopher Dunn
f57da48f48 maybe address warning
cmake -DCMAKE_BUILD_TYPE=debug -DJSONCPP_LIB_BUILD_STATIC=OFF
-DJSONCPP_LIB_BUILD_SHARED=ON -G "Visual Studio 10" ../..

`potentially uninitialized local variable 'dist' (line 2212 of
test_lib_json/main.cpp)`
2015-03-05 14:41:42 -06:00
Christopher Dunn
eaa3fd8eca maybe fix DLL symbols for VS 2015-03-05 10:11:43 -06:00
Christopher Dunn
ff63d034e5 1.5.2 <- 1.5.1
* Fixed compile error for VS2013.
* Added `operator[]` to Builders. Recalling previous minor versions for
  bug-fixes.
2015-03-05 09:18:44 -06:00
Christopher Dunn
2aa4557e79 Merge pull request #199 from open-source-parsers/set-builders
Setting builders
2015-03-05 09:18:06 -06:00
Christopher Dunn
37dde9d29d fix example in docs 2015-03-05 09:18:06 -06:00
Christopher Dunn
c312dd5ef7 Builder::operator[] plus tests 2015-03-05 09:18:01 -06:00
Christopher Dunn
42d7e59fe0 fix compiler-error and warnings for VS2013
fix issue #200
2015-03-05 09:15:10 -06:00
Christopher Dunn
a8104a8035 1.5.1 <- 1.5.0
Fixed Builders ::validate(). Added tests.
2015-03-04 21:18:05 -06:00
Christopher Dunn
7b22768c33 test Builders::validate() 2015-03-04 21:17:03 -06:00
Christopher Dunn
19c49a459d fix Builders::validate()
(cherry picked from commit 626cfcdbb8)
2015-03-04 21:14:53 -06:00
Christopher Dunn
99822b27cd clarify python version 2015-03-03 16:17:11 -06:00
Christopher Dunn
8a70297869 fix inline doxygen comments 2015-03-03 16:17:08 -06:00
Christopher Dunn
24f544996f no struct init
The C struct initializer is not standard C++.
GCC and Clang handle this (at least in some versions) but some
compilers might not.
2015-03-03 10:15:09 -06:00
Christopher Dunn
0c91927da2 assertions should be logic_error 2015-03-03 09:45:33 -06:00
Christopher Dunn
493f6dcebe keep StaticString (!allocated_) for copy ctor 2015-03-03 09:36:22 -06:00
Christopher Dunn
eaa06355e1 test Json::Value::null 2015-03-03 08:45:52 -06:00
Christopher Dunn
effd732aa1 null -> nullRef 2015-03-03 01:25:33 -06:00
Christopher Dunn
70cd04d49a 1.5.0 <- 1.4.4 2015-03-03 00:45:57 -06:00
Christopher Dunn
9e49e3d84a Merge pull request #197 from cdunn2001/allow-zero
allow zeroes in strings
2015-03-03 00:44:19 -06:00
Christopher Dunn
2d653bd15d fix security hole for string-key-lengths > 2^30 2015-03-03 00:14:54 -06:00
Christopher Dunn
585b267595 tests for zeroes
* ValueTest/zeroes
* ValueTest/zeroesInKeys
2015-03-03 00:14:54 -06:00
Christopher Dunn
c28610fb5d fix StaticString test
* support zeroes in string_
* support zeroes in writer; provide getString(char**, unsigned*)
* valueToQuotedStringN(), isCC0(), etc
* allow zeroes for cpptl ConstString
* allocated => non-static
2015-03-03 00:14:54 -06:00
Christopher Dunn
a53283568f cp duplicateStringValue() 2015-03-03 00:14:53 -06:00
Christopher Dunn
ef21fbc785 doc new behavior 2015-03-03 00:14:53 -06:00
Christopher Dunn
25342bac13 support UTF-8 for const methods 2015-03-03 00:14:53 -06:00
Christopher Dunn
2b9abc3ebf Merge pull request #195 from cdunn2001/len-in-czstring
Store length in CZString
2015-03-03 00:07:03 -06:00
Christopher Dunn
e6b46e4503 stop computing strlen() in CZString 2015-03-02 23:50:59 -06:00
Christopher Dunn
8a77037320 actually store length in CZString 2015-03-02 23:50:59 -06:00
Christopher Dunn
57ad051f67 allow length in CZString 2015-03-02 23:50:59 -06:00
Christopher Dunn
b383fdc61e use memcmp in CZString
This is a loss of efficiency, but it prepares for an increase when we
have stored lengths.
2015-03-02 23:50:59 -06:00
Mattes D
5d79275a5b Added MSVC+CMake generated files to .gitignore.
pull #193
2015-03-02 23:50:14 -06:00
Christopher Dunn
c1e834a110 Merge pull request #194 from cdunn2001/master
test StaticString
2015-03-02 17:14:36 -06:00
Christopher Dunn
0570f9eefb test StaticString 2015-03-02 17:06:09 -06:00
Christopher Dunn
b947b0b3df Merge pull request #192 from marklakata/size_t
changed length argument of duplicateStringValue from unsigned int to siz...
2015-03-02 17:03:24 -06:00
Mark Lakata
8051cf6ba7 changed length argument of duplicateStringValue from unsigned int to size_t, to avoid warnings in Visual Studio. 2015-03-02 11:57:17 -08:00
Christopher Dunn
c8bf184ea9 Merge pull request #189 from open-source-parsers/skip-py-tests
skip python jsontestrunner by default
2015-02-26 09:55:21 -06:00
Christopher Dunn
9998094eee skip python jsontestrunner by default
To run these tests, in cmake build-dir:
    make jsoncpp_check

TravisCI is now set to run these always.

For now, the test_json_lib unit-tests will still run.

issue #187
2015-02-26 09:41:45 -06:00
Christopher Dunn
4ac4cac2be Merge pull request #185 from open-source-parsers/drop-internal-map
`JSON_VALUE_USE_INTERNAL_MAP` and `JSON_USE_SIMPLE_INTERNAL_ALLOCATOR` did not actually compile with current compilers. In fact, as far as I can tell, they haven't worked since just after the 0.6.0-rc2 release. And according to blep, there are bugs, e.g. [this one](https://sourceforge.net/p/jsoncpp/bugs/27). It's probably better to hide the implementation of Value (maybe in the next major release) and to put experiments like this into completely separate classes.
2015-02-25 10:12:20 -06:00
Christopher Dunn
4788764844 drop JSON_VALUE_USE_INTERNAL_MAP, JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
And remove some old headers.

These were not actually compiling anymore, and there were outstanding,
known bugs, e.g. https://sourceforge.net/p/jsoncpp/bugs/27
2015-02-25 10:04:13 -06:00
Christopher Dunn
6c898441e3 test-amalgamate
Not tested via Travis (since this is outside cmake), but at least
we can more easily validate changes to `amalgamate.py`.
2015-02-25 10:04:12 -06:00
Christopher Dunn
7d1f656859 Merge pull request #183 from open-source-parsers/allow-single-quote
Allow single quote
2015-02-24 18:24:42 -06:00
Christopher Dunn
0c66e698fb allowSingleQuotes
issue #182
2015-02-24 15:49:45 -06:00
Christopher Dunn
b9229b7400 failing test for allowSingleQuotes 2015-02-23 16:40:06 -06:00
Christopher Dunn
f9db82af17 1.4.4 < 1.4.3
* fixed Readers when `allowDropNullPlaceholders`
2015-02-19 15:37:57 -06:00
Christopher Dunn
ae71879549 Merge pull request #179 from cdunn2001/drop-null
Fix failures for `allowDroppedNullPlaceholders`.
2015-02-19 12:38:16 -06:00
Christopher Dunn
7b3683ccd1 apply fix to old Reader 2015-02-19 11:37:17 -06:00
Christopher Dunn
58499031a4 fix all cases from issue -- all pass! 2015-02-19 11:35:28 -06:00
Christopher Dunn
2c8c1ac0ec all 8 failing cases from issue 2015-02-19 11:35:20 -06:00
Christopher Dunn
c58e93b014 fix failing object case 2015-02-19 11:34:35 -06:00
Christopher Dunn
eed193e151 object cases; 1st passes, 2nd fails 2015-02-19 11:34:35 -06:00
Christopher Dunn
4382a7b585 cases 0,1,5,9,12 from issue -- passing 2015-02-19 11:32:42 -06:00
60 changed files with 3263 additions and 3074 deletions

11
.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
* text=auto
*.h text
*.cpp text
*.json text
*.in text
*.sh eol=lf
*.bat eol=crlf
*.vcproj eol=crlf
*.vcxproj eol=crlf
*.sln eol=crlf
devtools/agent_vm* eol=crlf

39
.gitignore vendored
View File

@@ -10,4 +10,43 @@
/libs/
/doc/doxyfile
/dist/
#/version
#/include/json/version.h
# MSVC project files:
*.sln
*.vcxproj
*.filters
*.user
*.sdf
*.opensdf
*.suo
# MSVC build files:
*.lib
*.obj
*.tlog/
*.pdb
# CMake-generated files:
CMakeFiles/
CTestTestFile.cmake
cmake_install.cmake
pkg-config/jsoncpp.pc
jsoncpp_lib_static.dir/
# In case someone runs cmake in the root-dir:
/CMakeCache.txt
/Makefile
/include/Makefile
/src/Makefile
/src/jsontestrunner/Makefile
/src/jsontestrunner/jsontestrunner_exe
/src/lib_json/Makefile
/src/test_lib_json/Makefile
/src/test_lib_json/jsoncpp_test
# eclipse project files
.project
.cproject
/.settings/

View File

@@ -2,16 +2,42 @@
# http://about.travis-ci.org/docs/user/build-configuration/
# This file can be validated on:
# http://lint.travis-ci.org/
before_install: sudo apt-get install cmake
# See also
# http://stackoverflow.com/questions/22111549/travis-ci-with-clang-3-4-and-c11/30925448#30925448
# to allow C++11, though we are not yet building with -std=c++11
install:
# /usr/bin/gcc is 4.6 always, but gcc-X.Y is available.
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
# /usr/bin/clang is our version already, and clang-X.Y does not exist.
#- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.7" CC="clang-3.7"; fi
- echo ${PATH}
- ls /usr/local
- ls /usr/local/bin
- export PATH=/usr/local/bin:/usr/bin:${PATH}
- echo ${CXX}
- ${CXX} --version
- which valgrind
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.9
- g++-4.9
- clang
- valgrind
os:
- linux
language: cpp
compiler:
- gcc
- clang
script: cmake -DJSONCPP_WITH_CMAKE_PACKAGE=$CMAKE_PKG -DJSONCPP_LIB_BUILD_SHARED=$SHARED_LIB -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_VERBOSE_MAKEFILE=$VERBOSE_MAKE . && make
script: ./travis.sh
env:
matrix:
- SHARED_LIB=ON STATIC_LIB=ON CMAKE_PKG=ON BUILD_TYPE=release VERBOSE_MAKE=false
- SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug VERBOSE_MAKE=true VERBOSE
notifications:
email:
- aaronjjacobs@gmail.com
email: false
sudo: false

View File

@@ -1,12 +1,17 @@
# vim: et ts=4 sts=4 sw=4 tw=0
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.5)
PROJECT(jsoncpp)
ENABLE_TESTING()
OPTION(JSONCPP_WITH_TESTS "Compile and run JsonCpp test executables" ON)
OPTION(JSONCPP_WITH_TESTS "Compile and (for jsoncpp_check) run JsonCpp test executables" ON)
OPTION(JSONCPP_WITH_POST_BUILD_UNITTEST "Automatically run unit-tests as a post build step" ON)
OPTION(JSONCPP_WITH_WARNING_AS_ERROR "Force compilation to fail if a warning occurs" OFF)
OPTION(JSONCPP_WITH_STRICT_ISO "Issue all the warnings demanded by strict ISO C and ISO C++" ON)
OPTION(JSONCPP_WITH_PKGCONFIG_SUPPORT "Generate and install .pc files" ON)
OPTION(JSONCPP_WITH_CMAKE_PACKAGE "Generate and install cmake package files" OFF)
OPTION(BUILD_SHARED_LIBS "Build jsoncpp_lib as a shared library." OFF)
OPTION(BUILD_STATIC_LIBS "Build jsoncpp_lib static library." ON)
# Ensures that CMAKE_BUILD_TYPE is visible in cmake-gui on Unix
IF(NOT WIN32)
@@ -14,9 +19,10 @@ IF(NOT WIN32)
SET(CMAKE_BUILD_TYPE Release CACHE STRING
"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage."
FORCE)
ENDIF(NOT CMAKE_BUILD_TYPE)
ENDIF(NOT WIN32)
ENDIF()
ENDIF()
SET(DEBUG_LIBNAME_SUFFIX "" CACHE STRING "Optional suffix to append to the library name for a debug build")
SET(LIB_SUFFIX "" CACHE STRING "Optional arch-dependent suffix for the library installation directory")
SET(RUNTIME_INSTALL_DIR bin
@@ -34,7 +40,7 @@ MARK_AS_ADVANCED( RUNTIME_INSTALL_DIR ARCHIVE_INSTALL_DIR INCLUDE_INSTALL_DIR PA
# Set variable named ${VAR_NAME} to value ${VALUE}
FUNCTION(set_using_dynamic_name VAR_NAME VALUE)
SET( "${VAR_NAME}" "${VALUE}" PARENT_SCOPE)
ENDFUNCTION(set_using_dynamic_name)
ENDFUNCTION()
# Extract major, minor, patch from version text
# Parse a version string "X.Y.Z" and outputs
@@ -50,28 +56,41 @@ MACRO(jsoncpp_parse_version VERSION_TEXT OUPUT_PREFIX)
set_using_dynamic_name( "${OUPUT_PREFIX}_FOUND" TRUE )
ELSE( ${VERSION_TEXT} MATCHES ${VERSION_REGEX} )
set_using_dynamic_name( "${OUPUT_PREFIX}_FOUND" FALSE )
ENDIF( ${VERSION_TEXT} MATCHES ${VERSION_REGEX} )
ENDMACRO(jsoncpp_parse_version)
ENDIF()
ENDMACRO()
# Read out version from "version" file
FILE(STRINGS "version" JSONCPP_VERSION)
#FILE(STRINGS "version" JSONCPP_VERSION)
#SET( JSONCPP_VERSION_MAJOR X )
#SET( JSONCPP_VERSION_MINOR Y )
#SET( JSONCPP_VERSION_PATCH Z )
SET( JSONCPP_VERSION 1.7.5 )
jsoncpp_parse_version( ${JSONCPP_VERSION} JSONCPP_VERSION )
IF(NOT JSONCPP_VERSION_FOUND)
MESSAGE(FATAL_ERROR "Failed to parse version string properly. Expect X.Y.Z")
ENDIF(NOT JSONCPP_VERSION_FOUND)
#IF(NOT JSONCPP_VERSION_FOUND)
# MESSAGE(FATAL_ERROR "Failed to parse version string properly. Expect X.Y.Z")
#ENDIF(NOT JSONCPP_VERSION_FOUND)
SET( JSONCPP_USE_SECURE_MEMORY "0" CACHE STRING "-D...=1 to use memory-wiping allocator for STL" )
MESSAGE(STATUS "JsonCpp Version: ${JSONCPP_VERSION_MAJOR}.${JSONCPP_VERSION_MINOR}.${JSONCPP_VERSION_PATCH}")
# File version.h is only regenerated on CMake configure step
CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/src/lib_json/version.h.in"
"${PROJECT_SOURCE_DIR}/include/json/version.h" )
"${PROJECT_SOURCE_DIR}/include/json/version.h"
NEWLINE_STYLE UNIX )
CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/version.in"
"${PROJECT_SOURCE_DIR}/version"
NEWLINE_STYLE UNIX )
macro(UseCompilationWarningAsError)
if ( MSVC )
# Only enabled in debug because some old versions of VS STL generate
# warnings when compiled in release configuration.
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /WX ")
endif( MSVC )
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
if (JSONCPP_WITH_STRICT_ISO)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic-errors")
endif ()
endif()
endmacro()
# Include our configuration header
@@ -81,34 +100,52 @@ if ( MSVC )
# Only enabled in debug because some old versions of VS STL generate
# unreachable code warning when compiled in release configuration.
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W4 ")
endif( MSVC )
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# using regular Clang or AppleClang
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall")
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Werror=conversion -Werror=sign-compare")
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
# using GCC
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -Wall -Wextra -pedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Wextra")
# not yet ready for -Wsign-conversion
if (JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=conversion -pedantic")
endif ()
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Intel")
# using Intel compiler
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wconversion -Wshadow -Wextra -Werror=conversion")
if (JSONCPP_WITH_STRICT_ISO AND NOT JSONCPP_WITH_WARNING_AS_ERROR)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pedantic")
endif ()
endif()
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
endif(CCACHE_FOUND)
IF(JSONCPP_WITH_WARNING_AS_ERROR)
UseCompilationWarningAsError()
ENDIF(JSONCPP_WITH_WARNING_AS_ERROR)
ENDIF()
IF(JSONCPP_WITH_PKGCONFIG_SUPPORT)
CONFIGURE_FILE(
"pkg-config/jsoncpp.pc.in"
"pkg-config/jsoncpp.pc"
@ONLY)
INSTALL(FILES "${CMAKE_BINARY_DIR}/pkg-config/jsoncpp.pc"
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/pkg-config/jsoncpp.pc"
DESTINATION "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/pkgconfig")
ENDIF(JSONCPP_WITH_PKGCONFIG_SUPPORT)
ENDIF()
IF(JSONCPP_WITH_CMAKE_PACKAGE)
INSTALL(EXPORT jsoncpp
DESTINATION ${PACKAGE_INSTALL_DIR}/jsoncpp
FILE jsoncppConfig.cmake)
ENDIF(JSONCPP_WITH_CMAKE_PACKAGE)
ENDIF()
# Build the different applications
ADD_SUBDIRECTORY( src )

View File

@@ -16,15 +16,17 @@ format to store user input files.
## A note on backward-compatibility
* `1.y.z` is built with C++11.
* `0.8.z` can be used with older compilers.
* `0.y.z` can be used with older compilers.
* Major versions maintain binary-compatibility.
Using JsonCpp in your project
# Using JsonCpp in your project
-----------------------------
The recommended approach to integrating JsonCpp in your project is to build
the amalgamated source (a single `.cpp` file) with your own build system. This
ensures consistency of compilation flags and ABI compatibility. See the section
"Generating amalgamated source and header" for instructions.
The recommended approach to integrating JsonCpp in your project is to include
the [amalgamated source](#generating-amalgamated-source-and-header) (a single
`.cpp` file and two `.h` files) in your project, and compile and build as you
would any other source file. This ensures consistency of compilation flags and
ABI compatibility, issues which arise when building shared or static
libraries. See the next section for instructions.
The `include/` should be added to your compiler include path. Jsoncpp headers
should be included as follow:
@@ -34,6 +36,31 @@ should be included as follow:
If JsonCpp was built as a dynamic library on Windows, then your project needs to
define the macro `JSON_DLL`.
Generating amalgamated source and header
----------------------------------------
JsonCpp is provided with a script to generate a single header and a single
source file to ease inclusion into an existing project. The amalgamated source
can be generated at any time by running the following command from the
top-directory (this requires Python 2.6):
python amalgamate.py
It is possible to specify header name. See the `-h` option for detail.
By default, the following files are generated:
* `dist/jsoncpp.cpp`: source file that needs to be added to your project.
* `dist/json/json.h`: corresponding header file for use in your project. It is
equivalent to including `json/json.h` in non-amalgamated source. This header
only depends on standard headers.
* `dist/json/json-forwards.h`: header that provides forward declaration of all
JsonCpp types.
The amalgamated sources are generated by concatenating JsonCpp source in the
correct order and defining the macro `JSON_IS_AMALGAMATION` to prevent inclusion
of other headers.
# Contributing to JsonCpp
Building and testing with CMake
-------------------------------
[CMake][] is a C++ Makefiles/Solution generator. It is usually available on most
@@ -58,7 +85,7 @@ Steps for generating solution/makefiles using `cmake-gui`:
* Make "source code" point to the source directory.
* Make "where to build the binary" point to the directory to use for the build.
* Click on the "Grouped" check box.
* Review JsonCpp build options (tick `JSONCPP_LIB_BUILD_SHARED` to build as a
* Review JsonCpp build options (tick `BUILD_SHARED_LIBS` to build as a
dynamic library).
* Click the configure button at the bottom, then the generate button.
* The generated solution/makefiles can be found in the binary directory.
@@ -67,10 +94,10 @@ Alternatively, from the command-line on Unix in the source directory:
mkdir -p build/debug
cd build/debug
cmake -DCMAKE_BUILD_TYPE=debug -DJSONCPP_LIB_BUILD_STATIC=ON -DJSONCPP_LIB_BUILD_SHARED=OFF -G "Unix Makefiles" ../..
cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=OFF -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
make
Running `cmake -`" will display the list of available generators (passed using
Running `cmake -h` will display the list of available generators (passed using
the `-G` option).
By default CMake hides compilation commands. This can be modified by specifying
@@ -106,7 +133,7 @@ If you are building with Microsoft Visual Studio 2008, you need to set up the
environment by running `vcvars32.bat` (e.g. MSVC 2008 command prompt) before
running SCons.
# Running the tests manually
## Running the tests manually
You need to run tests manually only if you are troubleshooting an issue.
In the instructions below, replace `path/to/jsontest` with the path of the
@@ -142,29 +169,6 @@ Run the Python script `doxybuild.py` from the top directory:
See `doxybuild.py --help` for options.
Generating amalgamated source and header
----------------------------------------
JsonCpp is provided with a script to generate a single header and a single
source file to ease inclusion into an existing project. The amalgamated source
can be generated at any time by running the following command from the
top-directory (this requires Python 2.6):
python amalgamate.py
It is possible to specify header name. See the `-h` option for detail.
By default, the following files are generated:
* `dist/jsoncpp.cpp`: source file that needs to be added to your project.
* `dist/json/json.h`: corresponding header file for use in your project. It is
equivalent to including `json/json.h` in non-amalgamated source. This header
only depends on standard headers.
* `dist/json/json-forwards.h`: header that provides forward declaration of all
JsonCpp types.
The amalgamated sources are generated by concatenating JsonCpp source in the
correct order and defining the macro `JSON_IS_AMALGAMATION` to prevent inclusion
of other headers.
Adding a reader/writer test
---------------------------
To add a test, you need to create two files in test/data:

View File

@@ -1,6 +1,6 @@
"""Amalgate json-cpp library sources into a single source and header file.
Requires Python 2.6
Works with python2.6+ and python3.4+.
Example of invocation (must be invoked from json-cpp top directory):
python amalgate.py
@@ -67,6 +67,7 @@ def amalgamate_source(source_top_dir=None,
header.add_text("/// to prevent private header inclusion.")
header.add_text("#define JSON_IS_AMALGAMATION")
header.add_file("include/json/version.h")
#header.add_file("include/json/allocator.h") # Not available here.
header.add_file("include/json/config.h")
header.add_file("include/json/forwards.h")
header.add_file("include/json/features.h")
@@ -118,7 +119,6 @@ def amalgamate_source(source_top_dir=None,
lib_json = "src/lib_json"
source.add_file(os.path.join(lib_json, "json_tool.h"))
source.add_file(os.path.join(lib_json, "json_reader.cpp"))
source.add_file(os.path.join(lib_json, "json_batchallocator.h"))
source.add_file(os.path.join(lib_json, "json_valueiterator.inl"))
source.add_file(os.path.join(lib_json, "json_value.cpp"))
source.add_file(os.path.join(lib_json, "json_writer.cpp"))

35
appveyor.yml Normal file
View File

@@ -0,0 +1,35 @@
# This is a comment.
version: build.{build}
os: Windows Server 2012 R2
clone_folder: c:\projects\jsoncpp
platform:
- Win32
- x64
configuration:
- Debug
- Release
# scripts to run before build
before_build:
- echo "Running cmake..."
- cd c:\projects\jsoncpp
- cmake --version
- set PATH=C:\Program Files (x86)\MSBuild\14.0\Bin;%PATH%
- if %PLATFORM% == Win32 cmake .
- if %PLATFORM% == x64 cmake -G "Visual Studio 12 2013 Win64" .
build:
project: jsoncpp.sln # path to Visual Studio solution or project
deploy:
provider: GitHub
auth_token:
secure: K2Tp1q8pIZ7rs0Ot24ZMWuwr12Ev6Tc6QkhMjGQxoQG3ng1pXtgPasiJ45IDXGdg
on:
branch: master
appveyor_repo_tag: true

View File

@@ -16,7 +16,7 @@ dox:
# Then 'git add -A' and 'git push' in jsoncpp-docs.
build:
mkdir -p build/debug
cd build/debug; cmake -DCMAKE_BUILD_TYPE=debug -DJSONCPP_LIB_BUILD_SHARED=ON -G "Unix Makefiles" ../..
cd build/debug; cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_SHARED_LIBS=ON -G "Unix Makefiles" ../..
make -C build/debug
# Currently, this depends on include/json/version.h generated
@@ -24,6 +24,10 @@ build:
test-amalgamate:
python2.7 amalgamate.py
python3.4 amalgamate.py
cd dist; gcc -I. -c jsoncpp.cpp
valgrind:
valgrind --error-exitcode=42 --leak-check=full ./build/debug/src/test_lib_json/jsoncpp_test
clean:
\rm -rf *.gz *.asc dist/

View File

@@ -1 +1,6 @@
# module
# Copyright 2010 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
# module

View File

@@ -1,33 +1,33 @@
{
"cmake_variants" : [
{"name": "generator",
"generators": [
{"generator": [
"Visual Studio 7 .NET 2003",
"Visual Studio 9 2008",
"Visual Studio 9 2008 Win64",
"Visual Studio 10",
"Visual Studio 10 Win64",
"Visual Studio 11",
"Visual Studio 11 Win64"
]
},
{"generator": ["MinGW Makefiles"],
"env_prepend": [{"path": "c:/wut/prg/MinGW/bin"}]
}
]
},
{"name": "shared_dll",
"variables": [
["JSONCPP_LIB_BUILD_SHARED=true"],
["JSONCPP_LIB_BUILD_SHARED=false"]
]
},
{"name": "build_type",
"build_types": [
"debug",
"release"
]
}
]
}
{
"cmake_variants" : [
{"name": "generator",
"generators": [
{"generator": [
"Visual Studio 7 .NET 2003",
"Visual Studio 9 2008",
"Visual Studio 9 2008 Win64",
"Visual Studio 10",
"Visual Studio 10 Win64",
"Visual Studio 11",
"Visual Studio 11 Win64"
]
},
{"generator": ["MinGW Makefiles"],
"env_prepend": [{"path": "c:/wut/prg/MinGW/bin"}]
}
]
},
{"name": "shared_dll",
"variables": [
["BUILD_SHARED_LIBS=true"],
["BUILD_SHARED_LIBS=false"]
]
},
{"name": "build_type",
"build_types": [
"debug",
"release"
]
}
]
}

View File

@@ -1,26 +1,26 @@
{
"cmake_variants" : [
{"name": "generator",
"generators": [
{"generator": [
"Visual Studio 6",
"Visual Studio 7",
"Visual Studio 8 2005"
]
}
]
},
{"name": "shared_dll",
"variables": [
["JSONCPP_LIB_BUILD_SHARED=true"],
["JSONCPP_LIB_BUILD_SHARED=false"]
]
},
{"name": "build_type",
"build_types": [
"debug",
"release"
]
}
]
}
{
"cmake_variants" : [
{"name": "generator",
"generators": [
{"generator": [
"Visual Studio 6",
"Visual Studio 7",
"Visual Studio 8 2005"
]
}
]
},
{"name": "shared_dll",
"variables": [
["BUILD_SHARED_LIBS=true"],
["BUILD_SHARED_LIBS=false"]
]
},
{"name": "build_type",
"build_types": [
"debug",
"release"
]
}
]
}

View File

@@ -1,6 +1,9 @@
#!/usr/bin/env python
# encoding: utf-8
# Baptiste Lepilleur, 2009
# Copyright 2009 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
from dircache import listdir

View File

@@ -1,5 +1,11 @@
# Copyright 2010 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
import os.path
import sys
def fix_source_eol(path, is_dry_run = True, verbose = True, eol = '\n'):
"""Makes sure that all sources have the specified eol sequence (default: unix)."""

View File

@@ -1,3 +1,8 @@
# Copyright 2010 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from contextlib import closing
import os
import tarfile

View File

@@ -1946,8 +1946,7 @@ INCLUDE_FILE_PATTERNS = *.h
PREDEFINED = "_MSC_VER=1400" \
_CPPRTTI \
_WIN32 \
JSONCPP_DOC_EXCLUDE_IMPLEMENTATION \
JSON_VALUE_USE_INTERNAL_MAP
JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The

View File

@@ -96,13 +96,13 @@ features without losing binary-compatibility.
\code
// For convenience, use `writeString()` with a specialized builder.
Json::StreamWriterBuilder wbuilder;
wbuilder.settings_["indentation"] = "\t"; // simple Json::Value
wbuilder["indentation"] = "\t";
std::string document = Json::writeString(wbuilder, root);
// Here, using a specialized Builder, we discard comments and
// record errors as we parse.
Json::CharReaderBuilder rbuilder;
rbuilder.settings_["collectComments"] = false; // simple Json::Value
rbuilder["collectComments"] = false;
std::string errs;
bool ok = Json::parseFromStream(rbuilder, std::cin, &root, &errs);
\endcode

View File

@@ -1946,8 +1946,7 @@ INCLUDE_FILE_PATTERNS = *.h
PREDEFINED = "_MSC_VER=1400" \
_CPPRTTI \
_WIN32 \
JSONCPP_DOC_EXCLUDE_IMPLEMENTATION \
JSON_VALUE_USE_INTERNAL_MAP
JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The

View File

@@ -31,7 +31,7 @@ def find_program(*filenames):
paths = os.environ.get('PATH', '').split(os.pathsep)
suffixes = ('win32' in sys.platform) and '.exe .com .bat .cmd' or ''
for filename in filenames:
for name in [filename+ext for ext in suffixes.split()]:
for name in [filename+ext for ext in suffixes.split(' ')]:
for directory in paths:
full_path = os.path.join(directory, name)
if os.path.isfile(full_path):
@@ -72,7 +72,7 @@ def run_cmd(cmd, silent=False):
if silent:
status, output = getstatusoutput(cmd)
else:
status, output = os.system(' '.join(cmd)), ''
status, output = subprocess.call(cmd), ''
if status:
msg = 'Error while %s ...\n\terror=%d, output="""%s"""' %(info, status, output)
raise Exception(msg)

94
include/json/allocator.h Normal file
View File

@@ -0,0 +1,94 @@
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef CPPTL_JSON_ALLOCATOR_H_INCLUDED
#define CPPTL_JSON_ALLOCATOR_H_INCLUDED
#include <cstring>
#include <memory>
namespace Json {
template<typename T>
class SecureAllocator {
public:
// Type definitions
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
/**
* Allocate memory for N items using the standard allocator.
*/
pointer allocate(size_type n) {
// allocate using "global operator new"
return static_cast<pointer>(::operator new(n * sizeof(T)));
}
/**
* Release memory which was allocated for N items at pointer P.
*
* The memory block is filled with zeroes before being released.
* The pointer argument is tagged as "volatile" to prevent the
* compiler optimizing out this critical step.
*/
void deallocate(volatile pointer p, size_type n) {
std::memset(p, 0, n * sizeof(T));
// free using "global operator delete"
::operator delete(p);
}
/**
* Construct an item in-place at pointer P.
*/
template<typename... Args>
void construct(pointer p, Args&&... args) {
// construct using "placement new" and "perfect forwarding"
::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
}
size_type max_size() const {
return size_t(-1) / sizeof(T);
}
pointer address( reference x ) const {
return std::addressof(x);
}
const_pointer address( const_reference x ) const {
return std::addressof(x);
}
/**
* Destroy an item in-place at pointer P.
*/
void destroy(pointer p) {
// destroy using "explicit destructor"
p->~T();
}
// Boilerplate
SecureAllocator() {}
template<typename U> SecureAllocator(const SecureAllocator<U>&) {}
template<typename U> struct rebind { using other = SecureAllocator<U>; };
};
template<typename T, typename U>
bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
return true;
}
template<typename T, typename U>
bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
return false;
}
} //namespace Json
#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED

View File

@@ -13,20 +13,32 @@
#include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
/** It should not be possible for a maliciously designed file to
* cause an abort() or seg-fault, so these macros are used only
* for pre-condition violations and internal logic errors.
*/
#if JSON_USE_EXCEPTION
#include <stdexcept>
#define JSON_ASSERT(condition) \
if (!(condition)) {throw std::runtime_error( "assert json failed" );} // @todo <= add detail about condition in exception
#define JSON_FAIL_MESSAGE(message) do{std::ostringstream oss; oss << message; throw std::runtime_error(oss.str());}while(0)
//#define JSON_FAIL_MESSAGE(message) throw std::runtime_error(message)
// @todo <= add detail about condition in exception
# define JSON_ASSERT(condition) \
{if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
# define JSON_FAIL_MESSAGE(message) \
{ \
JSONCPP_OSTRINGSTREAM oss; oss << message; \
Json::throwLogicError(oss.str()); \
abort(); \
}
#else // JSON_USE_EXCEPTION
#define JSON_ASSERT(condition) assert(condition);
# define JSON_ASSERT(condition) assert(condition)
// The call to assert() will show the failure message in debug builds. In
// release bugs we abort, for a core-dump or debugger.
#define JSON_FAIL_MESSAGE(message) \
// release builds we abort, for a core-dump or debugger.
# define JSON_FAIL_MESSAGE(message) \
{ \
std::ostringstream oss; oss << message; \
JSONCPP_OSTRINGSTREAM oss; oss << message; \
assert(false && oss.str().c_str()); \
abort(); \
}

View File

@@ -5,6 +5,8 @@
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
#include <stddef.h>
#include <string> //typdef String
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
@@ -15,17 +17,6 @@
/// std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
/// If defined, indicates that Json specific container should be used
/// (hash table & simple deque container with customizable allocator).
/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332
//# define JSON_VALUE_USE_INTERNAL_MAP 1
/// Force usage of standard new/malloc based allocator instead of memory pool
/// based allocator.
/// The memory pools allocator used optimization (initializing Value and
/// ValueInternalLink
/// as if it was a POD) that may cause some validation tool to report errors.
/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
@@ -48,12 +39,12 @@
#ifdef JSON_IN_CPPTL
#define JSON_API CPPTL_API
#elif defined(JSON_DLL_BUILD)
#if defined(_MSC_VER)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
#if defined(_MSC_VER)
#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
@@ -67,26 +58,87 @@
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
#define JSON_USE_INT64_DOUBLE_CONVERSION 1
// Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
// characters in the debug information)
// All projects I've ever seen with VS6 were using this globally (not bothering
// with pragma push/pop).
#pragma warning(disable : 4786)
#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
#if defined(_MSC_VER) // MSVC
# if _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
// Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
// characters in the debug information)
// All projects I've ever seen with VS6 were using this globally (not bothering
// with pragma push/pop).
# pragma warning(disable : 4786)
# endif // MSVC 6
#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
#define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
# if _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
# endif
#endif // defined(_MSC_VER)
// In c++11 the override keyword allows you to explicity define that a function
// is intended to override the base-class version. This makes the code more
// managable and fixes a set of common hard-to-find bugs.
#if __cplusplus >= 201103L
# define JSONCPP_OVERRIDE override
#elif defined(_MSC_VER) && _MSC_VER > 1600
# define JSONCPP_OVERRIDE override
#else
# define JSONCPP_OVERRIDE
#endif
#ifndef JSON_HAS_RVALUE_REFERENCES
#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // MSVC >= 2010
#ifdef __clang__
#if __has_feature(cxx_rvalue_references)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // has_feature
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
#define JSON_HAS_RVALUE_REFERENCES 1
#endif // GXX_EXPERIMENTAL
#endif // __clang__ || __GNUC__
#endif // not defined JSON_HAS_RVALUE_REFERENCES
#ifndef JSON_HAS_RVALUE_REFERENCES
#define JSON_HAS_RVALUE_REFERENCES 0
#endif
#ifdef __clang__
#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
# endif // GNUC version
#endif // __clang__ || __GNUC__
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
#if __GNUC__ >= 6
# define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif
#if !defined(JSON_IS_AMALGAMATION)
# include "version.h"
# if JSONCPP_USING_SECURE_MEMORY
# include "allocator.h" //typedef Allocator
# endif
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
typedef int Int;
typedef unsigned int UInt;
@@ -100,13 +152,26 @@ typedef unsigned int LargestUInt;
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else // if defined(_MSC_VER) // Other platforms, use long long
typedef long long int Int64;
typedef unsigned long long int UInt64;
typedef int64_t Int64;
typedef uint64_t UInt64;
#endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
#define JSON_HAS_INT64
#endif // if defined(JSON_NO_INT64)
#if JSONCPP_USING_SECURE_MEMORY
#define JSONCPP_STRING std::basic_string<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTRINGSTREAM std::basic_ostringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_OSTREAM std::basic_ostream<char, std::char_traits<char>>
#define JSONCPP_ISTRINGSTREAM std::basic_istringstream<char, std::char_traits<char>, Json::SecureAllocator<char> >
#define JSONCPP_ISTREAM std::istream
#else
#define JSONCPP_STRING std::string
#define JSONCPP_OSTRINGSTREAM std::ostringstream
#define JSONCPP_OSTREAM std::ostream
#define JSONCPP_ISTRINGSTREAM std::istringstream
#define JSONCPP_ISTREAM std::istream
#endif // if JSONCPP_USING_SECURE_MEMORY
} // end namespace Json
#endif // JSON_CONFIG_H_INCLUDED

View File

@@ -31,12 +31,6 @@ class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
#ifdef JSON_VALUE_USE_INTERNAL_MAP
class ValueMapAllocator;
class ValueInternalLink;
class ValueInternalArray;
class ValueInternalMap;
#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
} // namespace Json

View File

@@ -42,9 +42,9 @@ public:
*
*/
struct StructuredError {
size_t offset_start;
size_t offset_limit;
std::string message;
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
JSONCPP_STRING message;
};
/** \brief Constructs a Reader allowing all features
@@ -99,7 +99,7 @@ public:
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
bool parse(std::istream& is, Value& root, bool collectComments = true);
bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
/** \brief Returns a user friendly string that list errors in the parsed
* document.
@@ -110,8 +110,8 @@ public:
* during parsing.
* \deprecated Use getFormattedErrorMessages() instead (typo fix).
*/
JSONCPP_DEPRECATED("Use getFormattedErrorMessages instead")
std::string getFormatedErrorMessages() const;
JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
JSONCPP_STRING getFormatedErrorMessages() const;
/** \brief Returns a user friendly string that list errors in the parsed
* document.
@@ -121,7 +121,7 @@ public:
* occurred
* during parsing.
*/
std::string getFormattedErrorMessages() const;
JSONCPP_STRING getFormattedErrorMessages() const;
/** \brief Returns a vector of structured erros encounted while parsing.
* \return A (possibly empty) vector of StructuredError objects. Currently
@@ -138,7 +138,7 @@ public:
* \return \c true if the error was successfully added, \c false if the
* Value offset exceeds the document size.
*/
bool pushError(const Value& value, const std::string& message);
bool pushError(const Value& value, const JSONCPP_STRING& message);
/** \brief Add a semantic error message with extra context.
* \param value JSON Value location associated with the error
@@ -147,7 +147,7 @@ public:
* \return \c true if the error was successfully added, \c false if either
* Value offset exceeds the document size.
*/
bool pushError(const Value& value, const std::string& message, const Value& extra);
bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
/** \brief Return whether there are any errors.
* \return \c true if there are no errors to report \c false if
@@ -183,7 +183,7 @@ private:
class ErrorInfo {
public:
Token token_;
std::string message_;
JSONCPP_STRING message_;
Location extra_;
};
@@ -203,7 +203,7 @@ private:
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, std::string& decoded);
bool decodeString(Token& token, JSONCPP_STRING& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token,
@@ -214,9 +214,9 @@ private:
Location& current,
Location end,
unsigned int& unicode);
bool addError(const std::string& message, Token& token, Location extra = 0);
bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const std::string& message,
bool addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
@@ -224,20 +224,20 @@ private:
Char getNextChar();
void
getLocationLineAndColumn(Location location, int& line, int& column) const;
std::string getLocationLineAndColumn(Location location) const;
JSONCPP_STRING getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
typedef std::stack<Value*> Nodes;
Nodes nodes_;
Errors errors_;
std::string document_;
JSONCPP_STRING document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value* lastValue_;
std::string commentsBefore_;
JSONCPP_STRING commentsBefore_;
Features features_;
bool collectComments_;
}; // Reader
@@ -266,10 +266,11 @@ public:
*/
virtual bool parse(
char const* beginDoc, char const* endDoc,
Value* root, std::string* errs) = 0;
Value* root, JSONCPP_STRING* errs) = 0;
class Factory {
class JSON_API Factory {
public:
virtual ~Factory() {}
/** \brief Allocate a CharReader via operator new().
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
@@ -279,15 +280,13 @@ public:
/** \brief Build a CharReader implementation.
\deprecated This is experimental and will be altered before the next release.
Usage:
\code
using namespace Json;
CharReaderBuilder builder;
builder.settings_["collectComments"] = false;
builder["collectComments"] = false;
Value value;
std::string errs;
JSONCPP_STRING errs;
bool ok = parseFromStream(builder, std::cin, &value, &errs);
\endcode
*/
@@ -310,6 +309,8 @@ public:
- true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
- `"allowNumericKeys": false or true`
- true if numeric object keys are allowed.
- `"allowSingleQuotes": false or true`
- true if '' are allowed for strings (both keys and values)
- `"stackLimit": integer`
- Exceeding stackLimit (recursive depth of `readValue()`) will
cause an exception.
@@ -318,6 +319,11 @@ public:
- `"failIfExtra": false or true`
- If true, `parse()` returns false when extra non-whitespace trails
the JSON value in the input string.
- `"rejectDupKeys": false or true`
- If true, `parse()` returns false when a key is duplicated within an object.
- `"allowSpecialFloats": false or true`
- If true, special float values (NaNs and infinities) are allowed
and their values are lossfree restorable.
You can examine 'settings_` yourself
to see the defaults. You can also write and read them just like any
@@ -327,24 +333,29 @@ public:
Json::Value settings_;
CharReaderBuilder();
virtual ~CharReaderBuilder();
~CharReaderBuilder() JSONCPP_OVERRIDE;
virtual CharReader* newCharReader() const;
CharReader* newCharReader() const JSONCPP_OVERRIDE;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](JSONCPP_STRING key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
*/
static void setDefaults(Json::Value* settings);
/** Same as old Features::strictMode().
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
* \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
*/
static void strictMode(Json::Value* settings);
};
@@ -353,9 +364,9 @@ public:
* Someday we might have a real StreamReader, but for now this
* is convenient.
*/
bool parseFromStream(
bool JSON_API parseFromStream(
CharReader::Factory const&,
std::istream&,
JSONCPP_ISTREAM&,
Value* root, std::string* errs);
/** \brief Read from 'sin' into 'root'.
@@ -382,7 +393,7 @@ bool parseFromStream(
\throw std::exception on parse error.
\see Json::operator<<()
*/
JSON_API std::istream& operator>>(std::istream&, Value&);
JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
} // namespace Json

View File

@@ -11,6 +11,7 @@
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <string>
#include <vector>
#include <exception>
#ifndef JSON_USE_CPPTL_SMALLMAP
#include <map>
@@ -21,6 +22,19 @@
#include <cpptl/forwards.h>
#endif
//Conditional NORETURN attribute on the throw functions would:
// a) suppress false positives from static code analysis
// b) possibly improve optimization opportunities.
#if !defined(JSONCPP_NORETURN)
# if defined(_MSC_VER)
# define JSONCPP_NORETURN __declspec(noreturn)
# elif defined(__GNUC__)
# define JSONCPP_NORETURN __attribute__ ((__noreturn__))
# else
# define JSONCPP_NORETURN
# endif
#endif
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
@@ -32,6 +46,46 @@
*/
namespace Json {
/** Base class for all exceptions we throw.
*
* We use nothing but these internally. Of course, STL can throw others.
*/
class JSON_API Exception : public std::exception {
public:
Exception(JSONCPP_STRING const& msg);
~Exception() throw() JSONCPP_OVERRIDE;
char const* what() const throw() JSONCPP_OVERRIDE;
protected:
JSONCPP_STRING msg_;
};
/** Exceptions which the user cannot easily avoid.
*
* E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
*
* \remark derived from Json::Exception
*/
class JSON_API RuntimeError : public Exception {
public:
RuntimeError(JSONCPP_STRING const& msg);
};
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
*
* These are precondition-violations (user bugs) and internal errors (our bugs).
*
* \remark derived from Json::Exception
*/
class JSON_API LogicError : public Exception {
public:
LogicError(JSONCPP_STRING const& msg);
};
/// used internally
JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
/// used internally
JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
/** \brief Type of the value held by a Value object.
*/
enum ValueType {
@@ -74,14 +128,14 @@ enum CommentPlacement {
*/
class JSON_API StaticString {
public:
explicit StaticString(const char* czstring) : str_(czstring) {}
explicit StaticString(const char* czstring) : c_str_(czstring) {}
operator const char*() const { return str_; }
operator const char*() const { return c_str_; }
const char* c_str() const { return str_; }
const char* c_str() const { return c_str_; }
private:
const char* str_;
const char* c_str_;
};
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
@@ -99,28 +153,29 @@ private:
* The type of the held value is represented by a #ValueType and
* can be obtained using type().
*
* values of an #objectValue or #arrayValue can be accessed using operator[]()
*methods.
* Non const methods will automatically create the a #nullValue element
* Values of an #objectValue or #arrayValue can be accessed using operator[]()
* methods.
* Non-const methods will automatically create the a #nullValue element
* if it does not exist.
* The sequence of an #arrayValue will be automatically resize and initialized
* The sequence of an #arrayValue will be automatically resized and initialized
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
*
* The get() methods can be used to obtanis default value in the case the
*required element
* does not exist.
* The get() methods can be used to obtain default value in the case the
* required element does not exist.
*
* It is possible to iterate over the list of a #objectValue values using
* the getMemberNames() method.
*
* \note #Value string-length fit in size_t, but keys must be < 2^30.
* (The reason is an implementation detail.) A #CharReader will raise an
* exception if a bound is exceeded to avoid security holes in your app,
* but the Value API does *not* check bounds. That is the responsibility
* of the caller.
*/
class JSON_API Value {
friend class ValueIteratorBase;
#ifdef JSON_VALUE_USE_INTERNAL_MAP
friend class ValueInternalLink;
friend class ValueInternalMap;
#endif
public:
typedef std::vector<std::string> Members;
typedef std::vector<JSONCPP_STRING> Members;
typedef ValueIterator iterator;
typedef ValueConstIterator const_iterator;
typedef Json::UInt UInt;
@@ -133,8 +188,10 @@ public:
typedef Json::LargestUInt LargestUInt;
typedef Json::ArrayIndex ArrayIndex;
static const Value& null; ///! We regret this reference to a global instance; prefer the simpler Value().
static const Value& nullRef; ///! just a kludge for binary-compatibility; same as null
static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
static Value const& nullSingleton(); ///< Prefer this to null or nullRef.
/// Minimum signed integer value that can be stored in a Json::Value.
static const LargestInt minLargestInt;
/// Maximum signed integer value that can be stored in a Json::Value.
@@ -160,7 +217,6 @@ public:
private:
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
#ifndef JSON_VALUE_USE_INTERNAL_MAP
class CZString {
public:
enum DuplicationPolicy {
@@ -169,20 +225,34 @@ private:
duplicateOnCopy
};
CZString(ArrayIndex index);
CZString(const char* cstr, DuplicationPolicy allocate);
CZString(const CZString& other);
CZString(char const* str, unsigned length, DuplicationPolicy allocate);
CZString(CZString const& other);
#if JSON_HAS_RVALUE_REFERENCES
CZString(CZString&& other);
#endif
~CZString();
CZString& operator=(CZString other);
bool operator<(const CZString& other) const;
bool operator==(const CZString& other) const;
bool operator<(CZString const& other) const;
bool operator==(CZString const& other) const;
ArrayIndex index() const;
const char* c_str() const;
//const char* c_str() const; ///< \deprecated
char const* data() const;
unsigned length() const;
bool isStaticString() const;
private:
void swap(CZString& other);
const char* cstr_;
ArrayIndex index_;
struct StringStorage {
unsigned policy_: 2;
unsigned length_: 30; // 1GB max
};
char const* cstr_; // actually, a prefixed string, unless policy is noDup
union {
ArrayIndex index_;
StringStorage storage_;
};
};
public:
@@ -191,7 +261,6 @@ public:
#else
typedef CppTL::SmallMap<CZString, Value> ObjectValues;
#endif // ifndef JSON_USE_CPPTL_SMALLMAP
#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
@@ -218,29 +287,39 @@ Json::Value obj_value(Json::objectValue); // {}
Value(UInt64 value);
#endif // if defined(JSON_HAS_INT64)
Value(double value);
Value(const char* value);
Value(const char* beginValue, const char* endValue);
Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
/** \brief Constructs a value from a static string.
* Like other value string constructor but do not duplicate the string for
* internal storage. The given string must remain alive after the call to this
* constructor.
* \note This works only for null-terminated strings. (We cannot change the
* size of this class, so we have nowhere to store the length,
* which might be computed later for various operations.)
*
* Example of usage:
* \code
* Json::Value aValue( StaticString("some text") );
* static StaticString foo("some text");
* Json::Value aValue(foo);
* \endcode
*/
Value(const StaticString& value);
Value(const std::string& value);
Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
#ifdef JSON_USE_CPPTL
Value(const CppTL::ConstString& value);
#endif
Value(bool value);
/// Deep copy.
Value(const Value& other);
#if JSON_HAS_RVALUE_REFERENCES
/// Move constructor
Value(Value&& other);
#endif
~Value();
// Deep copy, then swap(other).
/// Deep copy, then swap(other).
/// \note Over-write existing comments. To preserve comments, use #swapPayload().
Value& operator=(Value other);
/// Swap everything.
void swap(Value& other);
@@ -258,8 +337,16 @@ Json::Value obj_value(Json::objectValue); // {}
bool operator!=(const Value& other) const;
int compare(const Value& other) const;
const char* asCString() const;
std::string asString() const;
const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
unsigned getCStringLength() const; //Allows you to understand the length of the CString
#endif
JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
/** Get raw char* of string-value.
* \return false if !string. (Seg-fault if str or end are NULL.)
*/
bool getString(
char const** begin, char const** end) const;
#ifdef JSON_USE_CPPTL
CppTL::ConstString asConstString() const;
#endif
@@ -350,19 +437,23 @@ Json::Value obj_value(Json::objectValue); // {}
Value& append(const Value& value);
/// Access an object value by name, create a null member if it does not exist.
/// \note Because of our implementation, keys are limited to 2^30 -1 chars.
/// Exceeding that will cause an exception.
Value& operator[](const char* key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const char* key) const;
/// Access an object value by name, create a null member if it does not exist.
Value& operator[](const std::string& key);
/// \param key may contain embedded nulls.
Value& operator[](const JSONCPP_STRING& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
const Value& operator[](const std::string& key) const;
/// \param key may contain embedded nulls.
const Value& operator[](const JSONCPP_STRING& key) const;
/** \brief Access an object value by name, create a null member if it does not
exist.
* If the object as no entry for that name, then the member name used to store
* If the object has no entry for that name, then the member name used to store
* the new entry is not duplicated.
* Example of use:
* \code
@@ -380,13 +471,29 @@ Json::Value obj_value(Json::objectValue); // {}
const Value& operator[](const CppTL::ConstString& key) const;
#endif
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const char* key, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
Value get(const std::string& key, const Value& defaultValue) const;
/// \note deep copy
/// \note key may contain embedded nulls.
Value get(const char* begin, const char* end, const Value& defaultValue) const;
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
/// \param key may contain embedded nulls.
Value get(const JSONCPP_STRING& key, const Value& defaultValue) const;
#ifdef JSON_USE_CPPTL
/// Return the member named key if it exist, defaultValue otherwise.
/// \note deep copy
Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
#endif
/// Most general and efficient version of isMember()const, get()const,
/// and operator[]const
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
Value const* find(char const* begin, char const* end) const;
/// Most general and efficient version of object-mutators.
/// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
/// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
Value const* demand(char const* begin, char const* end);
/// \brief Remove and return the named member.
///
/// Do nothing if it did not exist.
@@ -396,14 +503,21 @@ Json::Value obj_value(Json::objectValue); // {}
/// \deprecated
Value removeMember(const char* key);
/// Same as removeMember(const char*)
/// \param key may contain embedded nulls.
/// \deprecated
Value removeMember(const std::string& key);
Value removeMember(const JSONCPP_STRING& key);
/// Same as removeMember(const char* begin, const char* end, Value* removed),
/// but 'key' is null-terminated.
bool removeMember(const char* key, Value* removed);
/** \brief Remove the named map member.
Update 'removed' iff removed.
\param key may contain embedded nulls.
\return true iff removed (no exceptions)
*/
bool removeMember(const char* key, Value* removed);
bool removeMember(JSONCPP_STRING const& key, Value* removed);
/// Same as removeMember(JSONCPP_STRING const& key, Value* removed)
bool removeMember(const char* begin, const char* end, Value* removed);
/** \brief Remove the indexed array element.
O(n) expensive operations.
@@ -413,9 +527,13 @@ Json::Value obj_value(Json::objectValue); // {}
bool removeIndex(ArrayIndex i, Value* removed);
/// Return true if the object has a member named key.
/// \note 'key' must be null-terminated.
bool isMember(const char* key) const;
/// Return true if the object has a member named key.
bool isMember(const std::string& key) const;
/// \param key may contain embedded nulls.
bool isMember(const JSONCPP_STRING& key) const;
/// Same as isMember(JSONCPP_STRING const& key)const
bool isMember(const char* begin, const char* end) const;
#ifdef JSON_USE_CPPTL
/// Return true if the object has a member named key.
bool isMember(const CppTL::ConstString& key) const;
@@ -434,16 +552,17 @@ Json::Value obj_value(Json::objectValue); // {}
//# endif
/// \deprecated Always pass len.
JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
void setComment(const char* comment, CommentPlacement placement);
/// Comments must be //... or /* ... */
void setComment(const char* comment, size_t len, CommentPlacement placement);
/// Comments must be //... or /* ... */
void setComment(const std::string& comment, CommentPlacement placement);
void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
bool hasComment(CommentPlacement placement) const;
/// Include delimiters and embedded newlines.
std::string getComment(CommentPlacement placement) const;
JSONCPP_STRING getComment(CommentPlacement placement) const;
std::string toStyledString() const;
JSONCPP_STRING toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
@@ -453,29 +572,17 @@ Json::Value obj_value(Json::objectValue); // {}
// Accessors for the [start, limit) range of bytes within the JSON text from
// which this value was parsed, if any.
void setOffsetStart(size_t start);
void setOffsetLimit(size_t limit);
size_t getOffsetStart() const;
size_t getOffsetLimit() const;
void setOffsetStart(ptrdiff_t start);
void setOffsetLimit(ptrdiff_t limit);
ptrdiff_t getOffsetStart() const;
ptrdiff_t getOffsetLimit() const;
private:
void initBasic(ValueType type, bool allocated = false);
Value& resolveReference(const char* key, bool isStatic);
Value& resolveReference(const char* key);
Value& resolveReference(const char* key, const char* end);
#ifdef JSON_VALUE_USE_INTERNAL_MAP
inline bool isItemAvailable() const { return itemIsUsed_ == 0; }
inline void setItemUsed(bool isUsed = true) { itemIsUsed_ = isUsed ? 1 : 0; }
inline bool isMemberNameStatic() const { return memberNameIsStatic_ == 0; }
inline void setMemberNameIsStatic(bool isStatic) {
memberNameIsStatic_ = isStatic ? 1 : 0;
}
#endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
private:
struct CommentInfo {
CommentInfo();
~CommentInfo();
@@ -499,26 +606,18 @@ private:
LargestUInt uint_;
double real_;
bool bool_;
char* string_;
#ifdef JSON_VALUE_USE_INTERNAL_MAP
ValueInternalArray* array_;
ValueInternalMap* map_;
#else
char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
ObjectValues* map_;
#endif
} value_;
ValueType type_ : 8;
unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
#ifdef JSON_VALUE_USE_INTERNAL_MAP
unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
unsigned int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
#endif
// If not allocated_, string_ must be null-terminated.
CommentInfo* comments_;
// [start, limit) byte offsets in the source JSON text from which this Value
// was extracted.
size_t start_;
size_t limit_;
ptrdiff_t start_;
ptrdiff_t limit_;
};
/** \brief Experimental and untested: represents an element of the "path" to
@@ -531,7 +630,7 @@ public:
PathArgument();
PathArgument(ArrayIndex index);
PathArgument(const char* key);
PathArgument(const std::string& key);
PathArgument(const JSONCPP_STRING& key);
private:
enum Kind {
@@ -539,7 +638,7 @@ private:
kindIndex,
kindKey
};
std::string key_;
JSONCPP_STRING key_;
ArrayIndex index_;
Kind kind_;
};
@@ -557,7 +656,7 @@ private:
*/
class JSON_API Path {
public:
Path(const std::string& path,
Path(const JSONCPP_STRING& path,
const PathArgument& a1 = PathArgument(),
const PathArgument& a2 = PathArgument(),
const PathArgument& a3 = PathArgument(),
@@ -574,355 +673,16 @@ private:
typedef std::vector<const PathArgument*> InArgs;
typedef std::vector<PathArgument> Args;
void makePath(const std::string& path, const InArgs& in);
void addPathInArg(const std::string& path,
void makePath(const JSONCPP_STRING& path, const InArgs& in);
void addPathInArg(const JSONCPP_STRING& path,
const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind);
void invalidPath(const std::string& path, int location);
void invalidPath(const JSONCPP_STRING& path, int location);
Args args_;
};
#ifdef JSON_VALUE_USE_INTERNAL_MAP
/** \brief Allocator to customize Value internal map.
* Below is an example of a simple implementation (default implementation
actually
* use memory pool for speed).
* \code
class DefaultValueMapAllocator : public ValueMapAllocator
{
public: // overridden from ValueMapAllocator
virtual ValueInternalMap *newMap()
{
return new ValueInternalMap();
}
virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
{
return new ValueInternalMap( other );
}
virtual void destructMap( ValueInternalMap *map )
{
delete map;
}
virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
{
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets( ValueInternalLink *links )
{
delete [] links;
}
virtual ValueInternalLink *allocateMapLink()
{
return new ValueInternalLink();
}
virtual void releaseMapLink( ValueInternalLink *link )
{
delete link;
}
};
* \endcode
*/
class JSON_API ValueMapAllocator {
public:
virtual ~ValueMapAllocator();
virtual ValueInternalMap* newMap() = 0;
virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) = 0;
virtual void destructMap(ValueInternalMap* map) = 0;
virtual ValueInternalLink* allocateMapBuckets(unsigned int size) = 0;
virtual void releaseMapBuckets(ValueInternalLink* links) = 0;
virtual ValueInternalLink* allocateMapLink() = 0;
virtual void releaseMapLink(ValueInternalLink* link) = 0;
};
/** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
* \internal previous_ & next_ allows for bidirectional traversal.
*/
class JSON_API ValueInternalLink {
public:
enum {
itemPerLink = 6
}; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
enum InternalFlags {
flagAvailable = 0,
flagUsed = 1
};
ValueInternalLink();
~ValueInternalLink();
Value items_[itemPerLink];
char* keys_[itemPerLink];
ValueInternalLink* previous_;
ValueInternalLink* next_;
};
/** \brief A linked page based hash-table implementation used internally by
*Value.
* \internal ValueInternalMap is a tradional bucket based hash-table, with a
*linked
* list in each bucket to handle collision. There is an addional twist in that
* each node of the collision linked list is a page containing a fixed amount of
* value. This provides a better compromise between memory usage and speed.
*
* Each bucket is made up of a chained list of ValueInternalLink. The last
* link of a given bucket can be found in the 'previous_' field of the following
*bucket.
* The last link of the last bucket is stored in tailLink_ as it has no
*following bucket.
* Only the last link of a bucket may contains 'available' item. The last link
*always
* contains at least one element unless is it the bucket one very first link.
*/
class JSON_API ValueInternalMap {
friend class ValueIteratorBase;
friend class Value;
public:
typedef unsigned int HashKey;
typedef unsigned int BucketIndex;
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
struct IteratorState {
IteratorState() : map_(0), link_(0), itemIndex_(0), bucketIndex_(0) {}
ValueInternalMap* map_;
ValueInternalLink* link_;
BucketIndex itemIndex_;
BucketIndex bucketIndex_;
};
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
ValueInternalMap();
ValueInternalMap(const ValueInternalMap& other);
ValueInternalMap& operator=(ValueInternalMap other);
~ValueInternalMap();
void swap(ValueInternalMap& other);
BucketIndex size() const;
void clear();
bool reserveDelta(BucketIndex growth);
bool reserve(BucketIndex newItemCount);
const Value* find(const char* key) const;
Value* find(const char* key);
Value& resolveReference(const char* key, bool isStatic);
void remove(const char* key);
void doActualRemove(ValueInternalLink* link,
BucketIndex index,
BucketIndex bucketIndex);
ValueInternalLink*& getLastLinkInBucket(BucketIndex bucketIndex);
Value& setNewItem(const char* key,
bool isStatic,
ValueInternalLink* link,
BucketIndex index);
Value& unsafeAdd(const char* key, bool isStatic, HashKey hashedKey);
HashKey hash(const char* key) const;
int compare(const ValueInternalMap& other) const;
private:
void makeBeginIterator(IteratorState& it) const;
void makeEndIterator(IteratorState& it) const;
static bool equals(const IteratorState& x, const IteratorState& other);
static void increment(IteratorState& iterator);
static void incrementBucket(IteratorState& iterator);
static void decrement(IteratorState& iterator);
static const char* key(const IteratorState& iterator);
static const char* key(const IteratorState& iterator, bool& isStatic);
static Value& value(const IteratorState& iterator);
static int distance(const IteratorState& x, const IteratorState& y);
private:
ValueInternalLink* buckets_;
ValueInternalLink* tailLink_;
BucketIndex bucketsSize_;
BucketIndex itemCount_;
};
/** \brief A simplified deque implementation used internally by Value.
* \internal
* It is based on a list of fixed "page", each page contains a fixed number of
*items.
* Instead of using a linked-list, a array of pointer is used for fast item
*look-up.
* Look-up for an element is as follow:
* - compute page index: pageIndex = itemIndex / itemsPerPage
* - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
*
* Insertion is amortized constant time (only the array containing the index of
*pointers
* need to be reallocated when items are appended).
*/
class JSON_API ValueInternalArray {
friend class Value;
friend class ValueIteratorBase;
public:
enum {
itemsPerPage = 8
}; // should be a power of 2 for fast divide and modulo.
typedef Value::ArrayIndex ArrayIndex;
typedef unsigned int PageIndex;
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
struct IteratorState // Must be a POD
{
IteratorState() : array_(0), currentPageIndex_(0), currentItemIndex_(0) {}
ValueInternalArray* array_;
Value** currentPageIndex_;
unsigned int currentItemIndex_;
};
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
ValueInternalArray();
ValueInternalArray(const ValueInternalArray& other);
ValueInternalArray& operator=(ValueInternalArray other);
~ValueInternalArray();
void swap(ValueInternalArray& other);
void clear();
void resize(ArrayIndex newSize);
Value& resolveReference(ArrayIndex index);
Value* find(ArrayIndex index) const;
ArrayIndex size() const;
int compare(const ValueInternalArray& other) const;
private:
static bool equals(const IteratorState& x, const IteratorState& other);
static void increment(IteratorState& iterator);
static void decrement(IteratorState& iterator);
static Value& dereference(const IteratorState& iterator);
static Value& unsafeDereference(const IteratorState& iterator);
static int distance(const IteratorState& x, const IteratorState& y);
static ArrayIndex indexOf(const IteratorState& iterator);
void makeBeginIterator(IteratorState& it) const;
void makeEndIterator(IteratorState& it) const;
void makeIterator(IteratorState& it, ArrayIndex index) const;
void makeIndexValid(ArrayIndex index);
Value** pages_;
ArrayIndex size_;
PageIndex pageCount_;
};
/** \brief Experimental: do not use. Allocator to customize Value internal
array.
* Below is an example of a simple implementation (actual implementation use
* memory pool).
\code
class DefaultValueArrayAllocator : public ValueArrayAllocator
{
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator()
{
}
virtual ValueInternalArray *newArray()
{
return new ValueInternalArray();
}
virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
{
return new ValueInternalArray( other );
}
virtual void destruct( ValueInternalArray *array )
{
delete array;
}
virtual void reallocateArrayPageIndex( Value **&indexes,
ValueInternalArray::PageIndex
&indexCount,
ValueInternalArray::PageIndex
minNewIndexCount )
{
ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
if ( minNewIndexCount > newIndexCount )
newIndexCount = minNewIndexCount;
void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
if ( !newIndexes )
throw std::bad_alloc();
indexCount = newIndexCount;
indexes = static_cast<Value **>( newIndexes );
}
virtual void releaseArrayPageIndex( Value **indexes,
ValueInternalArray::PageIndex indexCount )
{
if ( indexes )
free( indexes );
}
virtual Value *allocateArrayPage()
{
return static_cast<Value *>( malloc( sizeof(Value) *
ValueInternalArray::itemsPerPage ) );
}
virtual void releaseArrayPage( Value *value )
{
if ( value )
free( value );
}
};
\endcode
*/
class JSON_API ValueArrayAllocator {
public:
virtual ~ValueArrayAllocator();
virtual ValueInternalArray* newArray() = 0;
virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) = 0;
virtual void destructArray(ValueInternalArray* array) = 0;
/** \brief Reallocate array page index.
* Reallocates an array of pointer on each page.
* \param indexes [input] pointer on the current index. May be \c NULL.
* [output] pointer on the new index of at least
* \a minNewIndexCount pages.
* \param indexCount [input] current number of pages in the index.
* [output] number of page the reallocated index can handle.
* \b MUST be >= \a minNewIndexCount.
* \param minNewIndexCount Minimum number of page the new index must be able
* to
* handle.
*/
virtual void
reallocateArrayPageIndex(Value**& indexes,
ValueInternalArray::PageIndex& indexCount,
ValueInternalArray::PageIndex minNewIndexCount) = 0;
virtual void
releaseArrayPageIndex(Value** indexes,
ValueInternalArray::PageIndex indexCount) = 0;
virtual Value* allocateArrayPage() = 0;
virtual void releaseArrayPage(Value* value) = 0;
};
#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
/** \brief base class for Value iterators.
*
*/
@@ -933,14 +693,6 @@ public:
typedef int difference_type;
typedef ValueIteratorBase SelfType;
ValueIteratorBase();
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
#else
ValueIteratorBase(const ValueInternalArray::IteratorState& state);
ValueIteratorBase(const ValueInternalMap::IteratorState& state);
#endif
bool operator==(const SelfType& other) const { return isEqual(other); }
bool operator!=(const SelfType& other) const { return !isEqual(other); }
@@ -953,12 +705,23 @@ public:
/// Value.
Value key() const;
/// Return the index of the referenced Value. -1 if it is not an arrayValue.
/// Return the index of the referenced Value, or -1 if it is not an arrayValue.
UInt index() const;
/// Return the member name of the referenced Value, or "" if it is not an
/// objectValue.
/// \note Avoid `c_str()` on result, as embedded zeroes are possible.
JSONCPP_STRING name() const;
/// Return the member name of the referenced Value. "" if it is not an
/// objectValue.
const char* memberName() const;
/// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
JSONCPP_DEPRECATED("Use `key = name();` instead.")
char const* memberName() const;
/// Return the member name of the referenced Value, or NULL if it is not an
/// objectValue.
/// \note Better version than memberName(). Allows embedded nulls.
char const* memberName(char const** end) const;
protected:
Value& deref() const;
@@ -974,17 +737,15 @@ protected:
void copy(const SelfType& other);
private:
#ifndef JSON_VALUE_USE_INTERNAL_MAP
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
bool isNull_;
#else
union {
ValueInternalArray::IteratorState array_;
ValueInternalMap::IteratorState map_;
} iterator_;
bool isArray_;
#endif
public:
// For some reason, BORLAND needs these at the end, rather
// than earlier. No idea why.
ValueIteratorBase();
explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
};
/** \brief const iterator for object and array value.
@@ -995,23 +756,19 @@ class JSON_API ValueConstIterator : public ValueIteratorBase {
public:
typedef const Value value_type;
typedef unsigned int size_t;
typedef int difference_type;
//typedef unsigned int size_t;
//typedef int difference_type;
typedef const Value& reference;
typedef const Value* pointer;
typedef ValueConstIterator SelfType;
ValueConstIterator();
ValueConstIterator(ValueIterator const& other);
private:
/*! \internal Use by Value to create an iterator.
*/
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
#else
ValueConstIterator(const ValueInternalArray::IteratorState& state);
ValueConstIterator(const ValueInternalMap::IteratorState& state);
#endif
public:
SelfType& operator=(const ValueIteratorBase& other);
@@ -1056,18 +813,13 @@ public:
typedef ValueIterator SelfType;
ValueIterator();
ValueIterator(const ValueConstIterator& other);
explicit ValueIterator(const ValueConstIterator& other);
ValueIterator(const ValueIterator& other);
private:
/*! \internal Use by Value to create an iterator.
*/
#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueIterator(const Value::ObjectValues::iterator& current);
#else
ValueIterator(const ValueInternalArray::IteratorState& state);
ValueIterator(const ValueInternalMap::IteratorState& state);
#endif
public:
SelfType& operator=(const SelfType& other);

View File

@@ -1,14 +1,20 @@
// DO NOT EDIT. This file is generated by CMake from "version"
// and "version.h.in" files.
// DO NOT EDIT. This file (and "version") is generated by CMake.
// Run CMake configure step to update it.
#ifndef JSON_VERSION_H_INCLUDED
# define JSON_VERSION_H_INCLUDED
# define JSONCPP_VERSION_STRING "1.4.3"
# define JSONCPP_VERSION_STRING "1.7.5"
# define JSONCPP_VERSION_MAJOR 1
# define JSONCPP_VERSION_MINOR 4
# define JSONCPP_VERSION_PATCH 3
# define JSONCPP_VERSION_MINOR 7
# define JSONCPP_VERSION_PATCH 5
# define JSONCPP_VERSION_QUALIFIER
# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
#ifdef JSONCPP_USING_SECURE_MEMORY
#undef JSONCPP_USING_SECURE_MEMORY
#endif
#define JSONCPP_USING_SECURE_MEMORY 0
// If non-zero, the library zeroes any memory that it has allocated before
// it frees its memory.
#endif // JSON_VERSION_H_INCLUDED

View File

@@ -39,17 +39,17 @@ Usage:
*/
class JSON_API StreamWriter {
protected:
std::ostream* sout_; // not owned; will not delete
JSONCPP_OSTREAM* sout_; // not owned; will not delete
public:
StreamWriter();
virtual ~StreamWriter();
/** Write Value into document as configured in sub-class.
Do not take ownership of sout, but maintain a reference during function.
\pre sout != NULL
\return zero on success
\return zero on success (For now, we always return zero, so check the stream instead.)
\throw std::exception possibly, depending on configuration
*/
virtual int write(Value const& root, std::ostream* sout) = 0;
virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
/** \brief A simple abstract factory.
*/
@@ -66,7 +66,7 @@ public:
/** \brief Write into stringstream, then return string, for convenience.
* A StreamWriter will be created from the factory, used, and then deleted.
*/
std::string writeString(StreamWriter::Factory const& factory, Value const& root);
JSONCPP_STRING JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
/** \brief Build a StreamWriter implementation.
@@ -76,8 +76,8 @@ Usage:
using namespace Json;
Value value = ...;
StreamWriterBuilder builder;
builder.settings_["commentStyle"] = "None";
builder.settings_["indentation"] = " "; // or whatever you like
builder["commentStyle"] = "None";
builder["indentation"] = " "; // or whatever you like
std::unique_ptr<Json::StreamWriter> writer(
builder.newStreamWriter());
writer->write(value, &std::cout);
@@ -99,6 +99,10 @@ public:
Strictly speaking, this is not valid JSON. But when the output is being
fed to a browser's Javascript, it makes for smaller output and the
browser can handle the output just fine.
- "useSpecialFloats": false or true
- If true, outputs non-finite floating point values in the following way:
NaN values as "NaN", positive infinity as "Infinity", and negative infinity
as "-Infinity".
You can examine 'settings_` yourself
to see the defaults. You can also write and read them just like any
@@ -108,17 +112,21 @@ public:
Json::Value settings_;
StreamWriterBuilder();
virtual ~StreamWriterBuilder();
~StreamWriterBuilder() JSONCPP_OVERRIDE;
/**
* \throw std::exception if something goes wrong (e.g. invalid settings)
*/
virtual StreamWriter* newStreamWriter() const;
StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
/** \return true if 'settings' are legal and consistent;
* otherwise, indicate bad settings via 'invalid'.
*/
bool validate(Json::Value* invalid) const;
/** A simple way to update a specific setting.
*/
Value& operator[](JSONCPP_STRING key);
/** Called by ctor, but you can use this to reset settings_.
* \pre 'settings' != NULL (but Json::null is fine)
* \remark Defaults:
@@ -128,13 +136,13 @@ public:
};
/** \brief Abstract class for writers.
* \deprecated Use StreamWriter.
* \deprecated Use StreamWriter. (And really, this is an implementation detail.)
*/
class JSON_API Writer {
public:
virtual ~Writer();
virtual std::string write(const Value& root) = 0;
virtual JSONCPP_STRING write(const Value& root) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
@@ -147,9 +155,10 @@ public:
* \deprecated Use StreamWriterBuilder.
*/
class JSON_API FastWriter : public Writer {
public:
FastWriter();
virtual ~FastWriter() {}
~FastWriter() JSONCPP_OVERRIDE {}
void enableYAMLCompatibility();
@@ -163,12 +172,12 @@ public:
void omitEndingLineFeed();
public: // overridden from Writer
virtual std::string write(const Value& root);
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
std::string document_;
JSONCPP_STRING document_;
bool yamlCompatiblityEnabled_;
bool dropNullPlaceholders_;
bool omitEndingLineFeed_;
@@ -201,36 +210,36 @@ private:
class JSON_API StyledWriter : public Writer {
public:
StyledWriter();
virtual ~StyledWriter() {}
~StyledWriter() JSONCPP_OVERRIDE {}
public: // overridden from Writer
/** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
* \param root Value to serialize.
* \return String containing the JSON document that represents the root value.
*/
virtual std::string write(const Value& root);
JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
void pushValue(const std::string& value);
void pushValue(const JSONCPP_STRING& value);
void writeIndent();
void writeWithIndent(const std::string& value);
void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
static std::string normalizeEOL(const std::string& text);
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
typedef std::vector<std::string> ChildValues;
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
std::string document_;
std::string indentString_;
int rightMargin_;
int indentSize_;
JSONCPP_STRING document_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
unsigned int indentSize_;
bool addChildValues_;
};
@@ -262,7 +271,7 @@ private:
*/
class JSON_API StyledStreamWriter {
public:
StyledStreamWriter(std::string indentation = "\t");
StyledStreamWriter(JSONCPP_STRING indentation = "\t");
~StyledStreamWriter() {}
public:
@@ -272,46 +281,46 @@ public:
* \note There is no point in deriving from Writer, since write() should not
* return a value.
*/
void write(std::ostream& out, const Value& root);
void write(JSONCPP_OSTREAM& out, const Value& root);
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
void pushValue(const std::string& value);
void pushValue(const JSONCPP_STRING& value);
void writeIndent();
void writeWithIndent(const std::string& value);
void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
static std::string normalizeEOL(const std::string& text);
static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
typedef std::vector<std::string> ChildValues;
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
std::ostream* document_;
std::string indentString_;
int rightMargin_;
std::string indentation_;
JSONCPP_OSTREAM* document_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
JSONCPP_STRING indentation_;
bool addChildValues_ : 1;
bool indented_ : 1;
};
#if defined(JSON_HAS_INT64)
std::string JSON_API valueToString(Int value);
std::string JSON_API valueToString(UInt value);
JSONCPP_STRING JSON_API valueToString(Int value);
JSONCPP_STRING JSON_API valueToString(UInt value);
#endif // if defined(JSON_HAS_INT64)
std::string JSON_API valueToString(LargestInt value);
std::string JSON_API valueToString(LargestUInt value);
std::string JSON_API valueToString(double value);
std::string JSON_API valueToString(bool value);
std::string JSON_API valueToQuotedString(const char* value);
JSONCPP_STRING JSON_API valueToString(LargestInt value);
JSONCPP_STRING JSON_API valueToString(LargestUInt value);
JSONCPP_STRING JSON_API valueToString(double value);
JSONCPP_STRING JSON_API valueToString(bool value);
JSONCPP_STRING JSON_API valueToQuotedString(const char* value);
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
} // namespace Json

View File

@@ -1,46 +1,46 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_json", "lib_json.vcproj", "{B84F7231-16CE-41D8-8C08-7B523FF4225B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsontest", "jsontest.vcproj", "{25AF2DD2-D396-4668-B188-488C33B8E620}"
ProjectSection(ProjectDependencies) = postProject
{B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_lib_json", "test_lib_json.vcproj", "{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}"
ProjectSection(ProjectDependencies) = postProject
{B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
dummy = dummy
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.ActiveCfg = Debug|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.Build.0 = Debug|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.ActiveCfg = dummy|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.Build.0 = dummy|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.ActiveCfg = Release|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.Build.0 = Release|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.ActiveCfg = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.Build.0 = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.ActiveCfg = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.Build.0 = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Release.ActiveCfg = Release|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Release.Build.0 = Release|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.ActiveCfg = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.Build.0 = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.ActiveCfg = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.Build.0 = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.ActiveCfg = Release|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lib_json", "lib_json.vcproj", "{B84F7231-16CE-41D8-8C08-7B523FF4225B}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsontest", "jsontest.vcproj", "{25AF2DD2-D396-4668-B188-488C33B8E620}"
ProjectSection(ProjectDependencies) = postProject
{B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_lib_json", "test_lib_json.vcproj", "{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}"
ProjectSection(ProjectDependencies) = postProject
{B84F7231-16CE-41D8-8C08-7B523FF4225B} = {B84F7231-16CE-41D8-8C08-7B523FF4225B}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
dummy = dummy
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.ActiveCfg = Debug|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Debug.Build.0 = Debug|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.ActiveCfg = dummy|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.dummy.Build.0 = dummy|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.ActiveCfg = Release|Win32
{B84F7231-16CE-41D8-8C08-7B523FF4225B}.Release.Build.0 = Release|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.ActiveCfg = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Debug.Build.0 = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.ActiveCfg = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.dummy.Build.0 = Debug|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Release.ActiveCfg = Release|Win32
{25AF2DD2-D396-4668-B188-488C33B8E620}.Release.Build.0 = Release|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.ActiveCfg = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Debug.Build.0 = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.ActiveCfg = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.dummy.Build.0 = Debug|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.ActiveCfg = Release|Win32
{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

View File

@@ -1,119 +1,119 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="jsontest"
ProjectGUID="{25AF2DD2-D396-4668-B188-488C33B8E620}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/jsontest"
IntermediateDirectory="../../build/vs71/debug/jsontest"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/jsontest.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/jsontest.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/jsontest"
IntermediateDirectory="../../build/vs71/release/jsontest"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/jsontest.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\src\jsontestrunner\main.cpp">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="jsontest"
ProjectGUID="{25AF2DD2-D396-4668-B188-488C33B8E620}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/jsontest"
IntermediateDirectory="../../build/vs71/debug/jsontest"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/jsontest.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/jsontest.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/jsontest"
IntermediateDirectory="../../build/vs71/release/jsontest"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/jsontest.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\src\jsontestrunner\main.cpp">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,214 +1,205 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="lib_json"
ProjectGUID="{B84F7231-16CE-41D8-8C08-7B523FF4225B}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/lib_json"
IntermediateDirectory="../../build/vs71/debug/lib_json"
ConfigurationType="4"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
StringPooling="TRUE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/json_vc71_libmtd.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/lib_json"
IntermediateDirectory="../../build/vs71/release/lib_json"
ConfigurationType="4"
CharacterSet="2"
WholeProgramOptimization="TRUE">
<Tool
Name="VCCLCompilerTool"
GlobalOptimizations="TRUE"
EnableIntrinsicFunctions="TRUE"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="0"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
AssemblerOutput="4"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/json_vc71_libmt.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="dummy|Win32"
OutputDirectory="$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="2"
CharacterSet="2"
WholeProgramOptimization="TRUE">
<Tool
Name="VCCLCompilerTool"
GlobalOptimizations="TRUE"
EnableIntrinsicFunctions="TRUE"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="4"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
AssemblerOutput="4"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
GenerateDebugInformation="TRUE"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\include\json\autolink.h">
</File>
<File
RelativePath="..\..\include\json\config.h">
</File>
<File
RelativePath="..\..\include\json\features.h">
</File>
<File
RelativePath="..\..\include\json\forwards.h">
</File>
<File
RelativePath="..\..\include\json\json.h">
</File>
<File
RelativePath="..\..\src\lib_json\json_batchallocator.h">
</File>
<File
RelativePath="..\..\src\lib_json\json_internalarray.inl">
</File>
<File
RelativePath="..\..\src\lib_json\json_internalmap.inl">
</File>
<File
RelativePath="..\..\src\lib_json\json_reader.cpp">
</File>
<File
RelativePath="..\..\src\lib_json\json_value.cpp">
</File>
<File
RelativePath="..\..\src\lib_json\json_valueiterator.inl">
</File>
<File
RelativePath="..\..\src\lib_json\json_writer.cpp">
</File>
<File
RelativePath="..\..\include\json\reader.h">
</File>
<File
RelativePath="..\..\include\json\value.h">
</File>
<File
RelativePath="..\..\include\json\writer.h">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="lib_json"
ProjectGUID="{B84F7231-16CE-41D8-8C08-7B523FF4225B}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/lib_json"
IntermediateDirectory="../../build/vs71/debug/lib_json"
ConfigurationType="4"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
StringPooling="TRUE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/json_vc71_libmtd.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/lib_json"
IntermediateDirectory="../../build/vs71/release/lib_json"
ConfigurationType="4"
CharacterSet="2"
WholeProgramOptimization="TRUE">
<Tool
Name="VCCLCompilerTool"
GlobalOptimizations="TRUE"
EnableIntrinsicFunctions="TRUE"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="0"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
AssemblerOutput="4"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/json_vc71_libmt.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="dummy|Win32"
OutputDirectory="$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="2"
CharacterSet="2"
WholeProgramOptimization="TRUE">
<Tool
Name="VCCLCompilerTool"
GlobalOptimizations="TRUE"
EnableIntrinsicFunctions="TRUE"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="4"
EnableFunctionLevelLinking="TRUE"
DisableLanguageExtensions="TRUE"
ForceConformanceInForLoopScope="FALSE"
RuntimeTypeInfo="TRUE"
UsePrecompiledHeader="0"
AssemblerOutput="4"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
GenerateDebugInformation="TRUE"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\include\json\autolink.h">
</File>
<File
RelativePath="..\..\include\json\config.h">
</File>
<File
RelativePath="..\..\include\json\features.h">
</File>
<File
RelativePath="..\..\include\json\forwards.h">
</File>
<File
RelativePath="..\..\include\json\json.h">
</File>
<File
RelativePath="..\..\src\lib_json\json_reader.cpp">
</File>
<File
RelativePath="..\..\src\lib_json\json_value.cpp">
</File>
<File
RelativePath="..\..\src\lib_json\json_valueiterator.inl">
</File>
<File
RelativePath="..\..\src\lib_json\json_writer.cpp">
</File>
<File
RelativePath="..\..\include\json\reader.h">
</File>
<File
RelativePath="..\..\include\json\value.h">
</File>
<File
RelativePath="..\..\include\json\writer.h">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,130 +1,130 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="test_lib_json"
ProjectGUID="{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}"
RootNamespace="test_lib_json"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/test_lib_json"
IntermediateDirectory="../../build/vs71/debug/test_lib_json"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/test_lib_json.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/test_lib_json.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
Description="Running all unit tests"
CommandLine="$(TargetPath)"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/test_lib_json"
IntermediateDirectory="../../build/vs71/release/test_lib_json"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/test_lib_json.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
Description="Running all unit tests"
CommandLine="$(TargetPath)"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\src\test_lib_json\jsontest.cpp">
</File>
<File
RelativePath="..\..\src\test_lib_json\jsontest.h">
</File>
<File
RelativePath="..\..\src\test_lib_json\main.cpp">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="test_lib_json"
ProjectGUID="{B7A96B78-2782-40D2-8F37-A2DEF2B9C26D}"
RootNamespace="test_lib_json"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="../../build/vs71/debug/test_lib_json"
IntermediateDirectory="../../build/vs71/debug/test_lib_json"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/test_lib_json.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/test_lib_json.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
Description="Running all unit tests"
CommandLine="$(TargetPath)"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="../../build/vs71/release/test_lib_json"
IntermediateDirectory="../../build/vs71/release/test_lib_json"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories="../../include"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="0"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/test_lib_json.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"
Description="Running all unit tests"
CommandLine="$(TargetPath)"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<File
RelativePath="..\..\src\test_lib_json\jsontest.cpp">
</File>
<File
RelativePath="..\..\src\test_lib_json\jsontest.h">
</File>
<File
RelativePath="..\..\src\test_lib_json\main.cpp">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,3 +1,8 @@
# Copyright 2010 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
"""Tag the sandbox for release, make source and doc tarballs.
Requires Python 2.6
@@ -14,6 +19,7 @@ python makerelease.py 0.5.0 0.6.0-dev
Note: This was for Subversion. Now that we are in GitHub, we do not
need to build versioned tarballs anymore, so makerelease.py is defunct.
"""
from __future__ import print_function
import os.path
import subprocess

View File

@@ -1,3 +1,8 @@
# Copyright 2009 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
import fnmatch
import os

View File

@@ -1,3 +1,8 @@
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
import os
import os.path
from fnmatch import fnmatch

View File

@@ -1,3 +1,8 @@
# Copyright 2010 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
import re
from SCons.Script import * # the usual scons stuff you get in a SConscript
import collections

View File

@@ -1,3 +1,8 @@
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
"""tarball
Tool-specific initialization for tarball.

View File

@@ -2,4 +2,4 @@ ADD_SUBDIRECTORY(lib_json)
IF(JSONCPP_WITH_TESTS)
ADD_SUBDIRECTORY(jsontestrunner)
ADD_SUBDIRECTORY(test_lib_json)
ENDIF(JSONCPP_WITH_TESTS)
ENDIF()

View File

@@ -1,18 +1,15 @@
FIND_PACKAGE(PythonInterp 2.6 REQUIRED)
IF(JSONCPP_LIB_BUILD_SHARED)
ADD_DEFINITIONS( -DJSON_DLL )
ENDIF(JSONCPP_LIB_BUILD_SHARED)
FIND_PACKAGE(PythonInterp 2.6)
ADD_EXECUTABLE(jsontestrunner_exe
main.cpp
)
IF(JSONCPP_LIB_BUILD_SHARED)
IF(BUILD_SHARED_LIBS)
ADD_DEFINITIONS( -DJSON_DLL )
TARGET_LINK_LIBRARIES(jsontestrunner_exe jsoncpp_lib)
ELSE(JSONCPP_LIB_BUILD_SHARED)
ELSE(BUILD_SHARED_LIBS)
TARGET_LINK_LIBRARIES(jsontestrunner_exe jsoncpp_lib_static)
ENDIF(JSONCPP_LIB_BUILD_SHARED)
ENDIF()
SET_TARGET_PROPERTIES(jsontestrunner_exe PROPERTIES OUTPUT_NAME jsontestrunner_exe)
@@ -20,9 +17,9 @@ IF(PYTHONINTERP_FOUND)
# Run end to end parser/writer tests
SET(TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../test)
SET(RUNJSONTESTS_PATH ${TEST_DIR}/runjsontests.py)
ADD_CUSTOM_TARGET(jsoncpp_readerwriter_tests ALL
ADD_CUSTOM_TARGET(jsoncpp_readerwriter_tests
"${PYTHON_EXECUTABLE}" -B "${RUNJSONTESTS_PATH}" $<TARGET_FILE:jsontestrunner_exe> "${TEST_DIR}/data"
DEPENDS jsontestrunner_exe jsoncpp_test
)
ADD_CUSTOM_TARGET(jsoncpp_check DEPENDS jsoncpp_readerwriter_tests)
ENDIF(PYTHONINTERP_FOUND)
ENDIF()

View File

@@ -17,14 +17,14 @@
struct Options
{
std::string path;
JSONCPP_STRING path;
Json::Features features;
bool parseOnly;
typedef std::string (*writeFuncType)(Json::Value const&);
typedef JSONCPP_STRING (*writeFuncType)(Json::Value const&);
writeFuncType write;
};
static std::string normalizeFloatingPointStr(double value) {
static JSONCPP_STRING normalizeFloatingPointStr(double value) {
char buffer[32];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
sprintf_s(buffer, sizeof(buffer), "%.16g", value);
@@ -32,18 +32,18 @@ static std::string normalizeFloatingPointStr(double value) {
snprintf(buffer, sizeof(buffer), "%.16g", value);
#endif
buffer[sizeof(buffer) - 1] = 0;
std::string s(buffer);
std::string::size_type index = s.find_last_of("eE");
if (index != std::string::npos) {
std::string::size_type hasSign =
JSONCPP_STRING s(buffer);
JSONCPP_STRING::size_type index = s.find_last_of("eE");
if (index != JSONCPP_STRING::npos) {
JSONCPP_STRING::size_type hasSign =
(s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0;
std::string::size_type exponentStartIndex = index + 1 + hasSign;
std::string normalized = s.substr(0, exponentStartIndex);
std::string::size_type indexDigit =
JSONCPP_STRING::size_type exponentStartIndex = index + 1 + hasSign;
JSONCPP_STRING normalized = s.substr(0, exponentStartIndex);
JSONCPP_STRING::size_type indexDigit =
s.find_first_not_of('0', exponentStartIndex);
std::string exponent = "0";
JSONCPP_STRING exponent = "0";
if (indexDigit !=
std::string::npos) // There is an exponent different from 0
JSONCPP_STRING::npos) // There is an exponent different from 0
{
exponent = s.substr(indexDigit);
}
@@ -52,17 +52,18 @@ static std::string normalizeFloatingPointStr(double value) {
return s;
}
static std::string readInputTestFile(const char* path) {
static JSONCPP_STRING readInputTestFile(const char* path) {
FILE* file = fopen(path, "rb");
if (!file)
return std::string("");
return JSONCPP_STRING("");
fseek(file, 0, SEEK_END);
long size = ftell(file);
long const size = ftell(file);
unsigned long const usize = static_cast<unsigned long>(size);
fseek(file, 0, SEEK_SET);
std::string text;
JSONCPP_STRING text;
char* buffer = new char[size + 1];
buffer[size] = 0;
if (fread(buffer, 1, size, file) == (unsigned long)size)
if (fread(buffer, 1, usize, file) == usize)
text = buffer;
fclose(file);
delete[] buffer;
@@ -70,7 +71,7 @@ static std::string readInputTestFile(const char* path) {
}
static void
printValueTree(FILE* fout, Json::Value& value, const std::string& path = ".") {
printValueTree(FILE* fout, Json::Value& value, const JSONCPP_STRING& path = ".") {
if (value.hasComment(Json::commentBefore)) {
fprintf(fout, "%s\n", value.getComment(Json::commentBefore).c_str());
}
@@ -104,8 +105,8 @@ printValueTree(FILE* fout, Json::Value& value, const std::string& path = ".") {
break;
case Json::arrayValue: {
fprintf(fout, "%s=[]\n", path.c_str());
int size = value.size();
for (int index = 0; index < size; ++index) {
Json::ArrayIndex size = value.size();
for (Json::ArrayIndex index = 0; index < size; ++index) {
static char buffer[16];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
sprintf_s(buffer, sizeof(buffer), "[%d]", index);
@@ -119,11 +120,11 @@ printValueTree(FILE* fout, Json::Value& value, const std::string& path = ".") {
fprintf(fout, "%s={}\n", path.c_str());
Json::Value::Members members(value.getMemberNames());
std::sort(members.begin(), members.end());
std::string suffix = *(path.end() - 1) == '.' ? "" : ".";
JSONCPP_STRING suffix = *(path.end() - 1) == '.' ? "" : ".";
for (Json::Value::Members::iterator it = members.begin();
it != members.end();
++it) {
const std::string& name = *it;
const JSONCPP_STRING name = *it;
printValueTree(fout, value[name], path + suffix + name);
}
} break;
@@ -136,15 +137,15 @@ printValueTree(FILE* fout, Json::Value& value, const std::string& path = ".") {
}
}
static int parseAndSaveValueTree(const std::string& input,
const std::string& actual,
const std::string& kind,
static int parseAndSaveValueTree(const JSONCPP_STRING& input,
const JSONCPP_STRING& actual,
const JSONCPP_STRING& kind,
const Json::Features& features,
bool parseOnly,
Json::Value* root)
{
Json::Reader reader(features);
bool parsingSuccessful = reader.parse(input, *root);
bool parsingSuccessful = reader.parse(input.data(), input.data() + input.size(), *root);
if (!parsingSuccessful) {
printf("Failed to parse %s file: \n%s\n",
kind.c_str(),
@@ -162,36 +163,36 @@ static int parseAndSaveValueTree(const std::string& input,
}
return 0;
}
// static std::string useFastWriter(Json::Value const& root) {
// static JSONCPP_STRING useFastWriter(Json::Value const& root) {
// Json::FastWriter writer;
// writer.enableYAMLCompatibility();
// return writer.write(root);
// }
static std::string useStyledWriter(
static JSONCPP_STRING useStyledWriter(
Json::Value const& root)
{
Json::StyledWriter writer;
return writer.write(root);
}
static std::string useStyledStreamWriter(
static JSONCPP_STRING useStyledStreamWriter(
Json::Value const& root)
{
Json::StyledStreamWriter writer;
std::ostringstream sout;
JSONCPP_OSTRINGSTREAM sout;
writer.write(sout, root);
return sout.str();
}
static std::string useBuiltStyledStreamWriter(
static JSONCPP_STRING useBuiltStyledStreamWriter(
Json::Value const& root)
{
Json::StreamWriterBuilder builder;
return Json::writeString(builder, root);
}
static int rewriteValueTree(
const std::string& rewritePath,
const JSONCPP_STRING& rewritePath,
const Json::Value& root,
Options::writeFuncType write,
std::string* rewrite)
JSONCPP_STRING* rewrite)
{
*rewrite = write(root);
FILE* fout = fopen(rewritePath.c_str(), "wt");
@@ -204,13 +205,13 @@ static int rewriteValueTree(
return 0;
}
static std::string removeSuffix(const std::string& path,
const std::string& extension) {
static JSONCPP_STRING removeSuffix(const JSONCPP_STRING& path,
const JSONCPP_STRING& extension) {
if (extension.length() >= path.length())
return std::string("");
std::string suffix = path.substr(path.length() - extension.length());
return JSONCPP_STRING("");
JSONCPP_STRING suffix = path.substr(path.length() - extension.length());
if (suffix != extension)
return std::string("");
return JSONCPP_STRING("");
return path.substr(0, path.length() - extension.length());
}
@@ -237,18 +238,18 @@ static int parseCommandLine(
return printUsage(argv);
}
int index = 1;
if (std::string(argv[index]) == "--json-checker") {
if (JSONCPP_STRING(argv[index]) == "--json-checker") {
opts->features = Json::Features::strictMode();
opts->parseOnly = true;
++index;
}
if (std::string(argv[index]) == "--json-config") {
if (JSONCPP_STRING(argv[index]) == "--json-config") {
printConfig();
return 3;
}
if (std::string(argv[index]) == "--json-writer") {
if (JSONCPP_STRING(argv[index]) == "--json-writer") {
++index;
std::string const writerName(argv[index++]);
JSONCPP_STRING const writerName(argv[index++]);
if (writerName == "StyledWriter") {
opts->write = &useStyledWriter;
} else if (writerName == "StyledStreamWriter") {
@@ -270,22 +271,22 @@ static int runTest(Options const& opts)
{
int exitCode = 0;
std::string input = readInputTestFile(opts.path.c_str());
JSONCPP_STRING input = readInputTestFile(opts.path.c_str());
if (input.empty()) {
printf("Failed to read input or empty input: %s\n", opts.path.c_str());
return 3;
}
std::string basePath = removeSuffix(opts.path, ".json");
JSONCPP_STRING basePath = removeSuffix(opts.path, ".json");
if (!opts.parseOnly && basePath.empty()) {
printf("Bad input path. Path does not end with '.expected':\n%s\n",
opts.path.c_str());
return 3;
}
std::string const actualPath = basePath + ".actual";
std::string const rewritePath = basePath + ".rewrite";
std::string const rewriteActualPath = basePath + ".actual-rewrite";
JSONCPP_STRING const actualPath = basePath + ".actual";
JSONCPP_STRING const rewritePath = basePath + ".rewrite";
JSONCPP_STRING const rewriteActualPath = basePath + ".actual-rewrite";
Json::Value root;
exitCode = parseAndSaveValueTree(
@@ -294,7 +295,7 @@ static int runTest(Options const& opts)
if (exitCode || opts.parseOnly) {
return exitCode;
}
std::string rewrite;
JSONCPP_STRING rewrite;
exitCode = rewriteValueTree(rewritePath, root, opts.write, &rewrite);
if (exitCode) {
return exitCode;
@@ -310,12 +311,12 @@ static int runTest(Options const& opts)
}
int main(int argc, const char* argv[]) {
Options opts;
try {
int exitCode = parseCommandLine(argc, argv, &opts);
if (exitCode != 0) {
printf("Failed to parse command-line.");
return exitCode;
}
try {
return runTest(opts);
}
catch (const std::exception& e) {

View File

@@ -1,15 +1,8 @@
OPTION(JSONCPP_LIB_BUILD_SHARED "Build jsoncpp_lib as a shared library." OFF)
OPTION(JSONCPP_LIB_BUILD_STATIC "Build jsoncpp_lib static library." ON)
IF(BUILD_SHARED_LIBS)
SET(JSONCPP_LIB_BUILD_SHARED ON)
ENDIF(BUILD_SHARED_LIBS)
if( CMAKE_COMPILER_IS_GNUCXX )
#Get compiler version.
execute_process( COMMAND ${CMAKE_CXX_COMPILER} -dumpversion
OUTPUT_VARIABLE GNUCXX_VERSION )
#-Werror=* was introduced -after- GCC 4.1.2
if( GNUCXX_VERSION VERSION_GREATER 4.1.2 )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=strict-aliasing")
@@ -34,7 +27,6 @@ SOURCE_GROUP( "Public API" FILES ${PUBLIC_HEADERS} )
SET(jsoncpp_sources
json_tool.h
json_reader.cpp
json_batchallocator.h
json_valueiterator.inl
json_value.cpp
json_writer.cpp
@@ -45,13 +37,14 @@ IF(JSONCPP_WITH_CMAKE_PACKAGE)
SET(INSTALL_EXPORT EXPORT jsoncpp)
ELSE(JSONCPP_WITH_CMAKE_PACKAGE)
SET(INSTALL_EXPORT)
ENDIF(JSONCPP_WITH_CMAKE_PACKAGE)
ENDIF()
IF(JSONCPP_LIB_BUILD_SHARED)
IF(BUILD_SHARED_LIBS)
ADD_DEFINITIONS( -DJSON_DLL_BUILD )
ADD_LIBRARY(jsoncpp_lib SHARED ${PUBLIC_HEADERS} ${jsoncpp_sources})
SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES VERSION ${JSONCPP_VERSION} SOVERSION ${JSONCPP_VERSION_MAJOR})
SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES OUTPUT_NAME jsoncpp )
SET_TARGET_PROPERTIES( jsoncpp_lib PROPERTIES OUTPUT_NAME jsoncpp
DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} )
INSTALL( TARGETS jsoncpp_lib ${INSTALL_EXPORT}
RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR}
@@ -62,14 +55,15 @@ IF(JSONCPP_LIB_BUILD_SHARED)
TARGET_INCLUDE_DIRECTORIES( jsoncpp_lib PUBLIC
$<INSTALL_INTERFACE:${INCLUDE_INSTALL_DIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}>)
ENDIF(NOT CMAKE_VERSION VERSION_LESS 2.8.11)
ENDIF()
ENDIF()
IF(JSONCPP_LIB_BUILD_STATIC)
IF(BUILD_STATIC_LIBS)
ADD_LIBRARY(jsoncpp_lib_static STATIC ${PUBLIC_HEADERS} ${jsoncpp_sources})
SET_TARGET_PROPERTIES( jsoncpp_lib_static PROPERTIES VERSION ${JSONCPP_VERSION} SOVERSION ${JSONCPP_VERSION_MAJOR})
SET_TARGET_PROPERTIES( jsoncpp_lib_static PROPERTIES OUTPUT_NAME jsoncpp )
SET_TARGET_PROPERTIES( jsoncpp_lib_static PROPERTIES OUTPUT_NAME jsoncpp
DEBUG_OUTPUT_NAME jsoncpp${DEBUG_LIBNAME_SUFFIX} )
INSTALL( TARGETS jsoncpp_lib_static ${INSTALL_EXPORT}
RUNTIME DESTINATION ${RUNTIME_INSTALL_DIR}
@@ -81,6 +75,6 @@ IF(JSONCPP_LIB_BUILD_STATIC)
$<INSTALL_INTERFACE:${INCLUDE_INSTALL_DIR}>
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/${JSONCPP_INCLUDE_DIR}>
)
ENDIF(NOT CMAKE_VERSION VERSION_LESS 2.8.11)
ENDIF()
ENDIF()

View File

@@ -1,121 +0,0 @@
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED
#define JSONCPP_BATCHALLOCATOR_H_INCLUDED
#include <stdlib.h>
#include <assert.h>
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
namespace Json {
/* Fast memory allocator.
*
* This memory allocator allocates memory for a batch of object (specified by
* the page size, the number of object in each page).
*
* It does not allow the destruction of a single object. All the allocated
* objects can be destroyed at once. The memory can be either released or reused
* for future allocation.
*
* The in-place new operator must be used to construct the object using the
* pointer returned by allocate.
*/
template <typename AllocatedType, const unsigned int objectPerAllocation>
class BatchAllocator {
public:
BatchAllocator(unsigned int objectsPerPage = 255)
: freeHead_(0), objectsPerPage_(objectsPerPage) {
// printf( "Size: %d => %s\n", sizeof(AllocatedType),
// typeid(AllocatedType).name() );
assert(sizeof(AllocatedType) * objectPerAllocation >=
sizeof(AllocatedType*)); // We must be able to store a slist in the
// object free space.
assert(objectsPerPage >= 16);
batches_ = allocateBatch(0); // allocated a dummy page
currentBatch_ = batches_;
}
~BatchAllocator() {
for (BatchInfo* batch = batches_; batch;) {
BatchInfo* nextBatch = batch->next_;
free(batch);
batch = nextBatch;
}
}
/// allocate space for an array of objectPerAllocation object.
/// @warning it is the responsability of the caller to call objects
/// constructors.
AllocatedType* allocate() {
if (freeHead_) // returns node from free list.
{
AllocatedType* object = freeHead_;
freeHead_ = *(AllocatedType**)object;
return object;
}
if (currentBatch_->used_ == currentBatch_->end_) {
currentBatch_ = currentBatch_->next_;
while (currentBatch_ && currentBatch_->used_ == currentBatch_->end_)
currentBatch_ = currentBatch_->next_;
if (!currentBatch_) // no free batch found, allocate a new one
{
currentBatch_ = allocateBatch(objectsPerPage_);
currentBatch_->next_ = batches_; // insert at the head of the list
batches_ = currentBatch_;
}
}
AllocatedType* allocated = currentBatch_->used_;
currentBatch_->used_ += objectPerAllocation;
return allocated;
}
/// Release the object.
/// @warning it is the responsability of the caller to actually destruct the
/// object.
void release(AllocatedType* object) {
assert(object != 0);
*(AllocatedType**)object = freeHead_;
freeHead_ = object;
}
private:
struct BatchInfo {
BatchInfo* next_;
AllocatedType* used_;
AllocatedType* end_;
AllocatedType buffer_[objectPerAllocation];
};
// disabled copy constructor and assignement operator.
BatchAllocator(const BatchAllocator&);
void operator=(const BatchAllocator&);
static BatchInfo* allocateBatch(unsigned int objectsPerPage) {
const unsigned int mallocSize =
sizeof(BatchInfo) - sizeof(AllocatedType) * objectPerAllocation +
sizeof(AllocatedType) * objectPerAllocation * objectsPerPage;
BatchInfo* batch = static_cast<BatchInfo*>(malloc(mallocSize));
batch->next_ = 0;
batch->used_ = batch->buffer_;
batch->end_ = batch->buffer_ + objectsPerPage;
return batch;
}
BatchInfo* batches_;
BatchInfo* currentBatch_;
/// Head of a single linked list within the allocated space of freeed object
AllocatedType* freeHead_;
unsigned int objectsPerPage_;
};
} // namespace Json
#endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION
#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED

View File

@@ -1,360 +0,0 @@
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
// included by json_value.cpp
namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueInternalArray
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueArrayAllocator::~ValueArrayAllocator() {}
// //////////////////////////////////////////////////////////////////
// class DefaultValueArrayAllocator
// //////////////////////////////////////////////////////////////////
#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
class DefaultValueArrayAllocator : public ValueArrayAllocator {
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator() {}
virtual ValueInternalArray* newArray() { return new ValueInternalArray(); }
virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) {
return new ValueInternalArray(other);
}
virtual void destructArray(ValueInternalArray* array) { delete array; }
virtual void
reallocateArrayPageIndex(Value**& indexes,
ValueInternalArray::PageIndex& indexCount,
ValueInternalArray::PageIndex minNewIndexCount) {
ValueInternalArray::PageIndex newIndexCount = (indexCount * 3) / 2 + 1;
if (minNewIndexCount > newIndexCount)
newIndexCount = minNewIndexCount;
void* newIndexes = realloc(indexes, sizeof(Value*) * newIndexCount);
JSON_ASSERT_MESSAGE(newIndexes, "Couldn't realloc.");
indexCount = newIndexCount;
indexes = static_cast<Value**>(newIndexes);
}
virtual void releaseArrayPageIndex(Value** indexes,
ValueInternalArray::PageIndex indexCount) {
if (indexes)
free(indexes);
}
virtual Value* allocateArrayPage() {
return static_cast<Value*>(
malloc(sizeof(Value) * ValueInternalArray::itemsPerPage));
}
virtual void releaseArrayPage(Value* value) {
if (value)
free(value);
}
};
#else // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
/// @todo make this thread-safe (lock when accessign batch allocator)
class DefaultValueArrayAllocator : public ValueArrayAllocator {
public: // overridden from ValueArrayAllocator
virtual ~DefaultValueArrayAllocator() {}
virtual ValueInternalArray* newArray() {
ValueInternalArray* array = arraysAllocator_.allocate();
new (array) ValueInternalArray(); // placement new
return array;
}
virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) {
ValueInternalArray* array = arraysAllocator_.allocate();
new (array) ValueInternalArray(other); // placement new
return array;
}
virtual void destructArray(ValueInternalArray* array) {
if (array) {
array->~ValueInternalArray();
arraysAllocator_.release(array);
}
}
virtual void
reallocateArrayPageIndex(Value**& indexes,
ValueInternalArray::PageIndex& indexCount,
ValueInternalArray::PageIndex minNewIndexCount) {
ValueInternalArray::PageIndex newIndexCount = (indexCount * 3) / 2 + 1;
if (minNewIndexCount > newIndexCount)
newIndexCount = minNewIndexCount;
void* newIndexes = realloc(indexes, sizeof(Value*) * newIndexCount);
JSON_ASSERT_MESSAGE(newIndexes, "Couldn't realloc.");
indexCount = newIndexCount;
indexes = static_cast<Value**>(newIndexes);
}
virtual void releaseArrayPageIndex(Value** indexes,
ValueInternalArray::PageIndex indexCount) {
if (indexes)
free(indexes);
}
virtual Value* allocateArrayPage() {
return static_cast<Value*>(pagesAllocator_.allocate());
}
virtual void releaseArrayPage(Value* value) {
if (value)
pagesAllocator_.release(value);
}
private:
BatchAllocator<ValueInternalArray, 1> arraysAllocator_;
BatchAllocator<Value, ValueInternalArray::itemsPerPage> pagesAllocator_;
};
#endif // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
static ValueArrayAllocator*& arrayAllocator() {
static DefaultValueArrayAllocator defaultAllocator;
static ValueArrayAllocator* arrayAllocator = &defaultAllocator;
return arrayAllocator;
}
static struct DummyArrayAllocatorInitializer {
DummyArrayAllocatorInitializer() {
arrayAllocator(); // ensure arrayAllocator() statics are initialized before
// main().
}
} dummyArrayAllocatorInitializer;
// //////////////////////////////////////////////////////////////////
// class ValueInternalArray
// //////////////////////////////////////////////////////////////////
bool ValueInternalArray::equals(const IteratorState& x,
const IteratorState& other) {
return x.array_ == other.array_ &&
x.currentItemIndex_ == other.currentItemIndex_ &&
x.currentPageIndex_ == other.currentPageIndex_;
}
void ValueInternalArray::increment(IteratorState& it) {
JSON_ASSERT_MESSAGE(
it.array_ && (it.currentPageIndex_ - it.array_->pages_) * itemsPerPage +
it.currentItemIndex_ !=
it.array_->size_,
"ValueInternalArray::increment(): moving iterator beyond end");
++(it.currentItemIndex_);
if (it.currentItemIndex_ == itemsPerPage) {
it.currentItemIndex_ = 0;
++(it.currentPageIndex_);
}
}
void ValueInternalArray::decrement(IteratorState& it) {
JSON_ASSERT_MESSAGE(
it.array_ && it.currentPageIndex_ == it.array_->pages_ &&
it.currentItemIndex_ == 0,
"ValueInternalArray::decrement(): moving iterator beyond end");
if (it.currentItemIndex_ == 0) {
it.currentItemIndex_ = itemsPerPage - 1;
--(it.currentPageIndex_);
} else {
--(it.currentItemIndex_);
}
}
Value& ValueInternalArray::unsafeDereference(const IteratorState& it) {
return (*(it.currentPageIndex_))[it.currentItemIndex_];
}
Value& ValueInternalArray::dereference(const IteratorState& it) {
JSON_ASSERT_MESSAGE(
it.array_ && (it.currentPageIndex_ - it.array_->pages_) * itemsPerPage +
it.currentItemIndex_ <
it.array_->size_,
"ValueInternalArray::dereference(): dereferencing invalid iterator");
return unsafeDereference(it);
}
void ValueInternalArray::makeBeginIterator(IteratorState& it) const {
it.array_ = const_cast<ValueInternalArray*>(this);
it.currentItemIndex_ = 0;
it.currentPageIndex_ = pages_;
}
void ValueInternalArray::makeIterator(IteratorState& it,
ArrayIndex index) const {
it.array_ = const_cast<ValueInternalArray*>(this);
it.currentItemIndex_ = index % itemsPerPage;
it.currentPageIndex_ = pages_ + index / itemsPerPage;
}
void ValueInternalArray::makeEndIterator(IteratorState& it) const {
makeIterator(it, size_);
}
ValueInternalArray::ValueInternalArray() : pages_(0), size_(0), pageCount_(0) {}
ValueInternalArray::ValueInternalArray(const ValueInternalArray& other)
: pages_(0), size_(other.size_), pageCount_(0) {
PageIndex minNewPages = other.size_ / itemsPerPage;
arrayAllocator()->reallocateArrayPageIndex(pages_, pageCount_, minNewPages);
JSON_ASSERT_MESSAGE(pageCount_ >= minNewPages,
"ValueInternalArray::reserve(): bad reallocation");
IteratorState itOther;
other.makeBeginIterator(itOther);
Value* value;
for (ArrayIndex index = 0; index < size_; ++index, increment(itOther)) {
if (index % itemsPerPage == 0) {
PageIndex pageIndex = index / itemsPerPage;
value = arrayAllocator()->allocateArrayPage();
pages_[pageIndex] = value;
}
new (value) Value(dereference(itOther));
}
}
ValueInternalArray& ValueInternalArray::operator=(ValueInternalArray other) {
swap(other);
return *this;
}
ValueInternalArray::~ValueInternalArray() {
// destroy all constructed items
IteratorState it;
IteratorState itEnd;
makeBeginIterator(it);
makeEndIterator(itEnd);
for (; !equals(it, itEnd); increment(it)) {
Value* value = &dereference(it);
value->~Value();
}
// release all pages
PageIndex lastPageIndex = size_ / itemsPerPage;
for (PageIndex pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex)
arrayAllocator()->releaseArrayPage(pages_[pageIndex]);
// release pages index
arrayAllocator()->releaseArrayPageIndex(pages_, pageCount_);
}
void ValueInternalArray::swap(ValueInternalArray& other) {
Value** tempPages = pages_;
pages_ = other.pages_;
other.pages_ = tempPages;
ArrayIndex tempSize = size_;
size_ = other.size_;
other.size_ = tempSize;
PageIndex tempPageCount = pageCount_;
pageCount_ = other.pageCount_;
other.pageCount_ = tempPageCount;
}
void ValueInternalArray::clear() {
ValueInternalArray dummy;
swap(dummy);
}
void ValueInternalArray::resize(ArrayIndex newSize) {
if (newSize == 0)
clear();
else if (newSize < size_) {
IteratorState it;
IteratorState itEnd;
makeIterator(it, newSize);
makeIterator(itEnd, size_);
for (; !equals(it, itEnd); increment(it)) {
Value* value = &dereference(it);
value->~Value();
}
PageIndex pageIndex = (newSize + itemsPerPage - 1) / itemsPerPage;
PageIndex lastPageIndex = size_ / itemsPerPage;
for (; pageIndex < lastPageIndex; ++pageIndex)
arrayAllocator()->releaseArrayPage(pages_[pageIndex]);
size_ = newSize;
} else if (newSize > size_)
resolveReference(newSize);
}
void ValueInternalArray::makeIndexValid(ArrayIndex index) {
// Need to enlarge page index ?
if (index >= pageCount_ * itemsPerPage) {
PageIndex minNewPages = (index + 1) / itemsPerPage;
arrayAllocator()->reallocateArrayPageIndex(pages_, pageCount_, minNewPages);
JSON_ASSERT_MESSAGE(pageCount_ >= minNewPages,
"ValueInternalArray::reserve(): bad reallocation");
}
// Need to allocate new pages ?
ArrayIndex nextPageIndex = (size_ % itemsPerPage) != 0
? size_ - (size_ % itemsPerPage) + itemsPerPage
: size_;
if (nextPageIndex <= index) {
PageIndex pageIndex = nextPageIndex / itemsPerPage;
PageIndex pageToAllocate = (index - nextPageIndex) / itemsPerPage + 1;
for (; pageToAllocate-- > 0; ++pageIndex)
pages_[pageIndex] = arrayAllocator()->allocateArrayPage();
}
// Initialize all new entries
IteratorState it;
IteratorState itEnd;
makeIterator(it, size_);
size_ = index + 1;
makeIterator(itEnd, size_);
for (; !equals(it, itEnd); increment(it)) {
Value* value = &dereference(it);
new (value) Value(); // Construct a default value using placement new
}
}
Value& ValueInternalArray::resolveReference(ArrayIndex index) {
if (index >= size_)
makeIndexValid(index);
return pages_[index / itemsPerPage][index % itemsPerPage];
}
Value* ValueInternalArray::find(ArrayIndex index) const {
if (index >= size_)
return 0;
return &(pages_[index / itemsPerPage][index % itemsPerPage]);
}
ValueInternalArray::ArrayIndex ValueInternalArray::size() const {
return size_;
}
int ValueInternalArray::distance(const IteratorState& x,
const IteratorState& y) {
return indexOf(y) - indexOf(x);
}
ValueInternalArray::ArrayIndex
ValueInternalArray::indexOf(const IteratorState& iterator) {
if (!iterator.array_)
return ArrayIndex(-1);
return ArrayIndex((iterator.currentPageIndex_ - iterator.array_->pages_) *
itemsPerPage +
iterator.currentItemIndex_);
}
int ValueInternalArray::compare(const ValueInternalArray& other) const {
int sizeDiff(size_ - other.size_);
if (sizeDiff != 0)
return sizeDiff;
for (ArrayIndex index = 0; index < size_; ++index) {
int diff = pages_[index / itemsPerPage][index % itemsPerPage].compare(
other.pages_[index / itemsPerPage][index % itemsPerPage]);
if (diff != 0)
return diff;
}
return 0;
}
} // namespace Json

View File

@@ -1,473 +0,0 @@
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
// included by json_value.cpp
namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueInternalMap
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/** \internal MUST be safely initialized using memset( this, 0,
* sizeof(ValueInternalLink) );
* This optimization is used by the fast allocator.
*/
ValueInternalLink::ValueInternalLink() : previous_(0), next_(0) {}
ValueInternalLink::~ValueInternalLink() {
for (int index = 0; index < itemPerLink; ++index) {
if (!items_[index].isItemAvailable()) {
if (!items_[index].isMemberNameStatic())
free(keys_[index]);
} else
break;
}
}
ValueMapAllocator::~ValueMapAllocator() {}
#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
class DefaultValueMapAllocator : public ValueMapAllocator {
public: // overridden from ValueMapAllocator
virtual ValueInternalMap* newMap() { return new ValueInternalMap(); }
virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) {
return new ValueInternalMap(other);
}
virtual void destructMap(ValueInternalMap* map) { delete map; }
virtual ValueInternalLink* allocateMapBuckets(unsigned int size) {
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets(ValueInternalLink* links) { delete[] links; }
virtual ValueInternalLink* allocateMapLink() {
return new ValueInternalLink();
}
virtual void releaseMapLink(ValueInternalLink* link) { delete link; }
};
#else
/// @todo make this thread-safe (lock when accessign batch allocator)
class DefaultValueMapAllocator : public ValueMapAllocator {
public: // overridden from ValueMapAllocator
virtual ValueInternalMap* newMap() {
ValueInternalMap* map = mapsAllocator_.allocate();
new (map) ValueInternalMap(); // placement new
return map;
}
virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) {
ValueInternalMap* map = mapsAllocator_.allocate();
new (map) ValueInternalMap(other); // placement new
return map;
}
virtual void destructMap(ValueInternalMap* map) {
if (map) {
map->~ValueInternalMap();
mapsAllocator_.release(map);
}
}
virtual ValueInternalLink* allocateMapBuckets(unsigned int size) {
return new ValueInternalLink[size];
}
virtual void releaseMapBuckets(ValueInternalLink* links) { delete[] links; }
virtual ValueInternalLink* allocateMapLink() {
ValueInternalLink* link = linksAllocator_.allocate();
memset(link, 0, sizeof(ValueInternalLink));
return link;
}
virtual void releaseMapLink(ValueInternalLink* link) {
link->~ValueInternalLink();
linksAllocator_.release(link);
}
private:
BatchAllocator<ValueInternalMap, 1> mapsAllocator_;
BatchAllocator<ValueInternalLink, 1> linksAllocator_;
};
#endif
static ValueMapAllocator*& mapAllocator() {
static DefaultValueMapAllocator defaultAllocator;
static ValueMapAllocator* mapAllocator = &defaultAllocator;
return mapAllocator;
}
static struct DummyMapAllocatorInitializer {
DummyMapAllocatorInitializer() {
mapAllocator(); // ensure mapAllocator() statics are initialized before
// main().
}
} dummyMapAllocatorInitializer;
// h(K) = value * K >> w ; with w = 32 & K prime w.r.t. 2^32.
/*
use linked list hash map.
buckets array is a container.
linked list element contains 6 key/values. (memory = (16+4) * 6 + 4 = 124)
value have extra state: valid, available, deleted
*/
ValueInternalMap::ValueInternalMap()
: buckets_(0), tailLink_(0), bucketsSize_(0), itemCount_(0) {}
ValueInternalMap::ValueInternalMap(const ValueInternalMap& other)
: buckets_(0), tailLink_(0), bucketsSize_(0), itemCount_(0) {
reserve(other.itemCount_);
IteratorState it;
IteratorState itEnd;
other.makeBeginIterator(it);
other.makeEndIterator(itEnd);
for (; !equals(it, itEnd); increment(it)) {
bool isStatic;
const char* memberName = key(it, isStatic);
const Value& aValue = value(it);
resolveReference(memberName, isStatic) = aValue;
}
}
ValueInternalMap& ValueInternalMap::operator=(ValueInternalMap other) {
swap(other);
return *this;
}
ValueInternalMap::~ValueInternalMap() {
if (buckets_) {
for (BucketIndex bucketIndex = 0; bucketIndex < bucketsSize_;
++bucketIndex) {
ValueInternalLink* link = buckets_[bucketIndex].next_;
while (link) {
ValueInternalLink* linkToRelease = link;
link = link->next_;
mapAllocator()->releaseMapLink(linkToRelease);
}
}
mapAllocator()->releaseMapBuckets(buckets_);
}
}
void ValueInternalMap::swap(ValueInternalMap& other) {
ValueInternalLink* tempBuckets = buckets_;
buckets_ = other.buckets_;
other.buckets_ = tempBuckets;
ValueInternalLink* tempTailLink = tailLink_;
tailLink_ = other.tailLink_;
other.tailLink_ = tempTailLink;
BucketIndex tempBucketsSize = bucketsSize_;
bucketsSize_ = other.bucketsSize_;
other.bucketsSize_ = tempBucketsSize;
BucketIndex tempItemCount = itemCount_;
itemCount_ = other.itemCount_;
other.itemCount_ = tempItemCount;
}
void ValueInternalMap::clear() {
ValueInternalMap dummy;
swap(dummy);
}
ValueInternalMap::BucketIndex ValueInternalMap::size() const {
return itemCount_;
}
bool ValueInternalMap::reserveDelta(BucketIndex growth) {
return reserve(itemCount_ + growth);
}
bool ValueInternalMap::reserve(BucketIndex newItemCount) {
if (!buckets_ && newItemCount > 0) {
buckets_ = mapAllocator()->allocateMapBuckets(1);
bucketsSize_ = 1;
tailLink_ = &buckets_[0];
}
// BucketIndex idealBucketCount = (newItemCount +
// ValueInternalLink::itemPerLink) / ValueInternalLink::itemPerLink;
return true;
}
const Value* ValueInternalMap::find(const char* key) const {
if (!bucketsSize_)
return 0;
HashKey hashedKey = hash(key);
BucketIndex bucketIndex = hashedKey % bucketsSize_;
for (const ValueInternalLink* current = &buckets_[bucketIndex]; current != 0;
current = current->next_) {
for (BucketIndex index = 0; index < ValueInternalLink::itemPerLink;
++index) {
if (current->items_[index].isItemAvailable())
return 0;
if (strcmp(key, current->keys_[index]) == 0)
return &current->items_[index];
}
}
return 0;
}
Value* ValueInternalMap::find(const char* key) {
const ValueInternalMap* constThis = this;
return const_cast<Value*>(constThis->find(key));
}
Value& ValueInternalMap::resolveReference(const char* key, bool isStatic) {
HashKey hashedKey = hash(key);
if (bucketsSize_) {
BucketIndex bucketIndex = hashedKey % bucketsSize_;
ValueInternalLink** previous = 0;
BucketIndex index;
for (ValueInternalLink* current = &buckets_[bucketIndex]; current != 0;
previous = &current->next_, current = current->next_) {
for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
if (current->items_[index].isItemAvailable())
return setNewItem(key, isStatic, current, index);
if (strcmp(key, current->keys_[index]) == 0)
return current->items_[index];
}
}
}
reserveDelta(1);
return unsafeAdd(key, isStatic, hashedKey);
}
void ValueInternalMap::remove(const char* key) {
HashKey hashedKey = hash(key);
if (!bucketsSize_)
return;
BucketIndex bucketIndex = hashedKey % bucketsSize_;
for (ValueInternalLink* link = &buckets_[bucketIndex]; link != 0;
link = link->next_) {
BucketIndex index;
for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
if (link->items_[index].isItemAvailable())
return;
if (strcmp(key, link->keys_[index]) == 0) {
doActualRemove(link, index, bucketIndex);
return;
}
}
}
}
void ValueInternalMap::doActualRemove(ValueInternalLink* link,
BucketIndex index,
BucketIndex bucketIndex) {
// find last item of the bucket and swap it with the 'removed' one.
// set removed items flags to 'available'.
// if last page only contains 'available' items, then desallocate it (it's
// empty)
ValueInternalLink*& lastLink = getLastLinkInBucket(index);
BucketIndex lastItemIndex = 1; // a link can never be empty, so start at 1
for (; lastItemIndex < ValueInternalLink::itemPerLink;
++lastItemIndex) // may be optimized with dicotomic search
{
if (lastLink->items_[lastItemIndex].isItemAvailable())
break;
}
BucketIndex lastUsedIndex = lastItemIndex - 1;
Value* valueToDelete = &link->items_[index];
Value* valueToPreserve = &lastLink->items_[lastUsedIndex];
if (valueToDelete != valueToPreserve)
valueToDelete->swap(*valueToPreserve);
if (lastUsedIndex == 0) // page is now empty
{ // remove it from bucket linked list and delete it.
ValueInternalLink* linkPreviousToLast = lastLink->previous_;
if (linkPreviousToLast != 0) // can not deleted bucket link.
{
mapAllocator()->releaseMapLink(lastLink);
linkPreviousToLast->next_ = 0;
lastLink = linkPreviousToLast;
}
} else {
Value dummy;
valueToPreserve->swap(dummy); // restore deleted to default Value.
valueToPreserve->setItemUsed(false);
}
--itemCount_;
}
ValueInternalLink*&
ValueInternalMap::getLastLinkInBucket(BucketIndex bucketIndex) {
if (bucketIndex == bucketsSize_ - 1)
return tailLink_;
ValueInternalLink*& previous = buckets_[bucketIndex + 1].previous_;
if (!previous)
previous = &buckets_[bucketIndex];
return previous;
}
Value& ValueInternalMap::setNewItem(const char* key,
bool isStatic,
ValueInternalLink* link,
BucketIndex index) {
char* duplicatedKey = makeMemberName(key);
++itemCount_;
link->keys_[index] = duplicatedKey;
link->items_[index].setItemUsed();
link->items_[index].setMemberNameIsStatic(isStatic);
return link->items_[index]; // items already default constructed.
}
Value&
ValueInternalMap::unsafeAdd(const char* key, bool isStatic, HashKey hashedKey) {
JSON_ASSERT_MESSAGE(bucketsSize_ > 0,
"ValueInternalMap::unsafeAdd(): internal logic error.");
BucketIndex bucketIndex = hashedKey % bucketsSize_;
ValueInternalLink*& previousLink = getLastLinkInBucket(bucketIndex);
ValueInternalLink* link = previousLink;
BucketIndex index;
for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
if (link->items_[index].isItemAvailable())
break;
}
if (index == ValueInternalLink::itemPerLink) // need to add a new page
{
ValueInternalLink* newLink = mapAllocator()->allocateMapLink();
index = 0;
link->next_ = newLink;
previousLink = newLink;
link = newLink;
}
return setNewItem(key, isStatic, link, index);
}
ValueInternalMap::HashKey ValueInternalMap::hash(const char* key) const {
HashKey hash = 0;
while (*key)
hash += *key++ * 37;
return hash;
}
int ValueInternalMap::compare(const ValueInternalMap& other) const {
int sizeDiff(itemCount_ - other.itemCount_);
if (sizeDiff != 0)
return sizeDiff;
// Strict order guaranty is required. Compare all keys FIRST, then compare
// values.
IteratorState it;
IteratorState itEnd;
makeBeginIterator(it);
makeEndIterator(itEnd);
for (; !equals(it, itEnd); increment(it)) {
if (!other.find(key(it)))
return 1;
}
// All keys are equals, let's compare values
makeBeginIterator(it);
for (; !equals(it, itEnd); increment(it)) {
const Value* otherValue = other.find(key(it));
int valueDiff = value(it).compare(*otherValue);
if (valueDiff != 0)
return valueDiff;
}
return 0;
}
void ValueInternalMap::makeBeginIterator(IteratorState& it) const {
it.map_ = const_cast<ValueInternalMap*>(this);
it.bucketIndex_ = 0;
it.itemIndex_ = 0;
it.link_ = buckets_;
}
void ValueInternalMap::makeEndIterator(IteratorState& it) const {
it.map_ = const_cast<ValueInternalMap*>(this);
it.bucketIndex_ = bucketsSize_;
it.itemIndex_ = 0;
it.link_ = 0;
}
bool ValueInternalMap::equals(const IteratorState& x,
const IteratorState& other) {
return x.map_ == other.map_ && x.bucketIndex_ == other.bucketIndex_ &&
x.link_ == other.link_ && x.itemIndex_ == other.itemIndex_;
}
void ValueInternalMap::incrementBucket(IteratorState& iterator) {
++iterator.bucketIndex_;
JSON_ASSERT_MESSAGE(
iterator.bucketIndex_ <= iterator.map_->bucketsSize_,
"ValueInternalMap::increment(): attempting to iterate beyond end.");
if (iterator.bucketIndex_ == iterator.map_->bucketsSize_)
iterator.link_ = 0;
else
iterator.link_ = &(iterator.map_->buckets_[iterator.bucketIndex_]);
iterator.itemIndex_ = 0;
}
void ValueInternalMap::increment(IteratorState& iterator) {
JSON_ASSERT_MESSAGE(iterator.map_,
"Attempting to iterator using invalid iterator.");
++iterator.itemIndex_;
if (iterator.itemIndex_ == ValueInternalLink::itemPerLink) {
JSON_ASSERT_MESSAGE(
iterator.link_ != 0,
"ValueInternalMap::increment(): attempting to iterate beyond end.");
iterator.link_ = iterator.link_->next_;
if (iterator.link_ == 0)
incrementBucket(iterator);
} else if (iterator.link_->items_[iterator.itemIndex_].isItemAvailable()) {
incrementBucket(iterator);
}
}
void ValueInternalMap::decrement(IteratorState& iterator) {
if (iterator.itemIndex_ == 0) {
JSON_ASSERT_MESSAGE(iterator.map_,
"Attempting to iterate using invalid iterator.");
if (iterator.link_ == &iterator.map_->buckets_[iterator.bucketIndex_]) {
JSON_ASSERT_MESSAGE(iterator.bucketIndex_ > 0,
"Attempting to iterate beyond beginning.");
--(iterator.bucketIndex_);
}
iterator.link_ = iterator.link_->previous_;
iterator.itemIndex_ = ValueInternalLink::itemPerLink - 1;
}
}
const char* ValueInternalMap::key(const IteratorState& iterator) {
JSON_ASSERT_MESSAGE(iterator.link_,
"Attempting to iterate using invalid iterator.");
return iterator.link_->keys_[iterator.itemIndex_];
}
const char* ValueInternalMap::key(const IteratorState& iterator,
bool& isStatic) {
JSON_ASSERT_MESSAGE(iterator.link_,
"Attempting to iterate using invalid iterator.");
isStatic = iterator.link_->items_[iterator.itemIndex_].isMemberNameStatic();
return iterator.link_->keys_[iterator.itemIndex_];
}
Value& ValueInternalMap::value(const IteratorState& iterator) {
JSON_ASSERT_MESSAGE(iterator.link_,
"Attempting to iterate using invalid iterator.");
return iterator.link_->items_[iterator.itemIndex_];
}
int ValueInternalMap::distance(const IteratorState& x, const IteratorState& y) {
int offset = 0;
IteratorState it = x;
while (!equals(it, y))
increment(it);
return offset;
}
} // namespace Json

View File

@@ -17,11 +17,27 @@
#include <sstream>
#include <memory>
#include <set>
#include <stdexcept>
#include <limits>
#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
#if defined(_MSC_VER)
#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
#define snprintf sprintf_s
#elif _MSC_VER >= 1900 // VC++ 14.0 and above
#define snprintf std::snprintf
#else
#define snprintf _snprintf
#endif
#elif defined(__ANDROID__) || defined(__QNXNTO__)
#define snprintf snprintf
#elif __cplusplus >= 201103L
#if !defined(__MINGW32__) && !defined(__CYGWIN__)
#define snprintf std::snprintf
#endif
#endif
#if defined(__QNXNTO__)
#define sscanf std::sscanf
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
// Disable warning about strdup being deprecated.
@@ -33,7 +49,7 @@ static int stackDepth_g = 0; // see readValue()
namespace Json {
#if __cplusplus >= 201103L
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
typedef std::unique_ptr<CharReader> CharReaderPtr;
#else
typedef std::auto_ptr<CharReader> CharReaderPtr;
@@ -82,7 +98,8 @@ Reader::Reader(const Features& features)
bool
Reader::parse(const std::string& document, Value& root, bool collectComments) {
document_ = document;
JSONCPP_STRING documentCopy(document.data(), document.data() + document.capacity());
std::swap(documentCopy, document_);
const char* begin = document_.c_str();
const char* end = begin + document_.length();
return parse(begin, end, root, collectComments);
@@ -94,11 +111,11 @@ bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// Since JSONCPP_STRING is reference-counted, this at least does not
// create an extra copy.
std::string doc;
JSONCPP_STRING doc;
std::getline(sin, doc, (char)EOF);
return parse(doc, root, collectComments);
return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
}
bool Reader::parse(const char* beginDoc,
@@ -148,7 +165,7 @@ bool Reader::readValue() {
// But this deprecated class has a security problem: Bad input can
// cause a seg-fault. This seems like a fair, binary-compatible way
// to prevent the problem.
if (stackDepth_g >= stackLimit_g) throw std::runtime_error("Exceeded stackLimit in readValue().");
if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
++stackDepth_g;
Token token;
@@ -200,6 +217,8 @@ bool Reader::readValue() {
}
break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
@@ -209,8 +228,7 @@ bool Reader::readValue() {
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
}
// Else, fall through...
} // Else, fall through...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
@@ -351,9 +369,9 @@ bool Reader::readComment() {
return true;
}
static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
std::string normalized;
normalized.reserve(end - begin);
static JSONCPP_STRING normalizeEOL(Reader::Location begin, Reader::Location end) {
JSONCPP_STRING normalized;
normalized.reserve(static_cast<size_t>(end - begin));
Reader::Location current = begin;
while (current != end) {
char c = *current++;
@@ -373,7 +391,7 @@ static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
void
Reader::addComment(Location begin, Location end, CommentPlacement placement) {
assert(collectComments_);
const std::string& normalized = normalizeEOL(begin, end);
const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != 0);
lastValue_->setComment(normalized, placement);
@@ -412,25 +430,25 @@ void Reader::readNumber() {
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
}
}
bool Reader::readString() {
Char c = 0;
Char c = '\0';
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
@@ -443,7 +461,7 @@ bool Reader::readString() {
bool Reader::readObject(Token& tokenStart) {
Token tokenName;
std::string name;
JSONCPP_STRING name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
@@ -463,7 +481,7 @@ bool Reader::readObject(Token& tokenStart) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
name = numberName.asString();
name = JSONCPP_STRING(numberName.asCString());
} else {
break;
}
@@ -555,7 +573,7 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
++current;
// TODO: Help the compiler do the div and mod at compile time or get rid of them.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(-Value::minLargestInt)
isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
: Value::maxLargestUInt;
Value::LargestUInt threshold = maxIntegerValue / 10;
Value::LargestUInt value = 0;
@@ -563,7 +581,7 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
Value::UInt digit(c - '0');
Value::UInt digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
@@ -576,7 +594,9 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
}
value = value * 10 + digit;
}
if (isNegative)
if (isNegative && value == maxIntegerValue)
decoded = Value::minLargestInt;
else if (isNegative)
decoded = -Value::LargestInt(value);
else if (value <= Value::LargestUInt(Value::maxInt))
decoded = Value::LargestInt(value);
@@ -597,34 +617,10 @@ bool Reader::decodeDouble(Token& token) {
bool Reader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
// Sanity check to avoid buffer overflow exploits.
if (length < 0) {
return addError("Unable to parse token length", token);
}
// Avoid using a string constant for the format control string given to
// sscanf, as this can cause hard to debug crashes on OS X. See here for more
// info:
//
// http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
char format[] = "%lf";
if (length <= bufferSize) {
Char buffer[bufferSize + 1];
memcpy(buffer, token.start_, length);
buffer[length] = 0;
count = sscanf(buffer, format, &value);
} else {
std::string buffer(token.start_, token.end_);
count = sscanf(buffer.c_str(), format, &value);
}
if (count != 1)
return addError("'" + std::string(token.start_, token.end_) +
JSONCPP_STRING buffer(token.start_, token.end_);
JSONCPP_ISTRINGSTREAM is(buffer);
if (!(is >> value))
return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
"' is not a number.",
token);
decoded = value;
@@ -632,7 +628,7 @@ bool Reader::decodeDouble(Token& token, Value& decoded) {
}
bool Reader::decodeString(Token& token) {
std::string decoded_string;
JSONCPP_STRING decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
@@ -642,8 +638,8 @@ bool Reader::decodeString(Token& token) {
return true;
}
bool Reader::decodeString(Token& token, std::string& decoded) {
decoded.reserve(token.end_ - token.start_ - 2);
bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
@@ -727,13 +723,13 @@ bool Reader::decodeUnicodeCodePoint(Token& token,
bool Reader::decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& unicode) {
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.",
token,
current);
unicode = 0;
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
@@ -749,11 +745,12 @@ bool Reader::decodeUnicodeEscapeSequence(Token& token,
token,
current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool
Reader::addError(const std::string& message, Token& token, Location extra) {
Reader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
@@ -763,7 +760,7 @@ Reader::addError(const std::string& message, Token& token, Location extra) {
}
bool Reader::recoverFromError(TokenType skipUntilToken) {
int errorCount = int(errors_.size());
size_t const errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
@@ -775,7 +772,7 @@ bool Reader::recoverFromError(TokenType skipUntilToken) {
return false;
}
bool Reader::addErrorAndRecover(const std::string& message,
bool Reader::addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken) {
addError(message, token);
@@ -813,29 +810,21 @@ void Reader::getLocationLineAndColumn(Location location,
++line;
}
std::string Reader::getLocationLineAndColumn(Location location) const {
JSONCPP_STRING Reader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
#if defined(WINCE)
_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#else
sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#endif
#else
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#endif
return buffer;
}
// Deprecated. Preserved for backward compatibility
std::string Reader::getFormatedErrorMessages() const {
JSONCPP_STRING Reader::getFormatedErrorMessages() const {
return getFormattedErrorMessages();
}
std::string Reader::getFormattedErrorMessages() const {
std::string formattedMessage;
JSONCPP_STRING Reader::getFormattedErrorMessages() const {
JSONCPP_STRING formattedMessage;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
@@ -865,8 +854,8 @@ std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
return allErrors;
}
bool Reader::pushError(const Value& value, const std::string& message) {
size_t length = end_ - begin_;
bool Reader::pushError(const Value& value, const JSONCPP_STRING& message) {
ptrdiff_t const length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length)
return false;
@@ -882,8 +871,8 @@ bool Reader::pushError(const Value& value, const std::string& message) {
return true;
}
bool Reader::pushError(const Value& value, const std::string& message, const Value& extra) {
size_t length = end_ - begin_;
bool Reader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
ptrdiff_t const length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length
|| extra.getOffsetLimit() > length)
@@ -908,34 +897,22 @@ bool Reader::good() const {
class OurFeatures {
public:
static OurFeatures all();
static OurFeatures strictMode();
OurFeatures();
bool allowComments_;
bool strictRoot_;
bool allowDroppedNullPlaceholders_;
bool allowNumericKeys_;
bool allowSingleQuotes_;
bool failIfExtra_;
bool rejectDupKeys_;
bool allowSpecialFloats_;
int stackLimit_;
}; // OurFeatures
// exact copy of Implementation of class Features
// ////////////////////////////////
OurFeatures::OurFeatures()
: allowComments_(true), strictRoot_(false),
allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {}
OurFeatures OurFeatures::all() { return OurFeatures(); }
OurFeatures OurFeatures::strictMode() {
OurFeatures features;
features.allowComments_ = false;
features.strictRoot_ = true;
features.allowDroppedNullPlaceholders_ = false;
features.allowNumericKeys_ = false;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
@@ -945,9 +922,9 @@ public:
typedef char Char;
typedef const Char* Location;
struct StructuredError {
size_t offset_start;
size_t offset_limit;
std::string message;
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
JSONCPP_STRING message;
};
OurReader(OurFeatures const& features);
@@ -955,10 +932,10 @@ public:
const char* endDoc,
Value& root,
bool collectComments = true);
std::string getFormattedErrorMessages() const;
JSONCPP_STRING getFormattedErrorMessages() const;
std::vector<StructuredError> getStructuredErrors() const;
bool pushError(const Value& value, const std::string& message);
bool pushError(const Value& value, const std::string& message, const Value& extra);
bool pushError(const Value& value, const JSONCPP_STRING& message);
bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
bool good() const;
private:
@@ -976,6 +953,9 @@ private:
tokenTrue,
tokenFalse,
tokenNull,
tokenNaN,
tokenPosInf,
tokenNegInf,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
@@ -992,7 +972,7 @@ private:
class ErrorInfo {
public:
Token token_;
std::string message_;
JSONCPP_STRING message_;
Location extra_;
};
@@ -1005,14 +985,15 @@ private:
bool readCStyleComment();
bool readCppStyleComment();
bool readString();
void readNumber();
bool readStringSingleQuote();
bool readNumber(bool checkInf);
bool readValue();
bool readObject(Token& token);
bool readArray(Token& token);
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, std::string& decoded);
bool decodeString(Token& token, JSONCPP_STRING& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token,
@@ -1023,9 +1004,9 @@ private:
Location& current,
Location end,
unsigned int& unicode);
bool addError(const std::string& message, Token& token, Location extra = 0);
bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const std::string& message,
bool addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
@@ -1033,20 +1014,20 @@ private:
Char getNextChar();
void
getLocationLineAndColumn(Location location, int& line, int& column) const;
std::string getLocationLineAndColumn(Location location) const;
JSONCPP_STRING getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
typedef std::stack<Value*> Nodes;
Nodes nodes_;
Errors errors_;
std::string document_;
JSONCPP_STRING document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value* lastValue_;
std::string commentsBefore_;
JSONCPP_STRING commentsBefore_;
int stackDepth_;
OurFeatures const features_;
@@ -1057,7 +1038,9 @@ private:
OurReader::OurReader(OurFeatures const& features)
: errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
lastValue_(), commentsBefore_(), features_(features), collectComments_() {
lastValue_(), commentsBefore_(),
stackDepth_(0),
features_(features), collectComments_() {
}
bool OurReader::parse(const char* beginDoc,
@@ -1085,7 +1068,7 @@ bool OurReader::parse(const char* beginDoc,
Token token;
skipCommentTokens(token);
if (features_.failIfExtra_) {
if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
if ((features_.strictRoot_ || token.type_ != tokenError) && token.type_ != tokenEndOfStream) {
addError("Extra non-whitespace after JSON value.", token);
return false;
}
@@ -1109,7 +1092,7 @@ bool OurReader::parse(const char* beginDoc,
}
bool OurReader::readValue() {
if (stackDepth_ >= features_.stackLimit_) throw std::runtime_error("Exceeded stackLimit in readValue().");
if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
++stackDepth_;
Token token;
skipCommentTokens(token);
@@ -1159,7 +1142,33 @@ bool OurReader::readValue() {
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNaN:
{
Value v(std::numeric_limits<double>::quiet_NaN());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenPosInf:
{
Value v(std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNegInf:
{
Value v(-std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
@@ -1169,8 +1178,7 @@ bool OurReader::readValue() {
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
}
// Else, fall through...
} // else, fall through ...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
@@ -1218,6 +1226,12 @@ bool OurReader::readToken(Token& token) {
token.type_ = tokenString;
ok = readString();
break;
case '\'':
if (features_.allowSingleQuotes_) {
token.type_ = tokenString;
ok = readStringSingleQuote();
break;
} // else continue
case '/':
token.type_ = tokenComment;
ok = readComment();
@@ -1232,9 +1246,16 @@ bool OurReader::readToken(Token& token) {
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
readNumber(false);
break;
case '-':
if (readNumber(true)) {
token.type_ = tokenNumber;
} else {
token.type_ = tokenNegInf;
ok = features_.allowSpecialFloats_ && match("nfinity", 7);
}
break;
case 't':
token.type_ = tokenTrue;
@@ -1248,6 +1269,22 @@ bool OurReader::readToken(Token& token) {
token.type_ = tokenNull;
ok = match("ull", 3);
break;
case 'N':
if (features_.allowSpecialFloats_) {
token.type_ = tokenNaN;
ok = match("aN", 2);
} else {
ok = false;
}
break;
case 'I':
if (features_.allowSpecialFloats_) {
token.type_ = tokenPosInf;
ok = match("nfinity", 7);
} else {
ok = false;
}
break;
case ',':
token.type_ = tokenArraySeparator;
break;
@@ -1314,7 +1351,7 @@ bool OurReader::readComment() {
void
OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
assert(collectComments_);
const std::string& normalized = normalizeEOL(begin, end);
const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != 0);
lastValue_->setComment(normalized, placement);
@@ -1348,28 +1385,32 @@ bool OurReader::readCppStyleComment() {
return true;
}
void OurReader::readNumber() {
bool OurReader::readNumber(bool checkInf) {
const char *p = current_;
if (checkInf && p != end_ && *p == 'I') {
current_ = ++p;
return false;
}
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : 0;
c = (current_ = p) < end_ ? *p++ : '\0';
}
return true;
}
bool OurReader::readString() {
Char c = 0;
while (current_ != end_) {
@@ -1382,9 +1423,22 @@ bool OurReader::readString() {
return c == '"';
}
bool OurReader::readStringSingleQuote() {
Char c = 0;
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '\'')
break;
}
return c == '\'';
}
bool OurReader::readObject(Token& tokenStart) {
Token tokenName;
std::string name;
JSONCPP_STRING name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
@@ -1414,6 +1468,12 @@ bool OurReader::readObject(Token& tokenStart) {
return addErrorAndRecover(
"Missing ':' after object member name", colon, tokenObjectEnd);
}
if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
JSONCPP_STRING msg = "Duplicate key: '" + name + "'";
return addErrorAndRecover(
msg, tokenName, tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
bool ok = readValue();
@@ -1504,7 +1564,7 @@ bool OurReader::decodeNumber(Token& token, Value& decoded) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
Value::UInt digit(c - '0');
Value::UInt digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
@@ -1540,12 +1600,13 @@ bool OurReader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
ptrdiff_t const length = token.end_ - token.start_;
// Sanity check to avoid buffer overflow exploits.
if (length < 0) {
return addError("Unable to parse token length", token);
}
size_t const ulength = static_cast<size_t>(length);
// Avoid using a string constant for the format control string given to
// sscanf, as this can cause hard to debug crashes on OS X. See here for more
@@ -1556,16 +1617,17 @@ bool OurReader::decodeDouble(Token& token, Value& decoded) {
if (length <= bufferSize) {
Char buffer[bufferSize + 1];
memcpy(buffer, token.start_, length);
memcpy(buffer, token.start_, ulength);
buffer[length] = 0;
fixNumericLocaleInput(buffer, buffer + length);
count = sscanf(buffer, format, &value);
} else {
std::string buffer(token.start_, token.end_);
JSONCPP_STRING buffer(token.start_, token.end_);
count = sscanf(buffer.c_str(), format, &value);
}
if (count != 1)
return addError("'" + std::string(token.start_, token.end_) +
return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
"' is not a number.",
token);
decoded = value;
@@ -1573,7 +1635,7 @@ bool OurReader::decodeDouble(Token& token, Value& decoded) {
}
bool OurReader::decodeString(Token& token) {
std::string decoded_string;
JSONCPP_STRING decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
@@ -1583,8 +1645,8 @@ bool OurReader::decodeString(Token& token) {
return true;
}
bool OurReader::decodeString(Token& token, std::string& decoded) {
decoded.reserve(token.end_ - token.start_ - 2);
bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
@@ -1668,13 +1730,13 @@ bool OurReader::decodeUnicodeCodePoint(Token& token,
bool OurReader::decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& unicode) {
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.",
token,
current);
unicode = 0;
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
@@ -1690,11 +1752,12 @@ bool OurReader::decodeUnicodeEscapeSequence(Token& token,
token,
current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool
OurReader::addError(const std::string& message, Token& token, Location extra) {
OurReader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
@@ -1704,7 +1767,7 @@ OurReader::addError(const std::string& message, Token& token, Location extra) {
}
bool OurReader::recoverFromError(TokenType skipUntilToken) {
int errorCount = int(errors_.size());
size_t errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
@@ -1716,7 +1779,7 @@ bool OurReader::recoverFromError(TokenType skipUntilToken) {
return false;
}
bool OurReader::addErrorAndRecover(const std::string& message,
bool OurReader::addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken) {
addError(message, token);
@@ -1754,24 +1817,16 @@ void OurReader::getLocationLineAndColumn(Location location,
++line;
}
std::string OurReader::getLocationLineAndColumn(Location location) const {
JSONCPP_STRING OurReader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
#if defined(WINCE)
_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#else
sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#endif
#else
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#endif
return buffer;
}
std::string OurReader::getFormattedErrorMessages() const {
std::string formattedMessage;
JSONCPP_STRING OurReader::getFormattedErrorMessages() const {
JSONCPP_STRING formattedMessage;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
@@ -1801,8 +1856,8 @@ std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
return allErrors;
}
bool OurReader::pushError(const Value& value, const std::string& message) {
size_t length = end_ - begin_;
bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message) {
ptrdiff_t length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length)
return false;
@@ -1818,8 +1873,8 @@ bool OurReader::pushError(const Value& value, const std::string& message) {
return true;
}
bool OurReader::pushError(const Value& value, const std::string& message, const Value& extra) {
size_t length = end_ - begin_;
bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
ptrdiff_t length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length
|| extra.getOffsetLimit() > length)
@@ -1851,9 +1906,9 @@ public:
: collectComments_(collectComments)
, reader_(features)
{}
virtual bool parse(
bool parse(
char const* beginDoc, char const* endDoc,
Value* root, std::string* errs) {
Value* root, JSONCPP_STRING* errs) JSONCPP_OVERRIDE {
bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
if (errs) {
*errs = reader_.getFormattedErrorMessages();
@@ -1876,11 +1931,14 @@ CharReader* CharReaderBuilder::newCharReader() const
features.strictRoot_ = settings_["strictRoot"].asBool();
features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
features.stackLimit_ = settings_["stackLimit"].asInt();
features.failIfExtra_ = settings_["failIfExtra"].asBool();
features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
return new OurCharReader(collectComments, features);
}
static void getValidReaderKeys(std::set<std::string>* valid_keys)
static void getValidReaderKeys(std::set<JSONCPP_STRING>* valid_keys)
{
valid_keys->clear();
valid_keys->insert("collectComments");
@@ -1888,26 +1946,32 @@ static void getValidReaderKeys(std::set<std::string>* valid_keys)
valid_keys->insert("strictRoot");
valid_keys->insert("allowDroppedNullPlaceholders");
valid_keys->insert("allowNumericKeys");
valid_keys->insert("allowSingleQuotes");
valid_keys->insert("stackLimit");
valid_keys->insert("failIfExtra");
valid_keys->insert("rejectDupKeys");
valid_keys->insert("allowSpecialFloats");
}
bool CharReaderBuilder::validate(Json::Value* invalid) const
{
Json::Value my_invalid;
if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
Json::Value& inv = *invalid;
bool valid = true;
std::set<std::string> valid_keys;
std::set<JSONCPP_STRING> valid_keys;
getValidReaderKeys(&valid_keys);
Value::Members keys = settings_.getMemberNames();
size_t n = keys.size();
for (size_t i = 0; i < n; ++i) {
std::string const& key = keys[i];
JSONCPP_STRING const& key = keys[i];
if (valid_keys.find(key) == valid_keys.end()) {
inv[key] = settings_[key];
}
}
return valid;
return 0u == inv.size();
}
Value& CharReaderBuilder::operator[](JSONCPP_STRING key)
{
return settings_[key];
}
// static
void CharReaderBuilder::strictMode(Json::Value* settings)
@@ -1917,7 +1981,11 @@ void CharReaderBuilder::strictMode(Json::Value* settings)
(*settings)["strictRoot"] = true;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = true;
(*settings)["rejectDupKeys"] = true;
(*settings)["allowSpecialFloats"] = false;
//! [CharReaderBuilderStrictMode]
}
// static
@@ -1929,8 +1997,11 @@ void CharReaderBuilder::setDefaults(Json::Value* settings)
(*settings)["strictRoot"] = false;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = false;
(*settings)["rejectDupKeys"] = false;
(*settings)["allowSpecialFloats"] = false;
//! [CharReaderBuilderDefaults]
}
@@ -1938,12 +2009,12 @@ void CharReaderBuilder::setDefaults(Json::Value* settings)
// global functions
bool parseFromStream(
CharReader::Factory const& fact, std::istream& sin,
Value* root, std::string* errs)
CharReader::Factory const& fact, JSONCPP_ISTREAM& sin,
Value* root, JSONCPP_STRING* errs)
{
std::ostringstream ssin;
JSONCPP_OSTRINGSTREAM ssin;
ssin << sin.rdbuf();
std::string doc = ssin.str();
JSONCPP_STRING doc = ssin.str();
char const* begin = doc.data();
char const* end = begin + doc.size();
// Note that we do not actually need a null-terminator.
@@ -1951,16 +2022,16 @@ bool parseFromStream(
return reader->parse(begin, end, root, errs);
}
std::istream& operator>>(std::istream& sin, Value& root) {
JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM& sin, Value& root) {
CharReaderBuilder b;
std::string errs;
JSONCPP_STRING errs;
bool ok = parseFromStream(b, sin, &root, &errs);
if (!ok) {
fprintf(stderr,
"Error from reader: %s",
errs.c_str());
JSON_FAIL_MESSAGE("reader error");
throwRuntimeError(errs);
}
return sin;
}

View File

@@ -5,6 +5,7 @@
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#include <clocale>
/* This header provides common string manipulation support, such as UTF-8,
* portable conversion from/to string...
@@ -14,9 +15,29 @@
namespace Json {
/// Fallback for decimal_point on android, where the lconv is an empty struct.
template<typename Lconv, bool=(sizeof(Lconv) >= sizeof(char*))>
struct Locale {
static char decimalPoint() {
return '\0';
}
};
/// Return decimal_point for the current locale.
template<typename Lconv>
struct Locale<Lconv, true> {
static char decimalPoint() {
Lconv* lc = localeconv();
if (lc == NULL) {
return '\0';
}
return *(lc->decimal_point);
}
};
/// Converts a unicode code-point to UTF-8.
static inline std::string codePointToUTF8(unsigned int cp) {
std::string result;
static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) {
JSONCPP_STRING result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
@@ -30,8 +51,8 @@ static inline std::string codePointToUTF8(unsigned int cp) {
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
@@ -43,7 +64,7 @@ static inline std::string codePointToUTF8(unsigned int cp) {
return result;
}
/// Returns true if ch is a control character (in range [0,32[).
/// Returns true if ch is a control character (in range [1,31]).
static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
enum {
@@ -63,7 +84,7 @@ typedef char UIntToStringBuffer[uintToStringBufferSize];
static inline void uintToString(LargestUInt value, char*& current) {
*--current = 0;
do {
*--current = char(value % 10) + '0';
*--current = static_cast<char>(value % 10U + static_cast<unsigned>('0'));
value /= 10;
} while (value != 0);
}
@@ -82,6 +103,18 @@ static inline void fixNumericLocale(char* begin, char* end) {
}
}
static inline void fixNumericLocaleInput(char* begin, char* end) {
char decimalPoint = Locale<struct lconv>::decimalPoint();
if (decimalPoint != '\0' && decimalPoint != '.') {
while (begin < end) {
if (*begin == '.') {
*begin = decimalPoint;
}
++begin;
}
}
}
} // namespace Json {
#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED

File diff suppressed because it is too large Load Diff

View File

@@ -16,66 +16,27 @@ namespace Json {
// //////////////////////////////////////////////////////////////////
ValueIteratorBase::ValueIteratorBase()
#ifndef JSON_VALUE_USE_INTERNAL_MAP
: current_(), isNull_(true) {
}
#else
: isArray_(true), isNull_(true) {
iterator_.array_ = ValueInternalArray::IteratorState();
}
#endif
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIteratorBase::ValueIteratorBase(
const Value::ObjectValues::iterator& current)
: current_(current), isNull_(false) {}
#else
ValueIteratorBase::ValueIteratorBase(
const ValueInternalArray::IteratorState& state)
: isArray_(true) {
iterator_.array_ = state;
}
ValueIteratorBase::ValueIteratorBase(
const ValueInternalMap::IteratorState& state)
: isArray_(false) {
iterator_.map_ = state;
}
#endif
Value& ValueIteratorBase::deref() const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
return current_->second;
#else
if (isArray_)
return ValueInternalArray::dereference(iterator_.array_);
return ValueInternalMap::value(iterator_.map_);
#endif
}
void ValueIteratorBase::increment() {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
++current_;
#else
if (isArray_)
ValueInternalArray::increment(iterator_.array_);
ValueInternalMap::increment(iterator_.map_);
#endif
}
void ValueIteratorBase::decrement() {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
--current_;
#else
if (isArray_)
ValueInternalArray::decrement(iterator_.array_);
ValueInternalMap::decrement(iterator_.map_);
#endif
}
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance(const SelfType& other) const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
#ifdef JSON_USE_CPPTL_SMALLMAP
return other.current_ - current_;
#else
@@ -100,80 +61,58 @@ ValueIteratorBase::computeDistance(const SelfType& other) const {
}
return myDistance;
#endif
#else
if (isArray_)
return ValueInternalArray::distance(iterator_.array_,
other.iterator_.array_);
return ValueInternalMap::distance(iterator_.map_, other.iterator_.map_);
#endif
}
bool ValueIteratorBase::isEqual(const SelfType& other) const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
if (isNull_) {
return other.isNull_;
}
return current_ == other.current_;
#else
if (isArray_)
return ValueInternalArray::equals(iterator_.array_, other.iterator_.array_);
return ValueInternalMap::equals(iterator_.map_, other.iterator_.map_);
#endif
}
void ValueIteratorBase::copy(const SelfType& other) {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
current_ = other.current_;
isNull_ = other.isNull_;
#else
if (isArray_)
iterator_.array_ = other.iterator_.array_;
iterator_.map_ = other.iterator_.map_;
#endif
}
Value ValueIteratorBase::key() const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
if (czstring.c_str()) {
if (czstring.data()) {
if (czstring.isStaticString())
return Value(StaticString(czstring.c_str()));
return Value(czstring.c_str());
return Value(StaticString(czstring.data()));
return Value(czstring.data(), czstring.data() + czstring.length());
}
return Value(czstring.index());
#else
if (isArray_)
return Value(ValueInternalArray::indexOf(iterator_.array_));
bool isStatic;
const char* memberName = ValueInternalMap::key(iterator_.map_, isStatic);
if (isStatic)
return Value(StaticString(memberName));
return Value(memberName);
#endif
}
UInt ValueIteratorBase::index() const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
if (!czstring.c_str())
if (!czstring.data())
return czstring.index();
return Value::UInt(-1);
#else
if (isArray_)
return Value::UInt(ValueInternalArray::indexOf(iterator_.array_));
return Value::UInt(-1);
#endif
}
const char* ValueIteratorBase::memberName() const {
#ifndef JSON_VALUE_USE_INTERNAL_MAP
const char* name = (*current_).first.c_str();
return name ? name : "";
#else
if (!isArray_)
return ValueInternalMap::key(iterator_.map_);
return "";
#endif
JSONCPP_STRING ValueIteratorBase::name() const {
char const* keey;
char const* end;
keey = memberName(&end);
if (!keey) return JSONCPP_STRING();
return JSONCPP_STRING(keey, end);
}
char const* ValueIteratorBase::memberName() const {
const char* cname = (*current_).first.data();
return cname ? cname : "";
}
char const* ValueIteratorBase::memberName(char const** end) const {
const char* cname = (*current_).first.data();
if (!cname) {
*end = NULL;
return NULL;
}
*end = cname + (*current_).first.length();
return cname;
}
// //////////////////////////////////////////////////////////////////
@@ -186,19 +125,12 @@ const char* ValueIteratorBase::memberName() const {
ValueConstIterator::ValueConstIterator() {}
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueConstIterator::ValueConstIterator(
const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
#else
ValueConstIterator::ValueConstIterator(
const ValueInternalArray::IteratorState& state)
: ValueIteratorBase(state) {}
ValueConstIterator::ValueConstIterator(
const ValueInternalMap::IteratorState& state)
: ValueIteratorBase(state) {}
#endif
ValueConstIterator::ValueConstIterator(ValueIterator const& other)
: ValueIteratorBase(other) {}
ValueConstIterator& ValueConstIterator::
operator=(const ValueIteratorBase& other) {
@@ -216,19 +148,13 @@ operator=(const ValueIteratorBase& other) {
ValueIterator::ValueIterator() {}
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
#else
ValueIterator::ValueIterator(const ValueInternalArray::IteratorState& state)
: ValueIteratorBase(state) {}
ValueIterator::ValueIterator(const ValueInternalMap::IteratorState& state)
: ValueIteratorBase(state) {}
#endif
ValueIterator::ValueIterator(const ValueConstIterator& other)
: ValueIteratorBase(other) {}
: ValueIteratorBase(other) {
throwRuntimeError("ConstIterator to Iterator should never be allowed.");
}
ValueIterator::ValueIterator(const ValueIterator& other)
: ValueIteratorBase(other) {}

View File

@@ -12,13 +12,57 @@
#include <sstream>
#include <utility>
#include <set>
#include <stdexcept>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <cassert>
#include <cstring>
#include <cstdio>
#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
#include <float.h>
#define isfinite _finite
#elif defined(__sun) && defined(__SVR4) //Solaris
#if !defined(isfinite)
#include <ieeefp.h>
#define isfinite finite
#endif
#elif defined(_AIX)
#if !defined(isfinite)
#include <math.h>
#define isfinite finite
#endif
#elif defined(__hpux)
#if !defined(isfinite)
#if defined(__ia64) && !defined(finite)
#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
_Isfinitef(x) : _IsFinite(x)))
#else
#include <math.h>
#define isfinite finite
#endif
#endif
#else
#include <cmath>
#if !(defined(__QNXNTO__)) // QNX already defines isfinite
#define isfinite std::isfinite
#endif
#endif
#if defined(_MSC_VER)
#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
#define snprintf sprintf_s
#elif _MSC_VER >= 1900 // VC++ 14.0 and above
#define snprintf std::snprintf
#else
#define snprintf _snprintf
#endif
#elif defined(__ANDROID__) || defined(__QNXNTO__)
#define snprintf snprintf
#elif __cplusplus >= 201103L
#if !defined(__MINGW32__) && !defined(__CYGWIN__)
#define snprintf std::snprintf
#endif
#endif
#if defined(__BORLANDC__)
#include <float.h>
#define isfinite _finite
#define snprintf _snprintf
@@ -29,14 +73,9 @@
#pragma warning(disable : 4996)
#endif
#if defined(__sun) && defined(__SVR4) //Solaris
#include <ieeefp.h>
#define isfinite finite
#endif
namespace Json {
#if __cplusplus >= 201103L
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
#else
typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
@@ -50,20 +89,33 @@ static bool containsControlCharacter(const char* str) {
return false;
}
std::string valueToString(LargestInt value) {
static bool containsControlCharacter0(const char* str, unsigned len) {
char const* end = str + len;
while (end != str) {
if (isControlCharacter(*str) || 0==*str)
return true;
++str;
}
return false;
}
JSONCPP_STRING valueToString(LargestInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
bool isNegative = value < 0;
if (isNegative)
value = -value;
uintToString(LargestUInt(value), current);
if (isNegative)
if (value == Value::minLargestInt) {
uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
*--current = '-';
} else if (value < 0) {
uintToString(LargestUInt(-value), current);
*--current = '-';
} else {
uintToString(LargestUInt(value), current);
}
assert(current >= buffer);
return current;
}
std::string valueToString(LargestUInt value) {
JSONCPP_STRING valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
@@ -73,68 +125,65 @@ std::string valueToString(LargestUInt value) {
#if defined(JSON_HAS_INT64)
std::string valueToString(Int value) {
JSONCPP_STRING valueToString(Int value) {
return valueToString(LargestInt(value));
}
std::string valueToString(UInt value) {
JSONCPP_STRING valueToString(UInt value) {
return valueToString(LargestUInt(value));
}
#endif // # if defined(JSON_HAS_INT64)
std::string valueToString(double value) {
namespace {
JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) {
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
int len = -1;
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with
// visual studio 2005 to
// avoid warning.
#if defined(WINCE)
len = _snprintf(buffer, sizeof(buffer), "%.17g", value);
#else
len = sprintf_s(buffer, sizeof(buffer), "%.17g", value);
#endif
#else
char formatString[6];
sprintf(formatString, "%%.%dg", precision);
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), "%.17g", value);
len = snprintf(buffer, sizeof(buffer), formatString, value);
} else {
// IEEE standard states that NaN values will not compare to themselves
if (value != value) {
len = snprintf(buffer, sizeof(buffer), "null");
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
} else if (value < 0) {
len = snprintf(buffer, sizeof(buffer), "-1e+9999");
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
} else {
len = snprintf(buffer, sizeof(buffer), "1e+9999");
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
}
// For those, we do not need to call fixNumLoc, but it is fast.
}
#endif
assert(len >= 0);
fixNumericLocale(buffer, buffer + len);
return buffer;
}
}
std::string valueToString(bool value) { return value ? "true" : "false"; }
JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
std::string valueToQuotedString(const char* value) {
JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; }
JSONCPP_STRING valueToQuotedString(const char* value) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
!containsControlCharacter(value))
return std::string("\"") + value + "\"";
return JSONCPP_STRING("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to std::string is not efficient, but this should be rare.
// Appending to JSONCPP_STRING is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
std::string::size_type maxsize =
JSONCPP_STRING::size_type maxsize =
strlen(value) * 2 + 3; // allescaped+quotes+NULL
std::string result;
JSONCPP_STRING result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
for (const char* c = value; *c != 0; ++c) {
@@ -170,7 +219,85 @@ std::string valueToQuotedString(const char* value) {
// sequence from occurring.
default:
if (isControlCharacter(*c)) {
std::ostringstream oss;
JSONCPP_OSTRINGSTREAM oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
} else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
static char const* strnpbrk(char const* s, char const* accept, size_t n) {
assert((s || !n) && accept);
char const* const end = s + n;
for (char const* cur = s; cur < end; ++cur) {
int const c = *cur;
for (char const* a = accept; *a; ++a) {
if (*a == c) {
return cur;
}
}
}
return NULL;
}
static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
!containsControlCharacter0(value, length))
return JSONCPP_STRING("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to JSONCPP_STRING is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
JSONCPP_STRING::size_type maxsize =
length * 2 + 3; // allescaped+quotes+NULL
JSONCPP_STRING result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
for (const char* c = value; c != end; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.)
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if ((isControlCharacter(*c)) || (*c == 0)) {
JSONCPP_OSTRINGSTREAM oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
@@ -201,7 +328,7 @@ void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
std::string FastWriter::write(const Value& root) {
JSONCPP_STRING FastWriter::write(const Value& root) {
document_ = "";
writeValue(root);
if (!omitEndingLineFeed_)
@@ -225,15 +352,21 @@ void FastWriter::writeValue(const Value& value) {
document_ += valueToString(value.asDouble());
break;
case stringValue:
document_ += valueToQuotedString(value.asCString());
{
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
break;
}
case booleanValue:
document_ += valueToString(value.asBool());
break;
case arrayValue: {
document_ += '[';
int size = value.size();
for (int index = 0; index < size; ++index) {
ArrayIndex size = value.size();
for (ArrayIndex index = 0; index < size; ++index) {
if (index > 0)
document_ += ',';
writeValue(value[index]);
@@ -245,10 +378,10 @@ void FastWriter::writeValue(const Value& value) {
document_ += '{';
for (Value::Members::iterator it = members.begin(); it != members.end();
++it) {
const std::string& name = *it;
const JSONCPP_STRING& name = *it;
if (it != members.begin())
document_ += ',';
document_ += valueToQuotedString(name.c_str());
document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
document_ += yamlCompatiblityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
@@ -263,7 +396,7 @@ void FastWriter::writeValue(const Value& value) {
StyledWriter::StyledWriter()
: rightMargin_(74), indentSize_(3), addChildValues_() {}
std::string StyledWriter::write(const Value& root) {
JSONCPP_STRING StyledWriter::write(const Value& root) {
document_ = "";
addChildValues_ = false;
indentString_ = "";
@@ -289,8 +422,15 @@ void StyledWriter::writeValue(const Value& value) {
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
pushValue(valueToQuotedString(value.asCString()));
{
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
@@ -306,7 +446,7 @@ void StyledWriter::writeValue(const Value& value) {
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const std::string& name = *it;
const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -370,26 +510,25 @@ void StyledWriter::writeArrayValue(const Value& value) {
}
bool StyledWriter::isMultineArray(const Value& value) {
int size = value.size();
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
@@ -397,7 +536,7 @@ bool StyledWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
void StyledWriter::pushValue(const std::string& value) {
void StyledWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -415,15 +554,15 @@ void StyledWriter::writeIndent() {
document_ += indentString_;
}
void StyledWriter::writeWithIndent(const std::string& value) {
void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) {
writeIndent();
document_ += value;
}
void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); }
void StyledWriter::unindent() {
assert(int(indentString_.size()) >= indentSize_);
assert(indentString_.size() >= indentSize_);
indentString_.resize(indentString_.size() - indentSize_);
}
@@ -433,8 +572,8 @@ void StyledWriter::writeCommentBeforeValue(const Value& root) {
document_ += "\n";
writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
document_ += *iter;
if (*iter == '\n' &&
@@ -467,11 +606,11 @@ bool StyledWriter::hasCommentForValue(const Value& value) {
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
StyledStreamWriter::StyledStreamWriter(std::string indentation)
StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation)
: document_(NULL), rightMargin_(74), indentation_(indentation),
addChildValues_() {}
void StyledStreamWriter::write(std::ostream& out, const Value& root) {
void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_ = "";
@@ -500,8 +639,15 @@ void StyledStreamWriter::writeValue(const Value& value) {
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
pushValue(valueToQuotedString(value.asCString()));
{
// Is NULL possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
@@ -517,7 +663,7 @@ void StyledStreamWriter::writeValue(const Value& value) {
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const std::string& name = *it;
const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -583,26 +729,25 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
}
bool StyledStreamWriter::isMultineArray(const Value& value) {
int size = value.size();
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
@@ -610,7 +755,7 @@ bool StyledStreamWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
void StyledStreamWriter::pushValue(const std::string& value) {
void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -625,7 +770,7 @@ void StyledStreamWriter::writeIndent() {
*document_ << '\n' << indentString_;
}
void StyledStreamWriter::writeWithIndent(const std::string& value) {
void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) {
if (!indented_) writeIndent();
*document_ << value;
indented_ = false;
@@ -643,8 +788,8 @@ void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
return;
if (!indented_) writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*document_ << *iter;
if (*iter == '\n' &&
@@ -689,44 +834,50 @@ struct CommentStyle {
struct BuiltStyledStreamWriter : public StreamWriter
{
BuiltStyledStreamWriter(
std::string const& indentation,
JSONCPP_STRING const& indentation,
CommentStyle::Enum cs,
std::string const& colonSymbol,
std::string const& nullSymbol,
std::string const& endingLineFeedSymbol);
virtual int write(Value const& root, std::ostream* sout);
JSONCPP_STRING const& colonSymbol,
JSONCPP_STRING const& nullSymbol,
JSONCPP_STRING const& endingLineFeedSymbol,
bool useSpecialFloats,
unsigned int precision);
int write(Value const& root, JSONCPP_OSTREAM* sout) JSONCPP_OVERRIDE;
private:
void writeValue(Value const& value);
void writeArrayValue(Value const& value);
bool isMultineArray(Value const& value);
void pushValue(std::string const& value);
void pushValue(JSONCPP_STRING const& value);
void writeIndent();
void writeWithIndent(std::string const& value);
void writeWithIndent(JSONCPP_STRING const& value);
void indent();
void unindent();
void writeCommentBeforeValue(Value const& root);
void writeCommentAfterValueOnSameLine(Value const& root);
static bool hasCommentForValue(const Value& value);
typedef std::vector<std::string> ChildValues;
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
std::string indentString_;
int rightMargin_;
std::string indentation_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
JSONCPP_STRING indentation_;
CommentStyle::Enum cs_;
std::string colonSymbol_;
std::string nullSymbol_;
std::string endingLineFeedSymbol_;
JSONCPP_STRING colonSymbol_;
JSONCPP_STRING nullSymbol_;
JSONCPP_STRING endingLineFeedSymbol_;
bool addChildValues_ : 1;
bool indented_ : 1;
bool useSpecialFloats_ : 1;
unsigned int precision_;
};
BuiltStyledStreamWriter::BuiltStyledStreamWriter(
std::string const& indentation,
JSONCPP_STRING const& indentation,
CommentStyle::Enum cs,
std::string const& colonSymbol,
std::string const& nullSymbol,
std::string const& endingLineFeedSymbol)
JSONCPP_STRING const& colonSymbol,
JSONCPP_STRING const& nullSymbol,
JSONCPP_STRING const& endingLineFeedSymbol,
bool useSpecialFloats,
unsigned int precision)
: rightMargin_(74)
, indentation_(indentation)
, cs_(cs)
@@ -735,9 +886,11 @@ BuiltStyledStreamWriter::BuiltStyledStreamWriter(
, endingLineFeedSymbol_(endingLineFeedSymbol)
, addChildValues_(false)
, indented_(false)
, useSpecialFloats_(useSpecialFloats)
, precision_(precision)
{
}
int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
int BuiltStyledStreamWriter::write(Value const& root, JSONCPP_OSTREAM* sout)
{
sout_ = sout;
addChildValues_ = false;
@@ -764,11 +917,18 @@ void BuiltStyledStreamWriter::writeValue(Value const& value) {
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
break;
case stringValue:
pushValue(valueToQuotedString(value.asCString()));
{
// Is NULL is possible for value.string_? No.
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
@@ -784,10 +944,10 @@ void BuiltStyledStreamWriter::writeValue(Value const& value) {
indent();
Value::Members::iterator it = members.begin();
for (;;) {
std::string const& name = *it;
JSONCPP_STRING const& name = *it;
Value const& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
*sout_ << colonSymbol_;
writeValue(childValue);
if (++it == members.end()) {
@@ -842,7 +1002,7 @@ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
if (!indentation_.empty()) *sout_ << " ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*sout_ << ", ";
*sout_ << ((!indentation_.empty()) ? ", " : ",");
*sout_ << childValues_[index];
}
if (!indentation_.empty()) *sout_ << " ";
@@ -852,26 +1012,25 @@ void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
}
bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
int size = value.size();
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (int index = 0; index < size && !isMultiLine; ++index) {
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
Value const& childValue = value[index];
isMultiLine =
isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (int index = 0; index < size; ++index) {
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += int(childValues_[index].length());
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
@@ -879,7 +1038,7 @@ bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
return isMultiLine;
}
void BuiltStyledStreamWriter::pushValue(std::string const& value) {
void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -898,7 +1057,7 @@ void BuiltStyledStreamWriter::writeIndent() {
}
}
void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) {
if (!indented_) writeIndent();
*sout_ << value;
indented_ = false;
@@ -917,8 +1076,8 @@ void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
return;
if (!indented_) writeIndent();
const std::string& comment = root.getComment(commentBefore);
std::string::const_iterator iter = comment.begin();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*sout_ << *iter;
if (*iter == '\n' &&
@@ -968,58 +1127,66 @@ StreamWriterBuilder::~StreamWriterBuilder()
{}
StreamWriter* StreamWriterBuilder::newStreamWriter() const
{
std::string indentation = settings_["indentation"].asString();
std::string cs_str = settings_["commentStyle"].asString();
JSONCPP_STRING indentation = settings_["indentation"].asString();
JSONCPP_STRING cs_str = settings_["commentStyle"].asString();
bool eyc = settings_["enableYAMLCompatibility"].asBool();
bool dnp = settings_["dropNullPlaceholders"].asBool();
bool usf = settings_["useSpecialFloats"].asBool();
unsigned int pre = settings_["precision"].asUInt();
CommentStyle::Enum cs = CommentStyle::All;
if (cs_str == "All") {
cs = CommentStyle::All;
} else if (cs_str == "None") {
cs = CommentStyle::None;
} else {
throw std::runtime_error("commentStyle must be 'All' or 'None'");
throwRuntimeError("commentStyle must be 'All' or 'None'");
}
std::string colonSymbol = " : ";
JSONCPP_STRING colonSymbol = " : ";
if (eyc) {
colonSymbol = ": ";
} else if (indentation.empty()) {
colonSymbol = ":";
}
std::string nullSymbol = "null";
JSONCPP_STRING nullSymbol = "null";
if (dnp) {
nullSymbol = "";
}
std::string endingLineFeedSymbol = "";
if (pre > 17) pre = 17;
JSONCPP_STRING endingLineFeedSymbol = "";
return new BuiltStyledStreamWriter(
indentation, cs,
colonSymbol, nullSymbol, endingLineFeedSymbol);
colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
}
static void getValidWriterKeys(std::set<std::string>* valid_keys)
static void getValidWriterKeys(std::set<JSONCPP_STRING>* valid_keys)
{
valid_keys->clear();
valid_keys->insert("indentation");
valid_keys->insert("commentStyle");
valid_keys->insert("enableYAMLCompatibility");
valid_keys->insert("dropNullPlaceholders");
valid_keys->insert("useSpecialFloats");
valid_keys->insert("precision");
}
bool StreamWriterBuilder::validate(Json::Value* invalid) const
{
Json::Value my_invalid;
if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
Json::Value& inv = *invalid;
bool valid = true;
std::set<std::string> valid_keys;
std::set<JSONCPP_STRING> valid_keys;
getValidWriterKeys(&valid_keys);
Value::Members keys = settings_.getMemberNames();
size_t n = keys.size();
for (size_t i = 0; i < n; ++i) {
std::string const& key = keys[i];
JSONCPP_STRING const& key = keys[i];
if (valid_keys.find(key) == valid_keys.end()) {
inv[key] = settings_[key];
}
}
return valid;
return 0u == inv.size();
}
Value& StreamWriterBuilder::operator[](JSONCPP_STRING key)
{
return settings_[key];
}
// static
void StreamWriterBuilder::setDefaults(Json::Value* settings)
@@ -1029,17 +1196,19 @@ void StreamWriterBuilder::setDefaults(Json::Value* settings)
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
(*settings)["useSpecialFloats"] = false;
(*settings)["precision"] = 17;
//! [StreamWriterBuilderDefaults]
}
std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
std::ostringstream sout;
JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) {
JSONCPP_OSTRINGSTREAM sout;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout.str();
}
std::ostream& operator<<(std::ostream& sout, Value const& root) {
JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) {
StreamWriterBuilder builder;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);

View File

@@ -1,5 +1,4 @@
// DO NOT EDIT. This file is generated by CMake from "version"
// and "version.h.in" files.
// DO NOT EDIT. This file (and "version") is generated by CMake.
// Run CMake configure step to update it.
#ifndef JSON_VERSION_H_INCLUDED
# define JSON_VERSION_H_INCLUDED
@@ -11,4 +10,11 @@
# define JSONCPP_VERSION_QUALIFIER
# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
#ifdef JSONCPP_USING_SECURE_MEMORY
#undef JSONCPP_USING_SECURE_MEMORY
#endif
#define JSONCPP_USING_SECURE_MEMORY @JSONCPP_USE_SECURE_MEMORY@
// If non-zero, the library zeroes any memory that it has allocated before
// it frees its memory.
#endif // JSON_VERSION_H_INCLUDED

View File

@@ -1,7 +1,4 @@
IF(JSONCPP_LIB_BUILD_SHARED)
ADD_DEFINITIONS( -DJSON_DLL )
ENDIF(JSONCPP_LIB_BUILD_SHARED)
# vim: et ts=4 sts=4 sw=4 tw=0
ADD_EXECUTABLE( jsoncpp_test
jsontest.cpp
@@ -10,11 +7,12 @@ ADD_EXECUTABLE( jsoncpp_test
)
IF(JSONCPP_LIB_BUILD_SHARED)
IF(BUILD_SHARED_LIBS)
ADD_DEFINITIONS( -DJSON_DLL )
TARGET_LINK_LIBRARIES(jsoncpp_test jsoncpp_lib)
ELSE(JSONCPP_LIB_BUILD_SHARED)
ELSE(BUILD_SHARED_LIBS)
TARGET_LINK_LIBRARIES(jsoncpp_test jsoncpp_lib_static)
ENDIF(JSONCPP_LIB_BUILD_SHARED)
ENDIF()
# another way to solve issue #90
#set_target_properties(jsoncpp_test PROPERTIES COMPILE_FLAGS -ffloat-store)
@@ -22,9 +20,19 @@ ENDIF(JSONCPP_LIB_BUILD_SHARED)
# Run unit tests in post-build
# (default cmake workflow hides away the test result into a file, resulting in poor dev workflow?!?)
IF(JSONCPP_WITH_POST_BUILD_UNITTEST)
ADD_CUSTOM_COMMAND( TARGET jsoncpp_test
POST_BUILD
COMMAND $<TARGET_FILE:jsoncpp_test>)
ENDIF(JSONCPP_WITH_POST_BUILD_UNITTEST)
IF(BUILD_SHARED_LIBS)
# First, copy the shared lib, for Microsoft.
# Then, run the test executable.
ADD_CUSTOM_COMMAND( TARGET jsoncpp_test
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:jsoncpp_lib> $<TARGET_FILE_DIR:jsoncpp_test>
COMMAND $<TARGET_FILE:jsoncpp_test>)
ELSE(BUILD_SHARED_LIBS)
# Just run the test executable.
ADD_CUSTOM_COMMAND( TARGET jsoncpp_test
POST_BUILD
COMMAND $<TARGET_FILE:jsoncpp_test>)
ENDIF()
ENDIF()
SET_TARGET_PROPERTIES(jsoncpp_test PROPERTIES OUTPUT_NAME jsoncpp_test)

View File

@@ -81,7 +81,7 @@ TestResult::TestResult()
predicateStackTail_ = &rootPredicateNode_;
}
void TestResult::setTestName(const std::string& name) { name_ = name; }
void TestResult::setTestName(const JSONCPP_STRING& name) { name_ = name; }
TestResult&
TestResult::addFailure(const char* file, unsigned int line, const char* expr) {
@@ -163,7 +163,7 @@ void TestResult::printFailure(bool printTestName) const {
Failures::const_iterator itEnd = failures_.end();
for (Failures::const_iterator it = failures_.begin(); it != itEnd; ++it) {
const Failure& failure = *it;
std::string indent(failure.nestingLevel_ * 2, ' ');
JSONCPP_STRING indent(failure.nestingLevel_ * 2, ' ');
if (failure.file_) {
printf("%s%s(%d): ", indent.c_str(), failure.file_, failure.line_);
}
@@ -173,19 +173,19 @@ void TestResult::printFailure(bool printTestName) const {
printf("\n");
}
if (!failure.message_.empty()) {
std::string reindented = indentText(failure.message_, indent + " ");
JSONCPP_STRING reindented = indentText(failure.message_, indent + " ");
printf("%s\n", reindented.c_str());
}
}
}
std::string TestResult::indentText(const std::string& text,
const std::string& indent) {
std::string reindented;
std::string::size_type lastIndex = 0;
JSONCPP_STRING TestResult::indentText(const JSONCPP_STRING& text,
const JSONCPP_STRING& indent) {
JSONCPP_STRING reindented;
JSONCPP_STRING::size_type lastIndex = 0;
while (lastIndex < text.size()) {
std::string::size_type nextIndex = text.find('\n', lastIndex);
if (nextIndex == std::string::npos) {
JSONCPP_STRING::size_type nextIndex = text.find('\n', lastIndex);
if (nextIndex == JSONCPP_STRING::npos) {
nextIndex = text.size() - 1;
}
reindented += indent;
@@ -195,7 +195,7 @@ std::string TestResult::indentText(const std::string& text,
return reindented;
}
TestResult& TestResult::addToLastFailure(const std::string& message) {
TestResult& TestResult::addToLastFailure(const JSONCPP_STRING& message) {
if (messageTarget_ != 0) {
messageTarget_->message_ += message;
}
@@ -240,9 +240,9 @@ unsigned int Runner::testCount() const {
return static_cast<unsigned int>(tests_.size());
}
std::string Runner::testNameAt(unsigned int index) const {
JSONCPP_STRING Runner::testNameAt(unsigned int index) const {
TestCase* test = tests_[index]();
std::string name = test->testName();
JSONCPP_STRING name = test->testName();
delete test;
return name;
}
@@ -303,7 +303,7 @@ bool Runner::runAllTest(bool printSummary) const {
}
}
bool Runner::testIndex(const std::string& testName,
bool Runner::testIndex(const JSONCPP_STRING& testName,
unsigned int& indexOut) const {
unsigned int count = testCount();
for (unsigned int index = 0; index < count; ++index) {
@@ -323,10 +323,10 @@ void Runner::listTests() const {
}
int Runner::runCommandLine(int argc, const char* argv[]) const {
// typedef std::deque<std::string> TestNames;
// typedef std::deque<JSONCPP_STRING> TestNames;
Runner subrunner;
for (int index = 1; index < argc; ++index) {
std::string opt = argv[index];
JSONCPP_STRING opt = argv[index];
if (opt == "--list-tests") {
listTests();
return 0;
@@ -426,9 +426,23 @@ void Runner::printUsage(const char* appName) {
// Assertion functions
// //////////////////////////////////////////////////////////////////
JSONCPP_STRING ToJsonString(const char* toConvert) {
return JSONCPP_STRING(toConvert);
}
JSONCPP_STRING ToJsonString(JSONCPP_STRING in) {
return in;
}
#if JSONCPP_USING_SECURE_MEMORY
JSONCPP_STRING ToJsonString(std::string in) {
return JSONCPP_STRING(in.data(), in.data() + in.length());
}
#endif
TestResult& checkStringEqual(TestResult& result,
const std::string& expected,
const std::string& actual,
const JSONCPP_STRING& expected,
const JSONCPP_STRING& actual,
const char* file,
unsigned int line,
const char* expr) {

View File

@@ -32,8 +32,8 @@ class Failure {
public:
const char* file_;
unsigned int line_;
std::string expr_;
std::string message_;
JSONCPP_STRING expr_;
JSONCPP_STRING message_;
unsigned int nestingLevel_;
};
@@ -65,7 +65,7 @@ public:
/// \internal Implementation detail for predicate macros
PredicateContext* predicateStackTail_;
void setTestName(const std::string& name);
void setTestName(const JSONCPP_STRING& name);
/// Adds an assertion failure.
TestResult&
@@ -82,7 +82,7 @@ public:
// Generic operator that will work with anything ostream can deal with.
template <typename T> TestResult& operator<<(const T& value) {
std::ostringstream oss;
JSONCPP_OSTRINGSTREAM oss;
oss.precision(16);
oss.setf(std::ios_base::floatfield);
oss << value;
@@ -96,19 +96,19 @@ public:
TestResult& operator<<(Json::UInt64 value);
private:
TestResult& addToLastFailure(const std::string& message);
TestResult& addToLastFailure(const JSONCPP_STRING& message);
unsigned int getAssertionNestingLevel() const;
/// Adds a failure or a predicate context
void addFailureInfo(const char* file,
unsigned int line,
const char* expr,
unsigned int nestingLevel);
static std::string indentText(const std::string& text,
const std::string& indent);
static JSONCPP_STRING indentText(const JSONCPP_STRING& text,
const JSONCPP_STRING& indent);
typedef std::deque<Failure> Failures;
Failures failures_;
std::string name_;
JSONCPP_STRING name_;
PredicateContext rootPredicateNode_;
PredicateContext::Id lastUsedPredicateId_;
/// Failure which is the target of the messages added using operator <<
@@ -155,7 +155,7 @@ public:
unsigned int testCount() const;
/// Returns the name of the test case at the specified index
std::string testNameAt(unsigned int index) const;
JSONCPP_STRING testNameAt(unsigned int index) const;
/// Runs the test case at the specified index using the specified TestResult
void runTestAt(unsigned int index, TestResult& result) const;
@@ -168,7 +168,7 @@ private: // prevents copy construction and assignment
private:
void listTests() const;
bool testIndex(const std::string& testName, unsigned int& index) const;
bool testIndex(const JSONCPP_STRING& testName, unsigned int& index) const;
static void preventDialogOnCrash();
private:
@@ -191,9 +191,15 @@ TestResult& checkEqual(TestResult& result,
return result;
}
JSONCPP_STRING ToJsonString(const char* toConvert);
JSONCPP_STRING ToJsonString(JSONCPP_STRING in);
#if JSONCPP_USING_SECURE_MEMORY
JSONCPP_STRING ToJsonString(std::string in);
#endif
TestResult& checkStringEqual(TestResult& result,
const std::string& expected,
const std::string& actual,
const JSONCPP_STRING& expected,
const JSONCPP_STRING& actual,
const char* file,
unsigned int line,
const char* expr);
@@ -235,8 +241,8 @@ TestResult& checkStringEqual(TestResult& result,
/// \brief Asserts that two values are equals.
#define JSONTEST_ASSERT_STRING_EQUAL(expected, actual) \
JsonTest::checkStringEqual(*result_, \
std::string(expected), \
std::string(actual), \
JsonTest::ToJsonString(expected), \
JsonTest::ToJsonString(actual), \
__FILE__, \
__LINE__, \
#expected " == " #actual)
@@ -265,8 +271,8 @@ TestResult& checkStringEqual(TestResult& result,
} \
\
public: /* overidden from TestCase */ \
virtual const char* testName() const { return #FixtureType "/" #name; } \
virtual void runTestCase(); \
const char* testName() const JSONCPP_OVERRIDE { return #FixtureType "/" #name; } \
void runTestCase() JSONCPP_OVERRIDE; \
}; \
\
void Test##FixtureType##name::runTestCase()

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,10 @@
# removes all files created during testing
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
"""Removes all files created during testing."""
import glob
import os

View File

@@ -1,3 +1,8 @@
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
import glob
import os.path

View File

@@ -1,4 +1,11 @@
# Simple implementation of a json test runner to run the test against json-py.
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
"""Simple implementation of a json test runner to run the test against
json-py."""
from __future__ import print_function
import sys
import os.path

View File

@@ -1,3 +1,8 @@
# Copyright 2007 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
from __future__ import unicode_literals
from io import open

View File

@@ -1,3 +1,8 @@
# Copyright 2009 Baptiste Lepilleur
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
from __future__ import unicode_literals
from io import open

31
travis.sh Executable file
View File

@@ -0,0 +1,31 @@
#!/usr/bin/env sh
# This is called by `.travis.yml` via Travis CI.
# Travis supplies $TRAVIS_OS_NAME.
# http://docs.travis-ci.com/user/multi-os/
# Our .travis.yml also defines:
# - SHARED_LIB=ON/OFF
# - STATIC_LIB=ON/OFF
# - CMAKE_PKG=ON/OFF
# - BUILD_TYPE=release/debug
# - VERBOSE_MAKE=false/true
# - VERBOSE (set or not)
# -e: fail on error
# -v: show commands
# -x: show expanded commands
set -vex
env | sort
cmake -DJSONCPP_WITH_CMAKE_PACKAGE=$CMAKE_PKG -DBUILD_SHARED_LIBS=$SHARED_LIB -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_VERBOSE_MAKEFILE=$VERBOSE_MAKE .
make
cmake -DJSONCPP_WITH_CMAKE_PACKAGE=$CMAKE_PKG -DBUILD_SHARED_LIBS=$SHARED_LIB -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_VERBOSE_MAKEFILE=$VERBOSE_MAKE -DJSONCPP_USE_SECURE_MEMORY=1 .
make
# Python is not available in Travis for osx.
# https://github.com/travis-ci/travis-ci/issues/2320
if [ "$TRAVIS_OS_NAME" != "osx" ]
then
make jsoncpp_check
valgrind --error-exitcode=42 --leak-check=full ./src/test_lib_json/jsoncpp_test
fi

View File

@@ -1 +1 @@
1.4.3
1.7.5

1
version.in Normal file
View File

@@ -0,0 +1 @@
@JSONCPP_VERSION@