Compare commits

...

829 commits
v1.3 ... master

Author SHA1 Message Date
Petri Lehtinen
96d160df90
Merge pull request #692 from Andrew-Au/cmake_update/revised/merge
Some checks failed
tests / autotools (clang, no, macos-latest) (push) Has been cancelled
tests / autotools (clang, yes, macos-latest) (push) Has been cancelled
tests / autotools (gcc, no, macos-latest) (push) Has been cancelled
tests / autotools (gcc, yes, macos-latest) (push) Has been cancelled
tests / cmake (clang, macos-latest) (push) Has been cancelled
tests / cmake (gcc, macos-latest) (push) Has been cancelled
tests / cmake (msvc, windows-latest) (push) Has been cancelled
tests / lint (push) Failing after 4s
tests / autotools (clang, no, ubuntu-latest) (push) Failing after 3s
tests / autotools (clang, yes, ubuntu-latest) (push) Failing after 3s
tests / autotools (gcc, no, ubuntu-latest) (push) Failing after 3s
tests / autotools (gcc, yes, ubuntu-latest) (push) Failing after 3s
tests / cmake (clang, ubuntu-latest) (push) Successful in 23s
tests / cmake (gcc, ubuntu-latest) (push) Successful in 20s
tests / valgrind (push) Failing after 17m10s
Use target-based cmake settings
2025-04-04 07:18:04 +03:00
Petri Lehtinen
aef13f87f1 Set minimum cmake version to 3.10 2025-04-04 07:15:20 +03:00
Petri Lehtinen
c16ac732e4
Merge pull request #712 from akheron/fix-lint
Some checks failed
tests / lint (push) Failing after 31s
tests / autotools (clang, no, ubuntu-latest) (push) Failing after 30s
tests / autotools (clang, yes, ubuntu-latest) (push) Failing after 29s
tests / autotools (gcc, no, ubuntu-latest) (push) Failing after 30s
tests / autotools (gcc, yes, ubuntu-latest) (push) Failing after 28s
tests / cmake (clang, ubuntu-latest) (push) Failing after 39s
tests / cmake (gcc, ubuntu-latest) (push) Failing after 39s
tests / valgrind (push) Failing after 35s
tests / cmake (msvc, windows-latest) (push) Has been cancelled
tests / autotools (gcc, yes, macos-latest) (push) Has been cancelled
tests / cmake (clang, macos-latest) (push) Has been cancelled
tests / cmake (gcc, macos-latest) (push) Has been cancelled
tests / autotools (gcc, no, macos-latest) (push) Has been cancelled
tests / autotools (clang, no, macos-latest) (push) Has been cancelled
tests / autotools (clang, yes, macos-latest) (push) Has been cancelled
Fix code formatting
2025-03-23 22:39:12 +02:00
Petri Lehtinen
05a10aa8af Fix code formatting 2025-03-23 22:31:56 +02:00
Petri Lehtinen
4d7ac97b89
Merge pull request #710 from akheron/fix-readthedocs
Add readthedocs config
2025-03-23 21:59:36 +02:00
Petri Lehtinen
23905f372c Add readthedocs config 2025-03-23 21:58:05 +02:00
Petri Lehtinen
ed5cae4ed0 jansson 2.14.1
Some checks failed
tests / lint (push) Failing after 28s
tests / autotools (clang, no, ubuntu-latest) (push) Failing after 32s
tests / autotools (clang, yes, ubuntu-latest) (push) Failing after 30s
tests / autotools (gcc, no, ubuntu-latest) (push) Failing after 39s
tests / autotools (gcc, yes, ubuntu-latest) (push) Failing after 26s
tests / cmake (clang, ubuntu-latest) (push) Failing after 31s
tests / cmake (gcc, ubuntu-latest) (push) Failing after 23s
tests / valgrind (push) Failing after 29s
tests / autotools (gcc, yes, macos-latest) (push) Has been cancelled
tests / cmake (clang, macos-latest) (push) Has been cancelled
tests / cmake (gcc, macos-latest) (push) Has been cancelled
tests / cmake (msvc, windows-latest) (push) Has been cancelled
tests / autotools (clang, no, macos-latest) (push) Has been cancelled
tests / autotools (clang, yes, macos-latest) (push) Has been cancelled
tests / autotools (gcc, no, macos-latest) (push) Has been cancelled
2025-03-23 14:25:44 +02:00
Andrew White
0f9c18dd12 Use target-based cmake settings
- Update minimum required to CMake version 3.5 (versions older than 3.5 are
deprecated as of 3.27)
- update add_definitions to target_compile_definitions
- use target_include_directories for public library includes
- add jansson::jansson alias
2024-07-10 10:31:49 +10:00
Petri Lehtinen
61fc3d0e28
Merge pull request #686 from akheron/readme-badges
Update badges in README
2024-03-31 22:09:15 +03:00
Petri Lehtinen
cce8caba26 Update badges in README 2024-03-31 22:08:10 +03:00
Petri Lehtinen
50953fb1fa
Merge pull request #680 from akheron/dtoa
Use `dtoa()` for optimal encoding of reals
2024-03-31 22:02:09 +03:00
Petri Lehtinen
c780171cf3 Update CHANGES 2024-03-25 20:19:41 +02:00
Petri Lehtinen
2297a2e320 Update LICENSE to add an exception for src/dtoa.c 2024-03-25 20:19:23 +02:00
Petri Lehtinen
f5b3ab323c Add more tests 2024-03-25 20:08:23 +02:00
Petri Lehtinen
9d3abab610 Test with and without dtoa in CI 2024-03-25 20:08:23 +02:00
Petri Lehtinen
9699de8600 Fix tests 2024-03-25 20:08:23 +02:00
Petri Lehtinen
33a6c95d56 Fix compiler warnings 2024-03-25 20:08:23 +02:00
Petri Lehtinen
ed06f65412 Rename a symbol to avoid collision on Windows 2024-03-25 20:08:23 +02:00
Petri Lehtinen
8b975abca1 Use dtoa for double to string conversion 2024-03-25 20:08:23 +02:00
Petri Lehtinen
8660da0f7c
Merge pull request #685 from akheron/simplify-tests
Simplify tests even more
2024-03-25 20:07:53 +02:00
Petri Lehtinen
dcbeb58829 Simplify tests even more
Drop the useless `export` lines from `env` files.
2024-03-25 19:16:34 +02:00
Petri Lehtinen
53383b9e26
Merge pull request #683 from akheron/refactor-tests
Refactor tests
2024-03-21 20:43:31 +02:00
Petri Lehtinen
649c9357c6 Update CHANGES 2024-03-21 20:43:04 +02:00
Petri Lehtinen
73dc6960ad Show ctest output on failure in CI 2024-03-21 20:36:42 +02:00
Petri Lehtinen
88375fb10e Refactor tests to work better with CMake 2024-03-21 20:36:38 +02:00
Petri Lehtinen
0247b5e2e7 Improve clang-format scripts 2024-03-15 21:06:34 +02:00
Petri Lehtinen
842708ac0c
Merge pull request #677 from akheron/ditch-localeconv
Use sprintf() to determine locale's decimal point
2024-03-08 21:53:07 +02:00
Petri Lehtinen
2d1c13224f Use sprintf() to determine locale's decimal point
This should fix thread safety of encoding and decoding, since
localeconv() is not tread safe after all.
2024-03-08 21:36:21 +02:00
Petri Lehtinen
9b9b5e81cf
Merge pull request #679 from akheron/dependabot/github_actions/github-actions-cb1dee63db
Bump the github-actions group with 1 update
2024-03-08 06:42:02 +02:00
dependabot[bot]
0c9c11a89d
Bump the github-actions group with 1 update
Bumps the github-actions group with 1 update: [actions/upload-artifact](https://github.com/actions/upload-artifact).


Updates `actions/upload-artifact` from 3 to 4
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-07 20:09:47 +00:00
Petri Lehtinen
f52d79a4d3
Merge pull request #672 from pnacht/add-dependabot
Add dependabot, update GitHub Actions
2024-03-07 22:09:25 +02:00
Petri Lehtinen
2f1777ba80
Merge branch 'master' into add-dependabot 2024-03-07 22:08:46 +02:00
Petri Lehtinen
1e57cadbd3
Merge pull request #678 from akheron/ditch-coveralls
Ditch coveralls
2024-03-07 21:54:05 +02:00
Petri Lehtinen
0db4db1048 Ditch coveralls 2024-03-07 21:47:18 +02:00
Pedro Kaj Kjellerup Nacht
73d968feef
Bump GHA versions
Signed-off-by: Pedro Kaj Kjellerup Nacht <pnacht@google.com>
2023-12-06 23:10:14 +00:00
Pedro Kaj Kjellerup Nacht
0154c4af07
Add dependabot to update GHA
Signed-off-by: Pedro Kaj Kjellerup Nacht <pnacht@google.com>
2023-12-06 23:10:03 +00:00
Petri Lehtinen
60097f0096
Create SECURITY.md 2023-06-28 07:42:28 +03:00
Petri Lehtinen
bde28463f8
Merge pull request #646 from Bigpet/patch-1
Remove unused ${SOURCE_DIR}/include include path
2023-03-29 22:07:32 +03:00
Peter Tissen
e7c9ef8e52
Remove unused ${SOURCE_DIR}/include include path
The directory `${CMAKE_CURRENT_SOURCE_DIR}/include` is never created or used. Except in case of an in-source build but then  `${CMAKE_CURRENT_BINARY_DIR}/include` would be the same, so it would only duplicate the correct entry.

Not sure if the intermediary `JANSSON__INCLUDE_DIRS` is still necessary but I thought I'd change as little as possible.

The reason for eliminating this is that when you use CLion and sync into a docker container it will try to copy all include dirs back. Non-existant paths cause warnings every time.
2023-03-29 12:44:28 +02:00
Petri Lehtinen
a22dc95311
Merge pull request #640 from uniontech-lilinjie/master
fix typo
2023-01-11 22:25:45 +02:00
lilinjie
a7d04c8554 fix typo
Signed-off-by: lilinjie <lilinjie@uniontech.com>
2023-01-10 16:35:44 +08:00
Petri Lehtinen
e23f558007
Merge pull request #628 from neheb/patch-1
hashtable: change to ifdef
2022-08-24 17:10:48 +03:00
Rosen Penev
1894366598
hashtable: change to ifdef
All other usages use ifdef.
2022-08-22 18:13:57 -07:00
Petri Lehtinen
7e04530916 Remove the confusing vcpkg ad from README 2022-08-09 22:24:38 +03:00
Petri Lehtinen
011e625769
Merge pull request #626 from akheron/fix-example
Add a missing json_decref in the example
2022-08-09 22:05:05 +03:00
Petri Lehtinen
de5f2963ab Add a missing json_decref in the example 2022-08-09 22:00:45 +03:00
Petri Lehtinen
128e9c5f37
Merge pull request #610 from Thomas1664/master
Fix overwriting linker flags
2022-05-03 05:48:09 +03:00
Thomas Heinrichs
fe6e8eec7e Fix overwriting linker flags 2022-04-28 17:36:54 +02:00
Petri Lehtinen
addeeef408 Add some links to README 2021-11-22 16:30:12 +02:00
Petri Lehtinen
d82b436b2f
Merge pull request #598 from Mephistophiles/remove_internal_strlen
Reduce strlen's in jansson internals
2021-11-21 07:38:59 +02:00
Maxim Zhukov
586b4461e6 tests: add some cases in fixed size test
Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2021-11-20 22:57:10 +03:00
Maxim Zhukov
78418c84f1 value, pack: use key length from json_object iternals
Reduce the number of strlen calls in the jansson backend.

Test on my laptop (count of the instructions)

  Before:
  ❯ valgrind --tool=callgrind ./bin/test_object
  ==3105045== Events    : Ir
  ==3105045== Collected : 441453

  After:
  ❯ valgrind --tool=callgrind ./bin/test_object
  ==3144451== Events    : Ir
  ==3144451== Collected : 440597

Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2021-11-20 22:47:14 +03:00
Petri Lehtinen
eb81670881
Create CONTRIBUTING.md 2021-09-12 18:37:43 +03:00
Petri Lehtinen
0677666f65 Fix the check-exports tests for versioned symbols 2021-09-09 21:55:27 +03:00
Petri Lehtinen
684e18c927 jansson 2.14 2021-09-09 21:18:40 +03:00
Tomasz Paweł Gajc
e950e57e13 fix --version-script for good 2021-09-06 20:02:14 +03:00
tpgxyz
0dffb4284e use --version-script in case of linkers that does not support --default-symver 2021-04-23 06:41:58 +03:00
Petri Lehtinen
2de2c3d5fc Fix and simplify coveralls reporting 2021-01-26 22:07:32 +02:00
Petri Lehtinen
2cd3126651
Add name to the fuzz tests workflow 2021-01-26 20:03:12 +02:00
Petri Lehtinen
bde3cab216 Fix GitHub actions workflow syntax 2021-01-26 19:33:16 +02:00
Petri Lehtinen
f7aee00928 Use cifuzz actions 2021-01-25 22:20:33 +02:00
Petri Lehtinen
aa52a60ca8 README: Update build badge 2021-01-14 21:12:02 +02:00
Petri Lehtinen
d8aedd3682 Delete Travis CI config 2021-01-14 21:12:02 +02:00
Petri Lehtinen
0441ccd3c6 Also build on Visual Studio 2019 on AppVeyor 2021-01-14 21:12:02 +02:00
Petri Lehtinen
0bc4325222 GitHub Actions 2021-01-14 21:12:02 +02:00
Petri Lehtinen
fd3e9e3051 doc: Hoist a section 2020-11-19 17:31:13 +02:00
Petri Lehtinen
55ea6d44dd doc: Rename "Portability" to "Thread-safety"
Fixes #545
2020-11-19 17:27:03 +02:00
Petri Lehtinen
9a0fc069bf
Merge pull request #520 from Mephistophiles/getn
Add support getn, setn functions
2020-11-19 17:21:12 +02:00
Petri Lehtinen
cc318fc042
Merge pull request #555 from kiyolee/size_t-warnings
Fix size_t related MSVC compiler warnings
2020-11-15 06:32:29 +02:00
Kelvin Lee
638449c43d C11 %zd is bit overkill here. Especially requiring conditional compile. 2020-11-06 15:51:14 +11:00
Kelvin Lee
38c4b80ab7 Fix hashsize() should return size_t. 2020-11-06 08:40:20 +11:00
Kelvin Lee
ec1b6318e4 Use size_t to receive result from fread()/ftell(). 2020-11-05 22:06:38 +11:00
Kelvin Lee
1d8201c656 Print size_t properly with C11 %zd support. 2020-11-05 22:05:54 +11:00
Maxim Zhukov
0758caaac0 reuse key len from loop check for better performance
Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2020-09-01 10:22:14 +03:00
Maxim Zhukov
16a3899a9e conformance: remove U+0000 restriction for object keys
Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2020-09-01 10:22:14 +03:00
Maxim Zhukov
ca6775dee4 introduce new fixed-size key API
This commit added functions working with fixed-size strings (non null-terminated also).
It's helpful for the following cases:
* getting key from substring without copying to separate buffer (better perfomance)
* using pure UTF-8 keys for the objets
* hack: set binary structs as the keys (see test_binary_keys)

added functions:
 * json_object_getn
 * json_object_setn
 * json_object_setn_nocheck
 * json_object_setn_new
 * json_object_setn_new_nocheck
 * json_object_deln
 * json_object_iter_key_len

added iterators:
 * json_object_keylen_foreach
 * json_object_keylen_foreach_safe

Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2020-09-01 10:22:14 +03:00
Maxim Zhukov
ba4503804b pass length of the key to internal API
Use key length for internal API

Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2020-08-12 09:57:14 +03:00
Maxim Zhukov
966f9cc20a sort tests by alpha order
Signed-off-by: Maxim Zhukov <mussitantesmortem@gmail.com>
2020-08-12 09:57:07 +03:00
Petri Lehtinen
a740f15c17
Merge pull request #546 from i-ky/patch-1
Fix couple of typos
2020-08-09 10:28:12 +03:00
i-ky
601b568b8d
Fix couple of typos
"This sections describes" -> "This section describes"
2020-08-09 00:19:39 +03:00
Petri Lehtinen
1112580f4a
Merge pull request #544 from i-ky/patch-1
Lift "Depth of nested values" to a higher level
2020-08-08 20:25:37 +03:00
i-ky
d9c5b1d4df
Lift "Depth of nested values" to a higher level
Currently this section is under "Numbers" which seems to be wrong.
2020-08-08 14:10:16 +03:00
Petri Lehtinen
a154389827
Merge pull request #543 from ploxiln/sphinx3
doc: compatibility with Sphinx-3
2020-08-08 13:15:23 +03:00
Pierce Lopez
c329fd7bc8 doc: add return types for function-like macros
The Sphinx-3.0 c:function:: directive requires the return type.

Sphinx-3.0 also adds function-like macro support to the c:macro::
directive, which Sphinx-1.x and Sphinx-2.x do not support, but it
is probably a good idea to keep compatibility with slightly older
Sphinx for now.
2020-08-07 02:35:27 -04:00
Pierce Lopez
94318890c0 doc: do not use references for standard C types or file names
Use double-backtick quoting instead. It has the same effect
(because these links had nowhere to link to) but it does not
result in loud warnings about broken references by default with Sphinx-3.x.
2020-08-07 02:34:25 -04:00
Pierce Lopez
798d40c3f3 doc: convert refcounting directive to a class
Directive functions are no longer supported in Sphinx-3.0
but directive classes have been supported since early 1.x
2020-08-07 01:54:45 -04:00
Petri Lehtinen
73ccec0601
Merge pull request #540 from smcv/default-symver
build: Add a symbol version to all exported symbols
2020-07-20 13:01:34 +03:00
Simon McVittie
ca80d5127e build: Add a symbol version to all exported symbols for glibc
The --default-symver linker option attaches a default version definition
(the SONAME) to every exported symbol. It is supported since at least
GNU binutils 2.22 in 2011 (older versions not tested).

With this version definition, newly-linked binaries that depend on the
jansson shared library will refer to its symbols in a versioned form,
preventing their references from being resolved to a symbol of the same
name exported by json-c or json-glib if those libraries appear in
dependency search order before jansson, which will usually result in
a crash. This is necessary because ELF symbol resolution normally uses
a single flat namespace, not a tree like Windows symbol resolution.
At least one symbol (json_object_iter_next()) is exported by all three
JSON libraries.

Linking with -Bsymbolic is not enough to have this effect in all cases,
because -Bsymbolic only affects symbol lookup within a shared object,
for example when parse_json() calls json_decref(). It does not affect
calls from external code into jansson, unless jansson was statically
linked into the external caller.

This change will also not prevent code that depends on json-c or
json-glib from finding jansson's symbols and crashing; to prevent
that, a corresponding change in json-c or json-glib would be needed.

Adding a symbol-version is a backwards-compatible change, but once
added, removing or changing the symbol-version would be an incompatible
change that requires a SONAME bump.

Resolves: https://github.com/akheron/jansson/issues/523
(when combined with an equivalent change to json-c).

Signed-off-by: Simon McVittie <smcv@collabora.com>
2020-07-02 09:54:40 +01:00
Petri Lehtinen
52dfc3dd4a
Merge pull request #537 from stoeckmann/vsnprintf
Handle vsnprintf corner cases.
2020-05-23 20:42:25 +03:00
Tobias Stoeckmann
38b001edbd Handle vsnprintf corner cases.
The function vsnprintf returns a negative value on error, e.g. on
an invalid format. It's best to return NULL in such a case.

Also avoid a signed integer overflow if vsnprintf returns INT_MAX.
This is undefined behaviour in C and has to be avoided.

A negative value is returned with a call like:
json_sprintf("%111111111111111s", "", "");

INT_MAX is returned with a call like:
json_sprintf("%647s%2147483000s", "", "");
2020-05-23 12:34:40 +02:00
Petri Lehtinen
e9ebfa7e77 jansson 2.13.1 2020-05-07 21:38:59 +03:00
Petri Lehtinen
3f4d948652
Merge pull request #535 from xry111/clang-format-check-dist-fix
add `scripts` directory to EXTRA_DIST
2020-05-07 21:29:30 +03:00
Petri Lehtinen
a839d3cad6
Merge pull request #534 from xry111/shared_lib_interface_fix
add jansson_* to shared library exports
2020-05-07 21:28:47 +03:00
Xℹ Ruoyao
2d2efde34a add scripts directory to EXTRA_DIST 2020-05-06 18:01:19 +08:00
Xℹ Ruoyao
bcb6b6f3fd add jansson_* to shared library exports 2020-05-06 17:31:48 +08:00
Petri Lehtinen
2882ead5bb jansson 2.13 2020-05-05 07:07:16 +03:00
Petri Lehtinen
4c9018cc4c
Merge pull request #521 from NanXiao/patch-1
Update apiref.rst
2020-01-21 10:15:01 +02:00
Nan Xiao
e15fd861e1
Update apiref.rst 2020-01-21 14:27:52 +08:00
Petri Lehtinen
ca88677bdd
Merge pull request #510 from AllenX2018/improve-build-doc
add MinGW build guideline and tips to disable building docs
2019-10-24 11:23:00 +03:00
Petri Lehtinen
6e211b24fe
Fix the length of a section heading 2019-10-24 11:22:46 +03:00
Petri Lehtinen
50c9623e37
Merge pull request #509 from AllenX2018/update-CHANGES
add changes since v2.12
2019-10-24 11:19:52 +03:00
Petri Lehtinen
3704e1cd78
Small modifications to CHANGES 2019-10-24 11:19:34 +03:00
allen
67900c85d3 add changes since v2.12 2019-10-22 18:52:55 +08:00
Petri Lehtinen
d288cc157e
Merge pull request #508 from akheron/clang-format
Format code with clang-format
2019-10-21 11:07:53 +03:00
AllenX2018
5b8ff675b3 add MinGW build guideline, add new version of Visual Studio 2019-10-21 15:53:33 +08:00
Petri Lehtinen
78da35682a Set autoconf bug-report param to point to github issues 2019-10-21 08:56:03 +03:00
Petri Lehtinen
bb4f99e919 Fix clang-format version checking 2019-10-21 08:56:03 +03:00
Petri Lehtinen
f912430cda Run clang-format with make check 2019-10-21 08:56:03 +03:00
Petri Lehtinen
a8f5fa5f5a Tweak clang-format configuration a bit
Set ColumnLimit to 90, remove AllowShortCaseLabelsOnASingleLine.
2019-10-21 08:56:03 +03:00
Petri Lehtinen
7c0297abe8 Support running a specific clang-format version in CI 2019-10-21 08:55:01 +03:00
Petri Lehtinen
1a95a60f80 Run clang-format in CI, fail the build if everything's not formatted 2019-10-21 08:55:01 +03:00
Petri Lehtinen
be0fca914e Add scripts for running clang-format 2019-10-21 08:55:01 +03:00
Petri Lehtinen
79fe8c3435 Run clang-format on *.c, *.h 2019-10-21 08:55:01 +03:00
Petri Lehtinen
7dc463ee4e Add clang-format configuration 2019-10-21 08:53:03 +03:00
Petri Lehtinen
79075d5393
Merge pull request #498 from AllenX2018/fix-issue441
fix issue #441: remove strtod definition in strconv.c
2019-10-21 08:51:36 +03:00
willson-chen
c3958a326c remove undef __NO_ISOCEXT for strtod compatiblity 2019-10-21 11:13:39 +08:00
Petri Lehtinen
f75dc840e4
Merge pull request #499 from AllenX2018/fix-issue281
Add json_object_update_new, json_object_update_existing_new and json_object_update_missing_new
2019-10-18 16:18:28 +03:00
Petri Lehtinen
25e706cce7
Merge branch 'master' into fix-issue281 2019-10-17 13:37:33 +03:00
Petri Lehtinen
8b022dad76
Merge pull request #505 from AllenX2018/recursive_object_update
Recursive object update
2019-10-17 08:36:28 +03:00
Petri Lehtinen
0eec0327be
Merge pull request #500 from AllenX2018/fix-issue426
fix issue #426: fix pipe function in MinGW
2019-10-17 08:12:42 +03:00
Petri Lehtinen
e7bed4c109
Merge pull request #501 from AllenX2018/fix-issue481
fix issue #481
2019-10-17 08:11:19 +03:00
Petri Lehtinen
355aa42b48
Merge pull request #502 from AllenX2018/fix-issue453
fix issue #453:update FindSphinx.cmake to better align with find sphinx package.
2019-10-17 08:09:20 +03:00
Petri Lehtinen
92873e9d27
Merge pull request #503 from AllenX2018/loadfd-doc
add note for non-blocking file descriptor used for json_loadfd
2019-10-17 08:07:02 +03:00
Petri Lehtinen
9e1c37c889
Merge pull request #506 from AllenX2018/add-json_equal-test-case
fix typo & add negative test case for test_equal_complex
2019-10-17 07:33:36 +03:00
allen
010092c7bd fix typo & add negative test case for test_equal_complex 2019-10-15 17:41:57 +08:00
allen
fb602f331b update the test case of json_object_update_recursive 2019-10-14 17:32:24 +08:00
allen
00d2d274bc add loop check for json_object_update_recursive function 2019-10-12 15:36:05 +08:00
allen
b403bbba8d modify some words 2019-10-12 10:56:23 +08:00
Henrique Cabral
cb4727c4a9 Add json_object_update_recursive()
Support merging values nested within objects. For instance, merging:

    {
	"foo": 1,
	"bar": {
	    "baz": 2
	}
    }

with

    {
	"bar": {
	    "baz": 3
	}
    }

results in

    {
	"foo": 1,
	"bar": {
	    "baz": 3
	}
    }

instead of overwriting the value for the bar key.
2019-10-11 11:20:25 +08:00
allen
a585a2778e add note for non-blocking file descriptor used for json_loadfd 2019-10-10 19:43:17 +08:00
AllenX2018
4f26548e3a fix issue #453 2019-10-10 16:16:10 +08:00
allen
1f889c4b60 fix issue #481 2019-10-09 17:12:04 +08:00
allen
8682f2aab3 fix issue #281 2019-10-08 20:32:27 +08:00
AllenX2018
4f3305c506 fix issue #441
It already has "strtod" function in stdlib.h and because __USE_MINGW_ANSI_STDIO is desperated
2019-10-08 19:16:50 +08:00
AllenX2018
78ea35c8e9 fix issue #426 2019-10-08 16:19:40 +08:00
Petri Lehtinen
c436bec682
Merge pull request #496 from grdowns/vcpkg-instructions
Add vcpkg installation instructions
2019-09-27 15:08:00 +03:00
grdowns
f5c0afecdb Add vcpkg installation instructions 2019-09-26 16:54:02 -07:00
Petri Lehtinen
5371816480
Merge pull request #494 from luzpaz/typos
Fix various typos
2019-09-23 11:31:23 +03:00
Petri Lehtinen
09e455275c
Merge pull request #490 from AllenX2018/master
add loop check in json deep copy #457
2019-09-23 11:30:33 +03:00
luz.paz
3adf3e6a5a Fix various typos
Found via `codespell -q 2` (v1.17.0.dev0)
2019-09-20 13:35:56 -04:00
Allen
672b6df474
Update apiref.rst
fix the documentation about json_dumps. refs #471
2019-09-18 16:18:51 +08:00
allen
53e9dd848f add the loop key length macro for circular reference detect 2019-09-16 15:50:59 +08:00
allen
63fb81faa5 add loop check in json deep copy #457 2019-08-12 11:17:25 +08:00
Corey Farrell
a1f297aa83
Merge pull request #489 from AllenX2018/master
Update CMakeLists.txt
2019-08-09 04:37:06 -04:00
Allen
e68c5ea0b5
Update CMakeLists.txt
add "-Wno-format-truncation" to supress format truncation warning in cmake
2019-08-09 15:41:57 +08:00
Corey Farrell
af66d3f4c0
Merge pull request #487 from cmeister2/cmeister2/ossfuzzcorpus
ossfuzz: Zip up all "input" files to use as a seed corpus
2019-07-26 09:43:44 -04:00
Corey Farrell
a6f6ec1856
Merge pull request #485 from cmeister2/cmeister2/fuzzerdiags
ossfuzz: Improvements to json_load_dump_fuzzer
2019-07-26 08:58:16 -04:00
Max Dymond
287b5acb07
ossfuzz: Zip up all "input" files to use as a seed corpus 2019-07-24 19:41:45 +01:00
Max Dymond
3858607be0
Depending on the dump_mode byte, dump out as a string or as a callback. 2019-07-24 19:14:17 +01:00
Corey Farrell
0ed750a7ea
Merge pull request #486 from cmeister2/cmeister2/osstravis
Ensure OSS fuzz travis builds work for PRs
2019-07-24 13:46:24 -04:00
Max Dymond
7feae084b1
Use the correct branch for OSS Fuzz as well. 2019-07-24 10:50:21 +01:00
Max Dymond
a6f436fefc
Ensure OSS fuzz travis builds work for PRs
Use the correct repository for cloning when doing a push build or a
pull-request.

Only do one fuzzer build!
2019-07-24 10:43:03 +01:00
Max Dymond
66dec35c8c
ossfuzz: Improvements to json_load_dump_fuzzer
Add in diagnostics to json_load_dump_fuzzer so that if FUZZ_VERBOSE is
defined in the environment, additional debug information about the
current test case is output to stderr.

Replace json_dumps by json_dump_callback so that memory is not exhausted
by excessively nested json objects.
2019-07-24 10:17:19 +01:00
Corey Farrell
1ac79b2558
Merge pull request #484 from cmeister2/cmeister2/fixossafl
One byte fix to fix OSS Fuzz AFL support
2019-07-22 06:40:34 -04:00
Max Dymond
6e26599980
One byte fix to fix OSS Fuzz AFL support
"x$LIB_FUZZING_ENGINE" is not the correct filename to test for - remove
the x!
2019-07-22 11:23:54 +01:00
Corey Farrell
3bfa3f1946
Merge pull request #480 from cmeister2/cmeister2/ossfuzz
oss-fuzz: Create a fuzzing target for jansson
2019-07-22 05:29:22 -04:00
Corey Farrell
813c3e2c47
Merge pull request #483 from AllenX2018/master
correct spelling mistake
2019-07-22 04:19:26 -04:00
allen
c49fbc7082 correct spelling mistake 2019-07-22 11:00:31 +08:00
Max Dymond
24cc9dd078
Move ossfuzz directory and use Makefile.am 2019-07-19 09:52:37 +01:00
Max Dymond
100e5549b6
Create a fuzzing target for jansson 2019-06-28 14:05:39 +01:00
Corey Farrell
b333f3656d
Merge pull request #465 from seanbright/jansson-version
Add runtime version checking functions
2019-03-13 08:24:41 -04:00
Sean Bright
76300601d9 Add runtime version checking functions
This patch adds two new exported functions:

* `jansson_version_str` - Returns a human-readable version number
* `jansson_version_cmp` - Returns an integer less than, equal to, or greater
  than zero if the runtime version of Jansson is found, respectively, to be
  less than, to match, or be greater than the provided major, minor, and micro.
2019-03-12 13:03:34 -04:00
Petri Lehtinen
f4498d2856 CHANGES: Fix 2.12 release date 2018-11-26 10:59:06 +02:00
Petri Lehtinen
71c4e8ec21
Merge pull request #448 from coreyfarrell/2.12
jansson 2.12
2018-11-26 09:10:04 +01:00
Corey Farrell
10afd33efb
jansson 2.12 2018-11-25 03:40:56 -05:00
Corey Farrell
2a31c4f475
Merge pull request #447 from vsoch/update/install-readme
Update/install readme
2018-11-25 02:40:09 -05:00
vsoch
f44c137a84 extra comma! 2018-11-24 23:29:14 -08:00
vsoch
7197810714 small updates to README 2018-11-24 23:27:23 -08:00
Corey Farrell
4ba5c7cc5d
Merge pull request #445 from coreyfarrell/fix-444
Remove inappropriate jsonp_free which caused segmentation fault.
2018-11-08 16:00:32 -05:00
Corey Farrell
e262ea5fcd
Remove inappropriate jsonp_free which caused segmentation fault.
pack_string should never free str on error.  This wouldn't be a problem
except the check for `ours` was inverted.  Just remove the check for
ours since the true condition is unreachable.

json_vpack_ex also had an error check for s.has_error.  This can never
be true unless value is NULL.

Expand pack_unpack testing to cover empty format string, NULL object
value with non-null concatenated key, array containing a non-null object
after a NULL (error) string.

Fixes #444
2018-11-05 16:49:22 -05:00
Corey Farrell
6ac0eefed0
Merge pull request #436 from edgale/warnings
removed various warnings
2018-10-17 06:29:47 -04:00
Maximilian Röhrle
226b34d546
fixed extra bracket 2018-10-15 07:05:02 +02:00
Maximilian Röhrle
d115953347 removed explicit casts 2018-10-15 06:58:19 +02:00
Corey Farrell
15f77c8f47
Merge pull request #439 from coreyfarrell/codecoverage
Fix code coverage ignored paths.
2018-09-29 15:37:56 -04:00
Corey Farrell
ef080d17b5
Fix code coverage ignored paths.
* Replace 'tests/*' with '*/test/*'.
* Replace '/usr/*' with '/usr/include/*'.  This resolves an issue where
  it was impossible to test code coverage with the source in /usr/src.
* Ignore build/include/jansson.h as we just want src/jansson.h.
2018-09-29 14:36:54 -04:00
Corey Farrell
4f91b1d072
Merge pull request #438 from coreyfarrell/issue-437
json_pack: Improve handling of formats with '?' and '*'.
2018-09-28 14:47:33 -04:00
Corey Farrell
8d659113d5
More work on json_pack error reporting.
* Remove errant line-feed from pack_object error message.
* Correct error message in pack_object_inter.
* Create pack_integer / pack_real to get the correct error messages on
  failure when packing numeric values.
* Add tests for packing NAN and infinity directly, in an array and as
  an object value.
2018-09-25 18:03:06 -04:00
Corey Farrell
5df5fc5b13
json_pack: Improve handling of formats with '?' and '*'.
When NULL is received for an optional argument we should not set an
error message as this would block later error messages. If NULL is
received for a non-optional string we should set has_error. Set
has_error for UTF-8 errors to ensure optional strings with UTF-8
errors are not replaced with json_null(). Use 'purpose' argument in
NULL error messages of read_string.

Add error handling and tests for invalid formats where '+', '#', or '%'
is used on an optional string 's?' or 's*'.

Fix NULL string error messages to use 'purpose'.

Refactor skipping of '*' token, this is now handled by read_string and
pack_object_inter. This allows invalid format strings such as 's*#' and
's*+' to produce error messages.

Fixes #437
2018-09-25 16:35:19 -04:00
Petri Lehtinen
e65a490c44
Merge pull request #435 from edgale/master
unreferenced variable fix
2018-09-04 06:25:45 +03:00
Maximilian Röhrle
fc591913ac removed various warnings 2018-08-31 09:01:36 +02:00
Maximilian Röhrle
d83d3d9172 This fixes https://github.com/akheron/jansson/issues/434 2018-08-30 14:45:28 +02:00
Petri Lehtinen
020cc26b5c Rename a varialble that shadows another one
Fixes #430
2018-08-12 18:25:51 +03:00
Michal Privoznik
360b1ef5a1 Enable -Bsymbolic-functions linker flag whenever possible
It was discovered fairly recently that JSON parsing libraries use
common pattern to name their exported symbols (they all use
json_ prefix). So eventually it happens that two symbols from two
different libraries have the same name. This will lead to cryptic
crashes (see [1] and [2]). Linking with -Bsymbolic-functions
prevents this.

1: https://gitlab.gnome.org/GNOME/json-glib/issues/33
2: https://groups.google.com/forum/#!topic/jansson-users/7Efx-RI45IU

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2018-08-09 07:54:26 +03:00
Petri Lehtinen
37147b8a23
Merge pull request #423 from coreyfarrell/gcc-8
Deal with warnings under gcc 8.
2018-08-02 11:26:11 +03:00
Petri Lehtinen
8a00a56ec4
Merge pull request #424 from Crayon2000/patch-1
Update copyright for 2018
2018-07-30 13:42:05 +03:00
Petri Lehtinen
401ece058d
Merge pull request #427 from lxin/va_end
Call va_end after va_copy in json_vsprintf
2018-07-30 13:41:39 +03:00
Xin Long
66e4ee795d Call va_end after va_copy in json_vsprintf
As said in man doc:
  "Each  invocation  of va_copy() must be matched by a corresponding
   invocation of va_end() in the same function."

va_copy may alloc memory in some system, it's necessay to free it by
va_end.

Fixes: efe6c7b3f2 ("Add json_sprintf and json_vsprintf")
Signed-off-by: Xin Long <lucien.xin@gmail.com>
2018-07-25 17:44:00 +08:00
Crayon
3e13f514ce
Update copyright for 2018 2018-07-14 16:34:33 -04:00
Corey Farrell
81fe13eeed Deal with warnings under gcc 8.
Recent versions of gcc have introduced compiler warnings for string
operations that could be truncated.  This caused problems with -Werror.
src/error.c used strncpy to write "..." to a string, but skipped writing
the NUL terminator.  Switch this to use memcpy.  src/load.c produced
warnings from snprintf writing error strings that could be truncated.
Added code to autotools build to detect `-Wno-format-truncation', add it
to AM_CFLAGS if supported.
2018-07-14 13:24:55 -04:00
Petri Lehtinen
aed855e692 Avoid invalid memory read in json_pack()
Initial patch by @bharjoc-bitdefender

Fixes #421
2018-07-09 22:26:35 +03:00
Petri Lehtinen
b59ac57617
Merge pull request #415 from palmerc/master
CMake variable to number comparison changed to provide meaningful error
2018-05-22 07:38:17 +03:00
Cameron Lowell Palmer
904f5c28ac CMake variable to number comparison changed to provide meaningful error
message.  Explicitly specify STATIC and PIC
2018-05-18 10:35:05 +02:00
Petri Lehtinen
80cea73bf9
Merge pull request #408 from isaachier/cmake
CMake improvements, make package relocatable
2018-05-18 08:08:32 +03:00
Petri Lehtinen
e28bcfeac8
Merge pull request #417 from akheron/visual-studio-15
Appveyor & build instructions for Visual Studio 15 2017
2018-05-07 14:22:03 +03:00
Petri Lehtinen
fda9288b5f Update build instructions for Visual Studio 2018-05-07 11:17:08 +03:00
Petri Lehtinen
9ff08f6312 Also build with VS 2017 in appveyor 2018-05-07 08:39:49 +03:00
Petri Lehtinen
dd4743a51d
Merge pull request #412 from Mephistophiles/fix_defines
Fix JSON_HAVE_SYNC_BUILTINS define usage
2018-05-07 08:13:21 +03:00
Maxim Zhukov
50f29f9b1a Add JSON_HAVE_SYNC_BUILTINS and JSON_HAVE_ATOMIC_BUILTINS for autoheader
Added JSON_HAVE_SYNC_BUILTINS and JSON_HAVE_ATOMIC_BUILTINS defines to
jansson_config.h.cmake as well as in the autoheader for autoconf.
2018-03-22 17:46:29 +03:00
Petri Lehtinen
e5dbe7bb64
Merge pull request #409 from Mephistophiles/master
Fix error handling in json_pack
2018-03-22 10:40:41 +02:00
Maxim Zhukov
15105b66b4 Fix error handling in json_pack
Fixed a bug where the error message was not filled if an empty object
was passed to the json_pack.

Fixes #271
2018-03-22 11:16:40 +03:00
Petri Lehtinen
b23025d72b
Merge pull request #404 from coreyfarrell/func-attrs
Build: Add JANSSON_ATTRS macro.
2018-03-20 04:55:48 +02:00
Isaac Hier
2c98c30a02 Stop using absolute paths 2018-03-11 10:54:24 -04:00
Isaac Hier
bb71db204f Fix output file name for version config 2018-03-11 10:54:14 -04:00
Isaac Hier
92760bb363 Remove warning 2018-03-11 10:54:02 -04:00
Isaac Hier
fe7873e963 Fix package version config generation 2018-03-11 10:37:15 -04:00
Isaac Hier
a586c0654f Fix CMake include 2018-03-11 10:27:48 -04:00
Isaac Hier
6d7a02beb0 Clean up CMake install 2018-03-11 10:24:27 -04:00
Isaac Hier
b70364b362 Remove absolute path references 2018-03-11 10:11:09 -04:00
Isaac Hier
6d1ae86e1c Fix config file 2018-03-11 09:59:52 -04:00
Isaac Hier
a324d18940 Rename target file 2018-03-11 09:53:06 -04:00
Isaac Hier
44f6606df8 Rename config files 2018-03-11 09:47:29 -04:00
Isaac Hier
d8798468c6 Upgrade CMake to 3.1 for Hunter 2018-03-11 09:34:45 -04:00
Corey Farrell
749bef0b6a More test coverage.
* Add test_load_callback to CMakeList.txt
* Add json_dump, json_load and json_unpack chaos testing.
2018-03-06 23:28:14 -05:00
Corey Farrell
e37e52549f Add warn_unused_result to strbuffer_init.
This adds a compiler warning when strbuffer_init return value is
ignored.  unpack_object is updated to deal with errors produced
while building unrecognized_keys.
2018-03-06 08:27:20 -05:00
Corey Farrell
ea664722d4 Build: Add JANSSON_ATTRS macro.
This macro is used to conditionally generate GCC/CLANG __attribute__
declarations if supported.

This allows the compiler to produce warnings on certain incorrect
usages.  json_sprintf and json_vsprintf will produce warnings on invalid
format string.  Many functions will produce a warning if the result is
unused.  Specifically functions which allocate new objects will warn if
the result is ignored as this always results in a memory leak.
2018-03-06 07:25:16 -05:00
Petri Lehtinen
d098c0ff86
Merge pull request #400 from coreyfarrell/branch-coverage
Enable branch coverage reporting.
2018-02-20 15:39:36 +02:00
Petri Lehtinen
2d494c169f
Merge pull request #398 from coreyfarrell/test-coverage
Improve test coverage.
2018-02-20 15:39:19 +02:00
Corey Farrell
a5af280bac Enable branch coverage reporting. 2018-02-20 03:09:03 -05:00
Corey Farrell
73c22de516 Improve test coverage.
* Test equality of different length strings.
* Add tab to json_pack whitespace test.
* Test json_sprintf with empty result and invalid UTF.
* Test json_get_alloc_funcs with NULL arguments.
* Test invalid arguments.
* Add test_chaos to test allocation failure code paths.
* Remove redundant json_is_string checks from json_string_equal and
  json_string_copy.  Both functions are static and can only be called
  with a json string.

Fixes to issues found by test_chaos:
* Fix crash on OOM in pack_unpack.c:read_string().
* Unconditionally free string in string_create upon allocation failure.
  Update load.c:parse_value() to reflect this.  This resolves a leak on
  allocation failure for pack_unpack.c:pack_string() and
  value.c:json_sprintf().

Although not visible from CodeCoverage these changes significantly
increase branch coverage.  Especially in src/value.c where we previously
covered 67.4% of branches and now cover 96.3% of branches.
2018-02-15 10:12:31 -05:00
Petri Lehtinen
6dddf687d8
Merge pull request #396 from coreyfarrell/2.11
jansson 2.11
2018-02-11 20:11:41 +02:00
Corey Farrell
744fe5ed44 jansson 2.11 2018-02-09 12:31:18 -05:00
Petri Lehtinen
03620980cf
Merge pull request #395 from akheron/doc-utf-8
Document encoding requirements for callbacks
2018-02-09 10:10:34 +02:00
Petri Lehtinen
248d62111c
Merge pull request #368 from AmeyaVS/cmake_build_fix
Fix generated `pkg-config` file using cmake.
2018-02-09 09:45:36 +02:00
Petri Lehtinen
46dff2737d
Merge pull request #381 from phst/end-of-file-error-code
Use a more specific error code for premature end of input
2018-02-09 09:40:42 +02:00
Petri Lehtinen
fa0b5ece9e
Merge pull request #380 from phst/doc-error-code
document that json_error_code will be added in version 2.11
2018-02-09 09:39:38 +02:00
Petri Lehtinen
a6138a07b6 Document encoding requirements for callbacks
Original patch by @phst.

Fixes #369.
2018-02-09 09:35:53 +02:00
Petri Lehtinen
2863dde053
Merge pull request #393 from akheron/json_sprintf
Add json_sprintf and json_vsprintf
2018-02-09 08:15:16 +02:00
Petri Lehtinen
efe6c7b3f2 Add json_sprintf and json_vsprintf
Fixes #392
2018-02-09 07:37:33 +02:00
Petri Lehtinen
3e81f78366
Merge pull request #389 from coreyfarrell/threadsafety
Atomic references and thread safe json_dump
2018-02-08 20:19:07 +02:00
Corey Farrell
8104ce167a
Merge pull request #1 from akheron/threadsafety
Clarify thread safety docs, rename JANSSON_THREAD_SAFE
2018-02-08 11:58:30 -05:00
Petri Lehtinen
f44921e176 Clarify thread safety docs, rename JANSSON_THREAD_SAFE 2018-02-08 12:38:14 +02:00
Corey Farrell
3aee856d7b Docs: Update information on thread safety.
Fixes #387
2018-02-01 15:54:35 -05:00
Corey Farrell
37e0ee4d48 json_dump: Fix thread safety issue.
Circular reference detection in json_dump was not thread safe.  Replace
visited flag with a hashtable_t.

Issue #387
2018-02-01 15:54:25 -05:00
Corey Farrell
dc3b313e91 Use thread-safe reference counting if supported by the compiler.
This makes use of __atomic or __sync builtin compiler functions to make
json_decref and json_incref thread-safe.

Issue #387
2018-01-29 14:17:58 -05:00
Philipp Stephani
45228cada4 Use a more specific error code for premature end of input 2017-12-20 18:27:04 +01:00
Philipp Stephani
24d45272a7 document that json_error_code will be added in version 2.11 2017-12-18 23:51:32 +01:00
Petri Lehtinen
9e5af7c3b7
Merge pull request #374 from coreyfarrell/always-steal
json_pack: Enable more complete stealing of references.
2017-12-16 20:35:14 +02:00
Corey Farrell
6c78910011 apiref: Clarify documentation for unpack O format.
The `O` format causes reference counts to increase, but in an error they
are not released.  Callers to unpack functions that use the `O` format
should use pointers pre-initialized to NULL so they can safely release
the reference on error.

Also corrected typo which said this was like `O` (itself).

Fixes #135
2017-12-13 14:04:07 -05:00
Corey Farrell
89dad8959b json_object_iter_set_new: Fix error branch leak.
This function needs to release a reference to value if the other
arguments are invalid.

Issue #135
2017-12-13 14:04:07 -05:00
Corey Farrell
9a1d9c88fc json_pack: Enable more complete stealing of references.
Users of the "o" format have an expectation that the object reference
will be stolen.  Any error causes the collection process to end early.
This patch causes json_pack and related functions to continue scanning
the format and parameters so all references can be stolen to prevent
leaks.  This makes no attempt to continue processing if the format
string is broken or missing.

'make check' still passes.  Ran test_pack under valgrind and verified
that the leaked reference is fixed. Added a test which uses refcounts
to verify that the reference was correctly stolen after a NULL value
error.

Issue #135
2017-12-13 14:03:58 -05:00
Petri Lehtinen
02dade46c0
Merge pull request #375 from phniix/373_upstream_typo_in_cmakelists
Fixes akheron/jansson#373
2017-12-13 07:08:25 +02:00
Petri Lehtinen
bc5c6826ef
Merge pull request #377 from coreyfarrell/extra-refs
Remove extra reference actions in parsers.
2017-12-13 07:07:33 +02:00
Petri Lehtinen
217859f849
Merge pull request #378 from phst/doc
Document that length-aware string functions have been added in 2.7
2017-12-13 07:05:15 +02:00
Philipp Stephani
3951d39b40 Document that length-aware string functions have been added in 2.7 2017-12-10 16:53:01 +01:00
Corey Farrell
bd91753e91 Remove extra reference actions in parsers.
Make parse_object use json_object_set_new_nocheck and make parse_array
use json_array_append_new, remove json_decref from error and success
paths.

Fixes #376
2017-11-14 23:52:49 -05:00
Joe Hura
0b04762c94 Fixes akheron/jansson#373
'sys/time.h' is a typo, it should read: 'sys/types.h'
2017-11-07 19:32:14 +11:00
Petri Lehtinen
009ffa3fc8 Fix a compile error on macOS clang
Reported by Diederick Huijbers
2017-11-07 10:20:21 +02:00
Ameya Vikram Singh
89f0dde7ff Fix generated pkg-config file using cmake.
Fixed the generated `jansson.pc` with cmake to be consistent with the
one generated using GNU Autotools.
2017-10-29 23:57:25 +05:30
Petri Lehtinen
9e7847ed26 Merge pull request #365 from phst/bug352
Use last byte of error text as numeric error code
2017-10-09 08:07:42 +03:00
Philipp Stephani
112ccbd820 Use last byte of error text as numeric error code
Fixes #352
2017-10-03 11:42:07 +02:00
Petri Lehtinen
271ffda903 Make json_equal() const-correct
Fixes #344
2017-08-19 21:10:17 +03:00
Petri Lehtinen
3e5405c39e Work around gcc's -Wimplicit-fallthrough 2017-08-19 21:09:32 +03:00
Petri Lehtinen
93e8cd7d68 Merge pull request #359 from sanjay24/master
json_dump_file API returns success even when fclose fails
2017-08-06 07:14:18 +03:00
Sanjay Kumar
0abcbce3bb json_dump_file API returns success even when fclose fails (consider disk full case). API should check the return value of fclose before returning success to its caller. fwrite may not write anything into the file, it simply returns the number of bytes written into the buffer. When disk is full and fclose is called, it results in truncation of the file (resulting in zero sized file). Since, API is returning success, its caller can't take any remedial action on its failure. 2017-08-05 23:52:49 +05:30
Petri Lehtinen
4947f9a193 Merge pull request #356 from hellojaewon/master
Docs - Fix typo
2017-07-20 22:42:29 +03:00
최재원
ad6c1e37ad Fix typo 2017-07-16 19:16:34 +09:00
Petri Lehtinen
f52c3da717 Merge pull request #339 from npmccallum/optpack
Enable optional object members in json_pack()
2017-04-19 16:17:28 +03:00
Nathaniel McCallum
28666cead0 Enable optional object/array members in json_pack() 2017-04-19 07:19:29 -04:00
Petri Lehtinen
74028ff958 Merge commit '1b8bebf0bf8f1c0c3d92faf67a830bf8448897ed' 2017-04-13 13:46:35 +03:00
Petri Lehtinen
fbf720f2c5 Allow forward declaring json_error_t values 2017-04-13 13:39:43 +03:00
Mathieu Lirzin
1b8bebf0bf build: Use Autoconf macro @includedir@ for jansson.pc.
This is more consistent with what is done for other pkg-config
variables.
2017-04-12 22:36:58 +02:00
Petri Lehtinen
f7a70de84a Merge pull request #336 from akheron/issue-333
CMakeLists.txt: Remove extra parenthesis
2017-03-29 07:31:26 +03:00
Petri Lehtinen
17f77cf2c6 CMakeLists.txt: Remove extra parenthesis
Fixes #333
2017-03-29 07:08:19 +03:00
Nathaniel McCallum
b23201bb1a jansson 2.10 2017-03-02 20:49:42 +02:00
Petri Lehtinen
df454e3cf0 Merge pull request #329 from npmccallum/embed
Add JSON_EMBED encoding flag
2017-03-02 07:55:50 +02:00
Nathaniel McCallum
b8bb078cc2 Add JSON_EMBED encoding flag
The JSON_EMBED encoding flag causes the opening and closing characters
of the top-level array ('[', ']') or object ('{', '}') to be omitted
during encoding. This feature makes it possible to concatenate multiple
arrays or objects in the stream output. It also makes it possible to
perform outputs of partial composes.

One such example of a partial compose is when outputting a JWE object.
The output is a JSON object. But it has one top-level attribute
("ciphertext") that can grow out of proportion with the rest of the
metadata. With the JSON_EMBED flag, the other metadata can be composed
ahead of time and dumped during the beginning of output, where the
"ciphertext" and "tag" attributes can be streamed out in chunks. Thus,
the header material can be composed with Jansson and the ciphertext
itself can be composed manually.
2017-02-27 15:09:03 -05:00
Petri Lehtinen
3c51112063 Merge pull request #328 from npmccallum/master
Helper functions for network IO
2017-01-31 08:45:40 +02:00
Nathaniel McCallum
1672bb5a65 Implement json_dumpfd() and json_loadfd()
The primary use of these functions is easy loading
and dumping from stream sockets.

Signed-off-by: Nathaniel McCallum <npmccallum@redhat.com>
2017-01-27 09:15:18 +01:00
Nathaniel McCallum
b900967f6f Implement json_dumpb()
This function encodes the json_t object to a pre-allocated buffer.
It compliments the already existing json_loadb() function and is
useful for parsing JSON-RPC (among other protocols) when sent over
datagram sockets.

Signed-off-by: Nathaniel McCallum <npmccallum@redhat.com>
2017-01-26 16:16:24 +01:00
Petri Lehtinen
746c2c3a99 Merge pull request #321 from quiet/master
parens for LONG_LONG_INT in cmake
2016-11-16 07:11:03 +02:00
Brian Armstrong
2af820fb99 parens for LONG_LONG_INT in cmake
when this is defined as "", cmake bails with an error about arguments in
if
2016-11-12 18:58:38 -08:00
Petri Lehtinen
bc5741fb1a Merge pull request #314 from martinlindhe/condition-always-true
part of conditional expression is always true (!done)
2016-10-24 21:47:49 +03:00
Petri Lehtinen
575f951b3e Merge pull request #311 from robertmu/master
Fix passing redundant argument to error_set()
2016-10-24 21:45:50 +03:00
Petri Lehtinen
0cac862bbc Merge pull request #309 from halfaleague/larger-json-buffers
Allow parsing of buffers larger than 2GB on most 64 bit arch.
2016-10-24 21:42:30 +03:00
Martin Lindhe
4467bf243f part of conditional expression is always true (!done), found with pvs-studio 2016-10-19 16:39:26 +02:00
Robert Mu
ddd1e1f223 Fix passing redundant argument to error_set() 2016-10-07 22:11:19 +08:00
Luke Carmichael
d1e97737d6 Allow parsing of buffers larger than 2GB on most 64 bit arch.
size_t is usually 64 bits on most architectures -- this allows for larger .json files
2016-10-01 22:06:34 -04:00
Petri Lehtinen
98be7da3e2 doc: Change version to 2.10-dev 2016-09-18 14:52:26 +03:00
Petri Lehtinen
08cb7b6d6f doc: Change version to 2.9 2016-09-18 14:52:17 +03:00
Petri Lehtinen
b02db47881 jansson 2.9 2016-09-18 14:35:05 +03:00
Petri Lehtinen
074bb3838f Update copyrights for 2016 2016-09-18 14:17:03 +03:00
Petri Lehtinen
3ba3b23fdc Merge branch '2.8' 2016-09-16 08:05:48 +03:00
Matthew Johnston
e9fcab08fb Add install targets to be optional 2016-09-16 08:05:13 +03:00
Yuriy Romanenko
bdaf7584db Added test files to .gitignore 2016-09-16 08:05:13 +03:00
Petri Lehtinen
889280c976 Don't include jansson_config.h in dist tarballs
Fixes #306
2016-09-16 08:02:26 +03:00
Petri Lehtinen
f9e7aa5eeb Merge pull request #305 from warmwaffles/master
Allow install targets to be optionally defined
2016-09-12 07:46:52 +03:00
Matthew Johnston
9258671924 Add install targets to be optional 2016-09-11 00:04:49 -05:00
Petri Lehtinen
a2bbb44d96 Merge pull request #303 from groman2/yr-dev
Added test files to .gitignore
2016-09-08 07:59:04 +03:00
Yuriy Romanenko
16b516f976 Added test files to .gitignore 2016-09-07 10:13:52 -07:00
Petri Lehtinen
86196250b8 Merge branch '2.8' 2016-09-01 07:07:57 +03:00
Petri Lehtinen
ada5372cff Fix another typo 2016-09-01 07:06:25 +03:00
Petri Lehtinen
f11c1b9466 Merge pull request #302 from yujunz/patch-1
Fix typo
2016-09-01 07:05:20 +03:00
Yujun Zhang
811a30691e Fix typo 2016-09-01 08:44:08 +08:00
Petri Lehtinen
7d1af52ab4 Merge pull request #301 from npmccallum/master
Add support for the cleanup attribute in GCC/Clang
2016-08-31 17:57:23 +03:00
Nathaniel McCallum
63b9fd0552 Add support for the cleanup attribute in GCC/Clang
The new json_auto_t macro allows easy declaration of json_t types that
automatically decrement at the end of their scope.
2016-08-31 08:57:57 -04:00
Petri Lehtinen
b45745118d doc: Fix json_error_t::position type
Fixes #300
2016-08-31 12:18:25 +03:00
Petri Lehtinen
0ffecdbade doc: Fix json_error_t::position type
Fixes #300
2016-08-31 12:17:03 +03:00
Petri Lehtinen
ab1ba69027 Set documentation version to 2.9-dev 2016-08-30 21:19:51 +03:00
Petri Lehtinen
a5610c8895 Set documentation version to 2.8 2016-08-30 21:19:13 +03:00
Petri Lehtinen
012c5f0eca jansson 2.8 2016-08-30 21:09:28 +03:00
Petri Lehtinen
a931aace16 jansson 2.8 2016-08-26 20:35:52 +03:00
Petri Lehtinen
14573dc920 Merge pull request #293 from akheron/object-insertion-order
Always preserve insertion order of object items
2016-08-25 20:20:34 +03:00
Petri Lehtinen
71594af7d5 Merge pull request #298 from pasiopou/oom-crash
OOM crash
2016-08-11 22:15:01 +03:00
Andreas Pasiopoulos
6a4b3f878d Conform to c89 2016-08-11 18:51:29 +03:00
Andreas Pasiopoulos
86fdf76f79 Check the allocation was successful before freeing existing hashtable buckets
and increasing hashtable order

Fixes a crash observed when there is OOM in hashtable_do_rehash
2016-08-11 17:48:29 +03:00
Andreas Pasiopoulos
835290dfdf Add a test case for OOM while allocating memory 2016-08-11 17:18:46 +03:00
Petri Lehtinen
7daffabf07 Fix a typo 2016-06-24 06:55:49 +03:00
Petri Lehtinen
9df267054f Always preserve insertion order of object items 2016-06-20 21:10:23 +03:00
Petri Lehtinen
8f067962f6 Merge pull request #290 from Thynix/documentation
Polish API documentation
2016-06-20 07:29:29 +03:00
Steve Dougherty
603fdc9154 doc: fix code block formatting 2016-06-17 10:45:47 -04:00
Petri Lehtinen
520340998f Merge pull request #289 from akheron/simplify-snprintf-checks
Simplify snprintf and vsnprintf checking for Visual Studio
2016-06-03 12:29:55 +03:00
Petri Lehtinen
2d710d832f appveyor.yml: Build on all Visual Studio versions 2016-06-03 12:08:36 +03:00
Steve Dougherty
a8c834c882 doc: improve conciseness
The object_to_key_iter() example is now formatted like
json_object_foreach() and json_object_foreach(). The edited descriptions were
redundant, and the removed headers didn't add useful information.
2016-06-01 11:27:22 -04:00
Steve Dougherty
7438cc8ba8 doc: correct argument names
The function signatures use "json", not "root".
2016-06-01 11:27:22 -04:00
Petri Lehtinen
72fd2fec4c Simplify snprintf and vsnprintf checking for Visual Studio 2016-05-30 11:51:39 +03:00
Petri Lehtinen
762b299e71 Fix subnormal number parsing on mingw32
Patch by Blanca Elio Rosario.
2016-05-17 11:31:55 +03:00
Petri Lehtinen
013c3892c3 Merge pull request #284 from dev-zzo/issue-282
Don't crash on deeply nested values by limiting parser recursion depth
2016-05-03 13:07:46 +03:00
Dmitry Janushkevich
64ce0ad373 Fix for issue #282
The fix limits recursion depths when parsing arrays and objects.
The limit is configurable via the `JSON_PARSER_MAX_DEPTH` setting
within `jansson_config.h` and is set by default to 2048.

Update the RFC conformance document to note the limit; the RFC
allows limits to be set by the implementation so nothing has
actually changed w.r.t. conformance state.

Reported by Gustavo Grieco.
2016-05-03 10:22:06 +02:00
Petri Lehtinen
087ed94c45 Change readthedocs domain 2016-04-28 07:04:00 +03:00
Petri Lehtinen
006638a6a2 Merge pull request #275 from Mephistophiles/master
Fix proto in doc
2016-03-03 07:26:20 +02:00
Maxim Zhukov
130c2fff31 Fix proto in doc 2016-03-02 17:40:49 +03:00
Petri Lehtinen
cfd817895a doc: Fix a typo 2016-02-25 07:29:28 +02:00
Petri Lehtinen
ac97e0bf79 json_pack(): Document s?, o?, O? 2016-02-25 07:23:53 +02:00
Petri Lehtinen
1927eeb4b4 Merge pull request #270 from Alteous/master
Implemented json_pack() format specifiers 's?', 'o?', and 'O?'.
2016-02-25 07:13:04 +02:00
David Harvey-Macaulay
c8361441fe Revised commit. 2016-02-23 19:33:52 +00:00
David Harvey-Macaulay
107cfe9499 Implemented json_pack() format specifiers 's?', 'o?', and 'O?'. 2016-02-23 19:28:56 +00:00
David Harvey-Macaulay
811965b475 Implemented json_pack() format specifiers 's?', 'o?', and 'O?'. 2016-02-22 21:32:20 +00:00
Petri Lehtinen
e08101704c Merge pull request #268 from wingyplus/fix-libdir-pkg-config
Fix libdir is wrong path when compile with cmake
2016-02-11 07:29:57 +02:00
Petri Lehtinen
c17be5870b Merge pull request #267 from Mephistophiles/master
Optimized functions
2016-02-11 07:26:00 +02:00
Thanabodee Charoenpiriyakij
9d71d006cc Fix libdir is wrong when compile with cmake
because JANSSON_INSTALL_LIB_DIR is set to /usr/local/lib after
foreach loop
2016-02-10 18:46:43 +07:00
Maxim Zhukov
b698ca13de [Optimized functions]
Optimized json_equal, json_delete, json_copy, json_deep_copy
Replaced if to switch
Removed unnecessary check for NULL.
2016-02-03 17:34:54 +03:00
Petri Lehtinen
0f50bb10b6 Fix a typo 2015-12-23 08:18:27 +02:00
Petri Lehtinen
e6b60da043 Update CHANGES 2015-12-23 08:17:18 +02:00
Petri Lehtinen
89f4c15e6d Change doc version to 2.8-dev
It's shown in the front page of readthedocs/latest.
2015-12-23 07:40:58 +02:00
Petri Lehtinen
1c2e707b34 Fix a comment 2015-12-23 07:40:02 +02:00
Petri Lehtinen
52015cf35c Merge pull request #263 from wking/display-first-unrecognized-key
pack_unpack: List first unrecognized key in strict unpacking
2015-12-23 07:38:03 +02:00
W. Trevor King
1d513d063a pack_unpack: List unrecognized keys in strict unpacking
Otherwise figuring out what's wrong with your JSON can be tricky,
especially if you're using a single fmt string to validate a large,
complicated schema.

The comma delimiting will make separating keys that contain commas
difficult.  For example:

  {"foo, bar": true, "baz": false}

will generate errors like:

  2 object item(s) left unpacked: foo, bar, baz

but that seems like a small enough corner case to not be worth much
worrying.

I wanted to find a way to handle this without have_unrecognized_keys,
but the strbuffer tooling makes it look like I shouldn't be reaching
in to do things like:

  strbuffer_t unrecognized_keys;
  unrecognized_keys.value = NULL;

and then using 'unrecognized_keys.value == NULL' in place of
have_unrecognized_keys.
2015-12-22 10:05:31 -08:00
Petri Lehtinen
581d5b899c Add versionadded to json_get_alloc_funcs doc 2015-12-22 13:05:28 +02:00
Petri Lehtinen
4f49c07781 Merge pull request #264 from npmccallum/master
Add json_get_alloc_funcs() to allow alloc function fetching
2015-12-22 13:01:36 +02:00
Nathaniel McCallum
245e532934 Add json_get_alloc_funcs() to allow alloc function fetching
This is particularly useful in modular situations where the allocation
functions are either unknown or private. For instance, in such cases,
the caller of json_dumps() has no way to free the returned buffer.
2015-12-21 11:46:32 -05:00
Petri Lehtinen
e44b2231b5 doc: Fix a broken link
Fixes #258
2015-10-20 10:21:08 +03:00
Petri Lehtinen
40bd71f064 Merge pull request #257 from denis2342/master
changed code from while to do/while
2015-10-14 08:54:37 +03:00
Denis Ahrens
067dc50efe changed code from while to do/while 2015-10-12 16:11:56 +02:00
Petri Lehtinen
4876bda857 Merge pull request #255 from gonzzor/snprintf_dump.c
Improve usage of snprintf in dump.c
2015-10-05 15:43:45 +03:00
Jonas Jonsson
e89538f685 Format %x expects unsigned int, not int
Be more explicit that a cast is happening.
2015-10-05 14:00:44 +02:00
Jonas Jonsson
f7331c7194 Use sizeof(seq) instead of magic number 13
Be more future proof by keeping the number of magic constants low.
2015-10-05 13:59:09 +02:00
Petri Lehtinen
02464862ed Merge pull request #248 from phoenix0428/patch-1
Update test_memory_funcs.c
2015-09-08 21:13:08 +03:00
Petri Lehtinen
db0213ae56 Merge pull request #252 from OlehKulykov/master
Buildable with MS Compiler version  >= 1900
2015-09-01 21:13:25 +03:00
OlehKulykov
8f2298bad8 Buildable with MS Compiler version >= 1900 2015-08-31 23:43:29 +02:00
Petri Lehtinen
4c4f692bd6 Add json_object_foreach_safe
Fixes #230.
2015-08-26 17:32:55 +03:00
Kinam Kim
875b78dc97 Update test_memory_funcs.c 2015-08-13 16:44:31 +09:00
Petri Lehtinen
fef27e6d3e Merge branch '2.7' 2015-05-19 08:54:13 +03:00
Petri Lehtinen
1dab656dee doc: Copying doesn't preserve key insertion order
Fixes #237.
2015-05-19 08:54:09 +03:00
Petri Lehtinen
69678aaa35 doc: Copying doesn't preserve key insertion order
Fixes #237.
2015-05-19 08:49:10 +03:00
Petri Lehtinen
d384acd706 Merge pull request #234 from flok99/master
Optimized dump_indent to reduce the number of fwrite calls.
2015-05-04 09:00:26 +03:00
Folkert van Heusden
5d42e1520a Optimized dump_indent to reduce the number of fwrite calls. 2015-05-01 15:18:53 +02:00
Petri Lehtinen
d8753db4ac Merge pull request #233 from haldean/master
Use snprintf and strncpy in place of sprintf and strcpy

OpenBSD linker nags about using sprintf and strcpy.
2015-04-30 10:43:39 +03:00
Haldean
95dd927857 use snprintf and strncpy in place of sprintf and strcpy
This is both good practice and nice for OpenBSD users, who will no
longer get the nag message to not use sprintf/strcpy every time they
link against jansson. It's worth noting that the existing code seems
safe to me - bounds checks were already happening before the actual
calls - and that this is for extra security.
2015-04-30 00:11:25 -07:00
Petri Lehtinen
76760011ff Don't crash when building documentation man pages
Fixes #207.
2015-03-07 09:14:06 +02:00
Petri Lehtinen
11813f4128 Fix a use after free 2015-02-07 07:36:29 +02:00
Petri Lehtinen
8b1bdcacb7 Merge pull request #221 from lioncash/test
test_object: Fix a duplicate conditional check in test_iterators
2015-02-05 09:28:43 +02:00
Lioncash
c242b46016 test_object: Fix a duplicate conditional check in test_iterators 2015-02-05 01:26:13 -05:00
Petri Lehtinen
58c188e1d5 Merge pull request #217 from JoakimSoderberg/simple_parse_cmake
Compile simple_parse example for CMake project.
2015-01-14 08:05:51 +02:00
Petri Lehtinen
ffc18128f4 Merge pull request #216 from JoakimSoderberg/infinity_warning
Disable warning for deliberate use on MSVS.
2015-01-14 08:04:37 +02:00
Joakim Soderberg
6a38d0d431 Disable warning for deliberate use on MSVS.
Disable "warning C4756: overflow in constant arithmetic" when deliberately
triggering it in a test using infinity.
2015-01-13 16:30:00 +01:00
Joakim Soderberg
d0a8ad4c06 Compile simple_parse example for CMake project. 2015-01-13 16:17:48 +01:00
Petri Lehtinen
c244b1483e examples/README.rst: Fix formatting 2014-12-30 08:56:07 +02:00
Petri Lehtinen
fc83f10c85 Add Makefile.am for examples 2014-12-30 08:50:33 +02:00
Petri Lehtinen
8d561cd94e examples/simple_parse.c: Reindent, fix warnings & style 2014-12-30 08:50:33 +02:00
Petri Lehtinen
970c6988a5 Merge pull request #214 from rdpoor/master
adding simple-parse example
2014-12-30 08:33:34 +02:00
Robert Poor
220dcb7be3 use fgets() rather than getline() 2014-12-29 06:22:19 -08:00
Robert Poor
48e0488f07 adding simple-parse example 2014-12-26 10:49:15 -08:00
Petri Lehtinen
890760b2fb Increase test coverage 2014-12-19 08:35:46 +02:00
Petri Lehtinen
15653c47dd Add a test case for \u0000 2014-12-19 07:57:33 +02:00
Petri Lehtinen
5508ab403d Honor JSON_DECODE_INT_AS_REAL at lexical stage
This has the consequence that numbers are never converted to integers
when JSON_DECODE_INT_AS_REAL is set, and thus it works correctly all
integers that are representable as double.

Fixes #212.
2014-12-18 15:16:14 +02:00
Petri Lehtinen
d799ee11b4 doc: Update the Getting Started chapter
- It's not true anymore that there are no configure options that modify
  Jansson's behaviour

- Remove trailing whitespace
2014-12-18 14:47:08 +02:00
Petri Lehtinen
abaae7630e Make it possible to set initial hashtable size
Fixes #213.
2014-12-18 14:43:44 +02:00
Petri Lehtinen
5c1d87592a wip: add tests 2014-12-15 08:30:59 +02:00
Petri Lehtinen
5885035f5f Add coveralls.io badge to README.rst 2014-12-15 08:14:57 +02:00
Petri Lehtinen
dee4a7c29e Merge pull request #211 from JoakimSoderberg/coveralls
Add support for coverage/coveralls.io in cmake project.
2014-12-15 08:09:13 +02:00
david bigagli
82a55ef205 doc patch for jansson 2014-12-15 07:47:19 +02:00
Joakim Söderberg
19f33c0e71 Add support for coverage/coveralls.io in cmake project.
This adds support for http://coveralls.io/ to the cmake project. This can then be run via a new Travis job, which uploads json containing the coverage data to the website.

To use this, please login usin github at http://coveralls.io/ and enable the Jansson project. You can then get a nice percentage badge for code coverage after each Travis buid. Coveralls will also comment on pull request with coverage info.

To test and run it locally do:

```bash
$ mkdir build && cd build
$ cmake -DJANSSON_COVERALLS=ON -DCMAKE_BUILD_TYPE=Debug ..
$ cmake --build .                      # $ make
$ cmake --build . --target coveralls   # $ make coveralls
```

There is also another script that generates a local HTML page using lcov CodeCoverage.cmake which can be run using

```bash
$ make coverage
```

The required depdencies to run this are:
gcov
curl
lcov (is needed for the normal CodeCoverage script)
2014-12-12 23:57:01 +01:00
Petri Lehtinen
3c9e5c9925 Move the list member to the top of hashtable_pair struct
This may make debugging easier with limited debuggers.
2014-12-10 07:41:41 +02:00
Petri Lehtinen
1c38ab17f5 Include jansson_config.h with quotes
Fixes #209.
2014-12-04 10:45:26 +02:00
Petri Lehtinen
d5edfcc6fd Merge pull request #208 from skeid21/master
Fix warnings on LLVM 6.0 targetion iOS arm64.
2014-11-29 11:52:11 +02:00
Shawn Harris
9b435df3d4 Warnings - use size_t where appropriate to prevent warning when compilation is targeting 64 bit 2014-11-28 18:11:26 -07:00
Petri Lehtinen
bc743ad2d9 README: Documentation is hosted at RTD 2014-10-20 20:27:56 +03:00
Petri Lehtinen
19cc800ad3 Merge pull request #206 from chrullrich/fix-win-build
Fix CMake configuration for Windows build
2014-10-14 12:28:19 +03:00
Christian Ullrich
b52e7a69aa Fix CFLAGS for static-CRT build.
Setting the variables to only "/MT(d)" resets all other flags to their defaults, so the debug build used release flags.
2014-10-13 13:06:02 +02:00
Christian Ullrich
1395e4303a Fix static CRT selection. 2014-10-13 13:04:04 +02:00
Petri Lehtinen
d7a6269a17 Use expr instead of $((...)) in shell scripts
For Solaris 10 compatibility.
2014-10-03 08:49:08 +03:00
Petri Lehtinen
7fbe7c3960 Don't use the nonstandard __FUNCTION__ macro 2014-10-03 08:38:57 +03:00
Petri Lehtinen
ee27b7e3dd jansson 2.7 2014-10-02 13:10:45 +03:00
Petri Lehtinen
391d9101a8 Update CHANGES for 2.7 2014-10-02 08:57:07 +03:00
Petri Lehtinen
2137e0c895 Add AppVeyor badge to README.rst 2014-09-25 07:51:55 +03:00
Petri Lehtinen
5fc44e10aa Merge pull request #205 from JoakimSoderberg/appveyor
Added Windows CI support with appveyor
2014-09-25 07:45:24 +03:00
Joakim Soderberg
b94d767f86 Added Windows CI support with appveyor
Added support for http://www.appveyor.com/ (login via github account).

This will build the project and run the unit tests on Windows as well.
Possible to add a badge like with Travis in the README.md as well.
2014-09-24 18:08:45 +02:00
Petri Lehtinen
43f17d010a Merge pull request #204 from bgoglin/master
Don't use GNU-make specific export for global AM_CFLAGS
2014-08-27 08:02:59 +03:00
Petri Lehtinen
fa20e80860 Parse subnormal numbers correctly
Fixes #202.
2014-08-27 07:59:52 +03:00
Brice Goglin
485c7640a1 Don't use GNU-make specific export for global AM_CFLAGS
Just define it at configure time, it's automatically set in all makefiles.

Fixes #203.
2014-08-26 15:01:13 +02:00
Petri Lehtinen
d4a7de7c11 Android.mk: Add -DHAVE_STDINT_H to LOCAL_CFLAGS
See #200.
2014-07-31 07:50:31 +03:00
Petri Lehtinen
a6229a2d3e doc: Enhance string overview 2014-07-21 08:15:34 +03:00
Petri Lehtinen
abd151f5d7 Merge pull request #198 from Smilex/mem_fix
Fixed cases where file would be opened, but not closed.
2014-07-21 08:09:18 +03:00
Ian T. Jacobsen
4f1238af71 Fix whitespace issues 2014-07-16 00:21:16 +01:00
Ian T. Jacobsen
122a1e2af9 Fixed cases where file would be opened, but not closed. And small realloc memory issue. 2014-07-16 00:16:32 +01:00
Petri Lehtinen
c8d017bd88 Merge branch '2.6' 2014-07-12 06:43:07 +03:00
Petri Lehtinen
23b1b7ba9a Document JANSSON_BUILD_SHARED_LIBS CMake option
Fixes #187.
2014-07-12 06:42:36 +03:00
Petri Lehtinen
88943b64e3 Define JSON_MAX_INDENT
Fixes #191.
2014-07-07 11:34:50 +03:00
Petri Lehtinen
348401e7b8 CMake: Use add_definitions for compiler flags
Fixes #193.
2014-07-02 22:04:34 +03:00
Petri Lehtinen
df248712a5 Include android config in tarballs
Issue #166.
2014-06-28 22:41:48 +03:00
Petri Lehtinen
de1b5db70e Fix autoreconf on Debian
For some reason, Automake doesn't search the current directory correctly
when searching for helper scripts.

Fixes #182.
2014-05-14 16:03:22 +03:00
Petri Lehtinen
4debe8e567 Add missing tests for JSON_REAL_PRECISION 2014-05-07 08:19:39 +03:00
Petri Lehtinen
28d362cf28 Merge pull request #180 from Sannis/master
Enable usage of AddressSanitizer to check Jansson
2014-05-05 14:45:09 +03:00
Oleg Efimov
541cdf5960 Remove unneeded undef 2014-05-05 15:40:41 +04:00
Oleg Efimov
fc6e314498 Enable usage of AddressSanitizer to check Jansson 2014-05-04 00:34:08 +04:00
Petri Lehtinen
17b5fdd94b Add JSON_REAL_PRECISION
Fixes #178.
2014-04-30 12:46:34 +03:00
Petri Lehtinen
5b88cc5ded Merge branch '2.6' 2014-04-30 12:06:03 +03:00
Petri Lehtinen
db285b3764 Check uint16_t and uint8_t support correctly
Fixes #177.
2014-04-30 12:05:51 +03:00
Petri Lehtinen
a425f8c650 Rename variables to work aroung a GCC bug on Solaris
Fixes #175.
2014-04-23 12:17:14 +03:00
Petri Lehtinen
96f8916e50 Merge pull request #174 from KimJeongYeon/master
fix build error for android
2014-04-14 08:32:47 +03:00
KimJeongYeon
dd2bf2971e fix build error for android 2014-04-11 23:14:34 +09:00
Petri Lehtinen
34a64cfe53 Merge pull request #171 from firepick1/master
Solaris build fix
2014-04-08 20:39:46 +03:00
Karl Lew
571617ebfc use __sun instead of sun 2014-04-08 15:57:58 +00:00
Karl Lew
3bd8a5729d Merge remote-tracking branch 'refs/remotes/origin/master' 2014-04-06 04:31:34 +00:00
Karl Lew
33e4988180 SmartOS build fix 2014-04-06 04:28:52 +00:00
firepick1
663fbfb7a4 SmartOS (Solaris) build 2014-04-04 17:28:08 -07:00
Petri Lehtinen
88aa6a9e30 Remove VS2010 project files, CMake should be used on Windows instead
Fixes #165.
2014-03-04 08:28:52 +02:00
Petri Lehtinen
92e2588d6e Merge branch '2.6' 2014-02-16 22:22:14 +02:00
Petri Lehtinen
960ead07f2 Merge pull request #164 from vincentbernat/fix/gitignore
Add new autotools-generated files to .gitignore
2014-02-16 22:20:25 +02:00
Petri Lehtinen
78da1de021 Merge pull request #163 from vincentbernat/fix/unpack-mix-optional-and-strict
Fix unpack when mixing strict mode and optional keys
2014-02-16 22:20:02 +02:00
Petri Lehtinen
946531bd7b Merge pull request #162 from nmlgc/master
Three fixes for hashtable seeding on Windows
2014-02-16 22:19:37 +02:00
Petri Lehtinen
10009d61a7 Merge pull request #164 from vincentbernat/fix/gitignore
Add new autotools-generated files to .gitignore
2014-02-16 22:10:16 +02:00
Petri Lehtinen
49fc6b1194 Merge pull request #163 from vincentbernat/fix/unpack-mix-optional-and-strict
Fix unpack when mixing strict mode and optional keys
2014-02-16 22:09:41 +02:00
Petri Lehtinen
6e8b2e161a Merge pull request #162 from nmlgc/master
Three fixes for hashtable seeding on Windows
2014-02-16 22:09:09 +02:00
Vincent Bernat
3922f84a2f Add new autotools-generated files to .gitignore
Additionally, `/jansson_private_config.h.in` is also added as well as
"build" directory for those of us who like to use an out-of-tree build
system.
2014-02-15 17:47:48 +01:00
Vincent Bernat
56a50e147d Micro-optimization for JSON_STRICT when no optional key is used
The previous commit introduced a loop on all input keys to check the
strict mode. We can avoid this if we don't expect an optional key. In
this case, we fallback to the previous method to compare the length of
the set of expected keys and the length of the parsed keys.
2014-02-15 17:44:02 +01:00
Vincent Bernat
7a0b9af662 Allow to mix JSON_STRICT with optional keys
On unpack, one may want to mix `JSON_STRICT` and optional keys by using
a format like `{s:i,s?o!}`. Unfortunately, this fails the stric test
with `-1 object item(s) left unpacked` error when the second key is not
specified.

To fix that, we iter on each key and we check if we have successfully
unpacked them. This is less efficient than the previous method but it
brings correctness.
2014-02-15 17:40:22 +01:00
nmlgc
4fbe44605b Three fixes for hashtable seeding on Windows
First, wrap "advapi32.dll" into the TEXT() macro. If UNICODE is defined,
GetModuleHandle() redirects to GetModuleHandleW(), which excepts a wchar_t*
UTF-16 parameter, thus causing a compile error. TEXT() prefixes the string
literal with L in this case, and does nothing otherwise.

Second, make sure that CryptGenRandom() is actually called through the function
pointer retrieved by the call to GetProcAddress() above.

And third, replace _getpid() with the equivalent and more ubiquitous Win32 API
function GetCurrentProcessId(). Since _getpid() is not exported by all C
runtimes on Windows (most notably the Driver Development Kit), using it might
introduce previously unneeded runtime dependencies. GetCurrentProcessId(), on
the other hand, has been available in kernel32.dll since at least Windows 95,
just like the other API functions used in this code (GetModuleHandle() and
GetProcAddress()).
2014-02-15 17:11:11 +01:00
Petri Lehtinen
ea7a77236c Merge branch '2.6' 2014-02-12 08:56:17 +02:00
Petri Lehtinen
1dc87ed5a1 Make valgrind happy 2014-02-12 08:54:26 +02:00
Petri Lehtinen
50a811ca07 Fix feature checks to use correct __ATOMIC flags 2014-02-12 08:54:26 +02:00
Petri Lehtinen
4bbb53a25d Make valgrind happy 2014-02-12 08:54:06 +02:00
Petri Lehtinen
569295fe30 Fix feature checks to use correct __ATOMIC flags 2014-02-12 08:44:29 +02:00
Petri Lehtinen
3f5acaa3fb Merge branch '2.6' 2014-02-11 15:15:00 +02:00
Petri Lehtinen
42016a35c8 Oops, ATOMIC_ACQ_REL is not a correct memmodel for __atomic_store_n 2014-02-11 15:14:47 +02:00
Petri Lehtinen
17ec22f514 Merge branch '2.6' 2014-02-11 14:49:15 +02:00
Petri Lehtinen
e83ded066a jansson 2.6 2014-02-11 09:45:30 +02:00
Petri Lehtinen
492feb26ce Document json_object_seed() 2014-02-11 09:38:45 +02:00
Petri Lehtinen
8f80c2d838 CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
2014-02-11 08:41:30 +02:00
Chip Salzenberg
b9c588de3d expect "export" in test configs 2014-02-11 08:41:14 +02:00
Petri Lehtinen
a721d36f41 Merge pull request #161 from JoakimSoderberg/cmake_travis
Add CMake build to Travis config.
2014-01-28 06:02:17 -08:00
Petri Lehtinen
eee85cd53c Merge pull request #160 from JoakimSoderberg/cmake_memcheck_fix
Fix so that valgrind checks actually works with CMake.
2014-01-28 06:01:03 -08:00
Joakim Soderberg
7c80778827 Fix so that valgrind checks actually works with CMake.
The valgrind tests where not run on the suites.

And valgrind was always returning 0 so set an explicit exit code on exit. I also had forgotten to change the name of TEST_WITH_VALGRIND to JANSSON_TEST_WITH_VALGRIND so that the tests would never use valgrind.
2014-01-28 13:07:59 +00:00
Joakim Soderberg
4c2cc0e36c Add CMake build to Travis config. 2014-01-28 14:06:43 +01:00
Petri Lehtinen
a630e226ba Merge pull request #159 from JoakimSoderberg/config_fix
Make sure the private config is included.
2014-01-28 01:11:57 -08:00
Joakim Soderberg
0c95a22888 Make sure the private config is included. 2014-01-28 09:59:43 +01:00
Petri Lehtinen
30fdf6067e Update copyrights for 2014 2014-01-28 09:16:05 +02:00
Petri Lehtinen
cffc5df600 Merge pull request #157 from JoakimSoderberg/cmake_config_new
Cmake config
2014-01-27 23:10:55 -08:00
Joakim Soderberg
3fe8f74e7f Renamed config.h -> jansson_private_config.h
This is because it's really easy to get a name collission if compiling
Jansson as a subproject in a larger CMake project. If one project includes
several subprojects each having their own config.h, this will cause the
wrong file to be loaded.
2014-01-27 12:48:52 +01:00
Joakim Soderberg
913937c98d Added CMake config files.
This will simplify linking against the lib, both from the build-tree and
install-tree from other CMake projects.

CMakes find_package command uses these configs to locate the exported
targets for the library.

* Also changed so that all CMake options for the project are prepended
  with JANSSON_ so that there is no ambiguity when including this as a
  subdirectory in another CMake project.
2014-01-24 14:13:02 +01:00
Petri Lehtinen
b21cd65d30 Fix CMake build flags for MinGW 2014-01-16 08:03:05 +02:00
Petri Lehtinen
c89638d73c Merge pull request #151 from nmlgc/master
Check for key == NULL in json_object_get and json_object_del
2013-12-28 02:56:35 -08:00
nmlgc
98610bfcec Check for key == NULL in json_object_get and json_object_del 2013-12-28 06:11:49 +01:00
Petri Lehtinen
9c8b3c833f Merge branch '2.5' 2013-12-27 08:55:52 +02:00
Petri Lehtinen
dc69aa797b github_commits.c: GitHub API v3 requires a User-Agent header 2013-12-27 08:55:05 +02:00
Petri Lehtinen
4e8c4bfbd2 Merge branch '2.5' 2013-12-13 09:27:42 +02:00
Petri Lehtinen
316492e4d0 Merge 2013-12-13 09:26:58 +02:00
Petri Lehtinen
3347679d8f Merge branch '2.5' 2013-12-13 09:22:50 +02:00
Petri Lehtinen
b951baec0d Include CMake specific files in release tarballs
Fixes #147.
2013-12-13 09:22:36 +02:00
Petri Lehtinen
05f7d30e5a Add json_boolean_value as alias for json_is_true
Fixes #146.
2013-12-04 09:14:19 +02:00
Petri Lehtinen
34d8b92dce Merge branch '2.5' 2013-11-14 08:49:24 +02:00
Petri Lehtinen
67a7bc7376 doc: Set all memory to zero in secure_free 2013-11-14 08:49:16 +02:00
Petri Lehtinen
30a4c88843 Fix an off-by-one error 2013-10-15 08:49:40 +03:00
Petri Lehtinen
08be94e8e6 Don't call strlen twice
Oops.
2013-10-15 08:46:17 +03:00
Petri Lehtinen
d544852ff6 Avoid integer overflows with very long strings 2013-10-15 08:44:04 +03:00
Petri Lehtinen
8dc3233f3b Merge pull request #143 from chipdude/master
paper bag bug: json_string_set* functions should set the length too
2013-10-03 22:36:34 -07:00
Chip Salzenberg
c7d479c740 in simple string tests, always check lengths too 2013-10-03 19:07:50 -07:00
Chip Salzenberg
a76dc45512 paper bag bug: json_string_set* functions should set the length too 2013-10-03 19:07:20 -07:00
Petri Lehtinen
9bb5a266dd Merge pull request #142 from chipdude/master
fix type mismatch anywhere int != int32 (Vorne)
2013-09-30 22:41:25 -07:00
Chip Salzenberg
6ebd0bc7a6 fix type mismatch anywhere int != int32 (Vorne) 2013-09-30 16:56:01 -07:00
Petri Lehtinen
f8d8d524cf Document JSON_ALLOW_NUL and clarify NUL byte handling 2013-09-30 10:55:34 +03:00
Petri Lehtinen
1bfc33362e Add JSON_ALLOW_NUL decoding flag for enabling NUL byte support 2013-09-30 10:45:02 +03:00
Petri Lehtinen
5744468c99 Clarify json_string_length doc 2013-09-30 10:45:02 +03:00
Petri Lehtinen
4d5aead31c Fix NUL byte check for object keys 2013-09-30 10:45:02 +03:00
Petri Lehtinen
78a80b8899 load.c: Change an error message 2013-09-30 09:24:36 +03:00
Petri Lehtinen
b961e8101e Add Chip's changes to release notes 2013-09-30 08:56:39 +03:00
Petri Lehtinen
7876125a22 Document s% and s# for json_pack, s% for json_unpack 2013-09-30 08:47:05 +03:00
Petri Lehtinen
e2dcf94598 Merge pull request #141 from chipdude/nuls
add new public functions to jansson.def
2013-09-29 22:31:15 -07:00
Chip Salzenberg
6c1ce27095 add new public functions to jansson.def 2013-09-29 16:57:23 -07:00
Petri Lehtinen
46e27ae6d5 Merge pull request #140 from chipdude/nuls
Support "\u0000" in strings
2013-09-29 11:57:57 -07:00
Chip Salzenberg
0be5c959da document new null-friendly functions 2013-09-27 19:10:32 -07:00
Chip Salzenberg
face43929d expect "export" in test configs 2013-09-27 17:32:25 -07:00
Chip Salzenberg
dcaa90d21e dump \u sequences as upper case for readability (just like error messages) 2013-09-27 17:32:25 -07:00
Chip Salzenberg
9c259c07aa Support \u0000 - add size_t string lengths to API, load and dump \u000, etc.
Also:
  Steal strings during parsing for half the mallocs!
  Change all input-caused assertions to errors.  No crashes please, we're programmers.
2013-09-27 17:32:06 -07:00
Petri Lehtinen
e4d6a9f6f4 Add versionadded to the new json_pack() format specifiers 2013-09-23 09:34:28 +03:00
Petri Lehtinen
641002da37 jansson 2.5 2013-09-19 21:26:46 +03:00
Petri Lehtinen
9f9c9fe410 doc: Fix index type for json_array_foreach() 2013-09-19 21:26:46 +03:00
Petri Lehtinen
e39112b29c Merge branch '2.4' 2013-09-19 20:47:33 +03:00
Petri Lehtinen
bf2584703a Mention success first in json_load_callback_t docs 2013-09-19 20:47:17 +03:00
Phillip Howell
db8ca3645f Clarified json_load_callback_t return value docs 2013-09-19 20:47:02 +03:00
Petri Lehtinen
0490907fb3 Merge branch '2.4' 2013-09-19 20:46:07 +03:00
Petri Lehtinen
c2e8fdde9d Mention success first in json_load_callback_t docs 2013-09-19 20:45:51 +03:00
Petri Lehtinen
24c67966aa Mention success first in json_load_callback_t docs 2013-09-16 08:49:38 +03:00
Phillip Howell
0747d3943f Clarified json_load_callback_t return value docs 2013-09-16 08:49:38 +03:00
Petri Lehtinen
5f9ef108d0 Merge pull request #134 from lano1106/master
Replace strcpy with memcpy
2013-08-27 22:37:44 -07:00
Olivier Langlois
21599b95f8 Replace strcpy with memcpy
Since len is known, the copy function does not need to check byte by byte
the end of the string.

Signed-off-by: Olivier Langlois <olivier@olivierlanglois.net>
2013-08-27 22:47:18 -04:00
Petri Lehtinen
3196ad48ed pack: Add format specifiers s#, + and +# 2013-08-14 21:54:11 +03:00
Petri Lehtinen
49ad5328c7 doc: Add an example for circumventing problems with Windows heaps 2013-08-06 08:12:20 +03:00
Petri Lehtinen
71676acd0b Fix memory leaks and warnings in github_commits.c 2013-07-27 21:23:34 +03:00
Petri Lehtinen
2489ea90b1 Update copyrights for 2013 2013-07-23 13:20:06 +03:00
Petri Lehtinen
11d45b0090 Fix integer overflow in jsonp_strdup()
Fixes #129.
2013-07-21 13:00:32 +03:00
Petri Lehtinen
8490e377c0 Make the argument of json_deep_copy() const
Fixes #126.
2013-07-08 12:36:56 +03:00
Petri Lehtinen
ef666519f7 Merge pull request #128 from JoakimSoderberg/lex_unget_unsave_fix
BUGFIX: Compilation error with -DNDEBUG defined.
2013-07-01 21:41:55 -07:00
Joakim Soderberg
6fe231757e BUGFIX: Compilation error with -DNDEBUG defined.
When building a "MinSizeRel" with CMake I get a compilation error in lex_unget_unsave. This is because assertions are turned off using -DNDEBUG:

```
/usr/bin/gcc  -DHAVE_CONFIG_H -fPIC -Os -DNDEBUG -Ijansson/build/include -Ijansson/build/private_include    -Wall -Wextra -Wdeclaration-after-statement -Werror -o CMakeFiles/jansson.dir/src/load.c.o   -c jansson/src/load.c
jansson/src/load.c: In function âx_unget_unsaveâjansson/src/load.c:256:14: error: variable â set but not used [-Werror=unused-but-set-variable]
cc1: all warnings being treated as errors
```

This will then remove the insert, which makes the "d" variable unused, which is treated as an error since we have -Wall set. We can't simply get rid of the variable either and put the strbuffer_pop call in the assert call, since it's a macro and would remove the call entirely. So I simply added a check for NDEBUG to fix it.
2013-06-26 09:50:46 +00:00
Petri Lehtinen
84b5bfe173 Merge pull request #127 from cryptobiote/master
Adding option for MSVC for those who are linking statically.
2013-06-25 11:30:39 -07:00
cryptobiote
d9ee5a7f1b Update CMakeLists.txt 2013-06-25 09:36:11 -06:00
cryptobiote
19a19d1952 Adding option for MSVC for those who are linking statically. 2013-06-20 11:00:40 -06:00
Petri Lehtinen
68e201add8 Merge pull request #125 from jjwchoy/master
Prevent compiler warning
2013-06-13 22:59:22 -07:00
Jason Choy
62531bd012 Prevent unused-variable warning 2013-06-13 11:37:07 +01:00
Petri Lehtinen
f639fbd2c3 Tweak the JSON_DECODE_INT_AS_REAL test introduced in #123
Only run the imprecision part if json_int_t is long long, otherwise
the imprecision cannot be tested against json_int_t.

Also, convert the double value to json_int_t before checking the
imprecision, because otherwise the json_int_t is converted to double
and the imprecision happens in the "wrong direction".
2013-06-12 08:36:53 +03:00
Petri Lehtinen
a38704df58 Fix indentation in docs 2013-06-12 08:30:28 +03:00
Petri Lehtinen
8d439710cd Merge pull request #123 from jjwchoy/decode-ignore-int
Implemented a decode option to only decode numbers to reals
2013-06-11 22:23:40 -07:00
Jason Choy
120a90a155 Using jsonp_strtod instead of casting to double to catch double overflow 2013-06-11 15:09:08 +01:00
Jason Choy
c3e9725f02 Changed :versionadded for JSON_DECODE_INT_AS_REAL docs 2013-06-11 12:31:41 +01:00
Jason Choy
02a3829363 Renamed flag to JSON_DECODE_INT_AS_REAL and added documentation 2013-06-11 12:24:28 +01:00
Petri Lehtinen
018f7fea31 Merge pull request #120 from paulharris/mine_pre_2.5
Adjust CMakeLists.txt and .def: add _d postfix onto jansson_d.lib/dll
2013-06-09 22:18:05 -07:00
Jason Choy
e6bd0aba9d Added a simple test for the JSON_DECODE_NO_INT option 2013-06-09 15:34:30 +01:00
Jason Choy
9e7f11a847 Implemented a decode option to only decode numbers to reals and never integers 2013-06-09 15:14:47 +01:00
Petri Lehtinen
042d4b2a6b Merge pull request #121 from jjwchoy/master
Added missing return valua check in test
2013-06-07 05:17:46 -07:00
Jason Choy
ddd10b5e0b Added missing rv check - caught by clang 2013-06-07 13:08:22 +01:00
Paul Harris
2fd66fab1a Adjust CMakeLists.txt and .def: add _d postfix onto jansson_d.lib/dll
Had to remove the "LIBRARY" line from jansson.def, which was optional,
and was overriding CMake's desire for a specific name.
2013-06-02 22:00:32 +08:00
Petri Lehtinen
5cc594c9e8 Don't shadow the stdlib function index() with arg names
Fixes #119.
2013-05-21 08:54:27 +03:00
Petri Lehtinen
ffb7ef4b75 Merge pull request #118 from dtgriscom/master
Added json_array_foreach(), parallelling json_object_foreach()
2013-05-12 22:16:09 -07:00
Daniel Griscom
b49280be72 Fixed "comparison between signed and unsigned" warning 2013-05-12 15:45:33 -04:00
Daniel Griscom
7121134abd Removed (non-functioning) printfs from test code 2013-05-12 15:36:09 -04:00
Daniel Griscom
e8c812b500 Added test cases and documentation for json_array_foreach() 2013-05-12 15:34:26 -04:00
Daniel Griscom
6950cd203b Add json_array_foreach() #define, parallelling json_object_foreach() 2013-05-12 15:03:26 -04:00
Petri Lehtinen
d3bd463897 Merge pull request #115 from JoakimSoderberg/cmake_pkgconfig
Cmake pkgconfig
2013-05-06 22:38:28 -07:00
Joakim Soderberg
54d86fb4a4 Create and install the pkg-config file jansson.pc for CMake.
Use the same jansson.pc.in file as the ./configure script does to generate the jansson.pc file for pkg-config. Also make an install rule for this.
2013-05-06 12:34:52 +00:00
Joakim Soderberg
42d398243d Fix the cmake Sphinx find script.
The cmake sphinx find script version parsing assumes a format of 1.2.3, but sphinx version can be 1.2b3 as well, so parse those correctly as well.
2013-05-06 12:31:29 +00:00
Andrei Epure
f675514815 jansson:doc: modified incref doc
Signed-off-by: Andrei Epure <epure.andrei@gmail.com>
2013-04-29 15:32:52 +03:00
Andrei Epure
5793142861 test:suites:api: modified error message
In the "/* perform the same update again */" area the error
message should be "unable to update an non-empty object"
instead of "unable to update an empty object".

Signed-off-by: Andrei Epure <epure.andrei@gmail.com>
2013-04-29 15:32:52 +03:00
Petri Lehtinen
b227f96c45 Merge pull request #112 from JoakimSoderberg/fpic_cmake_support
Additional CMake documentation + Fpic cmake support
2013-04-29 03:56:23 -07:00
Joakim Soderberg
0687442f5d Fixed some minor issues. 2013-04-25 13:59:26 +00:00
Joakim Soderberg
8390c90a91 Added more detailed CMake documentation.
- Also added better FindSphinx support so that we can detect the version and not  have a fatal error if it's too old.
- Added support for building latex documentation with -DBUILD_LATEX. Off by default.
- Added suppor for building man pages with -DBUILD_MAN. On by default (unless sphins is too old to support it).
2013-04-24 14:14:00 +00:00
Joakim Soderberg
3000831365 Use -fPIC when possible.
So that we can link the library statically to shared libraries.
2013-04-18 09:25:17 +00:00
Petri Lehtinen
6b1cba94e3 Document CMake build process, deprecate the VS2010 project 2013-04-15 10:31:23 +03:00
Petri Lehtinen
9591d3a155 Tweak Android build documentation 2013-04-15 10:25:32 +03:00
Petri Lehtinen
83d04ddd68 Merge branch 'master' of git://github.com/svic/jansson 2013-04-15 10:21:31 +03:00
Petri Lehtinen
70232676f7 Merge branch '2.4' 2013-04-15 09:15:35 +03:00
Petri Lehtinen
257a716073 Fix the signature again, and also rest of the errors
Next time, remember to check with -Werror first...
2013-04-15 09:15:03 +03:00
Petri Lehtinen
0ccd2c7715 Merge branch '2.4' 2013-04-15 09:09:01 +03:00
Petri Lehtinen
42e307b3c5 Fix the signature of a test function 2013-04-15 09:08:47 +03:00
Petri Lehtinen
61cba2ae50 Merge branch '2.4' 2013-04-15 08:49:47 +03:00
Petri Lehtinen
867079c820 json_dump*(): Don't crash if json is NULL and JSON_ENCODE_ANY is set 2013-04-15 08:49:09 +03:00
Garner Lee
d20751d53d Add android doc. 2013-04-11 13:32:04 -07:00
Petri Lehtinen
6281d1c549 Merge pull request #108 from Zillode/1edff47af38a2335f88300ee6dc437118f5a20ff
Fixes redefined warnings ("_GNU_SOURCE")
2013-04-02 05:40:49 -07:00
Petri Lehtinen
8fd475bf96 Merge branch '2.4' 2013-04-01 14:41:14 +03:00
Petri Lehtinen
bbd3b0ca4f Fix a typo 2013-04-01 14:41:10 +03:00
Garner Lee
7c4f323abc Create Android.mk, preconfigured jansson_config.h and CleanSpec.mk for Android-like build systems. 2013-03-27 17:31:05 -07:00
Lode Hoste
1edff47af3 Do not define _GNU_SOURCE is already defined 2013-03-14 21:34:11 +01:00
Petri Lehtinen
dc2d54d9c6 Fix a refleak in test/bin/json_process.c 2013-03-14 22:24:57 +02:00
Petri Lehtinen
263fd0c9d3 Remove trailing whitespace 2013-03-14 22:18:21 +02:00
Petri Lehtinen
6db70f0301 cmake: Add stripped tests 2013-03-14 22:16:16 +02:00
Petri Lehtinen
70f663db29 Merge branch 'rebased_cmake_patch' of git://github.com/JoakimSoderberg/jansson 2013-03-14 22:16:10 +02:00
Joakim Söderberg
59bc1f42e4 Got rid of some warnings for unused variables. 2013-03-13 00:15:37 +01:00
Joakim Söderberg
b1b4f307d5 Add back the old ENV variabe approach to json_process.
Enable using the old envrionment variable passing of settings for json_process
so that the current autoconf test suite scripts can run nicely.

json_process now takes an optional command line parameter --env which
causes it to use the old method of reading the settings from
environment variables instead of directly from the "env" file.

Also added a --strip command line option, this will be used to
run the stripped tests with CMake as well.
2013-03-13 00:09:08 +01:00
Petri Lehtinen
a3e6369105 Merge branch '2.4' 2013-03-09 21:15:22 +02:00
Petri Lehtinen
3d0d61fdaf Use json_decref() properly in tutorial 2013-03-09 21:15:09 +02:00
Joakim Soderberg
650707fccc Moved *config.h.cmake to the cmake directory. 2013-03-07 18:38:47 +01:00
Joakim Soderberg
33b0855b27 Get rid of type warning on MSVC.
We should use json_int_t instead of int, since this can be different
depending on platform. Also MSVC warns that this can cause "loss of
information" since it's converting long long to int.
2013-03-07 16:27:41 +01:00
Joakim Soderberg
7214a222c7 Skip using a debug postfix with visual studio.
The output dir is different anyway, and this just makes it more
complicated to build projects that link to this, because they need
different link rules based on the build type.
2013-03-07 16:21:35 +01:00
Joakim Söderberg
81ce127048 Compile tests by default.
- Encourage actually using the unit tests by compiling them by default.
Set the WITHOUT_TESTS variable to build without instead...

- Changed comments to keep within 80 characters.
- Don't have a hard coded path for valgrind, simply assuem it's in the path instead (an OSX ports install puts it in /opt/local/bin for instance).
- Fixed building the shared lib.
2013-03-07 16:19:56 +01:00
Joakim Söderberg
344d2b00ea Fix incorrect cast to ssize_t.
gcc 4.2.1 warns about a possible incorrect cast to ssize_t when comparing against refcount, which is of type size_t. signed vs unsigned comparison.

Sinc warnings are treated as errors (as in the autoconf project) this would cause a compile error.
2013-03-07 16:13:40 +01:00
Joakim Söderberg
52a8072727 Rename the CMakeModules directory to simply cmake.
This is more consistent with the other directories in the project.
2013-03-07 16:12:08 +01:00
Joakim Soderberg
741e6915e2 Always use LF as line ending so that we don't get any problems with line
endings in any tests.
2013-03-07 16:12:07 +01:00
Joakim Soderberg
e40d52c550 Consolidated the CMake project.
- Moved everything to one CMakeLists.txt
- Added support for the json_process test suites (instead of just the API
  tests).
- Changed to use the modified json_process version that does away with the
  environment variables (originally written by DanielT).
- Had to exclude "test_memory_funcs" on MSVC, since void pointer
  arithmetics are not allowed as it is done in secure_malloc and
  secure_free.
- Had to add a check for "ssize_t". This is not available on Windows and
  maybe on some other platforms (used in test_pack.c)
- Result from running ctest (The failure seems unrelated to CMake, it's
  just that the expected result is in a different order):
99% tests passed, 1 tests failed out of 121

Total Test time (real) =   1.31 sec

The following tests FAILED:
         24 - valid__complex-array (Failed)
2013-03-07 16:11:07 +01:00
Paul Harris
3d5bea5714 Fixes for cmake for MSVC2010 2013-03-07 16:06:38 +01:00
Paul Harris
3e03b07831 Add CMake build system.
Added multiple CMake-related files to project.
Supports building the library and the tests.
See CMakeLists.txt for notes on how it works.

I had to adjust 3 existing files in order to disable some configuration
that should be taken care of by cmake/automake anyway.

I also added jansson.def from a future jansson version,
to test cmake's support for .def files (which works fine).
2013-03-07 16:06:01 +01:00
Petri Lehtinen
e00cd4f941 Merge branch '2.4' 2013-02-05 12:51:06 +02:00
Petri Lehtinen
a1882fee02 check-exports test: Filter out symbols that start with an underscore
These are usually internal to libc, and such symbols are exported in
the shared library on some platforms.
2013-02-05 12:48:38 +02:00
Petri Lehtinen
4a5626695c Merge branch '2.4' 2013-02-04 09:55:39 +02:00
Petri Lehtinen
afa1d37e20 Enable -Werror in Travis builds 2013-02-04 09:55:34 +02:00
Petri Lehtinen
b9967fdbcf Merge branch '2.4' 2013-02-04 09:52:31 +02:00
Petri Lehtinen
ccf6e48a52 Don't use -Werror by default
It may be problematic when compilers add new warnings over time.
./configure && make should always just work.
2013-02-04 09:51:42 +02:00
Petri Lehtinen
93a3c7f663 Enable gcc specific flags in tests correctly
... and fix issues found.
2013-02-04 09:49:58 +02:00
Petri Lehtinen
5dbac70a67 Compress bz2 doc tarballs with bzip2 instead of gzip
Fixes #99.
2013-01-06 14:18:28 +02:00
Petri Lehtinen
40c2e532b9 Merge branch '2.4' 2013-01-03 10:46:46 +02:00
Petri Lehtinen
02beb90db3 Make it possible to forward declare struct json_t
This allows e.g. to use json_t in a header file that doesn't include
jansson.h:

    struct json_t;
    typedef struct json_t json_t;

    json_t *foo(json_t *bar);
2013-01-03 10:45:38 +02:00
Petri Lehtinen
92bf4f6fa8 Merge branch '2.4' 2012-12-28 15:30:18 +02:00
Petri Lehtinen
8ad98c9ad3 Add travis build status image more cleverly 2012-12-28 15:30:15 +02:00
Petri Lehtinen
7a4ec36f31 Merge branch '2.4' 2012-12-28 14:27:49 +02:00
Petri Lehtinen
3fab956599 Add travis build status to README.rst 2012-12-28 14:27:31 +02:00
Petri Lehtinen
a2de27a828 travis: Run "make check" instead of "make test" 2012-12-28 14:22:24 +02:00
Petri Lehtinen
99855b2d63 travis: Bootstrap autotools before building 2012-12-28 14:20:25 +02:00
Petri Lehtinen
08c5ec8f01 Merge branch '2.4' 2012-12-28 14:11:59 +02:00
Petri Lehtinen
e9cb9dbf60 Fix // -> /* */ 2012-12-28 14:11:43 +02:00
Petri Lehtinen
8284b7d3da Merge branch '2.4' 2012-12-23 07:10:02 +02:00
Petri Lehtinen
511db446d7 Add Travis configuration 2012-12-23 07:09:55 +02:00
Petri Lehtinen
b98be1f18d Merge branch '2.4' 2012-12-10 08:47:11 +02:00
Jacob Potter
872f847655 Change const pointer to array
Closes #95.
2012-12-10 08:47:00 +02:00
Jacob Potter
f86bb0377f Mark some constant data as const.
Issue #95.
2012-12-10 08:47:00 +02:00
Attie Grande
c82cea9d32 fixed l_isxdigit() macro
Closes #97.
2012-12-10 08:47:00 +02:00
Petri Lehtinen
67c002f7c9 Merge branch '2.4' 2012-12-04 21:23:33 +02:00
Petri Lehtinen
e0a7f81b39 Really fix the off-by-one error in json_array_remove()
It didn't affect only the last element but all of them. One item too
much was always moved.
2012-12-04 21:20:59 +02:00
Petri Lehtinen
7b35a18ac0 Merge branch '2.4' 2012-12-04 09:33:48 +02:00
Petri Lehtinen
54d59c743c Fix an off-by-one error in json_array_remove()
Uninitialized memory was read when the last item of a "full" array was
removed.
2012-12-04 09:32:45 +02:00
Petri Lehtinen
6279610ce4 Merge branch '2.4' 2012-10-26 15:55:00 +03:00
Petri Lehtinen
ac0ca9223b Merge pull request #93 from bertwesarg/vpath-for-2.4
Support building and testing with VPATH.
2012-10-26 05:48:32 -07:00
Bert Wesarg
4853a3454c Support building and testing with VPATH. 2012-10-26 14:43:46 +02:00
Petri Lehtinen
cf1074e70e Add a script for making releases 2012-09-23 13:42:56 +03:00
Petri Lehtinen
5804e9de9b Set master for 2.5 development mode 2012-09-23 13:41:40 +03:00
Petri Lehtinen
3279aacdee jansson 2.4 2012-09-23 12:52:41 +03:00
Petri Lehtinen
2158670177 Distribute win32 files 2012-09-23 12:52:40 +03:00
Petri Lehtinen
4cff593dd4 Update CHANGES for v2.4 2012-09-22 14:26:16 +03:00
Petri Lehtinen
597423ea80 doc: Add versionadded directive for json_boolean() 2012-09-22 14:25:29 +03:00
Petri Lehtinen
c3fc1d7382 Merge pull request #90 from luke-jr/patch-1
Add -no-undefined to LDFLAGS
2012-09-18 21:11:26 -07:00
Luke Dashjr
c922354076 Add -no-undefined to LDFLAGS
This tells libtool that jansson does not require any external symbols, and allows building it as a shared library (DLL) on Windows.
2012-09-15 08:45:29 +00:00
Petri Lehtinen
4118315afa Disallow NaN or Inf real values 2012-09-13 21:30:19 +03:00
Petri Lehtinen
ee13c667f1 Fix json_real_set() to return -1 on error 2012-09-13 08:46:56 +03:00
Petri Lehtinen
23d563434a Fix a typo on doc/apiref.rst 2012-09-06 12:06:41 +03:00
Petri Lehtinen
6142dbd8d0 Fix a typo in README.rst 2012-09-05 21:16:43 +03:00
Petri Lehtinen
0dac319bc4 CHANGES entry for #88 2012-08-11 20:45:25 +03:00
Petri Lehtinen
0b871a113c Merge branch '2.3' 2012-08-11 20:45:15 +03:00
Alessandro Ghedini
8176527f56 fix check-exports test on ppc64 2012-08-11 20:42:21 +03:00
Petri Lehtinen
ec7bb71d75 Add an initial CHANGES entry for v2.4 2012-07-30 07:52:41 +03:00
Petri Lehtinen
b6a1d8cfd4 Add json_boolean() macro
Mostly for symmetry reasons. Makes it easier e.g. to:

  int ok = 0;
  if(something)
      ok = 1;

  json_object_set_new(obj, "ok", json_boolean(ok));

Fixes #86.
2012-07-30 07:20:37 +03:00
Petri Lehtinen
52924288b9 Merge branch '2.3' 2012-07-27 07:28:40 +03:00
Petri Lehtinen
7892ecce1c Fix a small error in tutorial
Fixes #84.
2012-07-27 07:28:18 +03:00
Petri Lehtinen
a501a39626 Document the JSON_ESCAPE_SLASH encoding flag 2012-06-29 13:32:17 +03:00
Petri Lehtinen
37bc3bbf4b Tweak slash escaping 2012-06-29 13:25:02 +03:00
Petri Lehtinen
2d46ea069b Merge branch 'fix-slash' of git://github.com/jrbasso/jansson
Fixes #81.
2012-06-29 13:24:55 +03:00
Juan Basso
b217cd6689 Created flag to dump escaping slash 2012-06-28 22:04:36 -04:00
Juan Basso
a0c262d08b Escaping the slash when dump 2012-06-27 23:54:08 -04:00
Petri Lehtinen
6ce273e2e6 Merge branch '2.3' 2012-06-06 21:10:28 +03:00
Paul Harris
f62b1f5d69 Bugfix: must cast void* to do pointer math
Fixes #78.
2012-06-06 21:09:47 +03:00
Paul Harris
2b87fdcb43 Bugfix: Changed all use of ssize_t to size_t.
ssize_t is only used in a test, and its comparing to a size_t variable.

Fixes #77.
2012-06-06 08:47:17 +03:00
Petri Lehtinen
c0139681cd Update the documentation to mention Visual Studio 2010 support 2012-05-19 21:22:59 +03:00
Petri Lehtinen
9d6f9511f5 Merge pull request #74 from rogerz/contrib
Add vs2010 solution and project, fix warnings under MinGW
2012-05-03 11:31:19 -07:00
Rogerz Zhang
a79f64e155 Fix build warnings under MinGW 2012-05-01 08:02:12 +08:00
Rogerz Zhang
7ca783c3bc Add vs2010 solution and project 2012-04-30 21:51:07 +08:00
Petri Lehtinen
ff0c05b8f1 Support building on Windows
Jansson now builds correctly with Visual C++ Express 2010.
2012-04-29 22:09:29 +03:00
Petri Lehtinen
4601bf71e5 Merge branch '2.3' 2012-04-26 22:11:22 +03:00
Jack Mitchell
c7f86abf6d fix slight typo in json_pack apiref example
Fixes #73.
2012-04-26 22:10:46 +03:00
Petri Lehtinen
f309e30320 Merge branch '2.3' 2012-04-26 22:09:48 +03:00
Jack Mitchell
233574e8e0 fix slight typo in json_pack apiref example
Fixes #73.
2012-04-26 22:09:29 +03:00
Petri Lehtinen
4a6939ef87 Merge branch '2.3' 2012-04-26 09:00:49 +03:00
Petri Lehtinen
42bc7a3c50 Check for missing args and envvars in run-tests.sh
Fixes #71.
2012-04-26 08:58:36 +03:00
Petri Lehtinen
abdb8d99d7 Merge branch '2.3'
Conflicts:
	configure.ac
	doc/conf.py
	src/jansson.h
2012-04-20 21:41:25 +03:00
Petri Lehtinen
ff6e6ee293 jansson 2.3.1 2012-04-20 21:35:00 +03:00
Petri Lehtinen
8b2bfd5586 Merge branch '2.3' 2012-04-18 21:59:10 +03:00
Petri Lehtinen
e46b912f53 Fix tutorial to use Github API v3
The v2 API will be shut down on May 1st 2012.

Fixes #65.
2012-04-18 21:58:52 +03:00
Petri Lehtinen
1581f26a7f Merge branch '2.3'
Closes #70.
2012-04-18 21:27:26 +03:00
Janne Kulmala
aabfd493d3 load: Change buffer_pos to be a size_t
buffer_pos should be type size_t, because it's used to store the
current position in the read buffer. Also, it never can be negative.
2012-04-18 21:21:17 +03:00
Janne Kulmala
bd72efbd80 load: Avoid unexpected behaviour in macro expansion
Macros can be dangerous if the inserted arguments are not properly
parenthesised. As macro expansion does a simple replacement, inserting
a certain expression can cause the evaluation order of the macro expression
to change.
2012-04-18 21:21:17 +03:00
Petri Lehtinen
e8fd3e3085 Document and tweak json_load_callback()
Change the return value of json_load_callback_t to size_t, as it's
feels more correct. The callback should return (size_t)-1 on failure.

Issue #57.
2012-03-26 21:53:21 +03:00
Petri Lehtinen
873eddaf19 Merge pull request #60 from rogerz/contrib
Ignore the binary test_load_callback
2012-03-25 10:46:45 -07:00
Rogerz
bd2c0c730d Ignore the binary test_load_callback 2012-03-25 13:22:09 +00:00
Petri Lehtinen
17a51a4bf0 Merge branch '2.3' 2012-03-22 09:02:51 +02:00
Petri Lehtinen
09c39adc55 Add json_load_callback to the list of exported symbols 2012-03-22 09:02:49 +02:00
Petri Lehtinen
cbb80baf03 Merge pull request #57 from rogerz/contrib
Add json_load_callback()
2012-03-22 00:00:24 -07:00
Rogerz Zhang
040bd7b0fa Add json_load_callback() 2012-03-22 14:52:57 +08:00
Petri Lehtinen
2637faa450 Make test stripping locale independent 2012-03-22 08:48:28 +02:00
Petri Lehtinen
952e1d4ba9 Merge branch '2.3'
Closes #56.
2012-03-21 14:03:51 +02:00
Rogerz Zhang
353b5e08ba Ignore *.exe 2012-03-21 14:03:46 +02:00
Petri Lehtinen
d286e7b753 Merge branch '2.3' 2012-03-20 20:56:00 +02:00
Petri Lehtinen
3c6e36ba2d Update copyright notices for 2012 2012-03-20 20:55:55 +02:00
Petri Lehtinen
9af64480e1 Merge branch '2.3' 2012-03-20 20:48:36 +02:00
Petri Lehtinen
4ae5736bd0 Make sure strtoll() is available when using long long 2012-03-20 20:47:57 +02:00
Petri Lehtinen
56039ed596 Merge branch '2.3' 2012-03-11 21:16:41 +02:00
Petri Lehtinen
02b915af54 Remove unused declarations 2012-03-11 21:12:52 +02:00
Petri Lehtinen
1eb274c555 Merge branch '2.3' 2012-03-08 15:03:03 +02:00
Petri Lehtinen
6ac6f311b5 Fix tests on shells that don't support the export FOO=bar syntax 2012-03-08 15:01:52 +02:00
Petri Lehtinen
f736e705b2 Merge branch '2.3' 2012-02-12 16:05:35 +02:00
Petri Lehtinen
54d88753a6 Disribute the check-exports tests 2012-02-12 16:05:27 +02:00
Petri Lehtinen
98a99fb2bd Merge branch '2.3' 2012-02-02 17:03:03 +02:00
Petri Lehtinen
ac97f6f225 doc: Fix the names of library version constants
Fixes #52.
2012-02-02 17:00:35 +02:00
Petri Lehtinen
60fd7ab781 Merge branch '2.3' 2012-01-30 21:23:49 +02:00
Petri Lehtinen
0d64e8ef89 Make test_load.c not depend on the C locale
Fixes #51.
2012-01-30 21:23:18 +02:00
Petri Lehtinen
a894980258 Set master to 2.4 development mode 2012-01-30 20:59:32 +02:00
Petri Lehtinen
f227483846 jansson 2.3 2012-01-27 21:02:12 +02:00
Petri Lehtinen
6cb14dd337 Add support for optional object keys for json_unpack() and friends
Initial patch by Andrew Thompson.
2012-01-26 21:16:36 +02:00
Petri Lehtinen
fa268b5017 Add json_object_update_{existing,missing}
Closes #37.
2012-01-24 21:03:36 +02:00
Petri Lehtinen
a307974731 Implement json_object_foreach()
Also change many places to use it internally to replace hand-crafted
iteration.

Closes #45, #46.
2012-01-24 21:01:24 +02:00
Petri Lehtinen
a2381948bb Make hashtable less generic
This will make it possible to implement json_object_foreach(). It
should also have some (positive) effect on speed.
2012-01-24 21:01:23 +02:00
Petri Lehtinen
5eb2c442a9 Fix a potential memory leak 2012-01-24 20:35:59 +02:00
Petri Lehtinen
f471e63bb3 Write number of bytes read to error position on successful decode
Closes #49.
2012-01-23 21:18:04 +02:00
Petri Lehtinen
bb24697d9b Merge branch '2.2' 2011-11-14 21:16:42 +02:00
Petri Lehtinen
c4a7bf90cf Revert "json_dump_file: Open the output file in wb mode"
JSON is read as text, so line endings should be preserved.

This reverts commit 32cd821273.
2011-11-14 21:16:36 +02:00
Petri Lehtinen
bef87fc258 Merge branch '2.2'
Closes GH-43.
2011-11-14 21:11:18 +02:00
Petri Lehtinen
68d6410da0 Update the documentation of JSON_DECODE_ANY 2011-11-14 21:10:16 +02:00
Andrea Marchesini
1e36667193 JSON_DECODE_ANY
Closes GH-4.
2011-11-14 21:10:09 +02:00
Petri Lehtinen
0931d938b0 doc: The same JSON values must not be encoded in parallel
Closes GH-42.
2011-11-14 21:01:34 +02:00
Petri Lehtinen
0f2cdd70ff Avoid problems with object's serial number growing too big
Transform serial key comparison from substraction to real comparison.
Reset serial to zero in json_object_clear() to avoid it growing out of
bounds when reusing objects.

Closes GH-40.
Closes GH-41.
2011-11-14 21:01:13 +02:00
Andrea Marchesini
5ec101ec21 json_load* return NULL if the first argument is NULL 2011-11-14 20:57:41 +02:00
Petri Lehtinen
72cd84b92a doc: The configure script can be used on MinGW 2011-11-02 08:01:49 +02:00
Petri Lehtinen
6799c8e4c9 Distribute jansson_config.h.win32 2011-11-02 07:57:19 +02:00
Petri Lehtinen
8484ea3fb2 Remove '+' and leading zeros from exponents in the encoder
Fixes GH-39.
2011-11-01 20:50:16 +02:00
Petri Lehtinen
92d9b89d59 Fix test file comparisons on MinGW
Don't output any DOS line terminators from json_process.

Issue GH-39.
2011-11-01 20:49:52 +02:00
Petri Lehtinen
bc98ab6a69 Use %I64d format for printing long longs on Windows
Fixes GH-38.
2011-11-01 20:49:28 +02:00
Petri Lehtinen
32cd821273 json_dump_file: Open the output file in wb mode
For maximum compatibility.
2011-10-07 20:52:54 +03:00
Petri Lehtinen
9c6cb42f17 jansson 2.2.1 2011-10-06 21:23:09 +03:00
Petri Lehtinen
ed06777937 Distribute doc/portability.rst 2011-10-06 21:23:09 +03:00
Petri Lehtinen
6362032513 json_load_file: Open the input file in rb mode
For maximum compatibility.
2011-10-04 21:11:31 +03:00
Petri Lehtinen
84f739036d Documentation fixes 2011-10-04 21:04:56 +03:00
Petri Lehtinen
0f358c8eaa doc: Add project status to introduction, add portability chapter
Move the multithreading-and-setlocale documentation to the new
portability chapter.

Fixes GH-36.
2011-10-03 22:42:39 +03:00
Petri Lehtinen
f0d5c04734 Make identifier decoding work under all locales
Replace isxxx() functions from ctype.h with locale-independent macros.

Fixes GH-35.
2011-10-03 21:43:16 +03:00
Petri Lehtinen
fd56deb7dd Use strchr() when searching for a single character 2011-10-03 08:52:30 +03:00
Petri Lehtinen
d7ddbf3661 Make real number encoding and decoding work under all locales
The decimal point '.' is changed to locale's decimal point
before/after JSON conversion to make C standard library's
locale-specific string conversion functions work correctly.

All the tests now call setlocale(LC_ALL, "") on startup to use the
locale set in the environment.

Fixes GH-32.
2011-10-02 21:31:17 +03:00
Petri Lehtinen
b6d0191e51 Implement all other encoding functions using json_dump_callback
This way we can check for JSON_ENCODE_ANY flag in one place only.
2011-09-24 21:10:34 +03:00
Petri Lehtinen
2a70d62251 Merge pull request #33 from bakulf/master
Little fixes
2011-09-20 11:11:55 -07:00
Andrea Marchesini
909874b1b9 scope error. result points to a out-of-score variable. 2011-09-20 13:10:32 +02:00
Andrea Marchesini
ff57dee13d unsed static variable removed 2011-09-20 11:46:29 +02:00
Petri Lehtinen
e4cc77ce52 doc: Clarify the result of 's' format of json_unpack()
Fixes GH-31.
2011-09-12 21:22:20 +03:00
Petri Lehtinen
889f295958 jansson 2.2 2011-09-02 21:39:40 +03:00
Petri Lehtinen
68809cd913 doc: json_dump_callback was added in v2.2 2011-09-02 21:29:01 +03:00
Petri Lehtinen
910fb92267 Merge branch '2.1' 2011-08-08 21:00:47 +03:00
Petri Lehtinen
f241e14cab doc: Explain the non-constness of the first parameter of json_unpack() et al
Fixes GH-30.
2011-08-08 20:59:10 +03:00
Petri Lehtinen
7e9c293986 Merge branch '2.1' 2011-06-30 21:48:51 +03:00
Petri Lehtinen
d43464a1ec Merge branch 'issue-29'
Fixes GH-29.
2011-06-30 21:48:33 +03:00
Petri Lehtinen
c7079a25eb doc: Add documentation for json_dump_callback() 2011-06-30 21:47:37 +03:00
JKL
54f38d250c test file for new json_dump_callback function 2011-06-30 21:47:12 +03:00
JKL
c7d543d36c new typedef json_dump_callback_t, function json_dump_callback 2011-06-30 21:47:12 +03:00
Petri Lehtinen
7fab57dcef doc: Fix several typos and other little errors 2011-06-30 21:04:49 +03:00
JKL
cd9757512d use size_t for strbuffer writes, and avoid integer overflow 2011-06-30 20:45:18 +03:00
Petri Lehtinen
c0193bfb7f Check that target is string and value is not NULL in json_string_set() 2011-06-17 21:42:19 +03:00
Petri Lehtinen
6e1f4bb560 doc: Clarify that removing from containers decrements the refcount
While at it, reword the object iteration protocol description a bit.
2011-06-17 20:53:32 +03:00
Petri Lehtinen
1358d0bfac CHANGES: Fix v2.1 release date 2011-06-10 21:53:14 +03:00
Petri Lehtinen
86d17a8dc2 jansson 2.1 2011-06-10 21:30:11 +03:00
Petri Lehtinen
3988ab2d27 Use `literal` syntax with macro and flag names in CHANGES 2011-06-07 21:40:09 +03:00
Petri Lehtinen
f7f7bf5ab2 Prepare for relase: Add CHANGES entry for v2.1 2011-06-07 21:33:59 +03:00
Petri Lehtinen
a76ba52f34 Add JSON_DISABLE_EOF_CHECK decoding flag
With this flag enabled, the decoder stops after a valid JSON input and
thus allows extra data after it.

Fixes GH-25.
2011-05-29 21:27:15 +03:00
Petri Lehtinen
9febdf333c Reduce code duplication in the decoder 2011-05-29 12:53:25 +03:00
Petri Lehtinen
013b8b3f60 Clear errno before calling strtod()
Fixes GH-27.
2011-05-24 09:59:41 +03:00
Petri Lehtinen
49fc708d4c Add JSON_REJECT_DUPLICATES decoding flag
With this flag, a decoding error is issued if any JSON object in the
input contains duplicate keys.

Fixes GH-3.
2011-05-15 13:57:49 +03:00
Petri Lehtinen
92f6f0f22c doc: Clarify that Unicode normalization or comparison algorithms are not used 2011-05-15 12:39:10 +03:00
Petri Lehtinen
e9e34f430e doc: Add "New in version 2.1" notes to new features 2011-05-14 20:52:14 +03:00
Petri Lehtinen
ab723c7fb5 docs: Add a note that object iteration doesn't give any particular order
Closes GH-15.
2011-05-14 13:04:35 +03:00
Petri Lehtinen
636d5f60f9 Add JSON_ENCODE_ANY flag to allow encoding any JSON value
Closes GH-19.
2011-05-14 12:57:12 +03:00
Petri Lehtinen
c3492973e1 Merge branch '2.0' 2011-04-21 13:15:58 +03:00
Petri Lehtinen
e20619e071 Fix a leak when memory allocation fails in json_object_set() & friends 2011-04-21 13:15:22 +03:00
Petri Lehtinen
b44e2be032 Add json_loadb() for decoding possibly non null-terminated strings
Thanks to Jonathan Landis for the initial patch.
2011-04-10 21:01:50 +03:00
Petri Lehtinen
76d6d700ad Merge branch '2.0' 2011-04-05 15:38:37 +03:00
Jim Meyering
c96763215d Avoid set-but-not-used warning/error in a test
Closes GH-20.
2011-04-05 15:36:13 +03:00
Petri Lehtinen
4a76900bd7 Merge branch '2.0'
Conflicts:
	doc/conf.py
	src/jansson.h
2011-03-31 21:26:19 +03:00
Petri Lehtinen
1c0a3b2a55 jansson 2.0.1 2011-03-31 16:59:26 +03:00
Petri Lehtinen
056702e541 Merge branch '2.0' 2011-03-31 16:39:33 +03:00
Petri Lehtinen
eab23f05d8 Fix a few malloc() and free() calls
Replace them with jsonp_malloc() and jsonp_free() to support the
custom memory allocation.
2011-03-31 16:37:43 +03:00
Petri Lehtinen
0944ac8d91 Fix invalid object key hashing in json_unpack() strict checking mode
The keys which are stored temporarily to a hashtable to make sure that
all object keys are unpacked, were hashed with the object key hashing
function. It is meant to compute hashes for object_key_t values, and
it works incorrectly for plain strings.

Fixed by introducing suitable functions for hashing and comparing
strings for string-keyed hashtables.
2011-03-30 12:57:48 +03:00
Petri Lehtinen
a5a43caa9a Merge branch '2.0' 2011-03-27 21:04:29 +03:00
Petri Lehtinen
5456fc59ab Set JANSSON_MICRO_VERSION to 255 (0xFF) for git master
Also, set documentation release to "2.0+git". This shows up in the
automatically built HTML documentation.

These changes makes it easier for library users to know that this
version is under development.

Closes GH-14.
2011-03-27 21:03:04 +03:00
Petri Lehtinen
279d8bf108 Use the correct number of parens in JANSSON_VERSION_HEX macro 2011-03-27 14:12:40 +03:00
Petri Lehtinen
38e35e0973 Test framework enhancements, fix the check_exports test
* Use "printf" instead of "echo -n" as it's more portable
* Treat a test as skipped if it exits with exit status of 77
* Skip the check_exports test if "nm -D" doesn't work
2011-03-27 13:34:43 +03:00
Petri Lehtinen
af18578928 Use the correct number of parens in JANSSON_VERSION_HEX macro 2011-03-23 08:25:50 +02:00
Petri Lehtinen
c30e92603c ANSI C requires struct initializers to be constant expressions
Closes GH-17.
2011-03-21 09:28:14 +02:00
Petri Lehtinen
6ecba84817 Fix json_object_size() return value
Return 0 as documented if the argument is not a JSON object.

Closes GH-18.
2011-03-21 08:22:34 +02:00
Petri Lehtinen
b90ed1accb Enhance portability of va_copy()
va_copy() is a C99 feature. In C89 implementations, it's sometimes
available as __va_copy(). If not, memcpy() should do the trick.
2011-03-20 21:23:37 +02:00
Petri Lehtinen
1111960120 Fix a declaration after statement
While at it, add -Wdeclaration-after-statement to AM_CFLAGS to catch
these in the future.
2011-03-10 21:28:53 +02:00
Petri Lehtinen
7f09f48e7e Distribute doc/upgrading.rst
Closes GH-16.
2011-03-10 21:26:18 +02:00
Petri Lehtinen
b397711a66 Check documentation in make distcheck
It seems that the only way to do this is to use the dvi make target,
as it's built in make distcheck after running configure.
2011-03-10 21:24:45 +02:00
Petri Lehtinen
cf9b384bcb jansson 2.0 2011-02-28 20:46:14 +02:00
Petri Lehtinen
42b651ef56 Fix packing of invalid UTF-8 strings 2011-02-27 21:34:12 +02:00
Petri Lehtinen
387298d4a6 Update README 2011-02-27 21:09:55 +02:00
Petri Lehtinen
cd854b5bc2 tests: Add missing json_decref() calls to suites/api/test_unpack.c 2011-02-25 22:24:12 +02:00
Petri Lehtinen
dd9b4e530c Remove invalid subdirs from test/suites/Makefile.am 2011-02-25 21:09:04 +02:00
Petri Lehtinen
b5dd566c83 doc: Change the title of the upgrading section 2011-02-25 21:01:13 +02:00
Petri Lehtinen
ff26dc60d1 Small documentation tweaks
- Capitalize section titles correctly

- Rename "Building on Windows" to "Building on non-Unix systems" and
  tweak the text accordingly.

- Remove the "Installing Prebuilt Binaries" section. This info is
  better in the web instead, as it may change.

- Mention that Sphinx 1.0 or newer is required.
2011-02-24 22:35:02 +02:00
Petri Lehtinen
53bc9d8a39 Add "Upgrading from older releases" to docs, tweak CHANGES a bit 2011-02-24 22:15:13 +02:00
Petri Lehtinen
a3468c9bd8 Add a CHANGES entry for version 2.0
Wow, lots of stuff. And it's been a long while after the last release.
2011-02-22 21:13:09 +02:00
Petri Lehtinen
58f9d65535 Add lots of tests for pack/unpack code, fix bugs found
Closes GH-12.
2011-02-22 19:08:51 +02:00
Petri Lehtinen
a33c3628da Move json_error_t documentation to its own section
json_error_t is used in the decoder and in the pack and unpack API's,
so it's better to have a separate section for it.
2011-02-22 13:53:58 +02:00
Petri Lehtinen
50dc64a7af Truncate error source from start, not end, if it's too long to fit
It's more helpful to see "...bar/baz.json" instead of "/long/path/to".
2011-02-22 13:34:37 +02:00
Petri Lehtinen
5df7b79397 Refactor decoder input stream
- Add a new field position to the json_error_t structure. This is the
  position in bytes from the beginning of the input.

- Keep track of line, column and input position in the stream level.
  Previously, only line was tracked, and it was in the lexer level, so
  this info was not available for UTF-8 decoding errors.

- While at it, refactor tests so that no separate "stripped" tests are
  required. json_process is now able to strip whitespace from its
  input, and the "valid" and "invalid" test suites now use this to
  test both non-stripped and stripped input.

Closes GH-9.
2011-02-22 12:07:37 +02:00
Petri Lehtinen
e54ea1f7c9 tests: Use "make STOP=1 check" to stop on first failure 2011-02-19 12:15:21 +02:00
Petri Lehtinen
4be9e9e7fe Add custom memory allocation
Thanks to Basile Starynkevitch for the suggestion and initial patch.
Thanks to Jonathan Landis and Deron Meranda for showing how this can
be utilized for implementing secure memory operations.
2011-02-17 10:10:53 +02:00
Graeme Smecher
dd7dd414f0 Resolve __va_list_tag ** -> va_list * type errors with clang and future GCCs
Functions taking va_args are munged to receive arguments of type
'__va_list_tag *'. This patch uses va_copy to coerce them to the expected type
so we don't get compiler errors.

Tested on x86_64, both 32-bit and 64-bit compiles.

Reported-By: Basile Starynkevitch <basile@starynkevitch.net>
2011-02-03 20:41:54 +02:00
Petri Lehtinen
f25698d08f Fix an unpack example in the docs 2011-01-30 12:53:54 +02:00
Petri Lehtinen
ef13fb9189 Tweak the default validation behaviour of the unpack API
Now, by default, unpacking doesn't check that all array and object
items are accessed. The check can be enabled globally by using the
JSON_STRICT flag (formerly JSON_UNPACK_ONLY), or on a per-value basis
by using the new '!' format character. The '*' format character is
still available to disable the global check on a per-value basis.
2011-01-29 21:38:07 +02:00
Petri Lehtinen
7706abcbed Use the Sphinx default theme again for documentation
The "haiku" theme doesn't show chapter contents in sidebar.
2011-01-26 09:27:19 +02:00
Petri Lehtinen
7d49fc75d5 Documentation for pack and unpack functions 2011-01-26 09:27:19 +02:00
Petri Lehtinen
908c62f327 Add the 'I' format for both pack and unpack 2011-01-25 21:41:35 +02:00
Petri Lehtinen
a1c185a376 Use 'f' for real and 'F' for number (real or integer) in unpack 2011-01-25 20:42:41 +02:00
Petri Lehtinen
ac96ac13d4 unpack: Unify and enhance error messages
Give the type name instead of its enum index in the error message when
an unexpected value is encountered while unpacking.
2011-01-25 20:37:53 +02:00
Petri Lehtinen
579c291882 Expand the pack/unpack API, implement unpack flags
Expand the pack/unpack API: json_(un)pack is the simple version with
no error output, json_(un)pack_ex has error output and flags,
json_v(un)pack_ex is a va_list version of json_(un)pack_ex.

Implement unpacking flags:

- JSON_UNPACK_ONLY turns off extra validation, i.e. array and object
  unpacking doesn't check that all items are unpacked. This is really
  just convenience for not adding '*' after each object and array.

- JSON_VALIDATE_ONLY turns off unpacking, i.e. no varargs are expected
  and nothing is unpacked.
2011-01-25 10:02:27 +02:00
Petri Lehtinen
2770dca2c0 Add validation features to json_unpack()
* By default, json_unpack() now checks that all items of arrays and
  objects are unpacked. This is useful for validation.

* Add format specifier '*' to suppress this check for individual
  arrays and objects. '*' must appear as the last format specifier
  before the closing ']' or '}'.
2011-01-25 08:53:55 +02:00
Petri Lehtinen
6825c2c706 Rename variadic.c to pack_unpack.c 2011-01-25 08:53:55 +02:00
Petri Lehtinen
6d1f28f050 Refactor json_unpack()
* Use the format string scanner from the previous commit (with the
  simpler separator skipping semantics)

* Split json_vnunpack() to three separate functions for unpacking
  objects, arrays and "simple" values

* Always return 0 on success, 1 on error

This shaves around 100 more lines from the original implementation.
2011-01-25 08:53:54 +02:00
Petri Lehtinen
7f3018a4fb Refactor json_pack()
* Implement a "scanner" that reads the format string, maintaining state

* Split json_vnpack() to three separate functions for packing objects,
  arrays and simple values. This makes it more clear what is being
  packed, and the object and array structures become more evident.

* Make the skipping of ignored character simpler, i.e. skip ':' and
  ',' independent of their context

This patch shaves around 80 lines of code from the original
implementation.
2011-01-24 21:26:23 +02:00
Petri Lehtinen
53383860e8 Unify style 2011-01-24 21:14:55 +02:00
Petri Lehtinen
fa7c2ea070 Update copyright notices for 2011 2011-01-22 13:43:14 +02:00
Petri Lehtinen
46f91797ec Build cleanly with gcc's -Werror=declaration-after-statement flag 2011-01-17 15:51:40 +02:00
Graeme Smecher
a242381024 Remove debugging printf 2011-01-15 12:45:08 +02:00
Graeme Smecher
3a7512d2b0 Make json_pack/json_unpack() recursive
Note that we pass va_list pointers around instead of just va_lists, which
would seem more intuitive. This is necessary since the behaviour of va_lists
passed as function parameters is finicky. Quoth stdarg(3):

	If ap is passed to a function that uses va_arg(ap,type) then the value
	of ap is undefined after the return of that function.

The pointer-passing strategy is used by Python's Py_BuildValue() for the same
purpose.
2011-01-14 21:43:48 +02:00
Petri Lehtinen
269e86b725 Emphasize the constness of the return value of json_string_value()
Closes GH-7.
2010-12-20 21:08:11 +02:00
Petri Lehtinen
bf32f6cd75 Document the version info constants 2010-12-19 21:55:00 +02:00
Petri Lehtinen
c7611e7a0d Make int32_t available when the configure script is not used 2010-12-18 23:02:54 +02:00
Petri Lehtinen
23bc8e468d Add version info to jansson.h 2010-12-14 20:58:40 +02:00
Petri Lehtinen
5422a862de Enhance error reporting
This patch adds two new fields to the json_error_t struct: column and
source. It also adds functions to populate json_error_t internally.

The column field is not currently used, but it will be utilized in the
decoder and pack/unpack functions.
2010-10-27 21:58:20 +03:00
Petri Lehtinen
818baf5fdb Move and enhance documentation on json_error_t 2010-10-26 21:20:34 +03:00
Petri Lehtinen
bb5d4efb2e Make json_error_t transparent again
After looking at the new code for a few days, I didn't like it
anymore. To prepare for the future, a few fields will be added to the
json_error_t struct later.

This reverts commit 23dd078c8d. Some
adjustments were needed because of newer commits.
2010-10-26 21:20:34 +03:00
Graeme Smecher
198d537be7 Adds json_pack / json_unpack variadic functions. 2010-10-26 08:59:06 +03:00
Petri Lehtinen
1acd1a7b56 Remove all "Added in version 1.x" info from documentation
As 2.0 will be backwards incompatible anyway, there's no need to
record which features were new in which 1.x releases.
2010-10-14 21:05:22 +03:00
Petri Lehtinen
23dd078c8d Make json_error_t opaque
All decoding functions now accept a json_error_t** parameter and set
it to point to a heap-allocated json_error_t structure if an error
occurs. The contents of json_error_t are no longer exposed directly, a
few functions to do it have been added instead. If an error occurs,
the user must free the json_error_t value.

This makes it possible to enhance the error reporting facilities in
the future without breaking ABI compatibility with older versions.

This is a backwards incompatible change.
2010-10-14 21:02:37 +03:00
Petri Lehtinen
781bda1404 Merge branch '1.3' 2010-09-06 20:48:25 +03:00
Petri Lehtinen
3d5c0f46f1 Run Sphinx without the -W flag when building documentation
In "make html", don't use the -W flag with Sphinx. This makes it
possible to create the documentation with Sphinx 1.0 without errors,
as the warning about using old-style C markup isn't turned to an
error.

Don't build documentation in "make check". Instead, add a new make
target "check-doc" to build the documentation with the -W flag.
2010-09-06 20:46:15 +03:00
Petri Lehtinen
8567816542 Use Sphinx 1.0, change the HTML theme 2010-09-05 22:00:47 +03:00
Petri Lehtinen
664c88ca97 Add a section describing how to build on Windows 2010-09-05 21:38:06 +03:00
Petri Lehtinen
cbb3855d97 On Windows, typedef int to int32_t
There's no inttypes.h or stdint.h in the stdlib on Windows.
2010-09-05 21:30:02 +03:00
Petri Lehtinen
3c4cf31a01 Add jansson_config.h.win32
As the configure script cannot be run on Windows, give the users a
jansson_config.h that they can use directly.
2010-09-05 21:21:37 +03:00
Petri Lehtinen
06eb436008 Move max() to jansson_private.h, define only if not already defined
On some platforms (Visual C++ for one) the standard library already
defines max() as a macro.
2010-09-05 21:18:46 +03:00
Petri Lehtinen
e3654c2245 Don't use designated struct initializers
It's a C99 feature and not available on all compilers (Visual C++, for
example).
2010-09-05 21:18:46 +03:00
Petri Lehtinen
a112563214 Use config.h only if it exists
This makes it easier to compile without the configure script (e.g. on
Windows).
2010-09-05 21:18:46 +03:00
Petri Lehtinen
976fc2279f Replace all occurences of inline with JSON_INLINE
This makes it easier to compile without the configure script (e.g. on
Windows).
2010-09-05 21:18:46 +03:00
Petri Lehtinen
56643d4311 Merge branch '1.3'
Conflicts:
	doc/apiref.rst
	src/jansson_private.h
2010-08-14 21:02:08 +03:00
Petri Lehtinen
cb8fcc7808 Set the version number to 2.0pre 2010-08-14 20:47:08 +03:00
Petri Lehtinen
b76c69de1b Clarify and document the integer type configuration 2010-08-14 20:42:15 +03:00
Petri Lehtinen
bfac1972e2 Add a flags parameter to all decoding functions for future needs
As of now, the parameter is unused, but may be needed in the future.
I'm adding it now so that in the future both API and ABI remain
backwards compatible as long as possible.

This is a backwards incompatible change.
2010-08-14 17:28:09 +03:00
Petri Lehtinen
f8d0e01e46 Change the maximum indentation size to 32 spaces in encoder
This is to free up bits from the flags parameter of json_dump
functions. I'm pretty sure no-one needs 256 spaces of indentation when
pretty-printing JSON values...

This is a backwards incompatible change.
2010-08-13 22:12:36 +03:00
Petri Lehtinen
ffbab6fedd Change the underlying type of JSON integer from long to json_int_t
json_int_t is typedef'd to long long if it's supported, or long
otherwise. There's also some supporting things, like the
JSON_INTEGER_FORMAT macro that expands to the printf() conversion
specifier that corresponds to json_int_t's actual type.

This is a backwards incompatible change.
2010-08-13 22:07:20 +03:00
Petri Lehtinen
145032a57f Make object_key_t portable
A flexible array member is unportable. Use a table of length 1
instead. This needs some adjustment to the memory allocatio, too.
2010-08-12 21:35:23 +03:00
Petri Lehtinen
519d52e2bb Beautify the container_of macro
Use offsetof instead of zero pointer dereference trickery.
2010-08-12 21:34:51 +03:00
Petri Lehtinen
94182a5acc Replace inline with JSON_INLINE in json_object_iter_set() declaration 2010-08-12 21:10:12 +03:00
Petri Lehtinen
f71eb7fe17 Check for gcc before setting gcc specific CFLAGS 2010-08-12 21:00:09 +03:00
Petri Lehtinen
7ce70533c9 Move site configuration to jansson_config.h
This way, more site configuration can be more easily added later.
2010-08-10 22:16:55 +03:00
Petri Lehtinen
014c49c285 Change JSON integer's underlying type from int to long
This is a backwards incompatible change.
2010-08-10 21:45:18 +03:00
Petri Lehtinen
6e3ca5c45c Clarify the documentation
Couple some string and number information from the RFC conformance
chapter in the API reference, and refer to the RFC conformance chapter
from API reference for more information.

Also, state more clearly that a JSON text must have an array or object
as the top-level value, and better document the string comparison
performed by json_equal().
2010-06-16 21:34:10 +03:00
Petri Lehtinen
68f2861e92 Unify unsigned integer usage in the API
Replace all occurences of unsigned int and unsigned long with size_t.

This is a backwards incompatible change, as the signature of many API
functions changes.
2010-06-15 15:38:59 +03:00
Petri Lehtinen
b354f8a35a configure.ac: Remove unneeded AC_PROG_CXX 2010-06-14 22:30:15 +03:00
Petri Lehtinen
b461c652b4 Add a few missing changes to CHANGES for v1.3
These were forgotten when releasing.
2010-06-14 14:35:38 +03:00
376 changed files with 20191 additions and 3437 deletions

5
.clang-format Normal file
View file

@ -0,0 +1,5 @@
BasedOnStyle: LLVM
AlignConsecutiveMacros: true
ColumnLimit: 90
IndentCaseLabels: true
IndentWidth: 4

15
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,15 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
groups:
github-actions:
patterns:
- "*"

31
.github/workflows/fuzz.yml vendored Normal file
View file

@ -0,0 +1,31 @@
name: oss-fuzz
on:
pull_request:
branches: [ master ]
paths:
- '**.c'
- '**.h'
jobs:
fuzz:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
id: build
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'jansson'
dry-run: false
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'jansson'
fuzz-seconds: 600
dry-run: false
- name: Upload Crash
uses: actions/upload-artifact@v4
if: failure() && steps.build.outcome == 'success'
with:
name: artifacts
path: ./out/artifacts

67
.github/workflows/tests.yml vendored Normal file
View file

@ -0,0 +1,67 @@
name: tests
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: ./scripts/clang-format-check
autotools:
strategy:
matrix:
os: ["ubuntu-latest", "macos-latest"]
cc: ["gcc", "clang"]
dtoa: ["yes", "no"]
runs-on: ${{ matrix.os }}
steps:
- if: ${{runner.os == 'macOS'}}
run: brew install autoconf automake libtool
- uses: actions/checkout@v4
- run: autoreconf -fi
- env:
CC: ${{ matrix.cc }}
CFLAGS: -Werror
run: ./configure --enable-dtoa=${{ matrix.dtoa }}
- run: make check
cmake:
strategy:
matrix:
os: ["ubuntu-latest", "macos-latest", "windows-latest"]
cc: ["gcc", "clang"]
exclude:
- os: windows-latest
cc: gcc
- os: windows-latest
cc: clang
include:
- os: windows-latest
cc: 'msvc' # Doesn't really matter, MSVC is always used on Windows
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v4
- env:
CC: ${{matrix.cc}}
run: cmake .
- run: cmake --build .
- run: ctest --output-on-failure
valgrind:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt update && sudo apt install valgrind
- run: cmake -DJANSSON_TEST_WITH_VALGRIND=ON .
- run: cmake --build .
- run: ctest --output-on-failure

12
.gitignore vendored
View file

@ -19,9 +19,19 @@ install-sh
libtool
ltmain.sh
missing
compile
test-driver
*.lo
*.la
stamp-h1
*.pyc
*.pc
/src/jansson.h
/src/jansson_config.h
/jansson_private_config.h.in
/jansson_private_config.h
/build
*.exe
.idea
cmake-build-debug/
*.log
*.trs

30
Android.mk Normal file
View file

@ -0,0 +1,30 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := arm
LOCAL_SRC_FILES := \
src/dump.c \
src/error.c \
src/hashtable.c \
src/hashtable_seed.c \
src/load.c \
src/memory.c \
src/pack_unpack.c \
src/strbuffer.c \
src/strconv.c \
src/utf.c \
src/value.c
LOCAL_C_INCLUDES += \
$(LOCAL_PATH) \
$(LOCAL_PATH)/android \
$(LOCAL_PATH)/src
LOCAL_MODULE_TAGS := optional
LOCAL_SHARED_LIBRARIES := libc
LOCAL_CFLAGS += -O3 -DHAVE_STDINT_H=1
LOCAL_MODULE:= libjansson
include $(BUILD_SHARED_LIBRARY)

810
CHANGES
View file

@ -1,8 +1,818 @@
Version 2.14.1
==============
Released 2025-03-23
* Fixes:
- Fix thread safety of encoding and decoding when `uselocale` or `newlocale`
is used to switch locales inside the threads (#674, #675, #677. Thanks to
Bruno Haible for the report and help with fixing.)
- Use David M. Gay's `dtoa()` algorithm to avoid misprinting issues of real
numbers that are not exactly representable as a `double` (#680).
If this is not desirable, use `./configure --disable-dtoa` or `cmake
-DUSE_DTOA=OFF .`
* Build:
- Make test output nicer in CMake based builds (#683)
- Simplify tests (#685)
Version 2.14
============
Released 2021-09-09
* New Features:
- Add `json_object_getn`, `json_object_setn`, `json_object_deln`, and the
corresponding `nocheck` functions. (#520, by Maxim Zhukov)
* Fixes:
- Handle `sprintf` corner cases (#537, by Tobias Stoeckmann)
* Build:
- Symbol versioning for all exported symbols (#540, by Simon McVittie)
- Fix compiler warnings (#555, by Kelvin Lee)
* Documentation:
- Small fixes (#544, #546, by @i-ky)
- Sphinx 3 compatibility (#543, by Pierce Lopez)
Version 2.13.1
==============
Released 2020-05-07
* Build:
- Include `jansson_version_str()` and `jansson_version_cmp()` in
shared library. (#534)
- Include ``scripts/`` in tarball. (#535)
Version 2.13
============
Released 2020-05-05
* New Features:
- Add `jansson_version_str()` and `jansson_version_cmp()` for runtime
version checking (#465).
- Add `json_object_update_new()`, `json_object_update_existing_new()`
and `json_object_update_missing_new()` functions (#499).
- Add `json_object_update_recursive()` (#505).
* Build:
- Add ``-Wno-format-truncation`` to suppress format truncation warnings (#489).
* Bug fixes:
- Remove ``strtod`` macro definition for MinGW (#498).
- Add infinite loop check in `json_deep_copy()` (#490).
- Add ``pipe`` macro definition for MinGW (#500).
- Enhance ``JANSSON_ATTRS`` macro to support earlier C standard(C89) (#501).
- Update version detection for sphinx-build (#502).
* Documentation:
- Fix typos (#483, #494).
- Document that call the custom free function to free the return value
of `json_dumps()` if you have a custom malloc/free (#490).
- Add vcpkg installation instructions (#496).
- Document that non-blocking file descriptor is not supported on
`json_loadfd()` (#503).
Version 2.12
============
Released 2018-11-26
* Bug fixes:
- Fix error message in `json_pack()` for NULL object (#409).
- Avoid invalid memory read in `json_pack()` (#421).
- Call va_end after va_copy in `json_vsprintf()` (#427).
- Improve handling of formats with '?' and '*' in `json_pack()` (#438).
- Remove inappropriate `jsonp_free()` which caused segmentation fault in
error handling (#444).
* Build:
- Add function attributes for GCC and CLANG to provide warnings on improper
use of jansson routines (#404).
- Many CMake fixes (#408, #412, #415).
- Enable -Bsymbolic-functions linker flag whenever possible.
- Resolve various compiler warnings (#423, #430, #435, #436).
- Fix code coverage ignored paths (#439).
* Other:
- Test coverage improvements (#398, #400).
- Add VS 2017 to appveyor, update Visual Studio documentation (#417).
- Update copyright for 2018 (#424).
- Update install instructions in README (#401).
Version 2.11
============
Released 2018-02-09
* New features:
- Add `json_pack()` format specifiers s*, o* and O* for values that
can be omitted if null (#339).
- Add `json_error_code()` to retrieve numeric error codes (#365, #380,
#381).
- Enable thread safety for `json_dump()` on all systems. Enable thread
safe `json_decref()` and `json_incref()` for modern compilers (#389).
- Add `json_sprintf()` and `json_vsprintf()` (#393).
* Bug Fixes:
- Fix incorrect report of success from `json_dump_file()` when an error
is returned by `fclose()` (#359).
- Make json_equal() const-correct (#344).
- Fix incomplete stealing of references by `json_pack()` (#374).
* Build:
- Work around gcc's -Wimplicit-fallthrough.
- Fix CMake detection of ``sys/types.h`` header (#375).
- Fix `jansson.pc` generated by CMake to be more consistent with the one
generated using GNU Autotools (#368).
* Other:
- Miscellaneous documentation fixes (#356, #378, #395).
- Remove unnecessary reference actions from parsers (#377).
Version 2.10
============
Released 2017-03-02
* New features:
- Add JSON_EMBED encoding flag allowing arrays and objects to be encoded
into existing streams (#329).
- Add `json_dumpb()` function for dumping to a pre-allocated buffer (#328).
- Add `json_dumpfd()` and `json_loadfd()` functions for dumping to streaming
file descriptors (#328).
- Add support for parsing buffers larger than 2GB (#309).
* Build:
- Fix CMake build when LONG_LONG_INT is defined as "" (#321)
* Other:
- Internal code cleanup (#311, #314)
Version 2.9
===========
Released 2016-09-18
* New features:
- Add ``json_auto_t`` to automatically decref a value that goes out
of scope. Available only on GCC and Clang. (#301)
* Build:
- Fix CMake build (at least on Linux) by removing conflicting
jansson_config.h from the distribution (#306)
- Change CMake install target generation to be optional (#305)
* Documentation:
- Small documentation fixes.
Version 2.8
===========
Released 2016-08-30
* New features:
- Always preserve insertion order of object items.
`json_object_iter()` and friends, `json_object_foreach()` and
`json_dumps()` and friends now always work in the insertion order of
object items (#293).
- Add `json_object_foreach_safe()` macro that allows
`json_object_del()` calls during iteration (#230).
- Add `json_get_alloc_funcs()` to allow reading the allocation
functions set by `json_set_alloc_funcs()` (#262, #264).
- Add `json_pack()` format specifiers s?, o? and O? for values that
can be null (#261, #270).
* Bug fixes:
- Fix a crash when parsing inputs consisting of very deeply nested
arrays or objects (#282, #284).
- Never convert numbers to integers in the parser when
JSON_DECODE_INT_AS_REAL is set. This fixes error messages for
overflowing numbers when JSON_DECODE_INT_AS_REAL is set (#212).
- Fix a use-after-free in `json_pack()` error handling.
- Fix subnormal number parsing on mingw32.
- Handle out-of-memory situations gracefully in the hashtable
implementation (#298).
* Build:
- Fix build with CMake on all versions of Visual Studio up to 2015
(#262, #289).
- Fix pkgconfig libdir when using CMake (#268).
- Fix CMake config for static CRT builds on Windows (#206).
- Fix warnings on LLVM 6.0 targeting iOS arm64 (#208).
- Add coverlls.io support via Travis for a nice test coverage badge
(#211).
- Don't expect ``jansson_config.h`` to be in the compiler's include
path (#209).
- Add a build-time option to set initial hashtable size (#213).
- Use snprintf and strncpy in place of sprintf and strcpy to silence
linker warnings on OpenBSD (#233).
* Documentation:
- Fix various typos in documentation, and a broken link (#258).
- Add an example program in ``examples/`` (#214, #217).
- Fix building of documentation man pages (#207).
- Document the fact that copying objects doesn't preserve the
insertion order of keys (#237).
* Tests:
- Don't use the nonstandard __FUNCTION__ macro in tests.
- Use expr instead of $((...)) in shell scripts for Solaris 10
compatibility.
- Disable Visual Studio warning C4756 when triggered deliberately in
tests (#216).
- Other minor fixes (#221, #248).
* Other changes:
- List all unrecognized object keys when strict unpacking fails
(#263).
- Alter the order of the members of the hashtable_pair struct for
easier debugging.
- Minor performance improvement to `json_dump()` and friends (#234).
- Minor style fixes (#255, #257).
Version 2.7
===========
Released 2014-10-02
* New features:
- `json_pack()` and friends: Add format specifiers ``s%`` and ``+%``
for a size_t string length (#141).
- `json_unpack()` and friends: Add format specifier ``s%`` for
unpacking the string length along with the string itself (#141).
- Add length-aware string constructors `json_stringn()` and
`json_stringn_nocheck()`, length-aware string mutators
`json_string_setn()` and `json_string_setn_nocheck()`, and a
function for getting string's length `json_string_length()` (#141,
#143).
- Support ``\u0000`` escapes in the decoder. The support can be
enabled by using the ``JSON_ALLOW_NUL`` decoding flag (#141).
- Add `json_boolean_value()` as an alias for `json_is_true()`
(#146).
- Add JSON_REAL_PRECISION encoding flag/macro for controlling real
number precision (#178).
- Define the maximum indentation as JSON_MAX_INDENT (#191).
* Bug fixes:
- Some malformed ``\uNNNN`` escapes could crash the decoder with an
assertion failure.
- Avoid integer overflows with very long strings in UTF-8 decoder and
hashtable.
- Check for *NULL* key in `json_object_get()` and
`json_object_del()` (#151).
- Enhance hashtable seeding on Windows (#162).
- `json_unpack()`: Allow mixing JSON_STRICT with optional keys
(#162, #163).
- Fix int/int32 mismatch (#142).
- Parse subnormal numbers correctly (#202).
* Build:
- Remove VS2010 build files. CMake should be used on Windows instead
(#165).
- Fix CMake build flags for MinGW (#193).
- Add CMake config files for find_package. Rename config.h to
jansson_private_config.h (#157, #159).
- Make Valgrind checks work with CMake (#160).
- Fix feature checks to use correct __ATOMIC flags.
- Fix CMake checks for uint16_t and uint8_t support (#177).
- Make Jansson build on SmartOS/Solaris (#171).
- Work around a GCC bug on Solaris (#175).
- Fix autoreconf on Debian (#182).
- Don't use GNU make specific export for global AM_CFLAGS (#203,
#204).
- Fix building on Android using the supplied Android.mk (#166,
#174).
- Android.mk: Add -DHAVE_STDINT_H to LOCAL_CFLAGS (#200).
* Documentation:
- Document JANSSON_BUILD_SHARED_LIBS CMake option (#187).
* Tests:
- Close file handles correctly (#198).
* Other changes:
- ``\uNNNN`` escapes are now encoded in upper case for better
readability.
- Enable usage of AddressSanitizer (#180).
Version 2.6
===========
Released 2014-02-11
* Security:
- CVE-2013-6401: The hash function used by the hashtable
implementation has been changed, and is automatically seeded with
random data when the first JSON object is created. This prevents
an attacker from causing large JSON objects with specially crafted
keys perform poorly.
* New features:
- `json_object_seed()`: Set the seed value of the hash function.
* Bug fixes:
- Include CMake specific files in the release tarball.
* Documentation:
- Fix tutorial source to send a User-Agent header, which is now
required by the GitHub API.
- Set all memory to zero in secure_free() example.
Version 2.5
===========
Released 2013-09-19
* New features:
- `json_pack()` and friends: Add format specifiers ``s#``, ``+`` and
``+#``.
- Add ``JSON_DECODE_INT_AS_REAL`` decoding flag to treat all numbers
as real in the decoder (#123).
- Add `json_array_foreach()`, paralleling `json_object_foreach()`
(#118).
* Bug fixes:
- `json_dumps()` and friends: Don't crash if json is *NULL* and
``JSON_ENCODE_ANY`` is set.
- Fix a theoretical integer overflow in `jsonp_strdup()`.
- Fix `l_isxdigit()` macro (#97).
- Fix an off-by-one error in `json_array_remove()`.
* Build:
- Support CMake in addition to GNU Autotools (#106, #107, #112,
#115, #120, #127).
- Support building for Android (#109).
- Don't use ``-Werror`` by default.
- Support building and testing with VPATH (#93).
- Fix compilation when ``NDEBUG`` is defined (#128)
* Tests:
- Fix a refleak in ``test/bin/json_process.c``.
* Documentation:
- Clarify the return value of `json_load_callback_t`.
- Document how to circumvent problems with separate heaps on Windows.
- Fix memory leaks and warnings in ``github_commits.c``.
- Use `json_decref()` properly in tutorial.
* Other:
- Make it possible to forward declare ``struct json_t``.
Version 2.4
===========
Released 2012-09-23
* New features:
- Add `json_boolean()` macro that returns the JSON true or false
value based on its argument (#86).
- Add `json_load_callback()` that calls a callback function
repeatedly to read the JSON input (#57).
- Add JSON_ESCAPE_SLASH encoding flag to escape all occurences of
``/`` with ``\/``.
* Bug fixes:
- Check for and reject NaN and Inf values for reals. Encoding these
values resulted in invalid JSON.
- Fix `json_real_set()` to return -1 on error.
* Build:
- Jansson now builds on Windows with Visual Studio 2010, and
includes solution and project files in ``win32/vs2010/``
directory.
- Fix build warnings (#77, #78).
- Add ``-no-undefined`` to LDFLAGS (#90).
* Tests:
- Fix the symbol exports test on Linux/PPC64 (#88).
* Documentation:
- Fix typos (#73, #84).
Version 2.3.1
=============
Released 2012-04-20
* Build issues:
- Only use ``long long`` if ``strtoll()`` is also available.
* Documentation:
- Fix the names of library version constants in documentation. (#52)
- Change the tutorial to use GitHub API v3. (#65)
* Tests:
- Make some tests locale independent. (#51)
- Distribute the library exports test in the tarball.
- Make test run on shells that don't support the ``export FOO=bar``
syntax.
Version 2.3
===========
Released 2012-01-27
* New features:
- `json_unpack()` and friends: Add support for optional object keys
with the ``{s?o}`` syntax.
- Add `json_object_update_existing()` and
`json_object_update_missing()`, for updating only existing keys or
only adding missing keys to an object. (#37)
- Add `json_object_foreach()` for more convenient iteration over
objects. (#45, #46)
- When decoding JSON, write the number of bytes that were read from
input to ``error.position`` also on success. This is handy with
``JSON_DISABLE_EOF_CHECK``.
- Add support for decoding any JSON value, not just arrays or
objects. The support is enabled with the new ``JSON_DECODE_ANY``
flag. Patch by Andrea Marchesini. (#4)
* Bug fixes
- Avoid problems with object's serial number growing too big. (#40,
#41)
- Decoding functions now return NULL if the first argument is NULL.
Patch by Andrea Marchesini.
- Include ``jansson_config.h.win32`` in the distribution tarball.
- Remove ``+`` and leading zeros from exponents in the encoder.
(#39)
- Make Jansson build and work on MinGW. (#39, #38)
* Documentation
- Note that the same JSON values must not be encoded in parallel by
separate threads. (#42)
- Document MinGW support.
Version 2.2.1
=============
Released 2011-10-06
* Bug fixes:
- Fix real number encoding and decoding under non-C locales. (#32)
- Fix identifier decoding under non-UTF-8 locales. (#35)
- `json_load_file()`: Open the input file in binary mode for maximum
compatibility.
* Documentation:
- Clarify the lifecycle of the result of the ``s`` fromat of
`json_unpack()`. (#31)
- Add some portability info. (#36)
- Little clarifications here and there.
* Other:
- Some style fixes, issues detected by static analyzers.
Version 2.2
===========
Released 2011-09-03
* New features:
- `json_dump_callback()`: Pass the encoder output to a callback
function in chunks.
* Bug fixes:
- `json_string_set()`: Check that target is a string and value is
not NULL.
* Other:
- Documentation typo fixes and clarifications.
Version 2.1
===========
Released 2011-06-10
* New features:
- `json_loadb()`: Decode a string with a given size, useful if the
string is not null terminated.
- Add ``JSON_ENCODE_ANY`` encoding flag to allow encoding any JSON
value. By default, only arrays and objects can be encoded. (#19)
- Add ``JSON_REJECT_DUPLICATES`` decoding flag to issue a decoding
error if any JSON object in the input contins duplicate keys. (#3)
- Add ``JSON_DISABLE_EOF_CHECK`` decoding flag to stop decoding after a
valid JSON input. This allows other data after the JSON data.
* Bug fixes:
- Fix an additional memory leak when memory allocation fails in
`json_object_set()` and friends.
- Clear errno before calling `strtod()` for better portability. (#27)
* Building:
- Avoid set-but-not-used warning/error in a test. (#20)
* Other:
- Minor clarifications to documentation.
Version 2.0.1
=============
Released 2011-03-31
* Bug fixes:
- Replace a few `malloc()` and `free()` calls with their
counterparts that support custom memory management.
- Fix object key hashing in json_unpack() strict checking mode.
- Fix the parentheses in ``JANSSON_VERSION_HEX`` macro.
- Fix `json_object_size()` return value.
- Fix a few compilation issues.
* Portability:
- Enhance portability of `va_copy()`.
- Test framework portability enhancements.
* Documentation:
- Distribute ``doc/upgrading.rst`` with the source tarball.
- Build documentation in strict mode in ``make distcheck``.
Version 2.0
===========
Released 2011-02-28
This release is backwards incompatible with the 1.x release series.
See the chapter "Upgrading from older versions" in documentation for
details.
* Backwards incompatible changes:
- Unify unsigned integer usage in the API: All occurences of
unsigned int and unsigned long have been replaced with size_t.
- Change JSON integer's underlying type to the widest signed integer
type available, i.e. long long if it's supported, otherwise long.
Add a typedef json_int_t that defines the type.
- Change the maximum indentation depth to 31 spaces in encoder. This
frees up bits from the flags parameter of encoding functions
`json_dumpf()`, `json_dumps()` and `json_dump_file()`.
- For future needs, add a flags parameter to all decoding functions
`json_loadf()`, `json_loads()` and `json_load_file()`.
* New features
- `json_pack()`, `json_pack_ex()`, `json_vpack_ex()`: Create JSON
values based on a format string.
- `json_unpack()`, `json_unpack_ex()`, `json_vunpack_ex()`: Simple
value extraction and validation functionality based on a format
string.
- Add column, position and source fields to the ``json_error_t``
struct.
- Enhance error reporting in the decoder.
- ``JANSSON_VERSION`` et al.: Preprocessor constants that define the
library version.
- `json_set_alloc_funcs()`: Set custom memory allocation functions.
* Fix many portability issues, especially on Windows.
* Configuration
- Add file ``jansson_config.h`` that contains site specific
configuration. It's created automatically by the configure script,
or can be created by hand if the configure script cannot be used.
The file ``jansson_config.h.win32`` can be used without
modifications on Windows systems.
- Add a section to documentation describing how to build Jansson on
Windows.
- Documentation now requires Sphinx 1.0 or newer.
Version 1.3
===========
Released 2010-06-13
* New functions:
- `json_object_iter_set()`, `json_object_iter_set_new()`: Change
object contents while iterating over it.
- `json_object_iter_at()`: Return an iterator that points to a
specific object item.
* New encoding flags:
- ``JSON_PRESERVE_ORDER``: Preserve the insertion order of object

674
CMakeLists.txt Normal file
View file

@ -0,0 +1,674 @@
cmake_minimum_required (VERSION 3.10)
project(jansson C)
# Options
option(JANSSON_BUILD_SHARED_LIBS "Build shared libraries." OFF)
option(USE_URANDOM "Use /dev/urandom to seed the hash function." ON)
option(USE_WINDOWS_CRYPTOAPI "Use CryptGenRandom to seed the hash function." ON)
option(USE_DTOA "Use dtoa for optimal floating-point to string conversions." ON)
if (MSVC)
# This option must match the settings used in your program, in particular if you
# are linking statically
option(JANSSON_STATIC_CRT "Link the static CRT libraries" OFF )
endif ()
option(JANSSON_EXAMPLES "Compile example applications" ON)
if (UNIX)
option(JANSSON_COVERAGE "(GCC Only! Requires gcov/lcov to be installed). Include target for doing coverage analysis for the test suite. Note that -DCMAKE_BUILD_TYPE=Debug must be set" OFF)
endif ()
# Set some nicer output dirs.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/lib)
set(JANSSON_TEMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/tmp)
# Give the debug version a different postfix for windows,
# so both the debug and release version can be built in the
# same build-tree on Windows (MSVC).
if (WIN32 AND NOT CMAKE_DEBUG_POSTFIX)
set(CMAKE_DEBUG_POSTFIX "_d")
endif()
# This is how I thought it should go
# set (JANSSON_VERSION "2.3.1")
# set (JANSSON_SOVERSION 2)
set(JANSSON_DISPLAY_VERSION "2.14.1")
# This is what is required to match the same numbers as automake's
set(JANSSON_VERSION "4.14.0")
set(JANSSON_SOVERSION 4)
# for CheckFunctionKeywords
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include (CheckCSourceCompiles)
include (CheckFunctionExists)
include (CheckFunctionKeywords)
include (CheckIncludeFiles)
include (CheckTypeSize)
# suppress format-truncation warning
include (CheckCCompilerFlag)
check_c_compiler_flag(-Wno-format-truncation HAS_NO_FORMAT_TRUNCATION)
if (HAS_NO_FORMAT_TRUNCATION)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-format-truncation")
endif()
if (MSVC)
# Turn off Microsofts "security" warnings.
add_definitions( "/W3 /D_CRT_SECURE_NO_WARNINGS /wd4005 /wd4996 /nologo" )
if (JANSSON_STATIC_CRT)
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd")
endif()
endif()
message("C compiler: ${CMAKE_C_COMPILER_ID}")
if (JANSSON_COVERAGE)
include(CodeCoverage)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
endif()
check_include_files (endian.h HAVE_ENDIAN_H)
check_include_files (fcntl.h HAVE_FCNTL_H)
check_include_files (sched.h HAVE_SCHED_H)
check_include_files (unistd.h HAVE_UNISTD_H)
check_include_files (sys/param.h HAVE_SYS_PARAM_H)
check_include_files (sys/stat.h HAVE_SYS_STAT_H)
check_include_files (sys/time.h HAVE_SYS_TIME_H)
check_include_files (sys/types.h HAVE_SYS_TYPES_H)
check_function_exists (close HAVE_CLOSE)
check_function_exists (getpid HAVE_GETPID)
check_function_exists (gettimeofday HAVE_GETTIMEOFDAY)
check_function_exists (open HAVE_OPEN)
check_function_exists (read HAVE_READ)
check_function_exists (sched_yield HAVE_SCHED_YIELD)
# Check for the int-type includes
check_include_files (stdint.h HAVE_STDINT_H)
include (TestBigEndian)
TEST_BIG_ENDIAN(WORDS_BIGENDIAN)
# Check our 64 bit integer sizes
check_type_size (__int64 __INT64)
check_type_size (int64_t INT64_T)
check_type_size ("long long" LONG_LONG_INT)
# Check our 32 bit integer sizes
check_type_size (int32_t INT32_T)
check_type_size (__int32 __INT32)
check_type_size ("long" LONG_INT)
check_type_size ("int" INT)
if (HAVE_INT32_T)
set (JSON_INT32 int32_t)
elseif (HAVE___INT32)
set (JSON_INT32 __int32)
elseif (HAVE_LONG_INT AND (LONG_INT EQUAL 4))
set (JSON_INT32 long)
elseif (HAVE_INT AND (INT EQUAL 4))
set (JSON_INT32 int)
else ()
message (FATAL_ERROR "Could not detect a valid 32-bit integer type")
endif ()
check_type_size ("unsigned long" UNSIGNED_LONG_INT)
check_type_size ("unsigned int" UNSIGNED_INT)
check_type_size ("unsigned short" UNSIGNED_SHORT)
check_type_size (uint32_t UINT32_T)
check_type_size (__uint32 __UINT32)
if (HAVE_UINT32_T)
set (JSON_UINT32 uint32_t)
elseif (HAVE___UINT32)
set (JSON_UINT32 __uint32)
elseif (HAVE_UNSIGNED_LONG_INT AND (UNSIGNED_LONG_INT EQUAL 4))
set (JSON_UINT32 "unsigned long")
elseif (HAVE_UNSIGNED_INT AND (UNSIGNED_INT EQUAL 4))
set (JSON_UINT32 "unsigned int")
else ()
message (FATAL_ERROR "Could not detect a valid unsigned 32-bit integer type")
endif ()
check_type_size (uint16_t UINT16_T)
check_type_size (__uint16 __UINT16)
if (HAVE_UINT16_T)
set (JSON_UINT16 uint16_t)
elseif (HAVE___UINT16)
set (JSON_UINT16 __uint16)
elseif (HAVE_UNSIGNED_INT AND (UNSIGNED_INT EQUAL 2))
set (JSON_UINT16 "unsigned int")
elseif (HAVE_UNSIGNED_SHORT AND (UNSIGNED_SHORT EQUAL 2))
set (JSON_UINT16 "unsigned short")
else ()
message (FATAL_ERROR "Could not detect a valid unsigned 16-bit integer type")
endif ()
check_type_size (uint8_t UINT8_T)
check_type_size (__uint8 __UINT8)
if (HAVE_UINT8_T)
set (JSON_UINT8 uint8_t)
elseif (HAVE___UINT8)
set (JSON_UINT8 __uint8)
else ()
set (JSON_UINT8 "unsigned char")
endif ()
# Check for ssize_t and SSIZE_T existence.
check_type_size(ssize_t SSIZE_T)
check_type_size(SSIZE_T UPPERCASE_SSIZE_T)
if(NOT HAVE_SSIZE_T)
if(HAVE_UPPERCASE_SSIZE_T)
set(JSON_SSIZE SSIZE_T)
else()
set(JSON_SSIZE int)
endif()
endif()
set(CMAKE_EXTRA_INCLUDE_FILES "")
# Check for all the variants of strtoll
check_function_exists (strtoll HAVE_STRTOLL)
check_function_exists (strtoq HAVE_STRTOQ)
check_function_exists (_strtoi64 HAVE__STRTOI64)
# Figure out what variant we should use
if (HAVE_STRTOLL)
set (JSON_STRTOINT strtoll)
elseif (HAVE_STRTOQ)
set (JSON_STRTOINT strtoq)
elseif (HAVE__STRTOI64)
set (JSON_STRTOINT _strtoi64)
else ()
# fallback to strtol (32 bit)
# this will set all the required variables
set (JSON_STRTOINT strtol)
set (JSON_INT_T long)
set (JSON_INTEGER_FORMAT "\"ld\"")
endif ()
# if we haven't defined JSON_INT_T, then we have a 64 bit conversion function.
# detect what to use for the 64 bit type.
# Note: I will prefer long long if I can get it, as that is what the automake system aimed for.
if (NOT DEFINED JSON_INT_T)
set (JSON_INTEGER_IS_LONG_LONG 1)
if (HAVE_LONG_LONG_INT AND (LONG_LONG_INT EQUAL 8))
set (JSON_INT_T "long long")
elseif (HAVE_INT64_T)
set (JSON_INT_T int64_t)
elseif (HAVE___INT64)
set (JSON_INT_T __int64)
else ()
message (FATAL_ERROR "Could not detect 64 bit type, although I detected the strtoll equivalent")
endif ()
# Apparently, Borland BCC and MSVC wants I64d,
# Borland BCC could also accept LD
# and gcc wants ldd,
# I am not sure what cygwin will want, so I will assume I64d
if (WIN32) # matches both msvc and cygwin
set (JSON_INTEGER_FORMAT "\"I64d\"")
else ()
set (JSON_INTEGER_FORMAT "\"lld\"")
endif ()
endif ()
check_include_files (locale.h HAVE_LOCALE_H)
check_function_exists(setlocale HAVE_SETLOCALE)
# Check what the inline keyword is.
# Note that the original JSON_INLINE was always set to just 'inline', so this goes further.
check_function_keywords("inline")
check_function_keywords("__inline")
check_function_keywords("__inline__")
if (HAVE_INLINE)
set(JSON_INLINE inline)
elseif (HAVE___INLINE)
set(JSON_INLINE __inline)
elseif (HAVE___INLINE__)
set(JSON_INLINE __inline__)
else()
# no inline on this platform
set (JSON_INLINE)
endif()
check_c_source_compiles ("int main() { unsigned long val; __sync_bool_compare_and_swap(&val, 0, 1); __sync_add_and_fetch(&val, 1); __sync_sub_and_fetch(&val, 1); return 0; } " HAVE_SYNC_BUILTINS)
check_c_source_compiles ("int main() { char l; unsigned long v; __atomic_test_and_set(&l, __ATOMIC_RELAXED); __atomic_store_n(&v, 1, __ATOMIC_RELEASE); __atomic_load_n(&v, __ATOMIC_ACQUIRE); __atomic_add_fetch(&v, 1, __ATOMIC_ACQUIRE); __atomic_sub_fetch(&v, 1, __ATOMIC_RELEASE); return 0; }" HAVE_ATOMIC_BUILTINS)
if (HAVE_SYNC_BUILTINS)
set(JSON_HAVE_SYNC_BUILTINS 1)
else()
set(JSON_HAVE_SYNC_BUILTINS 0)
endif()
if (HAVE_ATOMIC_BUILTINS)
set(JSON_HAVE_ATOMIC_BUILTINS 1)
else()
set(JSON_HAVE_ATOMIC_BUILTINS 0)
endif()
set (JANSSON_INITIAL_HASHTABLE_ORDER 3 CACHE STRING "Number of buckets new object hashtables contain is 2 raised to this power. The default is 3, so empty hashtables contain 2^3 = 8 buckets.")
# configure the public config file
configure_file (${CMAKE_CURRENT_SOURCE_DIR}/cmake/jansson_config.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/include/jansson_config.h)
# Copy the jansson.h file to the public include folder
file (COPY ${CMAKE_CURRENT_SOURCE_DIR}/src/jansson.h
DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/)
# configure the private config file
configure_file (${CMAKE_CURRENT_SOURCE_DIR}/cmake/jansson_private_config.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/private_include/jansson_private_config.h)
include_directories (${CMAKE_CURRENT_BINARY_DIR}/private_include)
# Configuration flags will be set on project later once we have defined the target
# Add the lib sources.
file(GLOB JANSSON_SRC src/*.c)
if (NOT USE_DTOA)
list(FILTER JANSSON_SRC EXCLUDE REGEX ".*dtoa\\.c$")
endif()
set(JANSSON_HDR_PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/hashtable.h
${CMAKE_CURRENT_SOURCE_DIR}/src/jansson_private.h
${CMAKE_CURRENT_SOURCE_DIR}/src/strbuffer.h
${CMAKE_CURRENT_SOURCE_DIR}/src/utf.h
${CMAKE_CURRENT_BINARY_DIR}/private_include/jansson_private_config.h)
set(JANSSON_HDR_PUBLIC
${CMAKE_CURRENT_BINARY_DIR}/include/jansson_config.h
${CMAKE_CURRENT_SOURCE_DIR}/src/jansson.h)
source_group("Library Sources" FILES ${JANSSON_SRC})
source_group("Library Private Headers" FILES ${JANSSON_HDR_PRIVATE})
source_group("Library Public Headers" FILES ${JANSSON_HDR_PUBLIC})
if(JANSSON_BUILD_SHARED_LIBS)
add_library(jansson SHARED
${JANSSON_SRC}
${JANSSON_HDR_PRIVATE}
${JANSSON_HDR_PUBLIC}
src/jansson.def)
# check if linker support --default-symver
list(APPEND CMAKE_REQUIRED_LIBRARIES "-Wl,--default-symver")
check_c_source_compiles(
"
int main (void)
{
return 0;
}
"
DSYMVER_WORKS
)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "-Wl,--default-symver")
if (SYMVER_WORKS)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--default-symver")
else()
# some linkers may only support --version-script
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/jansson.sym" "JANSSON_${JANSSON_SOVERSION} {
global:
*;
};
")
list(APPEND CMAKE_REQUIRED_LIBRARIES "-Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/jansson.sym")
check_c_source_compiles(
"
int main (void)
{
return 0;
}
"
VSCRIPT_WORKS
)
list(REMOVE_ITEM CMAKE_REQUIRED_LIBRARIES "-Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/jansson.sym")
if (VSCRIPT_WORKS)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/jansson.sym")
endif()
endif()
set_target_properties(jansson PROPERTIES
VERSION ${JANSSON_VERSION}
SOVERSION ${JANSSON_SOVERSION})
else()
add_library(jansson STATIC
${JANSSON_SRC}
${JANSSON_HDR_PRIVATE}
${JANSSON_HDR_PUBLIC})
set_target_properties(jansson PROPERTIES
POSITION_INDEPENDENT_CODE true)
endif()
# Now target jansson is declared, set per-target values
target_compile_definitions(jansson PUBLIC JANSSON_USING_CMAKE)
target_compile_definitions(jansson PRIVATE HAVE_CONFIG_H)
target_include_directories(jansson
PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
INTERFACE $<INSTALL_INTERFACE:include>
)
add_library( jansson::jansson ALIAS jansson )
if (JANSSON_EXAMPLES)
add_executable(simple_parse "${CMAKE_CURRENT_SOURCE_DIR}/examples/simple_parse.c")
target_link_libraries(simple_parse jansson)
endif()
# For building Documentation (uses Sphinx)
option(JANSSON_BUILD_DOCS "Build documentation (uses python-sphinx)." ON)
if (JANSSON_BUILD_DOCS)
find_package(Sphinx)
if (NOT SPHINX_FOUND)
message(WARNING "Sphinx not found. Cannot generate documentation!
Set -DJANSSON_BUILD_DOCS=OFF to get rid of this message.")
else()
if (Sphinx_VERSION_STRING VERSION_LESS 1.0)
message(WARNING "Your Sphinx version is too old!
This project requires Sphinx v1.0 or above to produce
proper documentation (you have v${Sphinx_VERSION_STRING}).
You will get output but it will have errors.")
endif()
# configured documentation tools and intermediate build results
set(BINARY_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/_build")
# Sphinx cache with pickled ReST documents
set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees")
# CMake could be used to build the conf.py file too,
# eg it could automatically write the version of the program or change the theme.
# if(NOT DEFINED SPHINX_THEME)
# set(SPHINX_THEME default)
# endif()
#
# if(NOT DEFINED SPHINX_THEME_DIR)
# set(SPHINX_THEME_DIR)
# endif()
#
# configure_file(
# "${CMAKE_CURRENT_SOURCE_DIR}/conf.py.in"
# "${BINARY_BUILD_DIR}/conf.py"
# @ONLY)
# TODO: Add support for all sphinx builders: http://sphinx-doc.org/builders.html
# Add documentation targets.
set(DOC_TARGETS html)
option(JANSSON_BUILD_MAN "Create a target for building man pages." ON)
if (JANSSON_BUILD_MAN)
if (Sphinx_VERSION_STRING VERSION_LESS 1.0)
message(WARNING "Sphinx version 1.0 > is required to build man pages. You have v${Sphinx_VERSION_STRING}.")
else()
list(APPEND DOC_TARGETS man)
endif()
endif()
option(JANSSON_BUILD_LATEX "Create a target for building latex docs (to create PDF)." OFF)
if (JANSSON_BUILD_LATEX)
find_package(LATEX)
if (NOT LATEX_COMPILER)
message("Couldn't find Latex, can't build latex docs using Sphinx")
else()
message("Latex found! If you have problems building, see Sphinx documentation for required Latex packages.")
list(APPEND DOC_TARGETS latex)
endif()
endif()
# The doc target will build all documentation targets.
add_custom_target(doc)
foreach (DOC_TARGET ${DOC_TARGETS})
add_custom_target(${DOC_TARGET}
${SPHINX_EXECUTABLE}
# -q # Enable for quiet mode
-b ${DOC_TARGET}
-d "${SPHINX_CACHE_DIR}"
# -c "${BINARY_BUILD_DIR}" # enable if using cmake-generated conf.py
"${CMAKE_CURRENT_SOURCE_DIR}/doc"
"${CMAKE_CURRENT_BINARY_DIR}/doc/${DOC_TARGET}"
COMMENT "Building ${DOC_TARGET} documentation with Sphinx")
add_dependencies(doc ${DOC_TARGET})
endforeach()
message("Building documentation enabled for: ${DOC_TARGETS}")
endif()
endif ()
option(JANSSON_WITHOUT_TESTS "Don't build tests ('make test' to execute tests)" OFF)
if (NOT JANSSON_WITHOUT_TESTS)
option(JANSSON_TEST_WITH_VALGRIND "Enable valgrind tests." OFF)
ENABLE_TESTING()
if (JANSSON_TEST_WITH_VALGRIND)
# TODO: Add FindValgrind.cmake instead of having a hardcoded path.
add_definitions(-DVALGRIND)
# enable valgrind
set(CMAKE_MEMORYCHECK_COMMAND valgrind)
set(CMAKE_MEMORYCHECK_COMMAND_OPTIONS
"--error-exitcode=1 --leak-check=full --show-reachable=yes --track-origins=yes -q")
set(MEMCHECK_COMMAND
"${CMAKE_MEMORYCHECK_COMMAND} ${CMAKE_MEMORYCHECK_COMMAND_OPTIONS}")
separate_arguments(MEMCHECK_COMMAND)
endif ()
#
# Test suites.
#
if (CMAKE_COMPILER_IS_GNUCC)
add_definitions(-Wall -Wextra -Wdeclaration-after-statement)
endif ()
set(api_tests
test_array
test_chaos
test_copy
test_dump
test_dump_callback
test_equal
test_fixed_size
test_load
test_load_callback
test_loadb
test_number
test_object
test_pack
test_simple
test_sprintf
test_unpack)
# Doing arithmetic on void pointers is not allowed by Microsofts compiler
# such as secure_malloc and secure_free is doing, so exclude it for now.
if (NOT MSVC)
list(APPEND api_tests test_memory_funcs)
endif()
# Helper macro for building and linking a test program.
macro(build_testprog name dir)
add_executable(${name} ${dir}/${name}.c)
add_dependencies(${name} jansson)
target_link_libraries(${name} jansson)
endmacro(build_testprog)
# Create executables and tests/valgrind tests for API tests.
foreach (test ${api_tests})
build_testprog(${test} ${CMAKE_CURRENT_SOURCE_DIR}/test/suites/api)
if (JANSSON_TEST_WITH_VALGRIND)
add_test(memcheck__${test}
${MEMCHECK_COMMAND} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${test}
WORKING_DIRECTORY ${JANSSON_TEMP_DIR})
else()
add_test(${test}
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${test}
WORKING_DIRECTORY ${JANSSON_TEMP_DIR})
endif ()
endforeach ()
# Test harness for the suites tests.
build_testprog(json_process ${CMAKE_CURRENT_SOURCE_DIR}/test/bin)
set(SUITE_TEST_CMD ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/json_process)
set(SUITES encoding-flags valid invalid invalid-unicode)
foreach (SUITE ${SUITES})
file(GLOB TESTDIRS test/suites/${SUITE}/*)
foreach (TESTDIR ${TESTDIRS})
if (IS_DIRECTORY ${TESTDIR})
get_filename_component(TNAME ${TESTDIR} NAME)
if ((USE_DTOA AND EXISTS ${TESTDIR}/skip_if_dtoa) OR
(NOT USE_DTOA AND EXISTS ${TESTDIR}/skip_unless_dtoa))
continue()
endif()
if (JANSSON_TEST_WITH_VALGRIND)
add_test(memcheck__${SUITE}__${TNAME}
${MEMCHECK_COMMAND} ${SUITE_TEST_CMD} ${TESTDIR})
else()
add_test(${SUITE}__${TNAME}
${SUITE_TEST_CMD} ${TESTDIR})
endif()
if ((${SUITE} STREQUAL "valid" OR ${SUITE} STREQUAL "invalid") AND NOT EXISTS ${TESTDIR}/nostrip)
if (JANSSON_TEST_WITH_VALGRIND)
add_test(memcheck__${SUITE}__${TNAME}__strip
${MEMCHECK_COMMAND} ${SUITE_TEST_CMD} --strip ${TESTDIR})
else()
add_test(${SUITE}__${TNAME}__strip
${SUITE_TEST_CMD} --strip ${TESTDIR})
endif()
endif ()
endif ()
endforeach ()
endforeach ()
if (JANSSON_COVERAGE)
SETUP_TARGET_FOR_COVERAGE(coverage coverage ctest)
endif ()
# Enable using "make check" just like the autotools project.
# By default cmake creates a target "make test"
add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND}
DEPENDS json_process ${api_tests})
endif ()
#
# Installation preparation.
#
# Allow the user to override installation directories.
set(JANSSON_INSTALL_LIB_DIR lib CACHE PATH "Installation directory for libraries")
set(JANSSON_INSTALL_BIN_DIR bin CACHE PATH "Installation directory for executables")
set(JANSSON_INSTALL_INCLUDE_DIR include CACHE PATH "Installation directory for header files")
if(WIN32 AND NOT CYGWIN)
set(DEF_INSTALL_CMAKE_DIR cmake)
else()
set(DEF_INSTALL_CMAKE_DIR lib/cmake/jansson)
endif()
set(JANSSON_INSTALL_CMAKE_DIR ${DEF_INSTALL_CMAKE_DIR} CACHE PATH "Installation directory for CMake files")
# Create pkg-conf file.
# (We use the same files as ./configure does, so we
# have to defined the same variables used there).
set(prefix ${CMAKE_INSTALL_PREFIX})
set(exec_prefix "\${prefix}")
set(libdir "\${exec_prefix}/${JANSSON_INSTALL_LIB_DIR}")
set(includedir "\${prefix}/${JANSSON_INSTALL_INCLUDE_DIR}")
set(VERSION ${JANSSON_DISPLAY_VERSION})
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/jansson.pc.in
${CMAKE_CURRENT_BINARY_DIR}/jansson.pc @ONLY)
# Make sure the paths are relative.
foreach(p LIB BIN INCLUDE CMAKE)
set(var JANSSON_INSTALL_${p}_DIR)
endforeach()
# Generate the config file for the build-tree.
set(JANSSON__INCLUDE_DIRS "${CMAKE_CURRENT_BINARY_DIR}/include")
set(JANSSON_INCLUDE_DIRS ${JANSSON__INCLUDE_DIRS} CACHE PATH "Jansson include directories")
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/janssonConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/janssonConfig.cmake
@ONLY)
# Generate the config file for the installation tree.
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/cmake/janssonConfigVersion.cmake"
VERSION ${JANSSON_VERSION}
COMPATIBILITY ExactVersion
)
configure_package_config_file(
"cmake/janssonConfig.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake/janssonConfig.cmake"
INSTALL_DESTINATION "${JANSSON_INSTALL_CMAKE_DIR}"
)
#
# Install targets.
#
option(JANSSON_INSTALL "Generate installation target" ON)
if (JANSSON_INSTALL)
install(TARGETS jansson
EXPORT janssonTargets
LIBRARY DESTINATION "lib"
ARCHIVE DESTINATION "lib"
RUNTIME DESTINATION "bin"
INCLUDES DESTINATION "include")
install(FILES ${JANSSON_HDR_PUBLIC}
DESTINATION "include")
# Install the pkg-config.
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/jansson.pc
DESTINATION lib/pkgconfig)
# Install the configs.
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/cmake/janssonConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/cmake/janssonConfigVersion.cmake
DESTINATION "${JANSSON_INSTALL_CMAKE_DIR}")
# Install exports for the install-tree.
install(EXPORT janssonTargets
NAMESPACE jansson::
DESTINATION "${JANSSON_INSTALL_CMAKE_DIR}")
endif()
# For use when simply using add_library from a parent project to build jansson.
set(JANSSON_LIBRARIES jansson CACHE STRING "jansson libraries")

3
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,3 @@
Hi, and thanks for contributing!
Please remember to add tests and documentation for new functionality. Backwards incompatible changes or features that are not directly related to JSON are likely to be rejected.

49
CleanSpec.mk Normal file
View file

@ -0,0 +1,49 @@
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# If you don't need to do a full clean build but would like to touch
# a file or delete some intermediate files, add a clean step to the end
# of the list. These steps will only be run once, if they haven't been
# run before.
#
# E.g.:
# $(call add-clean-step, touch -c external/sqlite/sqlite3.h)
# $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates)
#
# Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with
# files that are missing or have been moved.
#
# Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory.
# Use $(OUT_DIR) to refer to the "out" directory.
#
# If you need to re-do something that's already mentioned, just copy
# the command and add it to the bottom of the list. E.g., if a change
# that you made last week required touching a file and a change you
# made today requires touching the same file, just copy the old
# touch step and add it to the end of the list.
#
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
# ************************************************
# For example:
#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates)
#$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates)
#$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f)
#$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
# ************************************************

26
LICENSE
View file

@ -1,4 +1,11 @@
Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
# License
This project is licensed under the MIT license, except where otherwise noted.
The full text of the MIT license is included below.
## MIT License
Copyright (c) 2009-2024 Petri Lehtinen <petri@digip.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -17,3 +24,20 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Exceptions
### `src/dtoa.c`
Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
Permission to use, copy, modify, and distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included in all copies of any software which is or includes a copy
or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

View file

@ -1,7 +1,12 @@
EXTRA_DIST = CHANGES LICENSE README.rst
EXTRA_DIST = CHANGES LICENSE README.rst CMakeLists.txt cmake android examples scripts
SUBDIRS = doc src test
check-local: html
# "make distcheck" builds the dvi target, so use it to check that the
# documentation is built correctly.
dvi:
$(MAKE) SPHINXOPTS_EXTRA=-W html
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = jansson.pc
TESTS = scripts/clang-format-check

View file

@ -1,12 +1,17 @@
Jansson README
==============
.. |tests| image:: https://github.com/akheron/jansson/workflows/tests/badge.svg
.. |appveyor| image:: https://ci.appveyor.com/api/projects/status/lmhkkc4q8cwc65ko
|tests| |appveyor|
Jansson_ is a C library for encoding, decoding and manipulating JSON
data. Its main features and design principles are:
- Simple and intuitive API and data model
- Comprehensive documentation
- `Comprehensive documentation`_
- No dependencies on other libraries
@ -17,43 +22,49 @@ data. Its main features and design principles are:
Jansson is licensed under the `MIT license`_; see LICENSE in the
source distribution for details.
Compilation and Installation
----------------------------
If you obtained a source tarball, just use the standard autotools
commands::
If you obtained a ``jansson-X.Y.tar.*`` tarball from GitHub Releases, just use
the standard autotools commands::
$ ./configure && make && make install
If the source has been checked out from a Git repository, the
./configure script has to be generated fist. The easiest way is to use
autoreconf::
$ autoreconf -i
$ ./configure
$ make
$ make install
To run the test suite, invoke::
$ make check
If the source has been checked out from a Git repository, the ``configure``
script has to be generated first. The easiest way is to use autoreconf::
$ autoreconf -i
Documentation
-------------
Documentation is in the ``doc/`` subdirectory. It's written in
reStructuredText_ with Sphinx_ annotations, so reading it in plain may
be inconvenient. For this reason, prebuilt HTML documentation is
available at http://www.digip.org/jansson/doc/.
Documentation is available at http://jansson.readthedocs.io/en/latest/.
To generate HTML documentation yourself, invoke::
The documentation source is in the ``doc/`` subdirectory. To generate
HTML documentation, invoke::
make html
$ make html
and point your browser to ``doc/_build/html/index.html``. Sphinx_ is
required to generate the documentation.
Then, point your browser to ``doc/_build/html/index.html``. Sphinx_
1.0 or newer is required to generate the documentation.
Community
---------
* `Documentation <http://jansson.readthedocs.io/en/latest/>`_
* `Issue tracker <https://github.com/akheron/jansson/issues>`_
* `Mailing list <http://groups.google.com/group/jansson-users>`_
* `Wiki <https://github.com/akheron/jansson/wiki>`_ contains some development documentation
.. _Jansson: http://www.digip.org/jansson/
.. _`Comprehensive documentation`: http://jansson.readthedocs.io/en/latest/
.. _`MIT license`: http://www.opensource.org/licenses/mit-license.php
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
.. _Sphinx: http://sphinx.pocoo.org/

9
SECURITY.md Normal file
View file

@ -0,0 +1,9 @@
# Security Policy
## Supported Versions
Latest released version.
## Reporting a Vulnerability
Send an email to petri@digip.org.

39
android/jansson_config.h Normal file
View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2010-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*
*
* This file specifies a part of the site-specific configuration for
* Jansson, namely those things that affect the public API in
* jansson.h.
*
* The configure script copies this file to jansson_config.h and
* replaces @var@ substitutions by values that fit your system. If you
* cannot run the configure script, you can do the value substitution
* by hand.
*/
#ifndef JANSSON_CONFIG_H
#define JANSSON_CONFIG_H
/* If your compiler supports the inline keyword in C, JSON_INLINE is
defined to `inline', otherwise empty. In C++, the inline is always
supported. */
#ifdef __cplusplus
#define JSON_INLINE inline
#else
#define JSON_INLINE inline
#endif
/* If your compiler supports the `long long` type and the strtoll()
library function, JSON_INTEGER_IS_LONG_LONG is defined to 1,
otherwise to 0. */
#define JSON_INTEGER_IS_LONG_LONG 1
/* Maximum recursion depth for parsing JSON input.
This limits the depth of e.g. array-within-array constructions. */
#define JSON_PARSER_MAX_DEPTH 2048
#endif

18
appveyor.yml Normal file
View file

@ -0,0 +1,18 @@
environment:
matrix:
- VS: Visual Studio 9 2008
- VS: Visual Studio 10 2010
- VS: Visual Studio 11 2012
- VS: Visual Studio 12 2013
- VS: Visual Studio 14 2015
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
VS: Visual Studio 15 2017
- APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
VS: Visual Studio 16 2019
build_script:
- md build
- cd build
- cmake -G "%VS%" ..
- cmake --build . --config Release
- ctest --output-on-failure

View file

@ -0,0 +1,15 @@
include(CheckCSourceCompiles)
macro(check_function_keywords _wordlist)
set(${_result} "")
foreach(flag ${_wordlist})
string(REGEX REPLACE "[-+/ ()]" "_" flagname "${flag}")
string(TOUPPER "${flagname}" flagname)
set(have_flag "HAVE_${flagname}")
check_c_source_compiles("${flag} void func(); void func() { } int main() { func(); return 0; }" ${have_flag})
if(${have_flag} AND NOT ${_result})
set(${_result} "${flag}")
# break()
endif(${have_flag} AND NOT ${_result})
endforeach(flag)
endmacro(check_function_keywords)

163
cmake/CodeCoverage.cmake Normal file
View file

@ -0,0 +1,163 @@
#
# Boost Software License - Version 1.0 - August 17th, 2003
#
# Permission is hereby granted, free of charge, to any person or organization
# obtaining a copy of the software and accompanying documentation covered by
# this license (the "Software") to use, reproduce, display, distribute,
# execute, and transmit the Software, and to prepare derivative works of the
# Software, and to permit third-parties to whom the Software is furnished to
# do so, all subject to the following:
#
# The copyright notices in the Software and this entire statement, including
# the above license grant, this restriction and the following disclaimer,
# must be included in all copies of the Software, in whole or in part, and
# all derivative works of the Software, unless such copies or derivative
# works are solely in the form of machine-executable object code generated by
# a source language processor.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
# SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
# FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# USAGE:
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt:
# INCLUDE(CodeCoverage)
#
# 3. Set compiler flags to turn off optimization and enable coverage:
# SET(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
# SET(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
#
# 3. Use the function SETUP_TARGET_FOR_COVERAGE to create a custom make target
# which runs your test executable and produces a lcov code coverage report:
# Example:
# SETUP_TARGET_FOR_COVERAGE(
# my_coverage_target # Name for custom target.
# test_driver # Name of the test driver executable that runs the tests.
# # NOTE! This should always have a ZERO as exit code
# # otherwise the coverage generation will not complete.
# coverage # Name of output directory.
# )
#
# 4. Build a Debug build:
# cmake -DCMAKE_BUILD_TYPE=Debug ..
# make
# make my_coverage_target
#
#
# Check prereqs
FIND_PROGRAM( GCOV_PATH gcov )
FIND_PROGRAM( LCOV_PATH lcov )
FIND_PROGRAM( GENHTML_PATH genhtml )
FIND_PROGRAM( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/tests)
IF(NOT GCOV_PATH)
MESSAGE(FATAL_ERROR "gcov not found! Aborting...")
ENDIF() # NOT GCOV_PATH
IF(NOT (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUCC))
# Clang version 3.0.0 and greater now supports gcov as well.
MESSAGE(WARNING "Compiler is not GNU gcc! Clang Version 3.0.0 and greater supports gcov as well, but older versions don't.")
IF(NOT ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang"))
MESSAGE(FATAL_ERROR "Compiler is not GNU gcc or Clang! Aborting...")
ENDIF()
ENDIF() # NOT CMAKE_COMPILER_IS_GNUCXX
IF ( NOT CMAKE_BUILD_TYPE STREQUAL "Debug" )
MESSAGE( WARNING "Code coverage results with an optimized (non-Debug) build may be misleading" )
ENDIF() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"
# Param _targetname The name of new the custom make target
# Param _outputname lcov output is generated as _outputname.info
# HTML report is generated in _outputname/index.html
# Param _testrunner The name of the target which runs the tests.
# MUST return ZERO always, even on errors.
# If not, no coverage report will be created!
# Optional fourth parameter is passed as arguments to _testrunner
# Pass them in list form, e.g.: "-j;2" for -j 2
FUNCTION(SETUP_TARGET_FOR_COVERAGE _targetname _outputname _testrunner)
IF(NOT LCOV_PATH)
MESSAGE(FATAL_ERROR "lcov not found! Aborting...")
ENDIF() # NOT LCOV_PATH
IF(NOT GENHTML_PATH)
MESSAGE(FATAL_ERROR "genhtml not found! Aborting...")
ENDIF() # NOT GENHTML_PATH
# Setup target
ADD_CUSTOM_TARGET(${_targetname}
# Cleanup lcov
${LCOV_PATH} --directory . --zerocounters
# Run tests
COMMAND ${_testrunner} ${ARGV3}
# Capturing lcov counters and generating report
COMMAND ${LCOV_PATH} --directory . --capture --output-file ${_outputname}.info --rc lcov_branch_coverage=1
COMMAND ${LCOV_PATH} --remove ${_outputname}.info '*/build/include/*' '*/test/*' '/usr/include/*' --output-file ${_outputname}.info --rc lcov_branch_coverage=1
# COMMAND ${GENHTML_PATH} --branch-coverage -o ${_outputname} ${_outputname}.info.cleaned
# COMMAND ${CMAKE_COMMAND} -E remove ${_outputname}.info ${_outputname}.info.cleaned
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
)
# Show info where to find the report
ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
COMMAND ;
COMMENT "Open ./${_outputname}/index.html in your browser to view the coverage report."
)
ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE
# Param _targetname The name of new the custom make target
# Param _testrunner The name of the target which runs the tests
# Param _outputname cobertura output is generated as _outputname.xml
# Optional fourth parameter is passed as arguments to _testrunner
# Pass them in list form, e.g.: "-j;2" for -j 2
FUNCTION(SETUP_TARGET_FOR_COVERAGE_COBERTURA _targetname _testrunner _outputname)
IF(NOT PYTHON_EXECUTABLE)
MESSAGE(FATAL_ERROR "Python not found! Aborting...")
ENDIF() # NOT PYTHON_EXECUTABLE
IF(NOT GCOVR_PATH)
MESSAGE(FATAL_ERROR "gcovr not found! Aborting...")
ENDIF() # NOT GCOVR_PATH
ADD_CUSTOM_TARGET(${_targetname}
# Run tests
${_testrunner} ${ARGV3}
# Running gcovr
COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} -e '${CMAKE_SOURCE_DIR}/tests/' -o ${_outputname}.xml
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMENT "Running gcovr to produce Cobertura code coverage report."
)
# Show info where to find the report
ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
COMMAND ;
COMMENT "Cobertura code coverage report saved in ${_outputname}.xml."
)
ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE_COBERTURA

315
cmake/FindSphinx.cmake Normal file
View file

@ -0,0 +1,315 @@
#
# PART B. DOWNLOADING AGREEMENT - LICENSE FROM SBIA WITH RIGHT TO SUBLICENSE ("SOFTWARE LICENSE").
# ------------------------------------------------------------------------------------------------
#
# 1. As used in this Software License, "you" means the individual downloading and/or
# using, reproducing, modifying, displaying and/or distributing the Software and
# the institution or entity which employs or is otherwise affiliated with such
# individual in connection therewith. The Section of Biomedical Image Analysis,
# Department of Radiology at the Universiy of Pennsylvania ("SBIA") hereby grants
# you, with right to sublicense, with respect to SBIA's rights in the software,
# and data, if any, which is the subject of this Software License (collectively,
# the "Software"), a royalty-free, non-exclusive license to use, reproduce, make
# derivative works of, display and distribute the Software, provided that:
# (a) you accept and adhere to all of the terms and conditions of this Software
# License; (b) in connection with any copy of or sublicense of all or any portion
# of the Software, all of the terms and conditions in this Software License shall
# appear in and shall apply to such copy and such sublicense, including without
# limitation all source and executable forms and on any user documentation,
# prefaced with the following words: "All or portions of this licensed product
# (such portions are the "Software") have been obtained under license from the
# Section of Biomedical Image Analysis, Department of Radiology at the University
# of Pennsylvania and are subject to the following terms and conditions:"
# (c) you preserve and maintain all applicable attributions, copyright notices
# and licenses included in or applicable to the Software; (d) modified versions
# of the Software must be clearly identified and marked as such, and must not
# be misrepresented as being the original Software; and (e) you consider making,
# but are under no obligation to make, the source code of any of your modifications
# to the Software freely available to others on an open source basis.
#
# 2. The license granted in this Software License includes without limitation the
# right to (i) incorporate the Software into proprietary programs (subject to
# any restrictions applicable to such programs), (ii) add your own copyright
# statement to your modifications of the Software, and (iii) provide additional
# or different license terms and conditions in your sublicenses of modifications
# of the Software; provided that in each case your use, reproduction or
# distribution of such modifications otherwise complies with the conditions
# stated in this Software License.
#
# 3. This Software License does not grant any rights with respect to third party
# software, except those rights that SBIA has been authorized by a third
# party to grant to you, and accordingly you are solely responsible for
# (i) obtaining any permissions from third parties that you need to use,
# reproduce, make derivative works of, display and distribute the Software,
# and (ii) informing your sublicensees, including without limitation your
# end-users, of their obligations to secure any such required permissions.
#
# 4. The Software has been designed for research purposes only and has not been
# reviewed or approved by the Food and Drug Administration or by any other
# agency. YOU ACKNOWLEDGE AND AGREE THAT CLINICAL APPLICATIONS ARE NEITHER
# RECOMMENDED NOR ADVISED. Any commercialization of the Software is at the
# sole risk of the party or parties engaged in such commercialization.
# You further agree to use, reproduce, make derivative works of, display
# and distribute the Software in compliance with all applicable governmental
# laws, regulations and orders, including without limitation those relating
# to export and import control.
#
# 5. The Software is provided "AS IS" and neither SBIA nor any contributor to
# the software (each a "Contributor") shall have any obligation to provide
# maintenance, support, updates, enhancements or modifications thereto.
# SBIA AND ALL CONTRIBUTORS SPECIFICALLY DISCLAIM ALL EXPRESS AND IMPLIED
# WARRANTIES OF ANY KIND INCLUDING, BUT NOT LIMITED TO, ANY WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
# IN NO EVENT SHALL SBIA OR ANY CONTRIBUTOR BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ARISING IN ANY WAY RELATED
# TO THE SOFTWARE, EVEN IF SBIA OR ANY CONTRIBUTOR HAS BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGES. TO THE MAXIMUM EXTENT NOT PROHIBITED BY LAW OR
# REGULATION, YOU FURTHER ASSUME ALL LIABILITY FOR YOUR USE, REPRODUCTION,
# MAKING OF DERIVATIVE WORKS, DISPLAY, LICENSE OR DISTRIBUTION OF THE SOFTWARE
# AND AGREE TO INDEMNIFY AND HOLD HARMLESS SBIA AND ALL CONTRIBUTORS FROM
# AND AGAINST ANY AND ALL CLAIMS, SUITS, ACTIONS, DEMANDS AND JUDGMENTS ARISING
# THEREFROM.
#
# 6. None of the names, logos or trademarks of SBIA or any of SBIA's affiliates
# or any of the Contributors, or any funding agency, may be used to endorse
# or promote products produced in whole or in part by operation of the Software
# or derived from or based on the Software without specific prior written
# permission from the applicable party.
#
# 7. Any use, reproduction or distribution of the Software which is not in accordance
# with this Software License shall automatically revoke all rights granted to you
# under this Software License and render Paragraphs 1 and 2 of this Software
# License null and void.
#
# 8. This Software License does not grant any rights in or to any intellectual
# property owned by SBIA or any Contributor except those rights expressly
# granted hereunder.
#
#
# PART C. MISCELLANEOUS
# ---------------------
#
# This Agreement shall be governed by and construed in accordance with the laws
# of The Commonwealth of Pennsylvania without regard to principles of conflicts
# of law. This Agreement shall supercede and replace any license terms that you
# may have agreed to previously with respect to Software from SBIA.
#
##############################################################################
# @file FindSphinx.cmake
# @brief Find Sphinx documentation build tools.
#
# @par Input variables:
# <table border="0">
# <tr>
# @tp @b Sphinx_DIR @endtp
# <td>Installation directory of Sphinx tools. Can also be set as environment variable.</td>
# </tr>
# <tr>
# @tp @b SPHINX_DIR @endtp
# <td>Alternative environment variable for @c Sphinx_DIR.</td>
# </tr>
# <tr>
# @tp @b Sphinx_FIND_COMPONENTS @endtp
# <td>Sphinx build tools to look for, i.e., 'apidoc' and/or 'build'.</td>
# </tr>
# </table>
#
# @par Output variables:
# <table border="0">
# <tr>
# @tp @b Sphinx_FOUND @endtp
# <td>Whether all or only the requested Sphinx build tools were found.</td>
# </tr>
# <tr>
# @tp @b SPHINX_FOUND @endtp
# <td>Alias for @c Sphinx_FOUND.<td>
# </tr>
# <tr>
# @tp @b SPHINX_EXECUTABLE @endtp
# <td>Non-cached alias for @c Sphinx-build_EXECUTABLE.</td>
# </tr>
# <tr>
# @tp @b Sphinx_PYTHON_EXECUTABLE @endtp
# <td>Python executable used to run sphinx-build. This is either the
# by default found Python interpreter or a specific version as
# specified by the shebang (#!) of the sphinx-build script.</td>
# </tr>
# <tr>
# @tp @b Sphinx_PYTHON_OPTIONS @endtp
# <td>A list of Python options extracted from the shebang (#!) of the
# sphinx-build script. The -E option is added by this module
# if the Python executable is not the system default to avoid
# problems with a differing setting of the @c PYTHONHOME.</td>
# </tr>
# <tr>
# @tp @b Sphinx-build_EXECUTABLE @endtp
# <td>Absolute path of the found sphinx-build tool.</td>
# </tr>
# <tr>
# @tp @b Sphinx-apidoc_EXECUTABLE @endtp
# <td>Absolute path of the found sphinx-apidoc tool.</td>
# </tr>
# <tr>
# @tp @b Sphinx_VERSION_STRING @endtp
# <td>Sphinx version found e.g. 1.1.2.</td>
# </tr>
# <tr>
# @tp @b Sphinx_VERSION_MAJOR @endtp
# <td>Sphinx major version found e.g. 1.</td>
# </tr>
# <tr>
# @tp @b Sphinx_VERSION_MINOR @endtp
# <td>Sphinx minor version found e.g. 1.</td>
# </tr>
# <tr>
# @tp @b Sphinx_VERSION_PATCH @endtp
# <td>Sphinx patch version found e.g. 2.</td>
# </tr>
# </table>
#
# @ingroup CMakeFindModules
##############################################################################
set (_Sphinx_REQUIRED_VARS)
# ----------------------------------------------------------------------------
# initialize search
if (NOT Sphinx_DIR)
if (NOT $ENV{Sphinx_DIR} STREQUAL "")
set (Sphinx_DIR "$ENV{Sphinx_DIR}" CACHE PATH "Installation prefix of Sphinx (docutils)." FORCE)
else ()
set (Sphinx_DIR "$ENV{SPHINX_DIR}" CACHE PATH "Installation prefix of Sphinx (docutils)." FORCE)
endif ()
endif ()
# ----------------------------------------------------------------------------
# default components to look for
if (NOT Sphinx_FIND_COMPONENTS)
set (Sphinx_FIND_COMPONENTS "build")
elseif (NOT Sphinx_FIND_COMPONENTS MATCHES "^(build|apidoc)$")
message (FATAL_ERROR "Invalid Sphinx component in: ${Sphinx_FIND_COMPONENTS}")
endif ()
# ----------------------------------------------------------------------------
# find components, i.e., build tools
foreach (_Sphinx_TOOL IN LISTS Sphinx_FIND_COMPONENTS)
if (Sphinx_DIR)
find_program (
Sphinx-${_Sphinx_TOOL}_EXECUTABLE
NAMES sphinx-${_Sphinx_TOOL} sphinx-${_Sphinx_TOOL}.py
HINTS "${Sphinx_DIR}"
PATH_SUFFIXES bin
DOC "The sphinx-${_Sphinx_TOOL} Python script."
NO_DEFAULT_PATH
)
else ()
find_program (
Sphinx-${_Sphinx_TOOL}_EXECUTABLE
NAMES sphinx-${_Sphinx_TOOL} sphinx-${_Sphinx_TOOL}.py
DOC "The sphinx-${_Sphinx_TOOL} Python script."
)
endif ()
mark_as_advanced (Sphinx-${_Sphinx_TOOL}_EXECUTABLE)
list (APPEND _Sphinx_REQUIRED_VARS Sphinx-${_Sphinx_TOOL}_EXECUTABLE)
endforeach ()
# ----------------------------------------------------------------------------
# determine Python executable used by Sphinx
if (Sphinx-build_EXECUTABLE)
# extract python executable from shebang of sphinx-build
find_package (PythonInterp QUIET)
set (Sphinx_PYTHON_EXECUTABLE "${PYTHON_EXECUTABLE}")
set (Sphinx_PYTHON_OPTIONS)
file (STRINGS "${Sphinx-build_EXECUTABLE}" FIRST_LINE LIMIT_COUNT 1)
if (FIRST_LINE MATCHES "^#!(.*/python.*)") # does not match "#!/usr/bin/env python" !
string (REGEX REPLACE "^ +| +$" "" Sphinx_PYTHON_EXECUTABLE "${CMAKE_MATCH_1}")
if (Sphinx_PYTHON_EXECUTABLE MATCHES "([^ ]+) (.*)")
set (Sphinx_PYTHON_EXECUTABLE "${CMAKE_MATCH_1}")
string (REGEX REPLACE " +" ";" Sphinx_PYTHON_OPTIONS "${CMAKE_MATCH_2}")
endif ()
endif ()
# this is done to avoid problems with multiple Python versions being installed
# remember: CMake command if(STR EQUAL STR) is bad and may cause many troubles !
string (REGEX REPLACE "([.+*?^$])" "\\\\\\1" _Sphinx_PYTHON_EXECUTABLE_RE "${PYTHON_EXECUTABLE}")
list (FIND Sphinx_PYTHON_OPTIONS -E IDX)
if (IDX EQUAL -1 AND NOT Sphinx_PYTHON_EXECUTABLE MATCHES "^${_Sphinx_PYTHON_EXECUTABLE_RE}$")
list (INSERT Sphinx_PYTHON_OPTIONS 0 -E)
endif ()
unset (_Sphinx_PYTHON_EXECUTABLE_RE)
endif ()
# ----------------------------------------------------------------------------
# determine Sphinx version
# some quick experiments by @ploxiln
# - sphinx 1.7 and later have the version output format like "sphinx-build 1.7.2"
# - sphinx 1.2 through 1.6 have the version output format like "Sphinx (sphinx-build) 1.2.2"
# - sphinx 1.1 and before do not have a "--version" flag, but it causes the help output like "-h" does which includes version like "Sphinx v1.0.2"
if (Sphinx-build_EXECUTABLE)
# intentionally use invalid -h option here as the help that is shown then
# will include the Sphinx version information
if (Sphinx_PYTHON_EXECUTABLE)
execute_process (
COMMAND "${Sphinx_PYTHON_EXECUTABLE}" ${Sphinx_PYTHON_OPTIONS} "${Sphinx-build_EXECUTABLE}" --version
OUTPUT_VARIABLE _Sphinx_VERSION
ERROR_VARIABLE _Sphinx_VERSION
)
elseif (UNIX)
execute_process (
COMMAND "${Sphinx-build_EXECUTABLE}" --version
OUTPUT_VARIABLE _Sphinx_VERSION
ERROR_VARIABLE _Sphinx_VERSION
)
endif ()
# The sphinx version can also contain a "b" instead of the last dot.
# For example "Sphinx v1.2b1" or "Sphinx 1.7.0b2" so we cannot just split on "."
if (_Sphinx_VERSION MATCHES "sphinx-build ([0-9]+\\.[0-9]+(\\.|a?|b?)([0-9]*)(b?)([0-9]*))")
set (Sphinx_VERSION_STRING "${CMAKE_MATCH_1}")
set (_SPHINX_VERSION_FOUND)
elseif (_Sphinx_VERSION MATCHES "Sphinx v([0-9]+\\.[0-9]+(\\.|b?)([0-9]*)(b?)([0-9]*))")
set (Sphinx_VERSION_STRING "${CMAKE_MATCH_1}")
set (_SPHINX_VERSION_FOUND)
elseif (_Sphinx_VERSION MATCHES "Sphinx \\(sphinx-build\\) ([0-9]+\\.[0-9]+(\\.|a?|b?)([0-9]*)(b?)([0-9]*))")
set (Sphinx_VERSION_STRING "${CMAKE_MATCH_1}")
set (_SPHINX_VERSION_FOUND)
endif ()
endif ()
if(_SPHINX_VERSION_FOUND)
string(REGEX REPLACE "([0-9]+)\\.[0-9]+(\\.|b)[0-9]+" "\\1" Sphinx_VERSION_MAJOR ${Sphinx_VERSION_STRING})
string(REGEX REPLACE "[0-9]+\\.([0-9]+)(\\.|b)[0-9]+" "\\1" Sphinx_VERSION_MINOR ${Sphinx_VERSION_STRING})
string(REGEX REPLACE "[0-9]+\\.[0-9]+(\\.|b)([0-9]+)" "\\1" Sphinx_VERSION_PATCH ${Sphinx_VERSION_STRING})
# v1.2.0 -> v1.2
if (Sphinx_VERSION_PATCH EQUAL 0)
string (REGEX REPLACE "\\.0$" "" Sphinx_VERSION_STRING "${Sphinx_VERSION_STRING}")
endif ()
endif ()
# ----------------------------------------------------------------------------
# compatibility with FindPythonInterp.cmake and FindPerl.cmake
set (SPHINX_EXECUTABLE "${Sphinx-build_EXECUTABLE}")
# ----------------------------------------------------------------------------
# handle the QUIETLY and REQUIRED arguments and set SPHINX_FOUND to TRUE if
# all listed variables are TRUE
include (FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS (
Sphinx
REQUIRED_VARS
${_Sphinx_REQUIRED_VARS}
# VERSION_VAR # This isn't available until CMake 2.8.8 so don't use it.
Sphinx_VERSION_STRING
)
# ----------------------------------------------------------------------------
# set Sphinx_DIR
if (NOT Sphinx_DIR AND Sphinx-build_EXECUTABLE)
get_filename_component (Sphinx_DIR "${Sphinx-build_EXECUTABLE}" PATH)
string (REGEX REPLACE "/bin/?" "" Sphinx_DIR "${Sphinx_DIR}")
set (Sphinx_DIR "${Sphinx_DIR}" CACHE PATH "Installation directory of Sphinx tools." FORCE)
endif ()
unset (_Sphinx_VERSION)
unset (_Sphinx_REQUIRED_VARS)

View file

@ -0,0 +1,4 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/janssonTargets.cmake")
check_required_components("@PROJECT_NAME@")

View file

@ -0,0 +1,72 @@
/*
* Copyright (c) 2010-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*
*
* This file specifies a part of the site-specific configuration for
* Jansson, namely those things that affect the public API in
* jansson.h.
*
* The CMake system will generate the jansson_config.h file and
* copy it to the build and install directories.
*/
#ifndef JANSSON_CONFIG_H
#define JANSSON_CONFIG_H
/* Define this so that we can disable scattered automake configuration in source files */
#ifndef JANSSON_USING_CMAKE
#define JANSSON_USING_CMAKE
#endif
/* If your compiler supports the `long long` type and the strtoll()
library function, JSON_INTEGER_IS_LONG_LONG is defined to 1,
otherwise to 0. */
#cmakedefine JSON_INTEGER_IS_LONG_LONG 1
/* Bring in the cmake-detected defines */
#cmakedefine HAVE_STDINT_H 1
#cmakedefine HAVE_INTTYPES_H 1
#cmakedefine HAVE_SYS_TYPES_H 1
/* Include our standard type header for the integer typedef */
#if defined(HAVE_STDINT_H)
# include <stdint.h>
#elif defined(HAVE_INTTYPES_H)
# include <inttypes.h>
#elif defined(HAVE_SYS_TYPES_H)
# include <sys/types.h>
#endif
/* If your compiler supports the inline keyword in C, JSON_INLINE is
defined to `inline', otherwise empty. In C++, the inline is always
supported. */
#ifdef __cplusplus
#define JSON_INLINE inline
#else
#define JSON_INLINE @JSON_INLINE@
#endif
#define json_int_t @JSON_INT_T@
#define json_strtoint @JSON_STRTOINT@
#define JSON_INTEGER_FORMAT @JSON_INTEGER_FORMAT@
/* If __atomic builtins are available they will be used to manage
reference counts of json_t. */
#define JSON_HAVE_ATOMIC_BUILTINS @JSON_HAVE_ATOMIC_BUILTINS@
/* If __atomic builtins are not available we try using __sync builtins
to manage reference counts of json_t. */
#define JSON_HAVE_SYNC_BUILTINS @JSON_HAVE_SYNC_BUILTINS@
/* Maximum recursion depth for parsing JSON input.
This limits the depth of e.g. array-within-array constructions. */
#define JSON_PARSER_MAX_DEPTH 2048
#endif

View file

@ -0,0 +1,62 @@
#cmakedefine HAVE_ENDIAN_H 1
#cmakedefine HAVE_FCNTL_H 1
#cmakedefine HAVE_SCHED_H 1
#cmakedefine HAVE_UNISTD_H 1
#cmakedefine HAVE_SYS_PARAM_H 1
#cmakedefine HAVE_SYS_STAT_H 1
#cmakedefine HAVE_SYS_TIME_H 1
#cmakedefine HAVE_SYS_TYPES_H 1
#cmakedefine HAVE_STDINT_H 1
#cmakedefine HAVE_CLOSE 1
#cmakedefine HAVE_GETPID 1
#cmakedefine HAVE_GETTIMEOFDAY 1
#cmakedefine HAVE_OPEN 1
#cmakedefine HAVE_READ 1
#cmakedefine HAVE_SCHED_YIELD 1
#cmakedefine HAVE_SYNC_BUILTINS 1
#cmakedefine HAVE_ATOMIC_BUILTINS 1
#cmakedefine HAVE_LOCALE_H 1
#cmakedefine HAVE_SETLOCALE 1
#cmakedefine WORDS_BIGENDIAN 1
#cmakedefine HAVE_INT32_T 1
#ifndef HAVE_INT32_T
# define int32_t @JSON_INT32@
#endif
#cmakedefine HAVE_UINT32_T 1
#ifndef HAVE_UINT32_T
# define uint32_t @JSON_UINT32@
#endif
#cmakedefine HAVE_UINT16_T 1
#ifndef HAVE_UINT16_T
# define uint16_t @JSON_UINT16@
#endif
#cmakedefine HAVE_UINT8_T 1
#ifndef HAVE_UINT8_T
# define uint8_t @JSON_UINT8@
#endif
#cmakedefine HAVE_SSIZE_T 1
#ifndef HAVE_SSIZE_T
# define ssize_t @JSON_SSIZE@
#endif
#cmakedefine USE_URANDOM 1
#cmakedefine USE_WINDOWS_CRYPTOAPI 1
#cmakedefine USE_DTOA 1
#if USE_DTOA
# define DTOA_ENABLED 1
#else
# define DTOA_ENABLED 0
#endif
#define INITIAL_HASHTABLE_ORDER @JANSSON_INITIAL_HASHTABLE_ORDER@

View file

@ -1,22 +1,31 @@
AC_PREREQ([2.60])
AC_INIT([jansson], [1.3], [petri@digip.org])
AC_INIT([jansson], [2.14.1], [https://github.com/akheron/jansson/issues])
AC_CONFIG_AUX_DIR([.])
AM_INIT_AUTOMAKE([1.10 foreign])
AC_CONFIG_SRCDIR([src/value.c])
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_HEADERS([jansson_private_config.h])
# Checks for programs.
AC_PROG_CC
AC_PROG_CXX
AC_PROG_LIBTOOL
AM_CONDITIONAL([GCC], [test x$GCC = xyes])
# Checks for libraries.
# Checks for header files.
AC_CHECK_HEADERS([endian.h fcntl.h locale.h sched.h unistd.h sys/param.h sys/stat.h sys/time.h sys/types.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_TYPE_INT32_T
AC_TYPE_UINT32_T
AC_TYPE_UINT16_T
AC_TYPE_UINT8_T
AC_TYPE_LONG_LONG_INT
AC_C_BIGENDIAN
AC_C_INLINE
case $ac_cv_c_inline in
@ -27,15 +36,154 @@ esac
AC_SUBST([json_inline])
# Checks for library functions.
AC_CHECK_FUNCS([close getpid gettimeofday open read setlocale sched_yield strtoll])
AC_MSG_CHECKING([for gcc __sync builtins])
have_sync_builtins=no
AC_TRY_LINK(
[], [unsigned long val; __sync_bool_compare_and_swap(&val, 0, 1); __sync_add_and_fetch(&val, 1); __sync_sub_and_fetch(&val, 1);],
[have_sync_builtins=yes],
)
if test "x$have_sync_builtins" = "xyes"; then
AC_DEFINE([HAVE_SYNC_BUILTINS], [1],
[Define to 1 if gcc's __sync builtins are available])
json_have_sync_builtins=1
else
json_have_sync_builtins=0
fi
AC_SUBST([json_have_sync_builtins])
AC_MSG_RESULT([$have_sync_builtins])
AC_MSG_CHECKING([for gcc __atomic builtins])
have_atomic_builtins=no
AC_TRY_LINK(
[], [char l; unsigned long v; __atomic_test_and_set(&l, __ATOMIC_RELAXED); __atomic_store_n(&v, 1, __ATOMIC_RELEASE); __atomic_load_n(&v, __ATOMIC_ACQUIRE); __atomic_add_fetch(&v, 1, __ATOMIC_ACQUIRE); __atomic_sub_fetch(&v, 1, __ATOMIC_RELEASE);],
[have_atomic_builtins=yes],
)
if test "x$have_atomic_builtins" = "xyes"; then
AC_DEFINE([HAVE_ATOMIC_BUILTINS], [1],
[Define to 1 if gcc's __atomic builtins are available])
json_have_atomic_builtins=1
else
json_have_atomic_builtins=0
fi
AC_SUBST([json_have_atomic_builtins])
AC_MSG_RESULT([$have_atomic_builtins])
case "$ac_cv_type_long_long_int$ac_cv_func_strtoll" in
yesyes) json_have_long_long=1;;
*) json_have_long_long=0;;
esac
AC_SUBST([json_have_long_long])
# Features
AC_ARG_ENABLE([urandom],
[AS_HELP_STRING([--disable-urandom],
[Don't use /dev/urandom to seed the hash function])],
[use_urandom=$enableval], [use_urandom=yes])
if test "x$use_urandom" = xyes; then
AC_DEFINE([USE_URANDOM], [1],
[Define to 1 if /dev/urandom should be used for seeding the hash function])
fi
AC_ARG_ENABLE([windows-cryptoapi],
[AS_HELP_STRING([--disable-windows-cryptoapi],
[Don't use CryptGenRandom to seed the hash function])],
[use_windows_cryptoapi=$enableval], [use_windows_cryptoapi=yes])
if test "x$use_windows_cryptoapi" = xyes; then
AC_DEFINE([USE_WINDOWS_CRYPTOAPI], [1],
[Define to 1 if CryptGenRandom should be used for seeding the hash function])
fi
AC_ARG_ENABLE([initial-hashtable-order],
[AS_HELP_STRING([--enable-initial-hashtable-order=VAL],
[Number of buckets new object hashtables contain is 2 raised to this power. The default is 3, so empty hashtables contain 2^3 = 8 buckets.])],
[initial_hashtable_order=$enableval], [initial_hashtable_order=3])
AC_DEFINE_UNQUOTED([INITIAL_HASHTABLE_ORDER], [$initial_hashtable_order],
[Number of buckets new object hashtables contain is 2 raised to this power. E.g. 3 -> 2^3 = 8.])
AC_ARG_ENABLE([Bsymbolic],
[AS_HELP_STRING([--disable-Bsymbolic],
[Avoid linking with -Bsymbolic-function])],
[], [with_Bsymbolic=check])
if test "x$with_Bsymbolic" != "xno" ; then
AC_MSG_CHECKING([for -Bsymbolic-functions linker flag])
saved_LDFLAGS="${LDFLAGS}"
LDFLAGS=-Wl,-Bsymbolic-functions
AC_TRY_LINK(
[], [int main (void) { return 0; }],
[AC_MSG_RESULT([yes])
have_Bsymbolic=yes],
[AC_MSG_RESULT([no])
have_Bsymbolic=no]
)
LDFLAGS="${saved_LDFLAGS}"
if test "x$with_Bsymbolic" = "xcheck" ; then
with_Bsymbolic=$have_Bsymbolic;
fi
if test "x$with_Bsymbolic:x$have_Bsymbolic" = "xyes:xno" ; then
AC_MSG_ERROR([linker support is required for -Bsymbolic])
fi
fi
AS_IF([test "x$with_Bsymbolic" = "xyes"], [JSON_BSYMBOLIC_LDFLAGS=-Wl[,]-Bsymbolic-functions])
AC_SUBST(JSON_BSYMBOLIC_LDFLAGS)
# Enable symbol versioning on GNU libc
JSON_SYMVER_LDFLAGS=
AC_CHECK_DECL([__GLIBC__], [JSON_SYMVER_LDFLAGS=-Wl,--default-symver])
AC_SUBST([JSON_SYMVER_LDFLAGS])
AC_ARG_ENABLE([dtoa],
[AS_HELP_STRING([--enable-dtoa], [Use dtoa for optimal floating point to string conversion])],
[case "$enableval" in
yes) dtoa=yes ;;
no) dtoa=no ;;
*) AC_MSG_ERROR([bad value ${enableval} for --enable-dtoa]) ;;
esac], [dtoa=yes])
if test "$dtoa" = "yes"; then
AC_DEFINE([DTOA_ENABLED], [1],
[Define to 1 to use dtoa to convert floating points to strings])
fi
AM_CONDITIONAL([DTOA_ENABLED], [test "$dtoa" = "yes"])
AC_ARG_ENABLE([ossfuzzers],
[AS_HELP_STRING([--enable-ossfuzzers],
[Whether to generate the fuzzers for OSS-Fuzz])],
[have_ossfuzzers=yes], [have_ossfuzzers=no])
AM_CONDITIONAL([USE_OSSFUZZERS], [test "x$have_ossfuzzers" = "xyes"])
AC_SUBST([LIB_FUZZING_ENGINE])
AM_CONDITIONAL([USE_OSSFUZZ_FLAG], [test "x$LIB_FUZZING_ENGINE" = "x-fsanitize=fuzzer"])
AM_CONDITIONAL([USE_OSSFUZZ_STATIC], [test -f "$LIB_FUZZING_ENGINE"])
if test x$GCC = xyes; then
AC_MSG_CHECKING(for -Wno-format-truncation)
wnoformat_truncation="-Wno-format-truncation"
AS_IF([${CC} -Wno-format-truncation -Werror -S -o /dev/null -xc /dev/null > /dev/null 2>&1],
[AC_MSG_RESULT(yes)],
[AC_MSG_RESULT(no)
wnoformat_truncation=""])
AM_CFLAGS="-Wall -Wextra -Wdeclaration-after-statement -Wshadow ${wnoformat_truncation}"
fi
AC_SUBST([AM_CFLAGS])
AC_CONFIG_FILES([
jansson.pc
Makefile
doc/Makefile
src/Makefile
src/jansson.h
src/jansson_config.h
test/Makefile
test/bin/Makefile
test/ossfuzz/Makefile
test/suites/Makefile
test/suites/api/Makefile
])

9
doc/.readthedocs.yaml Normal file
View file

@ -0,0 +1,9 @@
version: 2
build:
os: ubuntu-22.04
tools:
python: "3.12"
sphinx:
configuration: doc/conf.py

View file

@ -1,9 +1,9 @@
EXTRA_DIST = conf.py apiref.rst changes.rst conformance.rst \
gettingstarted.rst github_commits.c index.rst tutorial.rst \
ext/refcounting.py
EXTRA_DIST = conf.py apiref.rst changes.rst conformance.rst \
gettingstarted.rst github_commits.c index.rst threadsafety.rst \
tutorial.rst upgrading.rst ext/refcounting.py
SPHINXBUILD = sphinx-build
SPHINXOPTS = -d _build/doctrees -W
SPHINXOPTS = -d _build/doctrees $(SPHINXOPTS_EXTRA)
html-local:
$(SPHINXBUILD) -b html $(SPHINXOPTS) $(srcdir) _build/html

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,10 @@
# -*- coding: utf-8 -*-
#
# Jansson documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 30 11:35:32 2009.
# sphinx-quickstart on Sun Sep 5 21:47:20 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
@ -15,44 +12,45 @@
# serve to show the default.
import sys, os
sys.path.insert(0, os.path.abspath('ext'))
# If your extensions (or modules documented by autodoc) are in another directory,
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('ext'))
# General configuration
# ---------------------
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['refcounting']
# Add any paths that contain templates here, relative to this directory.
templates_path = []
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jansson'
copyright = u'2009, 2010 Petri Lehtinen'
copyright = u'2009-2020, Petri Lehtinen'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.3'
version = '2.14.1'
# The full version, including alpha/beta/rc tags.
release = '1.3'
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@ -64,15 +62,13 @@ release = '1.3'
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
default_role = 'cfunc'
default_role = 'c:func'
primary_domain = 'c'
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
@ -88,14 +84,23 @@ default_role = 'cfunc'
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
@ -116,7 +121,7 @@ html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
@ -134,7 +139,7 @@ html_static_path = []
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
@ -142,23 +147,28 @@ html_static_path = []
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Janssondoc'
# Options for LaTeX output
# ------------------------
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
@ -167,10 +177,10 @@ htmlhelp_basename = 'Janssondoc'
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Jansson.tex', ur'Jansson Documentation',
ur'Petri Lehtinen', 'manual'),
('index', 'Jansson.tex', u'Jansson Documentation',
u'Petri Lehtinen', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@ -181,6 +191,12 @@ latex_documents = [
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
@ -188,4 +204,14 @@ latex_documents = [
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jansson', u'Jansson Documentation',
[u'Petri Lehtinen'], 1)
]

View file

@ -1,10 +1,11 @@
.. _rfc-conformance:
***************
RFC Conformance
***************
JSON is specified in :rfc:`4627`, *"The application/json Media Type
for JavaScript Object Notation (JSON)"*. This chapter discusses
Jansson's conformance to this specification.
for JavaScript Object Notation (JSON)"*.
Character Encoding
==================
@ -18,31 +19,37 @@ Strings
=======
JSON strings are mapped to C-style null-terminated character arrays,
and UTF-8 encoding is used internally. Strings may not contain
embedded null characters, not even escaped ones.
and UTF-8 encoding is used internally.
For example, trying to decode the following JSON text leads to a parse
error::
All Unicode codepoints U+0000 through U+10FFFF are allowed in string
values. However, U+0000 is allowed in object keys only for length-aware functions.
["this string contains the null character: \u0000"]
All other Unicode codepoints U+0001 through U+10FFFF are allowed.
Unicode normalization or any other transformation is never performed
on any strings (string values or object keys). When checking for
equivalence of strings or object keys, the comparison is performed
byte by byte between the original UTF-8 representations of the
strings.
Numbers
=======
.. _real-vs-integer:
Real vs. Integer
----------------
JSON makes no distinction between real and integer numbers; Jansson
does. Real numbers are mapped to the ``double`` type and integers to
the ``int`` type.
the ``json_int_t`` type, which is a typedef of ``long long`` or
``long``, depending on whether ``long long`` is supported by your
compiler or not.
A JSON number is considered to be a real number if its lexical
representation includes one of ``e``, ``E``, or ``.``; regardless if
its actual numeric value is a true integer (e.g., all of ``1E6``,
``3.0``, ``400E-2``, and ``3.14E3`` are mathematical integers, but
will be treated as real values).
will be treated as real values). With the ``JSON_DECODE_INT_AS_REAL``
decoder flag set all numbers are interpreted as real.
All other JSON numbers are considered integers.
@ -54,19 +61,19 @@ Overflow, Underflow & Precision
-------------------------------
Real numbers whose absolute values are too small to be represented in
a C double will be silently estimated with 0.0. Thus, depending on
a C ``double`` will be silently estimated with 0.0. Thus, depending on
platform, JSON numbers very close to zero such as 1E-999 may result in
0.0.
Real numbers whose absolute values are too large to be represented in
a C ``double`` type will result in an overflow error (a JSON decoding
a C ``double`` will result in an overflow error (a JSON decoding
error). Thus, depending on platform, JSON numbers like 1E+999 or
-1E+999 may result in a parsing error.
Likewise, integer numbers whose absolute values are too large to be
represented in the ``int`` type will result in an overflow error (a
JSON decoding error). Thus, depending on platform, JSON numbers like
1000000000000000 may result in parsing error.
represented in the ``json_int_t`` type (see above) will result in an
overflow error (a JSON decoding error). Thus, depending on platform,
JSON numbers like 1000000000000000 may result in parsing error.
Parsing JSON real numbers may result in a loss of precision. As long
as overflow does not occur (i.e. a total loss of precision), the
@ -94,9 +101,19 @@ Types
-----
No support is provided in Jansson for any C numeric types other than
``int`` and ``double``. This excludes things such as unsigned types,
``long``, ``long long``, ``long double``, etc. Obviously, shorter
types like ``short`` and ``float`` are implicitly handled via the
ordinary C type coercion rules (subject to overflow semantics). Also,
no support or hooks are provided for any supplemental "bignum" type
add-on packages.
``json_int_t`` and ``double``. This excludes things such as unsigned
types, ``long double``, etc. Obviously, shorter types like ``short``,
``int``, ``long`` (if ``json_int_t`` is ``long long``) and ``float``
are implicitly handled via the ordinary C type coercion rules (subject
to overflow semantics). Also, no support or hooks are provided for any
supplemental "bignum" type add-on packages.
Depth of nested values
======================
To avoid stack exhaustion, Jansson currently limits the nesting depth
for arrays and objects to a certain value (default: 2048), defined as
a macro ``JSON_PARSER_MAX_DEPTH`` within ``jansson_config.h``.
The limit is allowed to be set by the RFC; there is no recommended value
or required minimum depth to be supported.

View file

@ -19,13 +19,13 @@
<description of the json_object function>
:copyright: Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
:copyright: Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
:license: MIT, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import Directive
class refcounting(nodes.emphasis): pass
def visit(self, node):
self.visit_emphasis(node)
@ -40,20 +40,30 @@ def html_depart(self, node):
self.body.append('</em>')
def refcounting_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
if arguments[0] == 'borrow':
text = 'Return value: Borrowed reference.'
elif arguments[0] == 'new':
text = 'Return value: New reference.'
else:
raise Error('Valid arguments: new, borrow')
class refcounting(nodes.emphasis):
pass
class refcounting_directive(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
def run(self):
if self.arguments[0] == 'borrow':
text = 'Return value: Borrowed reference.'
elif self.arguments[0] == 'new':
text = 'Return value: New reference.'
else:
raise Error('Valid arguments: new, borrow')
return [refcounting(text, text)]
return [refcounting(text, text)]
def setup(app):
app.add_node(refcounting,
html=(html_visit, html_depart),
latex=(visit, depart),
text=(visit, depart))
app.add_directive('refcounting', refcounting_directive, 0, (1, 0, 0))
text=(visit, depart),
man=(visit, depart))
app.add_directive('refcounting', refcounting_directive)

View file

@ -10,6 +10,9 @@ Compiling and Installing Jansson
The Jansson source is available at
http://www.digip.org/jansson/releases/.
Unix-like systems (including MinGW)
-----------------------------------
Unpack the source tarball and change to the source directory:
.. parsed-literal::
@ -27,8 +30,7 @@ compiling and installing is extremely simple::
To change the destination directory (``/usr/local`` by default), use
the ``--prefix=DIR`` argument to ``./configure``. See ``./configure
--help`` for the list of all possible installation options. (There are
no options to customize the resulting Jansson binary.)
--help`` for the list of all possible configuration options.
The command ``make check`` runs the test suite distributed with
Jansson. This step is not strictly necessary, but it may find possible
@ -37,11 +39,11 @@ please report them.
If you obtained the source from a Git repository (or any other source
control system), there's no ``./configure`` script as it's not kept in
version control. To create the script, Autotools needs to be
version control. To create the script, the build system needs to be
bootstrapped. There are many ways to do this, but the easiest one is
to use ``autoreconf``::
autoreconf -vi
autoreconf -fi
This command creates the ``./configure`` script, which can then be
used as described above.
@ -51,18 +53,170 @@ used as described above.
.. _libtool: http://www.gnu.org/software/libtool/
Installing Prebuilt Binary Packages
-----------------------------------
.. _build-cmake:
Binary ``.deb`` packages for Ubuntu are available in `this PPA`_ at
Launchpad_. Follow the instructions in the PPA ("Technical details
about this PPA" link) to take the PPA into use. Then install the -dev
package::
CMake (various platforms, including Windows)
--------------------------------------------
sudo apt-get install libjansson-dev
Jansson can be built using CMake_. Create a build directory for an
out-of-tree build, change to that directory, and run ``cmake`` (or ``ccmake``,
``cmake-gui``, or similar) to configure the project.
.. _this PPA: http://launchpad.net/~petri/+archive/ppa
.. _Launchpad: http://launchpad.net/
See the examples below for more detailed information.
.. note:: In the below examples ``..`` is used as an argument for ``cmake``.
This is simply the path to the jansson project root directory.
In the example it is assumed you've created a sub-directory ``build``
and are using that. You could use any path you want.
.. _build-cmake-unix:
Unix (Make files)
^^^^^^^^^^^^^^^^^
Generating make files on unix:
.. parsed-literal::
bunzip2 -c jansson-|release|.tar.bz2 | tar xf -
cd jansson-|release|
mkdir build
cd build
cmake .. # or ccmake .. for a GUI.
.. note::
If you don't want to build docs or ``Sphinx`` is not installed, you should add ``"-DJANSSON_BUILD_DOCS=OFF"`` in the ``cmake`` command.
Then to build::
make
make check
make install
Windows (Visual Studio)
^^^^^^^^^^^^^^^^^^^^^^^
Creating Visual Studio project files from the command line:
.. parsed-literal::
<unpack>
cd jansson-|release|
md build
cd build
cmake -G "Visual Studio 15 2017" ..
.. note::
You should replace the name of the generator (``-G`` flag) matching
the Visual Studio version installed on your system. Currently, the
following versions are supported:
- ``Visual Studio 9 2008``
- ``Visual Studio 10 2010``
- ``Visual Studio 11 2012``
- ``Visual Studio 12 2013``
- ``Visual Studio 14 2015``
- ``Visual Studio 15 2017``
- ``Visual Studio 16 2019``
Any later version should also work.
You will now have a *Visual Studio Solution* in your build directory.
To run the unit tests build the ``RUN_TESTS`` project.
If you prefer a GUI the ``cmake`` line in the above example can
be replaced with::
cmake-gui ..
For command line help (including a list of available generators)
for CMake_ simply run::
cmake
To list available CMake_ settings (and what they are currently set to)
for the project, run::
cmake -LH ..
Windows (MinGW)
^^^^^^^^^^^^^^^
If you prefer using MinGW on Windows, make sure MinGW installed and ``{MinGW}/bin`` has been added to ``PATH``, then do the following commands:
.. parsed-literal::
<unpack>
cd jansson-|release|
md build
cd build
cmake -G "MinGW Makefiles" ..
mingw32-make
Mac OSX (Xcode)
^^^^^^^^^^^^^^^
If you prefer using Xcode instead of make files on OSX,
do the following. (Use the same steps as
for :ref:`Unix <build-cmake-unix>`)::
...
cmake -G "Xcode" ..
Additional CMake settings
^^^^^^^^^^^^^^^^^^^^^^^^^
Shared library
""""""""""""""
By default the CMake_ project will generate build files for building the
static library. To build the shared version use::
...
cmake -DJANSSON_BUILD_SHARED_LIBS=1 ..
Changing install directory (same as autoconf --prefix)
""""""""""""""""""""""""""""""""""""""""""""""""""""""
Just as with the autoconf_ project you can change the destination directory
for ``make install``. The equivalent for autoconfs ``./configure --prefix``
in CMake_ is::
...
cmake -DCMAKE_INSTALL_PREFIX:PATH=/some/other/path ..
make install
.. _CMake: http://www.cmake.org
Android
-------
Jansson can be built for Android platforms. Android.mk is in the
source root directory. The configuration header file is located in the
``android`` directory in the source distribution.
Other Systems
-------------
On non Unix-like systems, you may be unable to run the ``./configure``
script. In this case, follow these steps. All the files mentioned can
be found in the ``src/`` directory.
1. Create ``jansson_config.h`` (which has some platform-specific
parameters that are normally filled in by the ``./configure``
script). Edit ``jansson_config.h.in``, replacing all ``@variable@``
placeholders, and rename the file to ``jansson_config.h``.
2. Make ``jansson.h`` and ``jansson_config.h`` available to the
compiler, so that they can be found when compiling programs that
use Jansson.
3. Compile all the ``.c`` files (in the ``src/`` directory) into a
library file. Make the library available to the compiler, as in
step 2.
Building the Documentation
@ -77,14 +231,14 @@ documentation, invoke::
make html
and point your browser to ``doc/_build/html/index.html``. Sphinx_ is
required to generate the documentation.
and point your browser to ``doc/_build/html/index.html``. Sphinx_ 1.0
or newer is required to generate the documentation.
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
.. _Sphinx: http://sphinx.pocoo.org/
Compiling Programs That Use Jansson
Compiling Programs that Use Jansson
===================================
Jansson involves one C header file, :file:`jansson.h`, so it's enough
@ -101,7 +255,9 @@ link the program as follows::
cc -o prog prog.c -ljansson
Starting from version 1.2, there's also support for pkg-config_::
Starting from version 1.2, there's also support for pkg-config_:
.. code-block:: shell
cc -o prog prog.c `pkg-config --cflags --libs jansson`

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
@ -8,37 +8,33 @@
#include <stdlib.h>
#include <string.h>
#include <jansson.h>
#include <curl/curl.h>
#include <jansson.h>
#define BUFFER_SIZE (256 * 1024) /* 256 KB */
#define BUFFER_SIZE (256 * 1024) /* 256 KB */
#define URL_FORMAT "http://github.com/api/v2/json/commits/list/%s/%s/master"
#define URL_SIZE 256
#define URL_FORMAT "https://api.github.com/repos/%s/%s/commits"
#define URL_SIZE 256
/* Return the offset of the first newline in text or the length of
text if there's no newline */
static int newline_offset(const char *text)
{
static int newline_offset(const char *text) {
const char *newline = strchr(text, '\n');
if(!newline)
if (!newline)
return strlen(text);
else
return (int)(newline - text);
}
struct write_result
{
struct write_result {
char *data;
int pos;
};
static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream)
{
static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream) {
struct write_result *result = (struct write_result *)stream;
if(result->pos + size * nmemb >= BUFFER_SIZE - 1)
{
if (result->pos + size * nmemb >= BUFFER_SIZE - 1) {
fprintf(stderr, "error: too small buffer\n");
return 0;
}
@ -49,63 +45,75 @@ static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream)
return size * nmemb;
}
static char *request(const char *url)
{
CURL *curl;
static char *request(const char *url) {
CURL *curl = NULL;
CURLcode status;
char *data;
struct curl_slist *headers = NULL;
char *data = NULL;
long code;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
data = malloc(BUFFER_SIZE);
if(!curl || !data)
return NULL;
if (!curl)
goto error;
struct write_result write_result = {
.data = data,
.pos = 0
};
data = malloc(BUFFER_SIZE);
if (!data)
goto error;
struct write_result write_result = {.data = data, .pos = 0};
curl_easy_setopt(curl, CURLOPT_URL, url);
/* GitHub commits API v3 requires a User-Agent header */
headers = curl_slist_append(headers, "User-Agent: Jansson-Tutorial");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);
status = curl_easy_perform(curl);
if(status != 0)
{
if (status != 0) {
fprintf(stderr, "error: unable to request data from %s:\n", url);
fprintf(stderr, "%s\n", curl_easy_strerror(status));
return NULL;
goto error;
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if(code != 200)
{
if (code != 200) {
fprintf(stderr, "error: server responded with code %ld\n", code);
return NULL;
goto error;
}
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
curl_global_cleanup();
/* zero-terminate the result */
data[write_result.pos] = '\0';
return data;
error:
if (data)
free(data);
if (curl)
curl_easy_cleanup(curl);
if (headers)
curl_slist_free_all(headers);
curl_global_cleanup();
return NULL;
}
int main(int argc, char *argv[])
{
unsigned int i;
int main(int argc, char *argv[]) {
size_t i;
char *text;
char url[URL_SIZE];
json_t *root;
json_error_t error;
json_t *commits;
if(argc != 3)
{
if (argc != 3) {
fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
return 2;
@ -114,55 +122,57 @@ int main(int argc, char *argv[])
snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);
text = request(url);
if(!text)
if (!text)
return 1;
root = json_loads(text, &error);
root = json_loads(text, 0, &error);
free(text);
if(!root)
{
if (!root) {
fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
return 1;
}
commits = json_object_get(root, "commits");
if(!json_is_array(commits))
{
fprintf(stderr, "error: commits is not an array\n");
if (!json_is_array(root)) {
fprintf(stderr, "error: root is not an array\n");
json_decref(root);
return 1;
}
for(i = 0; i < json_array_size(commits); i++)
{
json_t *commit, *id, *message;
for (i = 0; i < json_array_size(root); i++) {
json_t *data, *sha, *commit, *message;
const char *message_text;
commit = json_array_get(commits, i);
if(!json_is_object(commit))
{
fprintf(stderr, "error: commit %d is not an object\n", i + 1);
data = json_array_get(root, i);
if (!json_is_object(data)) {
fprintf(stderr, "error: commit data %d is not an object\n", (int)(i + 1));
json_decref(root);
return 1;
}
id = json_object_get(commit, "id");
if(!json_is_string(id))
{
fprintf(stderr, "error: commit %d: id is not a string\n", i + 1);
sha = json_object_get(data, "sha");
if (!json_is_string(sha)) {
fprintf(stderr, "error: commit %d: sha is not a string\n", (int)(i + 1));
json_decref(root);
return 1;
}
commit = json_object_get(data, "commit");
if (!json_is_object(commit)) {
fprintf(stderr, "error: commit %d: commit is not an object\n", (int)(i + 1));
json_decref(root);
return 1;
}
message = json_object_get(commit, "message");
if(!json_is_string(message))
{
fprintf(stderr, "error: commit %d: message is not a string\n", i + 1);
if (!json_is_string(message)) {
fprintf(stderr, "error: commit %d: message is not a string\n", (int)(i + 1));
json_decref(root);
return 1;
}
message_text = json_string_value(message);
printf("%.8s %.*s\n",
json_string_value(id),
newline_offset(message_text),
printf("%.8s %.*s\n", json_string_value(sha), newline_offset(message_text),
message_text);
}

View file

@ -22,6 +22,11 @@ data. Its main features and design principles are:
Jansson is licensed under the `MIT license`_; see LICENSE in the
source distribution for details.
Jansson is used in production and its API is stable. It works on
numerous platforms, including numerous Unix like systems and Windows.
It's suitable for use on any system, including desktop, server, and
small embedded systems.
.. _`MIT license`: http://www.opensource.org/licenses/mit-license.php
.. _Jansson: http://www.digip.org/jansson/
@ -33,8 +38,10 @@ Contents
:maxdepth: 2
gettingstarted
upgrading
tutorial
conformance
threadsafety
apiref
changes

82
doc/threadsafety.rst Normal file
View file

@ -0,0 +1,82 @@
.. _thread-safety:
*************
Thread safety
*************
Jansson as a library is thread safe and has no mutable global state.
The only exceptions are the hash function seed and memory allocation
functions, see below.
There's no locking performed inside Jansson's code. **Read-only**
access to JSON values shared by multiple threads is safe, but
**mutating** a JSON value that's shared by multiple threads is not. A
multithreaded program must perform its own locking if JSON values
shared by multiple threads are mutated.
However, **reference count manipulation** (:func:`json_incref()`,
:func:`json_decref()`) is usually thread-safe, and can be performed on
JSON values that are shared among threads. The thread-safety of
reference counting can be checked with the
``JANSSON_THREAD_SAFE_REFCOUNT`` preprocessor constant. Thread-safe
reference count manipulation is achieved using compiler built-in
atomic functions, which are available in most modern compilers.
If compiler support is not available (``JANSSON_THREAD_SAFE_REFCOUNT``
is not defined), it may be very difficult to ensure thread safety of
reference counting. It's possible to have a reference to a value
that's also stored inside an array or object in another thread.
Modifying the container (adding or removing values) may trigger
concurrent access to such values, as containers manage the reference
count of their contained values.
Hash function seed
==================
To prevent an attacker from intentionally causing large JSON objects
with specially crafted keys to perform very slow, the hash function
used by Jansson is randomized using a seed value. The seed is
automatically generated on the first explicit or implicit call to
:func:`json_object()`, if :func:`json_object_seed()` has not been
called beforehand.
The seed is generated by using operating system's entropy sources if
they are available (``/dev/urandom``, ``CryptGenRandom()``). The
initialization is done in as thread safe manner as possible, by using
architecture specific lockless operations if provided by the platform
or the compiler.
If you're using threads, it's recommended to autoseed the hashtable
explicitly before spawning any threads by calling
``json_object_seed(0)`` , especially if you're unsure whether the
initialization is thread safe on your platform.
Memory allocation functions
===========================
Memory allocation functions should be set at most once, and only on
program startup. See :ref:`apiref-custom-memory-allocation`.
Locale
======
Jansson works fine under any locale.
However, if the host program is multithreaded and uses ``setlocale()``
to switch the locale in one thread while Jansson is currently encoding
or decoding JSON data in another thread, the result may be wrong or
the program may even crash.
Jansson uses locale specific functions for certain string conversions
in the encoder and decoder, and then converts the locale specific
values to/from the JSON representation. This fails if the locale
changes between the string conversion and the locale-to-JSON
conversion. This can only happen in multithreaded programs that use
``setlocale()``, because ``setlocale()`` switches the locale for all
running threads, not only the thread that calls ``setlocale()``.
If your program uses ``setlocale()`` as described above, consider
using the thread-safe ``uselocale()`` instead.

View file

@ -7,11 +7,10 @@ Tutorial
.. highlight:: c
In this tutorial, we create a program that fetches the latest commits
of a repository in GitHub_ over the web. One of the response formats
supported by `GitHub API`_ is JSON, so the result can be parsed using
Jansson.
of a repository in GitHub_ over the web. `GitHub API`_ uses JSON, so
the result can be parsed using Jansson.
To stick to the the scope of this tutorial, we will only cover the the
To stick to the scope of this tutorial, we will only cover the
parts of the program related to handling JSON data. For the best user
experience, the full source code is available:
:download:`github_commits.c`. To compile it (on Unix-like systems with
@ -31,56 +30,58 @@ name. Please note that the GitHub API is rate limited, so if you run
the program too many times within a short period of time, the sever
starts to respond with an error.
.. _GitHub: http://github.com/
.. _GitHub API: http://develop.github.com/
.. _GitHub: https://github.com/
.. _GitHub API: http://developer.github.com/
.. _libcurl: http://curl.haxx.se/
.. _tutorial-github-commits-api:
The GitHub Commits API
======================
The GitHub Repo Commits API
===========================
The `GitHub commits API`_ is used by sending HTTP requests to URLs
starting with ``http://github.com/api/v2/json/commits/``. Our program
only lists the latest commits, so the rest of the URL is
``list/USER/REPOSITORY/BRANCH``, where ``USER``, ``REPOSITORY`` and
``BRANCH`` are the GitHub user ID, the name of the repository, and the
name of the branch whose commits are to be listed, respectively.
The `GitHub Repo Commits API`_ is used by sending HTTP requests to
URLs like ``https://api.github.com/repos/USER/REPOSITORY/commits``,
where ``USER`` and ``REPOSITORY`` are the GitHub user ID and the name
of the repository whose commits are to be listed, respectively.
GitHub responds with a JSON object of the following form:
GitHub responds with a JSON array of the following form:
.. code-block:: none
{
"commits": [
{
"id": "<the commit ID>",
[
{
"sha": "<the commit ID>",
"commit": {
"message": "<the commit message>",
<more fields, not important to this tutorial>
<more fields, not important to this tutorial...>
},
{
"id": "<the commit ID>",
<more fields...>
},
{
"sha": "<the commit ID>",
"commit": {
"message": "<the commit message>",
<more fields, not important to this tutorial>
<more fields...>
},
<more commits...>
]
}
<more fields...>
},
<more commits...>
]
In our program, the HTTP request is sent using the following
function::
static char *request(const char *url);
It takes the URL as a parameter, preforms a HTTP GET request, and
It takes the URL as a parameter, performs a HTTP GET request, and
returns a newly allocated string that contains the response body. If
the request fails, an error message is printed to stderr and the
return value is *NULL*. For full details, refer to :download:`the code
<github_commits.c>`, as the actual implementation is not important
here.
.. _GitHub commits API: http://develop.github.com/p/commits.html
.. _GitHub Repo Commits API: http://developer.github.com/v3/repos/commits/
.. _tutorial-the-program:
@ -95,10 +96,10 @@ First the includes::
Like all the programs using Jansson, we need to include
:file:`jansson.h`.
The following definitions are used to build the GitHub commits API
request URL::
The following definitions are used to build the GitHub API request
URL::
#define URL_FORMAT "http://github.com/api/v2/json/commits/list/%s/%s/master"
#define URL_FORMAT "https://api.github.com/repos/%s/%s/commits"
#define URL_SIZE 256
The following function is used when formatting the result to find the
@ -118,20 +119,21 @@ first newline in the commit message::
The main function follows. In the beginning, we first declare a bunch
of variables and check the command line parameters::
unsigned int i;
char *text;
char url[URL_SIZE];
json_t *root;
json_error_t error;
json_t *commits;
if(argc != 3)
int main(int argc, char *argv[])
{
fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
return 2;
}
size_t i;
char *text;
char url[URL_SIZE];
json_t *root;
json_error_t error;
if(argc != 3)
{
fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
return 2;
}
Then we build the request URL using the user and repository names
given as command line parameters::
@ -149,10 +151,10 @@ If an error occurs, our function ``request`` prints the error and
returns *NULL*, so it's enough to just return 1 from the main
function.
Next we'll call :cfunc:`json_loads()` to decode the JSON text we got
Next we'll call :func:`json_loads()` to decode the JSON text we got
as a response::
root = json_loads(text, &error);
root = json_loads(text, 0, &error);
free(text);
if(!root)
@ -162,8 +164,8 @@ as a response::
}
We don't need the JSON text anymore, so we can free the ``text``
variable right after decoding it. If :cfunc:`json_loads()` fails, it
returns *NULL* and sets error information to the :ctype:`json_error_t`
variable right after decoding it. If :func:`json_loads()` fails, it
returns *NULL* and sets error information to the :type:`json_error_t`
structure given as the second parameter. In this case, our program
prints the error information out and returns 1 from the main function.
@ -171,47 +173,53 @@ Now we're ready to extract the data out of the decoded JSON response.
The structure of the response JSON was explained in section
:ref:`tutorial-github-commits-api`.
First, we'll extract the ``commits`` array from the JSON response::
We check that the returned value really is an array::
commits = json_object_get(root, "commits");
if(!json_is_array(commits))
if(!json_is_array(root))
{
fprintf(stderr, "error: commits is not an array\n");
fprintf(stderr, "error: root is not an array\n");
json_decref(root);
return 1;
}
This is the array that contains objects describing latest commits in
the repository. We check that the returned value really is an array.
If the key ``commits`` doesn't exist, :cfunc:`json_object_get()`
returns *NULL*, but :cfunc:`json_is_array()` handles this case, too.
Then we proceed to loop over all the commits in the array::
for(i = 0; i < json_array_size(commits); i++)
for(i = 0; i < json_array_size(root); i++)
{
json_t *commit, *id, *message;
json_t *data, *sha, *commit, *message;
const char *message_text;
commit = json_array_get(commits, i);
if(!json_is_object(commit))
data = json_array_get(root, i);
if(!json_is_object(data))
{
fprintf(stderr, "error: commit %d is not an object\n", i + 1);
fprintf(stderr, "error: commit data %d is not an object\n", i + 1);
json_decref(root);
return 1;
}
...
The function :cfunc:`json_array_size()` returns the size of a JSON
The function :func:`json_array_size()` returns the size of a JSON
array. First, we again declare some variables and then extract the
i'th element of the ``commits`` array using :cfunc:`json_array_get()`.
i'th element of the ``root`` array using :func:`json_array_get()`.
We also check that the resulting value is a JSON object.
Next we'll extract the commit ID and commit message, and check that
they both are JSON strings::
Next we'll extract the commit ID (a hexadecimal SHA-1 sum),
intermediate commit info object, and the commit message from that
object. We also do proper type checks::
id = json_object_get(commit, "id");
if(!json_is_string(id))
sha = json_object_get(data, "sha");
if(!json_is_string(sha))
{
fprintf(stderr, "error: commit %d: id is not a string\n", i + 1);
fprintf(stderr, "error: commit %d: sha is not a string\n", i + 1);
json_decref(root);
return 1;
}
commit = json_object_get(data, "commit");
if(!json_is_object(commit))
{
fprintf(stderr, "error: commit %d: commit is not an object\n", i + 1);
json_decref(root);
return 1;
}
@ -219,25 +227,26 @@ they both are JSON strings::
if(!json_is_string(message))
{
fprintf(stderr, "error: commit %d: message is not a string\n", i + 1);
json_decref(root);
return 1;
}
...
And finally, we'll print the first 8 characters of the commit ID and
the first line of the commit message. A C-style string is extracted
from a JSON string using :cfunc:`json_string_value()`::
from a JSON string using :func:`json_string_value()`::
message_text = json_string_value(message);
printf("%.8s %.*s\n",
json_string_value(id),
json_string_value(sha),
newline_offset(message_text),
message_text);
}
After sending the HTTP request, we decoded the JSON text using
:cfunc:`json_loads()`, remember? It returns a *new reference* to the
:func:`json_loads()`, remember? It returns a *new reference* to the
JSON value it decodes. When we're finished with the value, we'll need
to decrease the reference count using :cfunc:`json_decref()`. This way
to decrease the reference count using :func:`json_decref()`. This way
Jansson can release the resources::
json_decref(root);
@ -247,28 +256,32 @@ For a detailed explanation of reference counting in Jansson, see
:ref:`apiref-reference-count` in :ref:`apiref`.
The program's ready, let's test it and view the latest commits in
Jansson's repository::
Jansson's repository:
.. code-block:: shell
$ ./github_commits akheron jansson
86dc1d62 Fix indentation
b67e130f json_dumpf: Document the output shortage on error
4cd77771 Enhance handling of circular references
79009e62 json_dumps: Close the strbuffer if dumping fails
76999799 doc: Fix a small typo in apiref
22af193a doc/Makefile.am: Remove *.pyc in clean
951d091f Make integer, real and string mutable
185e107d Don't use non-portable asprintf()
ca7703fb Merge branch '1.0'
12cd4e8c jansson 1.0.4
<etc...>
1581f26a Merge branch '2.3'
aabfd493 load: Change buffer_pos to be a size_t
bd72efbd load: Avoid unexpected behaviour in macro expansion
e8fd3e30 Document and tweak json_load_callback()
873eddaf Merge pull request #60 from rogerz/contrib
bd2c0c73 Ignore the binary test_load_callback
17a51a4b Merge branch '2.3'
09c39adc Add json_load_callback to the list of exported symbols
cbb80baf Merge pull request #57 from rogerz/contrib
040bd7b0 Add json_load_callback()
2637faa4 Make test stripping locale independent
<...>
Conclusion
==========
In this tutorial, we implemented a program that fetches the latest
commits of a GitHub repository using the GitHub commits API. Jansson
was used to decode the JSON response and to extract the commit data.
commits of a GitHub repository using the GitHub Repo Commits API.
Jansson was used to decode the JSON response and to extract the commit
data.
This tutorial only covered a small part of Jansson. For example, we
did not create or manipulate JSON values at all. Proceed to

76
doc/upgrading.rst Normal file
View file

@ -0,0 +1,76 @@
.. highlight:: c
******************
Upgrading from 1.x
******************
This chapter lists the backwards incompatible changes introduced in
Jansson 2.0, and the steps that are needed for upgrading your code.
**The incompatibilities are not dramatic.** The biggest change is that
all decoding functions now require and extra parameter. Most programs
can be modified to work with 2.0 by adding a ``0`` as the second
parameter to all calls of :func:`json_loads()`, :func:`json_loadf()`
and :func:`json_load_file()`.
Compatibility
=============
Jansson 2.0 is backwards incompatible with the Jansson 1.x releases.
It is ABI incompatible, i.e. all programs dynamically linking to the
Jansson library need to be recompiled. It's also API incompatible,
i.e. the source code of programs using Jansson 1.x may need
modifications to make them compile against Jansson 2.0.
All the 2.x releases are guaranteed to be backwards compatible for
both ABI and API, so no recompilation or source changes are needed
when upgrading from 2.x to 2.y.
List of Incompatible Changes
============================
**Decoding flags**
For future needs, a ``flags`` parameter was added as the second
parameter to all decoding functions, i.e. :func:`json_loads()`,
:func:`json_loadf()` and :func:`json_load_file()`. All calls to
these functions need to be changed by adding a ``0`` as the second
argument. For example::
/* old code */
json_loads(input, &error);
/* new code */
json_loads(input, 0, &error);
**Underlying type of JSON integers**
The underlying C type of JSON integers has been changed from
``int`` to the widest available signed integer type, i.e.
``long long`` or ``long``, depending on whether
``long long`` is supported on your system or not. This makes
the whole 64-bit integer range available on most modern systems.
``jansson.h`` has a typedef :type:`json_int_t` to the underlying
integer type. ``int`` should still be used in most cases when
dealing with smallish JSON integers, as the compiler handles
implicit type coercion. Only when the full 64-bit range is needed,
:type:`json_int_t` should be explicitly used.
**Maximum encoder indentation depth**
The maximum argument of the ``JSON_INDENT()`` macro has been
changed from 255 to 31, to free up bits from the ``flags``
parameter of :func:`json_dumps()`, :func:`json_dumpf()` and
:func:`json_dump_file()`. If your code uses a bigger indentation
than 31, it needs to be changed.
**Unsigned integers in API functions**
Version 2.0 unifies unsigned integer usage in the API. All uses of
``unsigned int`` and ``unsigned long`` have been replaced
with ``size_t``. This includes flags, container sizes, etc.
This should not require source code changes, as both
``unsigned int`` and ``unsigned long`` are usually
compatible with ``size_t``.

4
examples/README.rst Normal file
View file

@ -0,0 +1,4 @@
Jansson examples
================
This directory contains simple example programs that use Jansson.

200
examples/simple_parse.c Normal file
View file

@ -0,0 +1,200 @@
/*
* Simple example of parsing and printing JSON using jansson.
*
* SYNOPSIS:
* $ examples/simple_parse
* Type some JSON > [true, false, null, 1, 0.0, -0.0, "", {"name": "barney"}]
* JSON Array of 8 elements:
* JSON True
* JSON False
* JSON Null
* JSON Integer: "1"
* JSON Real: 0.000000
* JSON Real: -0.000000
* JSON String: ""
* JSON Object of 1 pair:
* JSON Key: "name"
* JSON String: "barney"
*
* Copyright (c) 2014 Robert Poor <rdpoor@gmail.com>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <jansson.h>
#include <stdio.h>
#include <stdlib.h>
/* forward refs */
void print_json(json_t *root);
void print_json_aux(json_t *element, int indent);
void print_json_indent(int indent);
const char *json_plural(size_t count);
void print_json_object(json_t *element, int indent);
void print_json_array(json_t *element, int indent);
void print_json_string(json_t *element, int indent);
void print_json_integer(json_t *element, int indent);
void print_json_real(json_t *element, int indent);
void print_json_true(json_t *element, int indent);
void print_json_false(json_t *element, int indent);
void print_json_null(json_t *element, int indent);
void print_json(json_t *root) { print_json_aux(root, 0); }
void print_json_aux(json_t *element, int indent) {
switch (json_typeof(element)) {
case JSON_OBJECT:
print_json_object(element, indent);
break;
case JSON_ARRAY:
print_json_array(element, indent);
break;
case JSON_STRING:
print_json_string(element, indent);
break;
case JSON_INTEGER:
print_json_integer(element, indent);
break;
case JSON_REAL:
print_json_real(element, indent);
break;
case JSON_TRUE:
print_json_true(element, indent);
break;
case JSON_FALSE:
print_json_false(element, indent);
break;
case JSON_NULL:
print_json_null(element, indent);
break;
default:
fprintf(stderr, "unrecognized JSON type %d\n", json_typeof(element));
}
}
void print_json_indent(int indent) {
int i;
for (i = 0; i < indent; i++) {
putchar(' ');
}
}
const char *json_plural(size_t count) { return count == 1 ? "" : "s"; }
void print_json_object(json_t *element, int indent) {
size_t size;
const char *key;
json_t *value;
print_json_indent(indent);
size = json_object_size(element);
printf("JSON Object of %lld pair%s:\n", (long long)size, json_plural(size));
json_object_foreach(element, key, value) {
print_json_indent(indent + 2);
printf("JSON Key: \"%s\"\n", key);
print_json_aux(value, indent + 2);
}
}
void print_json_array(json_t *element, int indent) {
size_t i;
size_t size = json_array_size(element);
print_json_indent(indent);
printf("JSON Array of %lld element%s:\n", (long long)size, json_plural(size));
for (i = 0; i < size; i++) {
print_json_aux(json_array_get(element, i), indent + 2);
}
}
void print_json_string(json_t *element, int indent) {
print_json_indent(indent);
printf("JSON String: \"%s\"\n", json_string_value(element));
}
void print_json_integer(json_t *element, int indent) {
print_json_indent(indent);
printf("JSON Integer: \"%" JSON_INTEGER_FORMAT "\"\n", json_integer_value(element));
}
void print_json_real(json_t *element, int indent) {
print_json_indent(indent);
printf("JSON Real: %f\n", json_real_value(element));
}
void print_json_true(json_t *element, int indent) {
(void)element;
print_json_indent(indent);
printf("JSON True\n");
}
void print_json_false(json_t *element, int indent) {
(void)element;
print_json_indent(indent);
printf("JSON False\n");
}
void print_json_null(json_t *element, int indent) {
(void)element;
print_json_indent(indent);
printf("JSON Null\n");
}
/*
* Parse text into a JSON object. If text is valid JSON, returns a
* json_t structure, otherwise prints and error and returns null.
*/
json_t *load_json(const char *text) {
json_t *root;
json_error_t error;
root = json_loads(text, 0, &error);
if (root) {
return root;
} else {
fprintf(stderr, "json error on line %d: %s\n", error.line, error.text);
return (json_t *)0;
}
}
/*
* Print a prompt and return (by reference) a null-terminated line of
* text. Returns NULL on eof or some error.
*/
char *read_line(char *line, int max_chars) {
printf("Type some JSON > ");
fflush(stdout);
return fgets(line, max_chars, stdin);
}
/* ================================================================
* main
*/
#define MAX_CHARS 4096
int main(int argc, char *argv[]) {
char line[MAX_CHARS];
if (argc != 1) {
fprintf(stderr, "Usage: %s\n", argv[0]);
exit(-1);
}
while (read_line(line, MAX_CHARS) != (char *)NULL) {
/* parse text into JSON structure */
json_t *root = load_json(line);
if (root) {
/* print and release the JSON structure */
print_json(root);
json_decref(root);
}
}
return 0;
}

View file

@ -1,7 +1,7 @@
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=${prefix}/include
includedir=@includedir@
Name: Jansson
Description: Library for encoding, decoding and manipulating JSON data

70
release.sh Executable file
View file

@ -0,0 +1,70 @@
#!/bin/sh
#
# Use this script to easily make releases of Jansson. It configures
# the source tree, and builds and signs all tarballs.
die() {
echo $1 >&2
exit 1
}
confirm() {
local answer
read -p "$1 [yN]: " answer
[ "$answer" = "Y" -o "$answer" = "y" ] || exit 0
}
set -e
[ -f configure.ac ] || die "Must be run at project root directory"
# Determine version
v=$(grep AC_INIT configure.ac | sed -r 's/.*, \[(.+?)\],.*/\1/')
[ -n "$v" ] || die "Unable to determine version"
confirm "Version is $v, proceed?"
# Sanity checks
vi=$(grep version-info src/Makefile.am | sed 's/^[ \t]*//g' | cut -d" " -f2)
confirm "Libtool version-info is $vi, proceed?"
r=$(grep 'Released ' CHANGES | head -n 1)
confirm "Last CHANGES entry says \"$r\", proceed??"
dv=$(grep ^version doc/conf.py | sed -r "s/.*'(.*)'.*/\1/")
if [ "$dv" != "$v" ]; then
die "Documentation version ($dv) doesn't match library version"
fi
[ -f Makefile ] && make distclean || true
rm -f jansson-$v.tar.*
rm -rf jansson-$v-doc
rm -f jansson-$v-doc.tar.*
autoreconf -fi
./configure
# Run tests and make gz source tarball
: ${VALGRIND:=1}
export VALGRIND
make distcheck
# Make bzip2 source tarball
make dist-bzip2
# Sign source tarballs
for s in gz bz2; do
gpg --detach-sign --armor jansson-$v.tar.$s
done
# Build documentation
make html
mv doc/_build/html jansson-$v-doc
# Make and sign documentation tarballs
for s in gz bz2; do
[ $s = gz ] && compress=gzip
[ $s = bz2 ] && compress=bzip2
tar cf - jansson-$v-doc | $compress -9 -c > jansson-$v-doc.tar.$s
gpg --detach-sign --armor jansson-$v-doc.tar.$s
done
echo "All done"

3
scripts/clang-format Executable file
View file

@ -0,0 +1,3 @@
#!/bin/bash
git ls-files | grep '\.[ch]$' | xargs clang-format -i

30
scripts/clang-format-check Executable file
View file

@ -0,0 +1,30 @@
#!/bin/bash
CLANG_FORMAT=${CLANG_FORMAT:-clang-format}
CLANG_FORMAT_VERSION=${CLANG_FORMAT_VERSION:-}
if ! type $CLANG_FORMAT >/dev/null || \
! $CLANG_FORMAT --version | grep -q "version ${CLANG_FORMAT_VERSION}"; then
# If running tests, mark this test as skipped.
exit 77
fi
errors=0
paths=$(git ls-files | grep '\.[ch]$')
for path in $paths; do
echo "Checking $path"
$CLANG_FORMAT $path > $path.formatted
in=$(cat $path)
out=$(cat $path.formatted)
if [ "$in" != "$out" ]; then
diff -u $path $path.formatted
errors=1
fi
rm $path.formatted
done
if [ $errors -ne 0 ]; then
echo "Formatting errors detected, run ./scripts/clang-format to fix!"
exit 1
fi

View file

@ -1,20 +1,35 @@
EXTRA_DIST = jansson.def dtoa.c
include_HEADERS = jansson.h
nodist_include_HEADERS = jansson_config.h
lib_LTLIBRARIES = libjansson.la
libjansson_la_SOURCES = \
dump.c \
error.c \
hashtable.c \
hashtable.h \
hashtable_seed.c \
jansson_private.h \
load.c \
lookup3.h \
memory.c \
pack_unpack.c \
strbuffer.c \
strbuffer.h \
strconv.c \
utf.c \
utf.h \
util.h \
value.c
libjansson_la_LDFLAGS = \
-export-symbols-regex '^json_' \
-version-info 3:0:3
value.c \
version.c
AM_CFLAGS = -Wall -Wextra -Werror
if DTOA_ENABLED
libjansson_la_SOURCES += dtoa.c
endif
libjansson_la_LDFLAGS = \
-no-undefined \
-export-symbols-regex '^json_|^jansson_' \
-version-info 18:1:14 \
@JSON_SYMVER_LDFLAGS@ \
@JSON_BSYMBOLIC_LDFLAGS@

6265
src/dtoa.c Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,141 +1,183 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "jansson_private.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <jansson.h>
#include "jansson_private.h"
#include "jansson.h"
#include "strbuffer.h"
#include "utf.h"
#define MAX_INTEGER_STR_LENGTH 100
#define MAX_REAL_STR_LENGTH 100
#define MAX_INTEGER_STR_LENGTH 25
#define MAX_REAL_STR_LENGTH 25
typedef int (*dump_func)(const char *buffer, int size, void *data);
#define FLAGS_TO_INDENT(f) ((f) & 0x1F)
#define FLAGS_TO_PRECISION(f) (((f) >> 11) & 0x1F)
struct string
{
char *buffer;
int length;
int size;
struct buffer {
const size_t size;
size_t used;
char *data;
};
static int dump_to_strbuffer(const char *buffer, int size, void *data)
{
static int dump_to_strbuffer(const char *buffer, size_t size, void *data) {
return strbuffer_append_bytes((strbuffer_t *)data, buffer, size);
}
static int dump_to_file(const char *buffer, int size, void *data)
{
static int dump_to_buffer(const char *buffer, size_t size, void *data) {
struct buffer *buf = (struct buffer *)data;
if (buf->used + size <= buf->size)
memcpy(&buf->data[buf->used], buffer, size);
buf->used += size;
return 0;
}
static int dump_to_file(const char *buffer, size_t size, void *data) {
FILE *dest = (FILE *)data;
if(fwrite(buffer, size, 1, dest) != 1)
if (fwrite(buffer, size, 1, dest) != 1)
return -1;
return 0;
}
/* 256 spaces (the maximum indentation size) */
static char whitespace[] = " ";
static int dump_to_fd(const char *buffer, size_t size, void *data) {
#ifdef HAVE_UNISTD_H
int *dest = (int *)data;
if (write(*dest, buffer, size) == (ssize_t)size)
return 0;
#endif
return -1;
}
static int dump_indent(unsigned long flags, int depth, int space, dump_func dump, void *data)
{
if(JSON_INDENT(flags) > 0)
{
int i, ws_count = JSON_INDENT(flags);
/* 32 spaces (the maximum indentation size) */
static const char whitespace[] = " ";
if(dump("\n", 1, data))
static int dump_indent(size_t flags, int depth, int space, json_dump_callback_t dump,
void *data) {
if (FLAGS_TO_INDENT(flags) > 0) {
unsigned int ws_count = FLAGS_TO_INDENT(flags), n_spaces = depth * ws_count;
if (dump("\n", 1, data))
return -1;
for(i = 0; i < depth; i++)
{
if(dump(whitespace, ws_count, data))
while (n_spaces > 0) {
int cur_n =
n_spaces < sizeof whitespace - 1 ? n_spaces : sizeof whitespace - 1;
if (dump(whitespace, cur_n, data))
return -1;
n_spaces -= cur_n;
}
}
else if(space && !(flags & JSON_COMPACT))
{
} else if (space && !(flags & JSON_COMPACT)) {
return dump(" ", 1, data);
}
return 0;
}
static int dump_string(const char *str, int ascii, dump_func dump, void *data)
{
const char *pos, *end;
int32_t codepoint;
static int dump_string(const char *str, size_t len, json_dump_callback_t dump, void *data,
size_t flags) {
const char *pos, *end, *lim;
int32_t codepoint = 0;
if(dump("\"", 1, data))
if (dump("\"", 1, data))
return -1;
end = pos = str;
while(1)
{
lim = str + len;
while (1) {
const char *text;
char seq[13];
int length;
while(*end)
{
end = utf8_iterate(pos, &codepoint);
if(!end)
while (end < lim) {
end = utf8_iterate(pos, lim - pos, &codepoint);
if (!end)
return -1;
/* mandatory escape or control char */
if(codepoint == '\\' || codepoint == '"' || codepoint < 0x20)
if (codepoint == '\\' || codepoint == '"' || codepoint < 0x20)
break;
/* slash */
if ((flags & JSON_ESCAPE_SLASH) && codepoint == '/')
break;
/* non-ASCII */
if(ascii && codepoint > 0x7F)
if ((flags & JSON_ENSURE_ASCII) && codepoint > 0x7F)
break;
pos = end;
}
if(pos != str) {
if(dump(str, pos - str, data))
if (pos != str) {
if (dump(str, pos - str, data))
return -1;
}
if(end == pos)
if (end == pos)
break;
/* handle \, ", and control codes */
/* handle \, /, ", and control codes */
length = 2;
switch(codepoint)
{
case '\\': text = "\\\\"; break;
case '\"': text = "\\\""; break;
case '\b': text = "\\b"; break;
case '\f': text = "\\f"; break;
case '\n': text = "\\n"; break;
case '\r': text = "\\r"; break;
case '\t': text = "\\t"; break;
default:
{
switch (codepoint) {
case '\\':
text = "\\\\";
break;
case '\"':
text = "\\\"";
break;
case '\b':
text = "\\b";
break;
case '\f':
text = "\\f";
break;
case '\n':
text = "\\n";
break;
case '\r':
text = "\\r";
break;
case '\t':
text = "\\t";
break;
case '/':
text = "\\/";
break;
default: {
/* codepoint is in BMP */
if(codepoint < 0x10000)
{
sprintf(seq, "\\u%04x", codepoint);
if (codepoint < 0x10000) {
snprintf(seq, sizeof(seq), "\\u%04X", (unsigned int)codepoint);
length = 6;
}
/* not in BMP -> construct a UTF-16 surrogate pair */
else
{
else {
int32_t first, last;
codepoint -= 0x10000;
first = 0xD800 | ((codepoint & 0xffc00) >> 10);
last = 0xDC00 | (codepoint & 0x003ff);
sprintf(seq, "\\u%04x\\u%04x", first, last);
snprintf(seq, sizeof(seq), "\\u%04X\\u%04X", (unsigned int)first,
(unsigned int)last);
length = 12;
}
@ -144,7 +186,7 @@ static int dump_string(const char *str, int ascii, dump_func dump, void *data)
}
}
if(dump(text, length, data))
if (dump(text, length, data))
return -1;
str = pos = end;
@ -153,24 +195,33 @@ static int dump_string(const char *str, int ascii, dump_func dump, void *data)
return dump("\"", 1, data);
}
static int object_key_compare_keys(const void *key1, const void *key2)
{
return strcmp((*(const object_key_t **)key1)->key,
(*(const object_key_t **)key2)->key);
struct key_len {
const char *key;
int len;
};
static int compare_keys(const void *key1, const void *key2) {
const struct key_len *k1 = key1;
const struct key_len *k2 = key2;
const size_t min_size = k1->len < k2->len ? k1->len : k2->len;
int res = memcmp(k1->key, k2->key, min_size);
if (res)
return res;
return k1->len - k2->len;
}
static int object_key_compare_serials(const void *key1, const void *key2)
{
return (*(const object_key_t **)key1)->serial -
(*(const object_key_t **)key2)->serial;
}
static int do_dump(const json_t *json, size_t flags, int depth, hashtable_t *parents,
json_dump_callback_t dump, void *data) {
int embed = flags & JSON_EMBED;
static int do_dump(const json_t *json, unsigned long flags, int depth,
dump_func dump, void *data)
{
int ascii = flags & JSON_ENSURE_ASCII ? 1 : 0;
flags &= ~JSON_EMBED;
switch(json_typeof(json)) {
if (!json)
return -1;
switch (json_typeof(json)) {
case JSON_NULL:
return dump("null", 4, data);
@ -180,232 +231,190 @@ static int do_dump(const json_t *json, unsigned long flags, int depth,
case JSON_FALSE:
return dump("false", 5, data);
case JSON_INTEGER:
{
case JSON_INTEGER: {
char buffer[MAX_INTEGER_STR_LENGTH];
int size;
size = snprintf(buffer, MAX_INTEGER_STR_LENGTH, "%d", json_integer_value(json));
if(size >= MAX_INTEGER_STR_LENGTH)
size = snprintf(buffer, MAX_INTEGER_STR_LENGTH, "%" JSON_INTEGER_FORMAT,
json_integer_value(json));
if (size < 0 || size >= MAX_INTEGER_STR_LENGTH)
return -1;
return dump(buffer, size, data);
}
case JSON_REAL:
{
case JSON_REAL: {
char buffer[MAX_REAL_STR_LENGTH];
int size;
double value = json_real_value(json);
size = snprintf(buffer, MAX_REAL_STR_LENGTH, "%.17g",
json_real_value(json));
if(size >= MAX_REAL_STR_LENGTH)
size = jsonp_dtostr(buffer, MAX_REAL_STR_LENGTH, value,
FLAGS_TO_PRECISION(flags));
if (size < 0)
return -1;
/* Make sure there's a dot or 'e' in the output. Otherwise
a real is converted to an integer when decoding */
if(strchr(buffer, '.') == NULL &&
strchr(buffer, 'e') == NULL)
{
if(size + 2 >= MAX_REAL_STR_LENGTH) {
/* No space to append ".0" */
return -1;
}
buffer[size] = '.';
buffer[size + 1] = '0';
size += 2;
}
return dump(buffer, size, data);
}
case JSON_STRING:
return dump_string(json_string_value(json), ascii, dump, data);
return dump_string(json_string_value(json), json_string_length(json), dump,
data, flags);
case JSON_ARRAY:
{
int i;
int n;
json_array_t *array;
case JSON_ARRAY: {
size_t n;
size_t i;
/* Space for "0x", double the sizeof a pointer for the hex and a
* terminator. */
char key[2 + (sizeof(json) * 2) + 1];
size_t key_len;
/* detect circular references */
array = json_to_array(json);
if(array->visited)
goto array_error;
array->visited = 1;
if (jsonp_loop_check(parents, json, key, sizeof(key), &key_len))
return -1;
n = json_array_size(json);
if(dump("[", 1, data))
goto array_error;
if(n == 0) {
array->visited = 0;
return dump("]", 1, data);
if (!embed && dump("[", 1, data))
return -1;
if (n == 0) {
hashtable_del(parents, key, key_len);
return embed ? 0 : dump("]", 1, data);
}
if(dump_indent(flags, depth + 1, 0, dump, data))
goto array_error;
if (dump_indent(flags, depth + 1, 0, dump, data))
return -1;
for(i = 0; i < n; ++i) {
if(do_dump(json_array_get(json, i), flags, depth + 1,
dump, data))
goto array_error;
for (i = 0; i < n; ++i) {
if (do_dump(json_array_get(json, i), flags, depth + 1, parents, dump,
data))
return -1;
if(i < n - 1)
{
if(dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data))
goto array_error;
}
else
{
if(dump_indent(flags, depth, 0, dump, data))
goto array_error;
if (i < n - 1) {
if (dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data))
return -1;
} else {
if (dump_indent(flags, depth, 0, dump, data))
return -1;
}
}
array->visited = 0;
return dump("]", 1, data);
array_error:
array->visited = 0;
return -1;
hashtable_del(parents, key, key_len);
return embed ? 0 : dump("]", 1, data);
}
case JSON_OBJECT:
{
json_object_t *object;
case JSON_OBJECT: {
void *iter;
const char *separator;
int separator_length;
char loop_key[LOOP_KEY_LEN];
size_t loop_key_len;
if(flags & JSON_COMPACT) {
if (flags & JSON_COMPACT) {
separator = ":";
separator_length = 1;
}
else {
} else {
separator = ": ";
separator_length = 2;
}
/* detect circular references */
object = json_to_object(json);
if(object->visited)
goto object_error;
object->visited = 1;
if (jsonp_loop_check(parents, json, loop_key, sizeof(loop_key),
&loop_key_len))
return -1;
iter = json_object_iter((json_t *)json);
if(dump("{", 1, data))
goto object_error;
if(!iter) {
object->visited = 0;
return dump("}", 1, data);
if (!embed && dump("{", 1, data))
return -1;
if (!iter) {
hashtable_del(parents, loop_key, loop_key_len);
return embed ? 0 : dump("}", 1, data);
}
if(dump_indent(flags, depth + 1, 0, dump, data))
goto object_error;
if (dump_indent(flags, depth + 1, 0, dump, data))
return -1;
if(flags & JSON_SORT_KEYS || flags & JSON_PRESERVE_ORDER)
{
const object_key_t **keys;
unsigned int size;
unsigned int i;
int (*cmp_func)(const void *, const void *);
if (flags & JSON_SORT_KEYS) {
struct key_len *keys;
size_t size, i;
size = json_object_size(json);
keys = malloc(size * sizeof(object_key_t *));
if(!keys)
goto object_error;
keys = jsonp_malloc(size * sizeof(struct key_len));
if (!keys)
return -1;
i = 0;
while(iter)
{
keys[i] = jsonp_object_iter_fullkey(iter);
while (iter) {
struct key_len *keylen = &keys[i];
keylen->key = json_object_iter_key(iter);
keylen->len = json_object_iter_key_len(iter);
iter = json_object_iter_next((json_t *)json, iter);
i++;
}
assert(i == size);
if(flags & JSON_SORT_KEYS)
cmp_func = object_key_compare_keys;
else
cmp_func = object_key_compare_serials;
qsort(keys, size, sizeof(struct key_len), compare_keys);
qsort(keys, size, sizeof(object_key_t *), cmp_func);
for(i = 0; i < size; i++)
{
const char *key;
for (i = 0; i < size; i++) {
const struct key_len *key;
json_t *value;
key = keys[i]->key;
value = json_object_get(json, key);
key = &keys[i];
value = json_object_getn(json, key->key, key->len);
assert(value);
dump_string(key, ascii, dump, data);
if(dump(separator, separator_length, data) ||
do_dump(value, flags, depth + 1, dump, data))
{
free(keys);
goto object_error;
dump_string(key->key, key->len, dump, data, flags);
if (dump(separator, separator_length, data) ||
do_dump(value, flags, depth + 1, parents, dump, data)) {
jsonp_free(keys);
return -1;
}
if(i < size - 1)
{
if(dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data))
{
free(keys);
goto object_error;
if (i < size - 1) {
if (dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data)) {
jsonp_free(keys);
return -1;
}
}
else
{
if(dump_indent(flags, depth, 0, dump, data))
{
free(keys);
goto object_error;
} else {
if (dump_indent(flags, depth, 0, dump, data)) {
jsonp_free(keys);
return -1;
}
}
}
free(keys);
}
else
{
jsonp_free(keys);
} else {
/* Don't sort keys */
while(iter)
{
while (iter) {
void *next = json_object_iter_next((json_t *)json, iter);
const char *key = json_object_iter_key(iter);
const size_t key_len = json_object_iter_key_len(iter);
dump_string(json_object_iter_key(iter), ascii, dump, data);
if(dump(separator, separator_length, data) ||
do_dump(json_object_iter_value(iter), flags, depth + 1,
dump, data))
goto object_error;
dump_string(key, key_len, dump, data, flags);
if (dump(separator, separator_length, data) ||
do_dump(json_object_iter_value(iter), flags, depth + 1, parents,
dump, data))
return -1;
if(next)
{
if(dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data))
goto object_error;
}
else
{
if(dump_indent(flags, depth, 0, dump, data))
goto object_error;
if (next) {
if (dump(",", 1, data) ||
dump_indent(flags, depth + 1, 1, dump, data))
return -1;
} else {
if (dump_indent(flags, depth, 0, dump, data))
return -1;
}
iter = next;
}
}
object->visited = 0;
return dump("}", 1, data);
object_error:
object->visited = 0;
return -1;
hashtable_del(parents, loop_key, loop_key_len);
return embed ? 0 : dump("}", 1, data);
}
default:
@ -414,47 +423,68 @@ static int do_dump(const json_t *json, unsigned long flags, int depth,
}
}
char *json_dumps(const json_t *json, unsigned long flags)
{
char *json_dumps(const json_t *json, size_t flags) {
strbuffer_t strbuff;
char *result;
if(!json_is_array(json) && !json_is_object(json))
if (strbuffer_init(&strbuff))
return NULL;
if(strbuffer_init(&strbuff))
return NULL;
if (json_dump_callback(json, dump_to_strbuffer, (void *)&strbuff, flags))
result = NULL;
else
result = jsonp_strdup(strbuffer_value(&strbuff));
if(do_dump(json, flags, 0, dump_to_strbuffer, (void *)&strbuff)) {
strbuffer_close(&strbuff);
return NULL;
}
result = strdup(strbuffer_value(&strbuff));
strbuffer_close(&strbuff);
return result;
}
int json_dumpf(const json_t *json, FILE *output, unsigned long flags)
{
if(!json_is_array(json) && !json_is_object(json))
return -1;
size_t json_dumpb(const json_t *json, char *buffer, size_t size, size_t flags) {
struct buffer buf = {size, 0, buffer};
return do_dump(json, flags, 0, dump_to_file, (void *)output);
if (json_dump_callback(json, dump_to_buffer, (void *)&buf, flags))
return 0;
return buf.used;
}
int json_dump_file(const json_t *json, const char *path, unsigned long flags)
{
int json_dumpf(const json_t *json, FILE *output, size_t flags) {
return json_dump_callback(json, dump_to_file, (void *)output, flags);
}
int json_dumpfd(const json_t *json, int output, size_t flags) {
return json_dump_callback(json, dump_to_fd, (void *)&output, flags);
}
int json_dump_file(const json_t *json, const char *path, size_t flags) {
int result;
FILE *output = fopen(path, "w");
if(!output)
if (!output)
return -1;
result = json_dumpf(json, output, flags);
fclose(output);
if (fclose(output) != 0)
return -1;
return result;
}
int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data,
size_t flags) {
int res;
hashtable_t parents_set;
if (!(flags & JSON_ENCODE_ANY)) {
if (!json_is_array(json) && !json_is_object(json))
return -1;
}
if (hashtable_init(&parents_set))
return -1;
res = do_dump(json, flags, 0, &parents_set, callback, data);
hashtable_close(&parents_set);
return res;
}

59
src/error.c Normal file
View file

@ -0,0 +1,59 @@
#include "jansson_private.h"
#include <string.h>
void jsonp_error_init(json_error_t *error, const char *source) {
if (error) {
error->text[0] = '\0';
error->line = -1;
error->column = -1;
error->position = 0;
if (source)
jsonp_error_set_source(error, source);
else
error->source[0] = '\0';
}
}
void jsonp_error_set_source(json_error_t *error, const char *source) {
size_t length;
if (!error || !source)
return;
length = strlen(source);
if (length < JSON_ERROR_SOURCE_LENGTH)
strncpy(error->source, source, length + 1);
else {
size_t extra = length - JSON_ERROR_SOURCE_LENGTH + 4;
memcpy(error->source, "...", 3);
strncpy(error->source + 3, source + extra, length - extra + 1);
}
}
void jsonp_error_set(json_error_t *error, int line, int column, size_t position,
enum json_error_code code, const char *msg, ...) {
va_list ap;
va_start(ap, msg);
jsonp_error_vset(error, line, column, position, code, msg, ap);
va_end(ap);
}
void jsonp_error_vset(json_error_t *error, int line, int column, size_t position,
enum json_error_code code, const char *msg, va_list ap) {
if (!error)
return;
if (error->text[0] != '\0') {
/* error already set */
return;
}
error->line = line;
error->column = column;
error->position = (int)position;
vsnprintf(error->text, JSON_ERROR_TEXT_LENGTH - 1, msg, ap);
error->text[JSON_ERROR_TEXT_LENGTH - 2] = '\0';
error->text[JSON_ERROR_TEXT_LENGTH - 1] = code;
}

View file

@ -1,95 +1,89 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <config.h>
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include "hashtable.h"
#include "jansson_private.h" /* for container_of() */
#include <jansson_config.h> /* for JSON_INLINE */
#ifndef INITIAL_HASHTABLE_ORDER
#define INITIAL_HASHTABLE_ORDER 3
#endif
typedef struct hashtable_list list_t;
typedef struct hashtable_pair pair_t;
typedef struct hashtable_bucket bucket_t;
#define container_of(ptr_, type_, member_) \
((type_ *)((char *)ptr_ - (size_t)&((type_ *)0)->member_))
extern volatile uint32_t hashtable_seed;
#define list_to_pair(list_) container_of(list_, pair_t, list)
/* Implementation of the hash function */
#include "lookup3.h"
static inline void list_init(list_t *list)
{
#define list_to_pair(list_) container_of(list_, pair_t, list)
#define ordered_list_to_pair(list_) container_of(list_, pair_t, ordered_list)
#define hash_str(key, len) ((size_t)hashlittle((key), len, hashtable_seed))
static JSON_INLINE void list_init(list_t *list) {
list->next = list;
list->prev = list;
}
static inline void list_insert(list_t *list, list_t *node)
{
static JSON_INLINE void list_insert(list_t *list, list_t *node) {
node->next = list;
node->prev = list->prev;
list->prev->next = node;
list->prev = node;
}
static inline void list_remove(list_t *list)
{
static JSON_INLINE void list_remove(list_t *list) {
list->prev->next = list->next;
list->next->prev = list->prev;
}
static inline int bucket_is_empty(hashtable_t *hashtable, bucket_t *bucket)
{
static JSON_INLINE int bucket_is_empty(hashtable_t *hashtable, bucket_t *bucket) {
return bucket->first == &hashtable->list && bucket->first == bucket->last;
}
static void insert_to_bucket(hashtable_t *hashtable, bucket_t *bucket,
list_t *list)
{
if(bucket_is_empty(hashtable, bucket))
{
static void insert_to_bucket(hashtable_t *hashtable, bucket_t *bucket, list_t *list) {
if (bucket_is_empty(hashtable, bucket)) {
list_insert(&hashtable->list, list);
bucket->first = bucket->last = list;
}
else
{
} else {
list_insert(bucket->first, list);
bucket->first = list;
}
}
static unsigned int primes[] = {
5, 13, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469,
12582917, 25165843, 50331653, 100663319, 201326611, 402653189,
805306457, 1610612741
};
static const unsigned int num_primes = sizeof(primes) / sizeof(unsigned int);
static inline unsigned int num_buckets(hashtable_t *hashtable)
{
return primes[hashtable->num_buckets];
}
static pair_t *hashtable_find_pair(hashtable_t *hashtable, bucket_t *bucket,
const void *key, unsigned int hash)
{
const char *key, size_t key_len, size_t hash) {
list_t *list;
pair_t *pair;
if(bucket_is_empty(hashtable, bucket))
if (bucket_is_empty(hashtable, bucket))
return NULL;
list = bucket->first;
while(1)
{
while (1) {
pair = list_to_pair(list);
if(pair->hash == hash && hashtable->cmp_keys(pair->key, key))
if (pair->hash == hash && pair->key_len == key_len &&
memcmp(pair->key, key, key_len) == 0)
return pair;
if(list == bucket->last)
if (list == bucket->last)
break;
list = list->next;
@ -99,84 +93,75 @@ static pair_t *hashtable_find_pair(hashtable_t *hashtable, bucket_t *bucket,
}
/* returns 0 on success, -1 if key was not found */
static int hashtable_do_del(hashtable_t *hashtable,
const void *key, unsigned int hash)
{
static int hashtable_do_del(hashtable_t *hashtable, const char *key, size_t key_len,
size_t hash) {
pair_t *pair;
bucket_t *bucket;
unsigned int index;
size_t index;
index = hash % num_buckets(hashtable);
index = hash & hashmask(hashtable->order);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
pair = hashtable_find_pair(hashtable, bucket, key, key_len, hash);
if (!pair)
return -1;
if(&pair->list == bucket->first && &pair->list == bucket->last)
if (&pair->list == bucket->first && &pair->list == bucket->last)
bucket->first = bucket->last = &hashtable->list;
else if(&pair->list == bucket->first)
else if (&pair->list == bucket->first)
bucket->first = pair->list.next;
else if(&pair->list == bucket->last)
else if (&pair->list == bucket->last)
bucket->last = pair->list.prev;
list_remove(&pair->list);
list_remove(&pair->ordered_list);
json_decref(pair->value);
if(hashtable->free_key)
hashtable->free_key(pair->key);
if(hashtable->free_value)
hashtable->free_value(pair->value);
free(pair);
jsonp_free(pair);
hashtable->size--;
return 0;
}
static void hashtable_do_clear(hashtable_t *hashtable)
{
static void hashtable_do_clear(hashtable_t *hashtable) {
list_t *list, *next;
pair_t *pair;
for(list = hashtable->list.next; list != &hashtable->list; list = next)
{
for (list = hashtable->list.next; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
if(hashtable->free_key)
hashtable->free_key(pair->key);
if(hashtable->free_value)
hashtable->free_value(pair->value);
free(pair);
json_decref(pair->value);
jsonp_free(pair);
}
}
static int hashtable_do_rehash(hashtable_t *hashtable)
{
static int hashtable_do_rehash(hashtable_t *hashtable) {
list_t *list, *next;
pair_t *pair;
unsigned int i, index, new_size;
size_t i, index, new_size, new_order;
struct hashtable_bucket *new_buckets;
free(hashtable->buckets);
new_order = hashtable->order + 1;
new_size = hashsize(new_order);
hashtable->num_buckets++;
new_size = num_buckets(hashtable);
hashtable->buckets = malloc(new_size * sizeof(bucket_t));
if(!hashtable->buckets)
new_buckets = jsonp_malloc(new_size * sizeof(bucket_t));
if (!new_buckets)
return -1;
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
jsonp_free(hashtable->buckets);
hashtable->buckets = new_buckets;
hashtable->order = new_order;
for (i = 0; i < hashsize(hashtable->order); i++) {
hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list;
}
list = hashtable->list.next;
list_init(&hashtable->list);
for(; list != &hashtable->list; list = next) {
for (; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
index = pair->hash % new_size;
@ -186,190 +171,170 @@ static int hashtable_do_rehash(hashtable_t *hashtable)
return 0;
}
hashtable_t *hashtable_create(key_hash_fn hash_key, key_cmp_fn cmp_keys,
free_fn free_key, free_fn free_value)
{
hashtable_t *hashtable = malloc(sizeof(hashtable_t));
if(!hashtable)
return NULL;
if(hashtable_init(hashtable, hash_key, cmp_keys, free_key, free_value))
{
free(hashtable);
return NULL;
}
return hashtable;
}
void hashtable_destroy(hashtable_t *hashtable)
{
hashtable_close(hashtable);
free(hashtable);
}
int hashtable_init(hashtable_t *hashtable,
key_hash_fn hash_key, key_cmp_fn cmp_keys,
free_fn free_key, free_fn free_value)
{
unsigned int i;
int hashtable_init(hashtable_t *hashtable) {
size_t i;
hashtable->size = 0;
hashtable->num_buckets = 0; /* index to primes[] */
hashtable->buckets = malloc(num_buckets(hashtable) * sizeof(bucket_t));
if(!hashtable->buckets)
hashtable->order = INITIAL_HASHTABLE_ORDER;
hashtable->buckets = jsonp_malloc(hashsize(hashtable->order) * sizeof(bucket_t));
if (!hashtable->buckets)
return -1;
list_init(&hashtable->list);
list_init(&hashtable->ordered_list);
hashtable->hash_key = hash_key;
hashtable->cmp_keys = cmp_keys;
hashtable->free_key = free_key;
hashtable->free_value = free_value;
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
for (i = 0; i < hashsize(hashtable->order); i++) {
hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list;
}
return 0;
}
void hashtable_close(hashtable_t *hashtable)
{
void hashtable_close(hashtable_t *hashtable) {
hashtable_do_clear(hashtable);
free(hashtable->buckets);
jsonp_free(hashtable->buckets);
}
int hashtable_set(hashtable_t *hashtable, void *key, void *value)
{
static pair_t *init_pair(json_t *value, const char *key, size_t key_len, size_t hash) {
pair_t *pair;
/* offsetof(...) returns the size of pair_t without the last,
flexible member. This way, the correct amount is
allocated. */
if (key_len >= (size_t)-1 - offsetof(pair_t, key)) {
/* Avoid an overflow if the key is very long */
return NULL;
}
pair = jsonp_malloc(offsetof(pair_t, key) + key_len + 1);
if (!pair)
return NULL;
pair->hash = hash;
memcpy(pair->key, key, key_len);
pair->key[key_len] = '\0';
pair->key_len = key_len;
pair->value = value;
list_init(&pair->list);
list_init(&pair->ordered_list);
return pair;
}
int hashtable_set(hashtable_t *hashtable, const char *key, size_t key_len,
json_t *value) {
pair_t *pair;
bucket_t *bucket;
unsigned int hash, index;
size_t hash, index;
/* rehash if the load ratio exceeds 1 */
if(hashtable->size >= num_buckets(hashtable))
if(hashtable_do_rehash(hashtable))
if (hashtable->size >= hashsize(hashtable->order))
if (hashtable_do_rehash(hashtable))
return -1;
hash = hashtable->hash_key(key);
index = hash % num_buckets(hashtable);
hash = hash_str(key, key_len);
index = hash & hashmask(hashtable->order);
bucket = &hashtable->buckets[index];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
pair = hashtable_find_pair(hashtable, bucket, key, key_len, hash);
if(pair)
{
if(hashtable->free_key)
hashtable->free_key(key);
if(hashtable->free_value)
hashtable->free_value(pair->value);
if (pair) {
json_decref(pair->value);
pair->value = value;
}
else
{
pair = malloc(sizeof(pair_t));
if(!pair)
} else {
pair = init_pair(value, key, key_len, hash);
if (!pair)
return -1;
pair->key = key;
pair->value = value;
pair->hash = hash;
list_init(&pair->list);
insert_to_bucket(hashtable, bucket, &pair->list);
list_insert(&hashtable->ordered_list, &pair->ordered_list);
hashtable->size++;
}
return 0;
}
void *hashtable_get(hashtable_t *hashtable, const void *key)
{
void *hashtable_get(hashtable_t *hashtable, const char *key, size_t key_len) {
pair_t *pair;
unsigned int hash;
size_t hash;
bucket_t *bucket;
hash = hashtable->hash_key(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
hash = hash_str(key, key_len);
bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
pair = hashtable_find_pair(hashtable, bucket, key, key_len, hash);
if (!pair)
return NULL;
return pair->value;
}
int hashtable_del(hashtable_t *hashtable, const void *key)
{
unsigned int hash = hashtable->hash_key(key);
return hashtable_do_del(hashtable, key, hash);
int hashtable_del(hashtable_t *hashtable, const char *key, size_t key_len) {
size_t hash = hash_str(key, key_len);
return hashtable_do_del(hashtable, key, key_len, hash);
}
void hashtable_clear(hashtable_t *hashtable)
{
unsigned int i;
void hashtable_clear(hashtable_t *hashtable) {
size_t i;
hashtable_do_clear(hashtable);
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
for (i = 0; i < hashsize(hashtable->order); i++) {
hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list;
}
list_init(&hashtable->list);
list_init(&hashtable->ordered_list);
hashtable->size = 0;
}
void *hashtable_iter(hashtable_t *hashtable)
{
return hashtable_iter_next(hashtable, &hashtable->list);
void *hashtable_iter(hashtable_t *hashtable) {
return hashtable_iter_next(hashtable, &hashtable->ordered_list);
}
void *hashtable_iter_at(hashtable_t *hashtable, const void *key)
{
void *hashtable_iter_at(hashtable_t *hashtable, const char *key, size_t key_len) {
pair_t *pair;
unsigned int hash;
size_t hash;
bucket_t *bucket;
hash = hashtable->hash_key(key);
bucket = &hashtable->buckets[hash % num_buckets(hashtable)];
hash = hash_str(key, key_len);
bucket = &hashtable->buckets[hash & hashmask(hashtable->order)];
pair = hashtable_find_pair(hashtable, bucket, key, hash);
if(!pair)
pair = hashtable_find_pair(hashtable, bucket, key, key_len, hash);
if (!pair)
return NULL;
return &pair->list;
return &pair->ordered_list;
}
void *hashtable_iter_next(hashtable_t *hashtable, void *iter)
{
void *hashtable_iter_next(hashtable_t *hashtable, void *iter) {
list_t *list = (list_t *)iter;
if(list->next == &hashtable->list)
if (list->next == &hashtable->ordered_list)
return NULL;
return list->next;
}
void *hashtable_iter_key(void *iter)
{
pair_t *pair = list_to_pair((list_t *)iter);
void *hashtable_iter_key(void *iter) {
pair_t *pair = ordered_list_to_pair((list_t *)iter);
return pair->key;
}
void *hashtable_iter_value(void *iter)
{
pair_t *pair = list_to_pair((list_t *)iter);
size_t hashtable_iter_key_len(void *iter) {
pair_t *pair = ordered_list_to_pair((list_t *)iter);
return pair->key_len;
}
void *hashtable_iter_value(void *iter) {
pair_t *pair = ordered_list_to_pair((list_t *)iter);
return pair->value;
}
void hashtable_iter_set(hashtable_t *hashtable, void *iter, void *value)
{
pair_t *pair = list_to_pair((list_t *)iter);
if(hashtable->free_value)
hashtable->free_value(pair->value);
void hashtable_iter_set(void *iter, json_t *value) {
pair_t *pair = ordered_list_to_pair((list_t *)iter);
json_decref(pair->value);
pair->value = value;
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
@ -8,20 +8,24 @@
#ifndef HASHTABLE_H
#define HASHTABLE_H
typedef unsigned int (*key_hash_fn)(const void *key);
typedef int (*key_cmp_fn)(const void *key1, const void *key2);
typedef void (*free_fn)(void *key);
#include "jansson.h"
#include <stdlib.h>
struct hashtable_list {
struct hashtable_list *prev;
struct hashtable_list *next;
};
/* "pair" may be a bit confusing a name, but think of it as a
key-value pair. In this case, it just encodes some extra data,
too */
struct hashtable_pair {
void *key;
void *value;
unsigned int hash;
struct hashtable_list list;
struct hashtable_list ordered_list;
size_t hash;
json_t *value;
size_t key_len;
char key[1];
};
struct hashtable_bucket {
@ -30,60 +34,27 @@ struct hashtable_bucket {
};
typedef struct hashtable {
unsigned int size;
size_t size;
struct hashtable_bucket *buckets;
unsigned int num_buckets; /* index to primes[] */
size_t order; /* hashtable has pow(2, order) buckets */
struct hashtable_list list;
key_hash_fn hash_key;
key_cmp_fn cmp_keys; /* returns non-zero for equal keys */
free_fn free_key;
free_fn free_value;
struct hashtable_list ordered_list;
} hashtable_t;
/**
* hashtable_create - Create a hashtable object
*
* @hash_key: The key hashing function
* @cmp_keys: The key compare function. Returns non-zero for equal and
* zero for unequal unequal keys
* @free_key: If non-NULL, called for a key that is no longer referenced.
* @free_value: If non-NULL, called for a value that is no longer referenced.
*
* Returns a new hashtable object that should be freed with
* hashtable_destroy when it's no longer used, or NULL on failure (out
* of memory).
*/
hashtable_t *hashtable_create(key_hash_fn hash_key, key_cmp_fn cmp_keys,
free_fn free_key, free_fn free_value);
/**
* hashtable_destroy - Destroy a hashtable object
*
* @hashtable: The hashtable
*
* Destroys a hashtable created with hashtable_create().
*/
void hashtable_destroy(hashtable_t *hashtable);
#define hashtable_key_to_iter(key_) \
(&(container_of(key_, struct hashtable_pair, key)->ordered_list))
/**
* hashtable_init - Initialize a hashtable object
*
* @hashtable: The (statically allocated) hashtable object
* @hash_key: The key hashing function
* @cmp_keys: The key compare function. Returns non-zero for equal and
* zero for unequal unequal keys
* @free_key: If non-NULL, called for a key that is no longer referenced.
* @free_value: If non-NULL, called for a value that is no longer referenced.
*
* Initializes a statically allocated hashtable object. The object
* should be cleared with hashtable_close when it's no longer used.
*
* Returns 0 on success, -1 on error (out of memory).
*/
int hashtable_init(hashtable_t *hashtable,
key_hash_fn hash_key, key_cmp_fn cmp_keys,
free_fn free_key, free_fn free_value);
int hashtable_init(hashtable_t *hashtable) JANSSON_ATTRS((warn_unused_result));
/**
* hashtable_close - Release all resources used by a hashtable object
@ -99,40 +70,40 @@ void hashtable_close(hashtable_t *hashtable);
*
* @hashtable: The hashtable object
* @key: The key
* @key: The length of key
* @serial: For addition order of keys
* @value: The value
*
* If a value with the given key already exists, its value is replaced
* with the new value.
*
* Key and value are "stealed" in the sense that hashtable frees them
* automatically when they are no longer used. The freeing is
* accomplished by calling free_key and free_value functions that were
* supplied to hashtable_new. In case one or both of the free
* functions is NULL, the corresponding item is not "stealed".
* with the new value. Value is "stealed" in the sense that hashtable
* doesn't increment its refcount but decreases the refcount when the
* value is no longer needed.
*
* Returns 0 on success, -1 on failure (out of memory).
*/
int hashtable_set(hashtable_t *hashtable, void *key, void *value);
int hashtable_set(hashtable_t *hashtable, const char *key, size_t key_len, json_t *value);
/**
* hashtable_get - Get a value associated with a key
*
* @hashtable: The hashtable object
* @key: The key
* @key: The length of key
*
* Returns value if it is found, or NULL otherwise.
*/
void *hashtable_get(hashtable_t *hashtable, const void *key);
void *hashtable_get(hashtable_t *hashtable, const char *key, size_t key_len);
/**
* hashtable_del - Remove a value from the hashtable
*
* @hashtable: The hashtable object
* @key: The key
* @key: The length of key
*
* Returns 0 on success, or -1 if the key was not found.
*/
int hashtable_del(hashtable_t *hashtable, const void *key);
int hashtable_del(hashtable_t *hashtable, const char *key, size_t key_len);
/**
* hashtable_clear - Clear hashtable
@ -165,11 +136,12 @@ void *hashtable_iter(hashtable_t *hashtable);
*
* @hashtable: The hashtable object
* @key: The key that the iterator should point to
* @key: The length of key
*
* Like hashtable_iter() but returns an iterator pointing to a
* specific key.
*/
void *hashtable_iter_at(hashtable_t *hashtable, const void *key);
void *hashtable_iter_at(hashtable_t *hashtable, const char *key, size_t key_len);
/**
* hashtable_iter_next - Advance an iterator
@ -189,6 +161,13 @@ void *hashtable_iter_next(hashtable_t *hashtable, void *iter);
*/
void *hashtable_iter_key(void *iter);
/**
* hashtable_iter_key_len - Retrieve the key length pointed by an iterator
*
* @iter: The iterator
*/
size_t hashtable_iter_key_len(void *iter);
/**
* hashtable_iter_value - Retrieve the value pointed by an iterator
*
@ -202,6 +181,6 @@ void *hashtable_iter_value(void *iter);
* @iter: The iterator
* @value: The value to set
*/
void hashtable_iter_set(hashtable_t *hashtable, void *iter, void *value);
void hashtable_iter_set(void *iter, json_t *value);
#endif

277
src/hashtable_seed.c Normal file
View file

@ -0,0 +1,277 @@
/* Generate sizeof(uint32_t) bytes of as random data as possible to seed
the hash function.
*/
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
#include <stdio.h>
#include <time.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_SCHED_H
#include <sched.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if defined(_WIN32)
/* For GetModuleHandle(), GetProcAddress() and GetCurrentProcessId() */
#include <windows.h>
#endif
#include "jansson.h"
static uint32_t buf_to_uint32(char *data) {
size_t i;
uint32_t result = 0;
for (i = 0; i < sizeof(uint32_t); i++)
result = (result << 8) | (unsigned char)data[i];
return result;
}
/* /dev/urandom */
#if !defined(_WIN32) && defined(USE_URANDOM)
static int seed_from_urandom(uint32_t *seed) {
/* Use unbuffered I/O if we have open(), close() and read(). Otherwise
fall back to fopen() */
char data[sizeof(uint32_t)];
int ok;
#if defined(HAVE_OPEN) && defined(HAVE_CLOSE) && defined(HAVE_READ)
int urandom;
urandom = open("/dev/urandom", O_RDONLY);
if (urandom == -1)
return 1;
ok = read(urandom, data, sizeof(uint32_t)) == sizeof(uint32_t);
close(urandom);
#else
FILE *urandom;
urandom = fopen("/dev/urandom", "rb");
if (!urandom)
return 1;
ok = fread(data, 1, sizeof(uint32_t), urandom) == sizeof(uint32_t);
fclose(urandom);
#endif
if (!ok)
return 1;
*seed = buf_to_uint32(data);
return 0;
}
#endif
/* Windows Crypto API */
#if defined(_WIN32) && defined(USE_WINDOWS_CRYPTOAPI)
#include <wincrypt.h>
typedef BOOL(WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv, LPCSTR pszContainer,
LPCSTR pszProvider, DWORD dwProvType,
DWORD dwFlags);
typedef BOOL(WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen, BYTE *pbBuffer);
typedef BOOL(WINAPI *CRYPTRELEASECONTEXT)(HCRYPTPROV hProv, DWORD dwFlags);
static int seed_from_windows_cryptoapi(uint32_t *seed) {
HINSTANCE hAdvAPI32 = NULL;
CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;
CRYPTGENRANDOM pCryptGenRandom = NULL;
CRYPTRELEASECONTEXT pCryptReleaseContext = NULL;
HCRYPTPROV hCryptProv = 0;
BYTE data[sizeof(uint32_t)];
int ok;
hAdvAPI32 = GetModuleHandle(TEXT("advapi32.dll"));
if (hAdvAPI32 == NULL)
return 1;
pCryptAcquireContext =
(CRYPTACQUIRECONTEXTA)GetProcAddress(hAdvAPI32, "CryptAcquireContextA");
if (!pCryptAcquireContext)
return 1;
pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(hAdvAPI32, "CryptGenRandom");
if (!pCryptGenRandom)
return 1;
pCryptReleaseContext =
(CRYPTRELEASECONTEXT)GetProcAddress(hAdvAPI32, "CryptReleaseContext");
if (!pCryptReleaseContext)
return 1;
if (!pCryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
return 1;
ok = pCryptGenRandom(hCryptProv, sizeof(uint32_t), data);
pCryptReleaseContext(hCryptProv, 0);
if (!ok)
return 1;
*seed = buf_to_uint32((char *)data);
return 0;
}
#endif
/* gettimeofday() and getpid() */
static int seed_from_timestamp_and_pid(uint32_t *seed) {
#ifdef HAVE_GETTIMEOFDAY
/* XOR of seconds and microseconds */
struct timeval tv;
gettimeofday(&tv, NULL);
*seed = (uint32_t)tv.tv_sec ^ (uint32_t)tv.tv_usec;
#else
/* Seconds only */
*seed = (uint32_t)time(NULL);
#endif
/* XOR with PID for more randomness */
#if defined(_WIN32)
*seed ^= (uint32_t)GetCurrentProcessId();
#elif defined(HAVE_GETPID)
*seed ^= (uint32_t)getpid();
#endif
return 0;
}
static uint32_t generate_seed() {
uint32_t seed = 0;
int done = 0;
#if !defined(_WIN32) && defined(USE_URANDOM)
if (seed_from_urandom(&seed) == 0)
done = 1;
#endif
#if defined(_WIN32) && defined(USE_WINDOWS_CRYPTOAPI)
if (seed_from_windows_cryptoapi(&seed) == 0)
done = 1;
#endif
if (!done) {
/* Fall back to timestamp and PID if no better randomness is
available */
seed_from_timestamp_and_pid(&seed);
}
/* Make sure the seed is never zero */
if (seed == 0)
seed = 1;
return seed;
}
volatile uint32_t hashtable_seed = 0;
#if defined(HAVE_ATOMIC_BUILTINS) && (defined(HAVE_SCHED_YIELD) || !defined(_WIN32))
static volatile char seed_initialized = 0;
void json_object_seed(size_t seed) {
uint32_t new_seed = (uint32_t)seed;
if (hashtable_seed == 0) {
if (__atomic_test_and_set(&seed_initialized, __ATOMIC_RELAXED) == 0) {
/* Do the seeding ourselves */
if (new_seed == 0)
new_seed = generate_seed();
__atomic_store_n(&hashtable_seed, new_seed, __ATOMIC_RELEASE);
} else {
/* Wait for another thread to do the seeding */
do {
#ifdef HAVE_SCHED_YIELD
sched_yield();
#endif
} while (__atomic_load_n(&hashtable_seed, __ATOMIC_ACQUIRE) == 0);
}
}
}
#elif defined(HAVE_SYNC_BUILTINS) && (defined(HAVE_SCHED_YIELD) || !defined(_WIN32))
void json_object_seed(size_t seed) {
uint32_t new_seed = (uint32_t)seed;
if (hashtable_seed == 0) {
if (new_seed == 0) {
/* Explicit synchronization fences are not supported by the
__sync builtins, so every thread getting here has to
generate the seed value.
*/
new_seed = generate_seed();
}
do {
if (__sync_bool_compare_and_swap(&hashtable_seed, 0, new_seed)) {
/* We were the first to seed */
break;
} else {
/* Wait for another thread to do the seeding */
#ifdef HAVE_SCHED_YIELD
sched_yield();
#endif
}
} while (hashtable_seed == 0);
}
}
#elif defined(_WIN32)
static long seed_initialized = 0;
void json_object_seed(size_t seed) {
uint32_t new_seed = (uint32_t)seed;
if (hashtable_seed == 0) {
if (InterlockedIncrement(&seed_initialized) == 1) {
/* Do the seeding ourselves */
if (new_seed == 0)
new_seed = generate_seed();
hashtable_seed = new_seed;
} else {
/* Wait for another thread to do the seeding */
do {
SwitchToThread();
} while (hashtable_seed == 0);
}
}
}
#else
/* Fall back to a thread-unsafe version */
void json_object_seed(size_t seed) {
uint32_t new_seed = (uint32_t)seed;
if (hashtable_seed == 0) {
if (new_seed == 0)
new_seed = generate_seed();
hashtable_seed = new_seed;
}
}
#endif

83
src/jansson.def Normal file
View file

@ -0,0 +1,83 @@
EXPORTS
json_delete
json_true
json_false
json_null
json_sprintf
json_vsprintf
json_string
json_stringn
json_string_nocheck
json_stringn_nocheck
json_string_value
json_string_length
json_string_set
json_string_setn
json_string_set_nocheck
json_string_setn_nocheck
json_integer
json_integer_value
json_integer_set
json_real
json_real_value
json_real_set
json_number_value
json_array
json_array_size
json_array_get
json_array_set_new
json_array_append_new
json_array_insert_new
json_array_remove
json_array_clear
json_array_extend
json_object
json_object_size
json_object_get
json_object_getn
json_object_set_new
json_object_setn_new
json_object_set_new_nocheck
json_object_setn_new_nocheck
json_object_del
json_object_deln
json_object_clear
json_object_update
json_object_update_existing
json_object_update_missing
json_object_update_recursive
json_object_iter
json_object_iter_at
json_object_iter_next
json_object_iter_key
json_object_iter_key_len
json_object_iter_value
json_object_iter_set_new
json_object_key_to_iter
json_object_seed
json_dumps
json_dumpb
json_dumpf
json_dumpfd
json_dump_file
json_dump_callback
json_loads
json_loadb
json_loadf
json_loadfd
json_load_file
json_load_callback
json_equal
json_copy
json_deep_copy
json_pack
json_pack_ex
json_vpack_ex
json_unpack
json_unpack_ex
json_vunpack_ex
json_set_alloc_funcs
json_get_alloc_funcs
jansson_version_str
jansson_version_cmp

419
src/jansson.h Normal file
View file

@ -0,0 +1,419 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef JANSSON_H
#define JANSSON_H
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> /* for size_t */
#include "jansson_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/* version */
#define JANSSON_MAJOR_VERSION 2
#define JANSSON_MINOR_VERSION 14
#define JANSSON_MICRO_VERSION 1
/* Micro version is omitted if it's 0 */
#define JANSSON_VERSION "2.14.1"
/* Version as a 3-byte hex number, e.g. 0x010201 == 1.2.1. Use this
for numeric comparisons, e.g. #if JANSSON_VERSION_HEX >= ... */
#define JANSSON_VERSION_HEX \
((JANSSON_MAJOR_VERSION << 16) | (JANSSON_MINOR_VERSION << 8) | \
(JANSSON_MICRO_VERSION << 0))
/* If __atomic or __sync builtins are available the library is thread
* safe for all read-only functions plus reference counting. */
#if JSON_HAVE_ATOMIC_BUILTINS || JSON_HAVE_SYNC_BUILTINS
#define JANSSON_THREAD_SAFE_REFCOUNT 1
#endif
#if defined(__GNUC__) || defined(__clang__)
#define JANSSON_ATTRS(x) __attribute__(x)
#else
#define JANSSON_ATTRS(x)
#endif
/* types */
typedef enum {
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_INTEGER,
JSON_REAL,
JSON_TRUE,
JSON_FALSE,
JSON_NULL
} json_type;
typedef struct json_t {
json_type type;
volatile size_t refcount;
} json_t;
#ifndef JANSSON_USING_CMAKE /* disabled if using cmake */
#if JSON_INTEGER_IS_LONG_LONG
#ifdef _WIN32
#define JSON_INTEGER_FORMAT "I64d"
#else
#define JSON_INTEGER_FORMAT "lld"
#endif
typedef long long json_int_t;
#else
#define JSON_INTEGER_FORMAT "ld"
typedef long json_int_t;
#endif /* JSON_INTEGER_IS_LONG_LONG */
#endif
#define json_typeof(json) ((json)->type)
#define json_is_object(json) ((json) && json_typeof(json) == JSON_OBJECT)
#define json_is_array(json) ((json) && json_typeof(json) == JSON_ARRAY)
#define json_is_string(json) ((json) && json_typeof(json) == JSON_STRING)
#define json_is_integer(json) ((json) && json_typeof(json) == JSON_INTEGER)
#define json_is_real(json) ((json) && json_typeof(json) == JSON_REAL)
#define json_is_number(json) (json_is_integer(json) || json_is_real(json))
#define json_is_true(json) ((json) && json_typeof(json) == JSON_TRUE)
#define json_is_false(json) ((json) && json_typeof(json) == JSON_FALSE)
#define json_boolean_value json_is_true
#define json_is_boolean(json) (json_is_true(json) || json_is_false(json))
#define json_is_null(json) ((json) && json_typeof(json) == JSON_NULL)
/* construction, destruction, reference counting */
json_t *json_object(void);
json_t *json_array(void);
json_t *json_string(const char *value);
json_t *json_stringn(const char *value, size_t len);
json_t *json_string_nocheck(const char *value);
json_t *json_stringn_nocheck(const char *value, size_t len);
json_t *json_integer(json_int_t value);
json_t *json_real(double value);
json_t *json_true(void);
json_t *json_false(void);
#define json_boolean(val) ((val) ? json_true() : json_false())
json_t *json_null(void);
/* do not call JSON_INTERNAL_INCREF or JSON_INTERNAL_DECREF directly */
#if JSON_HAVE_ATOMIC_BUILTINS
#define JSON_INTERNAL_INCREF(json) \
__atomic_add_fetch(&json->refcount, 1, __ATOMIC_ACQUIRE)
#define JSON_INTERNAL_DECREF(json) \
__atomic_sub_fetch(&json->refcount, 1, __ATOMIC_RELEASE)
#elif JSON_HAVE_SYNC_BUILTINS
#define JSON_INTERNAL_INCREF(json) __sync_add_and_fetch(&json->refcount, 1)
#define JSON_INTERNAL_DECREF(json) __sync_sub_and_fetch(&json->refcount, 1)
#else
#define JSON_INTERNAL_INCREF(json) (++json->refcount)
#define JSON_INTERNAL_DECREF(json) (--json->refcount)
#endif
static JSON_INLINE json_t *json_incref(json_t *json) {
if (json && json->refcount != (size_t)-1)
JSON_INTERNAL_INCREF(json);
return json;
}
/* do not call json_delete directly */
void json_delete(json_t *json);
static JSON_INLINE void json_decref(json_t *json) {
if (json && json->refcount != (size_t)-1 && JSON_INTERNAL_DECREF(json) == 0)
json_delete(json);
}
#if defined(__GNUC__) || defined(__clang__)
static JSON_INLINE void json_decrefp(json_t **json) {
if (json) {
json_decref(*json);
*json = NULL;
}
}
#define json_auto_t json_t __attribute__((cleanup(json_decrefp)))
#endif
/* error reporting */
#define JSON_ERROR_TEXT_LENGTH 160
#define JSON_ERROR_SOURCE_LENGTH 80
typedef struct json_error_t {
int line;
int column;
int position;
char source[JSON_ERROR_SOURCE_LENGTH];
char text[JSON_ERROR_TEXT_LENGTH];
} json_error_t;
enum json_error_code {
json_error_unknown,
json_error_out_of_memory,
json_error_stack_overflow,
json_error_cannot_open_file,
json_error_invalid_argument,
json_error_invalid_utf8,
json_error_premature_end_of_input,
json_error_end_of_input_expected,
json_error_invalid_syntax,
json_error_invalid_format,
json_error_wrong_type,
json_error_null_character,
json_error_null_value,
json_error_null_byte_in_key,
json_error_duplicate_key,
json_error_numeric_overflow,
json_error_item_not_found,
json_error_index_out_of_range
};
static JSON_INLINE enum json_error_code json_error_code(const json_error_t *e) {
return (enum json_error_code)e->text[JSON_ERROR_TEXT_LENGTH - 1];
}
/* getters, setters, manipulation */
void json_object_seed(size_t seed);
size_t json_object_size(const json_t *object);
json_t *json_object_get(const json_t *object, const char *key)
JANSSON_ATTRS((warn_unused_result));
json_t *json_object_getn(const json_t *object, const char *key, size_t key_len)
JANSSON_ATTRS((warn_unused_result));
int json_object_set_new(json_t *object, const char *key, json_t *value);
int json_object_setn_new(json_t *object, const char *key, size_t key_len, json_t *value);
int json_object_set_new_nocheck(json_t *object, const char *key, json_t *value);
int json_object_setn_new_nocheck(json_t *object, const char *key, size_t key_len,
json_t *value);
int json_object_del(json_t *object, const char *key);
int json_object_deln(json_t *object, const char *key, size_t key_len);
int json_object_clear(json_t *object);
int json_object_update(json_t *object, json_t *other);
int json_object_update_existing(json_t *object, json_t *other);
int json_object_update_missing(json_t *object, json_t *other);
int json_object_update_recursive(json_t *object, json_t *other);
void *json_object_iter(json_t *object);
void *json_object_iter_at(json_t *object, const char *key);
void *json_object_key_to_iter(const char *key);
void *json_object_iter_next(json_t *object, void *iter);
const char *json_object_iter_key(void *iter);
size_t json_object_iter_key_len(void *iter);
json_t *json_object_iter_value(void *iter);
int json_object_iter_set_new(json_t *object, void *iter, json_t *value);
#define json_object_foreach(object, key, value) \
for (key = json_object_iter_key(json_object_iter(object)); \
key && (value = json_object_iter_value(json_object_key_to_iter(key))); \
key = json_object_iter_key( \
json_object_iter_next(object, json_object_key_to_iter(key))))
#define json_object_keylen_foreach(object, key, key_len, value) \
for (key = json_object_iter_key(json_object_iter(object)), \
key_len = json_object_iter_key_len(json_object_key_to_iter(key)); \
key && (value = json_object_iter_value(json_object_key_to_iter(key))); \
key = json_object_iter_key( \
json_object_iter_next(object, json_object_key_to_iter(key))), \
key_len = json_object_iter_key_len(json_object_key_to_iter(key)))
#define json_object_foreach_safe(object, n, key, value) \
for (key = json_object_iter_key(json_object_iter(object)), \
n = json_object_iter_next(object, json_object_key_to_iter(key)); \
key && (value = json_object_iter_value(json_object_key_to_iter(key))); \
key = json_object_iter_key(n), \
n = json_object_iter_next(object, json_object_key_to_iter(key)))
#define json_object_keylen_foreach_safe(object, n, key, key_len, value) \
for (key = json_object_iter_key(json_object_iter(object)), \
n = json_object_iter_next(object, json_object_key_to_iter(key)), \
key_len = json_object_iter_key_len(json_object_key_to_iter(key)); \
key && (value = json_object_iter_value(json_object_key_to_iter(key))); \
key = json_object_iter_key(n), key_len = json_object_iter_key_len(n), \
n = json_object_iter_next(object, json_object_key_to_iter(key)))
#define json_array_foreach(array, index, value) \
for (index = 0; \
index < json_array_size(array) && (value = json_array_get(array, index)); \
index++)
static JSON_INLINE int json_object_set(json_t *object, const char *key, json_t *value) {
return json_object_set_new(object, key, json_incref(value));
}
static JSON_INLINE int json_object_setn(json_t *object, const char *key, size_t key_len,
json_t *value) {
return json_object_setn_new(object, key, key_len, json_incref(value));
}
static JSON_INLINE int json_object_set_nocheck(json_t *object, const char *key,
json_t *value) {
return json_object_set_new_nocheck(object, key, json_incref(value));
}
static JSON_INLINE int json_object_setn_nocheck(json_t *object, const char *key,
size_t key_len, json_t *value) {
return json_object_setn_new_nocheck(object, key, key_len, json_incref(value));
}
static JSON_INLINE int json_object_iter_set(json_t *object, void *iter, json_t *value) {
return json_object_iter_set_new(object, iter, json_incref(value));
}
static JSON_INLINE int json_object_update_new(json_t *object, json_t *other) {
int ret = json_object_update(object, other);
json_decref(other);
return ret;
}
static JSON_INLINE int json_object_update_existing_new(json_t *object, json_t *other) {
int ret = json_object_update_existing(object, other);
json_decref(other);
return ret;
}
static JSON_INLINE int json_object_update_missing_new(json_t *object, json_t *other) {
int ret = json_object_update_missing(object, other);
json_decref(other);
return ret;
}
size_t json_array_size(const json_t *array);
json_t *json_array_get(const json_t *array, size_t index)
JANSSON_ATTRS((warn_unused_result));
int json_array_set_new(json_t *array, size_t index, json_t *value);
int json_array_append_new(json_t *array, json_t *value);
int json_array_insert_new(json_t *array, size_t index, json_t *value);
int json_array_remove(json_t *array, size_t index);
int json_array_clear(json_t *array);
int json_array_extend(json_t *array, json_t *other);
static JSON_INLINE int json_array_set(json_t *array, size_t ind, json_t *value) {
return json_array_set_new(array, ind, json_incref(value));
}
static JSON_INLINE int json_array_append(json_t *array, json_t *value) {
return json_array_append_new(array, json_incref(value));
}
static JSON_INLINE int json_array_insert(json_t *array, size_t ind, json_t *value) {
return json_array_insert_new(array, ind, json_incref(value));
}
const char *json_string_value(const json_t *string);
size_t json_string_length(const json_t *string);
json_int_t json_integer_value(const json_t *integer);
double json_real_value(const json_t *real);
double json_number_value(const json_t *json);
int json_string_set(json_t *string, const char *value);
int json_string_setn(json_t *string, const char *value, size_t len);
int json_string_set_nocheck(json_t *string, const char *value);
int json_string_setn_nocheck(json_t *string, const char *value, size_t len);
int json_integer_set(json_t *integer, json_int_t value);
int json_real_set(json_t *real, double value);
/* pack, unpack */
json_t *json_pack(const char *fmt, ...) JANSSON_ATTRS((warn_unused_result));
json_t *json_pack_ex(json_error_t *error, size_t flags, const char *fmt, ...)
JANSSON_ATTRS((warn_unused_result));
json_t *json_vpack_ex(json_error_t *error, size_t flags, const char *fmt, va_list ap)
JANSSON_ATTRS((warn_unused_result));
#define JSON_VALIDATE_ONLY 0x1
#define JSON_STRICT 0x2
int json_unpack(json_t *root, const char *fmt, ...);
int json_unpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt, ...);
int json_vunpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt,
va_list ap);
/* sprintf */
json_t *json_sprintf(const char *fmt, ...)
JANSSON_ATTRS((warn_unused_result, format(printf, 1, 2)));
json_t *json_vsprintf(const char *fmt, va_list ap)
JANSSON_ATTRS((warn_unused_result, format(printf, 1, 0)));
/* equality */
int json_equal(const json_t *value1, const json_t *value2);
/* copying */
json_t *json_copy(json_t *value) JANSSON_ATTRS((warn_unused_result));
json_t *json_deep_copy(const json_t *value) JANSSON_ATTRS((warn_unused_result));
/* decoding */
#define JSON_REJECT_DUPLICATES 0x1
#define JSON_DISABLE_EOF_CHECK 0x2
#define JSON_DECODE_ANY 0x4
#define JSON_DECODE_INT_AS_REAL 0x8
#define JSON_ALLOW_NUL 0x10
typedef size_t (*json_load_callback_t)(void *buffer, size_t buflen, void *data);
json_t *json_loads(const char *input, size_t flags, json_error_t *error)
JANSSON_ATTRS((warn_unused_result));
json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error)
JANSSON_ATTRS((warn_unused_result));
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error)
JANSSON_ATTRS((warn_unused_result));
json_t *json_loadfd(int input, size_t flags, json_error_t *error)
JANSSON_ATTRS((warn_unused_result));
json_t *json_load_file(const char *path, size_t flags, json_error_t *error)
JANSSON_ATTRS((warn_unused_result));
json_t *json_load_callback(json_load_callback_t callback, void *data, size_t flags,
json_error_t *error) JANSSON_ATTRS((warn_unused_result));
/* encoding */
#define JSON_MAX_INDENT 0x1F
#define JSON_INDENT(n) ((n) & JSON_MAX_INDENT)
#define JSON_COMPACT 0x20
#define JSON_ENSURE_ASCII 0x40
#define JSON_SORT_KEYS 0x80
#define JSON_PRESERVE_ORDER 0x100
#define JSON_ENCODE_ANY 0x200
#define JSON_ESCAPE_SLASH 0x400
#define JSON_REAL_PRECISION(n) (((n) & 0x1F) << 11)
#define JSON_EMBED 0x10000
typedef int (*json_dump_callback_t)(const char *buffer, size_t size, void *data);
char *json_dumps(const json_t *json, size_t flags) JANSSON_ATTRS((warn_unused_result));
size_t json_dumpb(const json_t *json, char *buffer, size_t size, size_t flags);
int json_dumpf(const json_t *json, FILE *output, size_t flags);
int json_dumpfd(const json_t *json, int output, size_t flags);
int json_dump_file(const json_t *json, const char *path, size_t flags);
int json_dump_callback(const json_t *json, json_dump_callback_t callback, void *data,
size_t flags);
/* custom memory allocation */
typedef void *(*json_malloc_t)(size_t);
typedef void (*json_free_t)(void *);
void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn);
void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn);
/* runtime version checking */
const char *jansson_version_str(void);
int jansson_version_cmp(int major, int minor, int micro);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -1,191 +0,0 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef JANSSON_H
#define JANSSON_H
#include <stdio.h>
#ifndef __cplusplus
#define JSON_INLINE @json_inline@
#else
#define JSON_INLINE inline
extern "C" {
#endif
/* types */
typedef enum {
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_INTEGER,
JSON_REAL,
JSON_TRUE,
JSON_FALSE,
JSON_NULL
} json_type;
typedef struct {
json_type type;
unsigned long refcount;
} json_t;
#define json_typeof(json) ((json)->type)
#define json_is_object(json) (json && json_typeof(json) == JSON_OBJECT)
#define json_is_array(json) (json && json_typeof(json) == JSON_ARRAY)
#define json_is_string(json) (json && json_typeof(json) == JSON_STRING)
#define json_is_integer(json) (json && json_typeof(json) == JSON_INTEGER)
#define json_is_real(json) (json && json_typeof(json) == JSON_REAL)
#define json_is_number(json) (json_is_integer(json) || json_is_real(json))
#define json_is_true(json) (json && json_typeof(json) == JSON_TRUE)
#define json_is_false(json) (json && json_typeof(json) == JSON_FALSE)
#define json_is_boolean(json) (json_is_true(json) || json_is_false(json))
#define json_is_null(json) (json && json_typeof(json) == JSON_NULL)
/* construction, destruction, reference counting */
json_t *json_object(void);
json_t *json_array(void);
json_t *json_string(const char *value);
json_t *json_string_nocheck(const char *value);
json_t *json_integer(int value);
json_t *json_real(double value);
json_t *json_true(void);
json_t *json_false(void);
json_t *json_null(void);
static JSON_INLINE
json_t *json_incref(json_t *json)
{
if(json && json->refcount != (unsigned int)-1)
++json->refcount;
return json;
}
/* do not call json_delete directly */
void json_delete(json_t *json);
static JSON_INLINE
void json_decref(json_t *json)
{
if(json && json->refcount != (unsigned int)-1 && --json->refcount == 0)
json_delete(json);
}
/* getters, setters, manipulation */
unsigned int json_object_size(const json_t *object);
json_t *json_object_get(const json_t *object, const char *key);
int json_object_set_new(json_t *object, const char *key, json_t *value);
int json_object_set_new_nocheck(json_t *object, const char *key, json_t *value);
int json_object_del(json_t *object, const char *key);
int json_object_clear(json_t *object);
int json_object_update(json_t *object, json_t *other);
void *json_object_iter(json_t *object);
void *json_object_iter_at(json_t *object, const char *key);
void *json_object_iter_next(json_t *object, void *iter);
const char *json_object_iter_key(void *iter);
json_t *json_object_iter_value(void *iter);
int json_object_iter_set_new(json_t *object, void *iter, json_t *value);
static JSON_INLINE
int json_object_set(json_t *object, const char *key, json_t *value)
{
return json_object_set_new(object, key, json_incref(value));
}
static JSON_INLINE
int json_object_set_nocheck(json_t *object, const char *key, json_t *value)
{
return json_object_set_new_nocheck(object, key, json_incref(value));
}
static inline
int json_object_iter_set(json_t *object, void *iter, json_t *value)
{
return json_object_iter_set_new(object, iter, json_incref(value));
}
unsigned int json_array_size(const json_t *array);
json_t *json_array_get(const json_t *array, unsigned int index);
int json_array_set_new(json_t *array, unsigned int index, json_t *value);
int json_array_append_new(json_t *array, json_t *value);
int json_array_insert_new(json_t *array, unsigned int index, json_t *value);
int json_array_remove(json_t *array, unsigned int index);
int json_array_clear(json_t *array);
int json_array_extend(json_t *array, json_t *other);
static JSON_INLINE
int json_array_set(json_t *array, unsigned int index, json_t *value)
{
return json_array_set_new(array, index, json_incref(value));
}
static JSON_INLINE
int json_array_append(json_t *array, json_t *value)
{
return json_array_append_new(array, json_incref(value));
}
static JSON_INLINE
int json_array_insert(json_t *array, unsigned int index, json_t *value)
{
return json_array_insert_new(array, index, json_incref(value));
}
const char *json_string_value(const json_t *string);
int json_integer_value(const json_t *integer);
double json_real_value(const json_t *real);
double json_number_value(const json_t *json);
int json_string_set(json_t *string, const char *value);
int json_string_set_nocheck(json_t *string, const char *value);
int json_integer_set(json_t *integer, int value);
int json_real_set(json_t *real, double value);
/* equality */
int json_equal(json_t *value1, json_t *value2);
/* copying */
json_t *json_copy(json_t *value);
json_t *json_deep_copy(json_t *value);
/* loading, printing */
#define JSON_ERROR_TEXT_LENGTH 160
typedef struct {
char text[JSON_ERROR_TEXT_LENGTH];
int line;
} json_error_t;
json_t *json_loads(const char *input, json_error_t *error);
json_t *json_loadf(FILE *input, json_error_t *error);
json_t *json_load_file(const char *path, json_error_t *error);
#define JSON_INDENT(n) (n & 0xFF)
#define JSON_COMPACT 0x100
#define JSON_ENSURE_ASCII 0x200
#define JSON_SORT_KEYS 0x400
#define JSON_PRESERVE_ORDER 0x800
char *json_dumps(const json_t *json, unsigned long flags);
int json_dumpf(const json_t *json, FILE *output, unsigned long flags);
int json_dump_file(const json_t *json, const char *path, unsigned long flags);
#ifdef __cplusplus
}
#endif
#endif

47
src/jansson_config.h.in Normal file
View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2010-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*
*
* This file specifies a part of the site-specific configuration for
* Jansson, namely those things that affect the public API in
* jansson.h.
*
* The configure script copies this file to jansson_config.h and
* replaces @var@ substitutions by values that fit your system. If you
* cannot run the configure script, you can do the value substitution
* by hand.
*/
#ifndef JANSSON_CONFIG_H
#define JANSSON_CONFIG_H
/* If your compiler supports the inline keyword in C, JSON_INLINE is
defined to `inline', otherwise empty. In C++, the inline is always
supported. */
#ifdef __cplusplus
#define JSON_INLINE inline
#else
#define JSON_INLINE @json_inline@
#endif
/* If your compiler supports the `long long` type and the strtoll()
library function, JSON_INTEGER_IS_LONG_LONG is defined to 1,
otherwise to 0. */
#define JSON_INTEGER_IS_LONG_LONG @json_have_long_long@
/* If __atomic builtins are available they will be used to manage
reference counts of json_t. */
#define JSON_HAVE_ATOMIC_BUILTINS @json_have_atomic_builtins@
/* If __atomic builtins are not available we try using __sync builtins
to manage reference counts of json_t. */
#define JSON_HAVE_SYNC_BUILTINS @json_have_sync_builtins@
/* Maximum recursion depth for parsing JSON input.
This limits the depth of e.g. array-within-array constructions. */
#define JSON_PARSER_MAX_DEPTH 2048
#endif

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
@ -8,30 +8,46 @@
#ifndef JANSSON_PRIVATE_H
#define JANSSON_PRIVATE_H
#include "jansson.h"
#include "hashtable.h"
#include "jansson.h"
#include "jansson_private_config.h"
#include "strbuffer.h"
#include <stddef.h>
#define container_of(ptr_, type_, member_) \
((type_ *)((char *)ptr_ - (size_t)&((type_ *)0)->member_))
#define container_of(ptr_, type_, member_) \
((type_ *)((char *)ptr_ - offsetof(type_, member_)))
/* On some platforms, max() may already be defined */
#ifndef max
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif
/* va_copy is a C99 feature. In C89 implementations, it's sometimes
available as __va_copy. If not, memcpy() should do the trick. */
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(a, b) memcpy(&(a), &(b), sizeof(va_list))
#endif
#endif
typedef struct {
json_t json;
hashtable_t hashtable;
unsigned long serial;
int visited;
} json_object_t;
typedef struct {
json_t json;
unsigned int size;
unsigned int entries;
size_t size;
size_t entries;
json_t **table;
int visited;
} json_array_t;
typedef struct {
json_t json;
char *value;
size_t length;
} json_string_t;
typedef struct {
@ -41,20 +57,58 @@ typedef struct {
typedef struct {
json_t json;
int value;
json_int_t value;
} json_integer_t;
#define json_to_object(json_) container_of(json_, json_object_t, json)
#define json_to_array(json_) container_of(json_, json_array_t, json)
#define json_to_string(json_) container_of(json_, json_string_t, json)
#define json_to_real(json_) container_of(json_, json_real_t, json)
#define json_to_real(json_) container_of(json_, json_real_t, json)
#define json_to_integer(json_) container_of(json_, json_integer_t, json)
typedef struct {
unsigned long serial;
char key[];
} object_key_t;
/* Create a string by taking ownership of an existing buffer */
json_t *jsonp_stringn_nocheck_own(const char *value, size_t len);
const object_key_t *jsonp_object_iter_fullkey(void *iter);
/* Error message formatting */
void jsonp_error_init(json_error_t *error, const char *source);
void jsonp_error_set_source(json_error_t *error, const char *source);
void jsonp_error_set(json_error_t *error, int line, int column, size_t position,
enum json_error_code code, const char *msg, ...);
void jsonp_error_vset(json_error_t *error, int line, int column, size_t position,
enum json_error_code code, const char *msg, va_list ap);
/* Locale independent string<->double conversions */
int jsonp_strtod(strbuffer_t *strbuffer, double *out);
int jsonp_dtostr(char *buffer, size_t size, double value, int prec);
/* Wrappers for custom memory functions */
void *jsonp_malloc(size_t size) JANSSON_ATTRS((warn_unused_result));
void jsonp_free(void *ptr);
char *jsonp_strndup(const char *str, size_t length) JANSSON_ATTRS((warn_unused_result));
char *jsonp_strdup(const char *str) JANSSON_ATTRS((warn_unused_result));
char *jsonp_strndup(const char *str, size_t len) JANSSON_ATTRS((warn_unused_result));
/* Circular reference check*/
/* Space for "0x", double the sizeof a pointer for the hex and a terminator. */
#define LOOP_KEY_LEN (2 + (sizeof(json_t *) * 2) + 1)
int jsonp_loop_check(hashtable_t *parents, const json_t *json, char *key, size_t key_size,
size_t *key_len_out);
/* Windows compatibility */
#if defined(_WIN32) || defined(WIN32)
#if defined(_MSC_VER) /* MS compiller */
#if (_MSC_VER < 1900) && \
!defined(snprintf) /* snprintf not defined yet & not introduced */
#define snprintf _snprintf
#endif
#if (_MSC_VER < 1500) && \
!defined(vsnprintf) /* vsnprintf not defined yet & not introduced */
#define vsnprintf(b, c, f, a) _vsnprintf(b, c, f, a)
#endif
#else /* Other Windows compiller, old definition */
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
#endif
#endif

1077
src/load.c

File diff suppressed because it is too large Load diff

382
src/lookup3.h Normal file
View file

@ -0,0 +1,382 @@
// clang-format off
/*
-------------------------------------------------------------------------------
lookup3.c, by Bob Jenkins, May 2006, Public Domain.
These are functions for producing 32-bit hashes for hash table lookup.
hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
are externally useful functions. Routines to test the hash are included
if SELF_TEST is defined. You can use this free for any purpose. It's in
the public domain. It has no warranty.
You probably want to use hashlittle(). hashlittle() and hashbig()
hash byte arrays. hashlittle() is is faster than hashbig() on
little-endian machines. Intel and AMD are little-endian machines.
On second thought, you probably want hashlittle2(), which is identical to
hashlittle() except it returns two 32-bit hashes for the price of one.
You could implement hashbig2() if you wanted but I haven't bothered here.
If you want to find a hash of, say, exactly 7 integers, do
a = i1; b = i2; c = i3;
mix(a,b,c);
a += i4; b += i5; c += i6;
mix(a,b,c);
a += i7;
final(a,b,c);
then use c as the hash value. If you have a variable length array of
4-byte integers to hash, use hashword(). If you have a byte array (like
a character string), use hashlittle(). If you have several byte arrays, or
a mix of things, see the comments above hashlittle().
Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
then mix those integers. This is fast (you can do a lot more thorough
mixing with 12*3 instructions on 3 integers than you can with 3 instructions
on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-------------------------------------------------------------------------------
*/
#include <stdlib.h>
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h> /* defines uint32_t etc */
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h> /* attempt to define endianness */
#endif
#ifdef HAVE_ENDIAN_H
# include <endian.h> /* attempt to define endianness */
#endif
/*
* My best guess at if you are big-endian or little-endian. This may
* need adjustment.
*/
#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
__BYTE_ORDER == __LITTLE_ENDIAN) || \
(defined(i386) || defined(__i386__) || defined(__i486__) || \
defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
# define HASH_LITTLE_ENDIAN 1
# define HASH_BIG_ENDIAN 0
#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
__BYTE_ORDER == __BIG_ENDIAN) || \
(defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
# define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 1
#else
# define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 0
#endif
#define hashsize(n) ((size_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
/*
-------------------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.
This is reversible, so any information in (a,b,c) before mix() is
still in (a,b,c) after mix().
If four pairs of (a,b,c) inputs are run through mix(), or through
mix() in reverse, there are at least 32 bits of the output that
are sometimes the same for one pair and different for another pair.
This was tested for:
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
satisfy this are
4 6 8 16 19 4
9 15 3 18 27 15
14 9 3 7 17 3
Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
for "differ" defined as + with a one-bit base and a two-bit delta. I
used http://burtleburtle.net/bob/hash/avalanche.html to choose
the operations, constants, and arrangements of the variables.
This does not achieve avalanche. There are input bits of (a,b,c)
that fail to affect some output bits of (a,b,c), especially of a. The
most thoroughly mixed value is c, but it doesn't really even achieve
avalanche in c.
This allows some parallelism. Read-after-writes are good at doubling
the number of bits affected, so the goal of mixing pulls in the opposite
direction as the goal of parallelism. I did what I could. Rotates
seem to cost as much as shifts on every machine I could lay my hands
on, and rotates are much kinder to the top and bottom bits, so I used
rotates.
-------------------------------------------------------------------------------
*/
#define mix(a,b,c) \
{ \
a -= c; a ^= rot(c, 4); c += b; \
b -= a; b ^= rot(a, 6); a += c; \
c -= b; c ^= rot(b, 8); b += a; \
a -= c; a ^= rot(c,16); c += b; \
b -= a; b ^= rot(a,19); a += c; \
c -= b; c ^= rot(b, 4); b += a; \
}
/*
-------------------------------------------------------------------------------
final -- final mixing of 3 32-bit values (a,b,c) into c
Pairs of (a,b,c) values differing in only a few bits will usually
produce values of c that look totally different. This was tested for
* pairs that differed by one bit, by two bits, in any combination
of top bits of (a,b,c), or in any combination of bottom bits of
(a,b,c).
* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
is commonly produced by subtraction) look like a single 1-bit
difference.
* the base values were pseudorandom, all zero but one bit set, or
all zero plus a counter that starts at zero.
These constants passed:
14 11 25 16 4 14 24
12 14 25 16 4 14 24
and these came close:
4 8 15 26 3 22 24
10 8 15 26 3 22 24
11 8 15 26 3 22 24
-------------------------------------------------------------------------------
*/
#define final(a,b,c) \
{ \
c ^= b; c -= rot(b,14); \
a ^= c; a -= rot(c,11); \
b ^= a; b -= rot(a,25); \
c ^= b; c -= rot(b,16); \
a ^= c; a -= rot(c,4); \
b ^= a; b -= rot(a,14); \
c ^= b; c -= rot(b,24); \
}
/*
-------------------------------------------------------------------------------
hashlittle() -- hash a variable-length key into a 32-bit value
k : the key (the unaligned variable-length array of bytes)
length : the length of the key, counting by bytes
initval : can be any 4-byte value
Returns a 32-bit value. Every bit of the key affects every bit of
the return value. Two keys differing by one or two bits will have
totally different hash values.
The best hash table sizes are powers of 2. There is no need to do
mod a prime (mod is sooo slow!). If you need less than 32 bits,
use a bitmask. For example, if you need only 10 bits, do
h = (h & hashmask(10));
In which case, the hash table should have hashsize(10) elements.
If you are hashing n strings (uint8_t **)k, do it like this:
for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
code any way you wish, private, educational, or commercial. It's free.
Use for hash table lookup, or anything where one collision in 2^^32 is
acceptable. Do NOT use for cryptographic purposes.
-------------------------------------------------------------------------------
*/
static uint32_t hashlittle(const void *key, size_t length, uint32_t initval)
{
uint32_t a,b,c; /* internal state */
union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
/* Set up the internal state */
a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
u.ptr = key;
if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
/* Detect Valgrind or AddressSanitizer */
#ifdef VALGRIND
# define NO_MASKING_TRICK 1
#else
# if defined(__has_feature) /* Clang */
# if __has_feature(address_sanitizer) /* is ASAN enabled? */
# define NO_MASKING_TRICK 1
# endif
# else
# if defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x, is ASAN enabled? */
# define NO_MASKING_TRICK 1
# endif
# endif
#endif
#ifdef NO_MASKING_TRICK
const uint8_t *k8;
#endif
/*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
b += k[1];
c += k[2];
mix(a,b,c);
length -= 12;
k += 3;
}
/*----------------------------- handle the last (probably partial) block */
/*
* "k[2]&0xffffff" actually reads beyond the end of the string, but
* then masks off the part it's not allowed to read. Because the
* string is aligned, the masked-off tail is in the same word as the
* rest of the string. Every machine with memory protection I've seen
* does it on word boundaries, so is OK with this. But VALGRIND will
* still catch it and complain. The masking trick does make the hash
* noticeably faster for short strings (like English words).
*/
#ifndef NO_MASKING_TRICK
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
case 6 : b+=k[1]&0xffff; a+=k[0]; break;
case 5 : b+=k[1]&0xff; a+=k[0]; break;
case 4 : a+=k[0]; break;
case 3 : a+=k[0]&0xffffff; break;
case 2 : a+=k[0]&0xffff; break;
case 1 : a+=k[0]&0xff; break;
case 0 : return c; /* zero length strings require no mixing */
}
#else /* make valgrind happy */
k8 = (const uint8_t *)k;
switch(length)
{
case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[1]; a+=k[0]; break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]; break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
case 1 : a+=k8[0]; break;
case 0 : return c;
}
#endif /* !valgrind */
} else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
const uint8_t *k8;
/*--------------- all but last block: aligned reads and different mixing */
while (length > 12)
{
a += k[0] + (((uint32_t)k[1])<<16);
b += k[2] + (((uint32_t)k[3])<<16);
c += k[4] + (((uint32_t)k[5])<<16);
mix(a,b,c);
length -= 12;
k += 6;
}
/*----------------------------- handle the last (probably partial) block */
k8 = (const uint8_t *)k;
switch(length)
{
case 12: c+=k[4]+(((uint32_t)k[5])<<16);
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
case 10: c+=k[4];
b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 9 : c+=k8[8]; /* fall through */
case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
case 6 : b+=k[2];
a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 5 : b+=k8[4]; /* fall through */
case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
break;
case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
case 2 : a+=k[0];
break;
case 1 : a+=k8[0];
break;
case 0 : return c; /* zero length requires no mixing */
}
} else { /* need to read the key one byte at a time */
const uint8_t *k = (const uint8_t *)key;
/*--------------- all but the last block: affect some 32 bits of (a,b,c) */
while (length > 12)
{
a += k[0];
a += ((uint32_t)k[1])<<8;
a += ((uint32_t)k[2])<<16;
a += ((uint32_t)k[3])<<24;
b += k[4];
b += ((uint32_t)k[5])<<8;
b += ((uint32_t)k[6])<<16;
b += ((uint32_t)k[7])<<24;
c += k[8];
c += ((uint32_t)k[9])<<8;
c += ((uint32_t)k[10])<<16;
c += ((uint32_t)k[11])<<24;
mix(a,b,c);
length -= 12;
k += 12;
}
/*-------------------------------- last block: affect all 32 bits of (c) */
switch(length) /* all the case statements fall through */
{
case 12: c+=((uint32_t)k[11])<<24; /* fall through */
case 11: c+=((uint32_t)k[10])<<16; /* fall through */
case 10: c+=((uint32_t)k[9])<<8; /* fall through */
case 9 : c+=k[8]; /* fall through */
case 8 : b+=((uint32_t)k[7])<<24; /* fall through */
case 7 : b+=((uint32_t)k[6])<<16; /* fall through */
case 6 : b+=((uint32_t)k[5])<<8; /* fall through */
case 5 : b+=k[4]; /* fall through */
case 4 : a+=((uint32_t)k[3])<<24; /* fall through */
case 3 : a+=((uint32_t)k[2])<<16; /* fall through */
case 2 : a+=((uint32_t)k[1])<<8; /* fall through */
case 1 : a+=k[0];
break;
case 0 : return c;
}
}
final(a,b,c);
return c;
}

61
src/memory.c Normal file
View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2011-2012 Basile Starynkevitch <basile@starynkevitch.net>
*
* Jansson is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#include <stdlib.h>
#include <string.h>
#include "jansson.h"
#include "jansson_private.h"
/* C89 allows these to be macros */
#undef malloc
#undef free
/* memory function pointers */
static json_malloc_t do_malloc = malloc;
static json_free_t do_free = free;
void *jsonp_malloc(size_t size) {
if (!size)
return NULL;
return (*do_malloc)(size);
}
void jsonp_free(void *ptr) {
if (!ptr)
return;
(*do_free)(ptr);
}
char *jsonp_strdup(const char *str) { return jsonp_strndup(str, strlen(str)); }
char *jsonp_strndup(const char *str, size_t len) {
char *new_str;
new_str = jsonp_malloc(len + 1);
if (!new_str)
return NULL;
memcpy(new_str, str, len);
new_str[len] = '\0';
return new_str;
}
void json_set_alloc_funcs(json_malloc_t malloc_fn, json_free_t free_fn) {
do_malloc = malloc_fn;
do_free = free_fn;
}
void json_get_alloc_funcs(json_malloc_t *malloc_fn, json_free_t *free_fn) {
if (malloc_fn)
*malloc_fn = do_malloc;
if (free_fn)
*free_fn = do_free;
}

936
src/pack_unpack.c Normal file
View file

@ -0,0 +1,936 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2011-2012 Graeme Smecher <graeme.smecher@mail.mcgill.ca>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "jansson.h"
#include "jansson_private.h"
#include "utf.h"
#include <string.h>
typedef struct {
int line;
int column;
size_t pos;
char token;
} token_t;
typedef struct {
const char *start;
const char *fmt;
token_t prev_token;
token_t token;
token_t next_token;
json_error_t *error;
size_t flags;
int line;
int column;
size_t pos;
int has_error;
} scanner_t;
#define token(scanner) ((scanner)->token.token)
static const char *const type_names[] = {"object", "array", "string", "integer",
"real", "true", "false", "null"};
#define type_name(x) type_names[json_typeof(x)]
static const char unpack_value_starters[] = "{[siIbfFOon";
static void scanner_init(scanner_t *s, json_error_t *error, size_t flags,
const char *fmt) {
s->error = error;
s->flags = flags;
s->fmt = s->start = fmt;
memset(&s->prev_token, 0, sizeof(token_t));
memset(&s->token, 0, sizeof(token_t));
memset(&s->next_token, 0, sizeof(token_t));
s->line = 1;
s->column = 0;
s->pos = 0;
s->has_error = 0;
}
static void next_token(scanner_t *s) {
const char *t;
s->prev_token = s->token;
if (s->next_token.line) {
s->token = s->next_token;
s->next_token.line = 0;
return;
}
if (!token(s) && !*s->fmt)
return;
t = s->fmt;
s->column++;
s->pos++;
/* skip space and ignored chars */
while (*t == ' ' || *t == '\t' || *t == '\n' || *t == ',' || *t == ':') {
if (*t == '\n') {
s->line++;
s->column = 1;
} else
s->column++;
s->pos++;
t++;
}
s->token.token = *t;
s->token.line = s->line;
s->token.column = s->column;
s->token.pos = s->pos;
if (*t)
t++;
s->fmt = t;
}
static void prev_token(scanner_t *s) {
s->next_token = s->token;
s->token = s->prev_token;
}
static void set_error(scanner_t *s, const char *source, enum json_error_code code,
const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
jsonp_error_vset(s->error, s->token.line, s->token.column, s->token.pos, code, fmt,
ap);
jsonp_error_set_source(s->error, source);
va_end(ap);
}
static json_t *pack(scanner_t *s, va_list *ap);
/* ours will be set to 1 if jsonp_free() must be called for the result
afterwards */
static char *read_string(scanner_t *s, va_list *ap, const char *purpose, size_t *out_len,
int *ours, int optional) {
char t;
strbuffer_t strbuff;
const char *str;
size_t length;
next_token(s);
t = token(s);
prev_token(s);
*ours = 0;
if (t != '#' && t != '%' && t != '+') {
/* Optimize the simple case */
str = va_arg(*ap, const char *);
if (!str) {
if (!optional) {
set_error(s, "<args>", json_error_null_value, "NULL %s", purpose);
s->has_error = 1;
}
return NULL;
}
length = strlen(str);
if (!utf8_check_string(str, length)) {
set_error(s, "<args>", json_error_invalid_utf8, "Invalid UTF-8 %s", purpose);
s->has_error = 1;
return NULL;
}
*out_len = length;
return (char *)str;
} else if (optional) {
set_error(s, "<format>", json_error_invalid_format,
"Cannot use '%c' on optional strings", t);
s->has_error = 1;
return NULL;
}
if (strbuffer_init(&strbuff)) {
set_error(s, "<internal>", json_error_out_of_memory, "Out of memory");
s->has_error = 1;
}
while (1) {
str = va_arg(*ap, const char *);
if (!str) {
set_error(s, "<args>", json_error_null_value, "NULL %s", purpose);
s->has_error = 1;
}
next_token(s);
if (token(s) == '#') {
length = va_arg(*ap, int);
} else if (token(s) == '%') {
length = va_arg(*ap, size_t);
} else {
prev_token(s);
length = s->has_error ? 0 : strlen(str);
}
if (!s->has_error && strbuffer_append_bytes(&strbuff, str, length) == -1) {
set_error(s, "<internal>", json_error_out_of_memory, "Out of memory");
s->has_error = 1;
}
next_token(s);
if (token(s) != '+') {
prev_token(s);
break;
}
}
if (s->has_error) {
strbuffer_close(&strbuff);
return NULL;
}
if (!utf8_check_string(strbuff.value, strbuff.length)) {
set_error(s, "<args>", json_error_invalid_utf8, "Invalid UTF-8 %s", purpose);
strbuffer_close(&strbuff);
s->has_error = 1;
return NULL;
}
*out_len = strbuff.length;
*ours = 1;
return strbuffer_steal_value(&strbuff);
}
static json_t *pack_object(scanner_t *s, va_list *ap) {
json_t *object = json_object();
next_token(s);
while (token(s) != '}') {
char *key;
size_t len;
int ours;
json_t *value;
char valueOptional;
if (!token(s)) {
set_error(s, "<format>", json_error_invalid_format,
"Unexpected end of format string");
goto error;
}
if (token(s) != 's') {
set_error(s, "<format>", json_error_invalid_format,
"Expected format 's', got '%c'", token(s));
goto error;
}
key = read_string(s, ap, "object key", &len, &ours, 0);
next_token(s);
next_token(s);
valueOptional = token(s);
prev_token(s);
value = pack(s, ap);
if (!value) {
if (ours)
jsonp_free(key);
if (valueOptional != '*') {
set_error(s, "<args>", json_error_null_value, "NULL object value");
s->has_error = 1;
}
next_token(s);
continue;
}
if (s->has_error)
json_decref(value);
if (!s->has_error && json_object_set_new_nocheck(object, key, value)) {
set_error(s, "<internal>", json_error_out_of_memory,
"Unable to add key \"%s\"", key);
s->has_error = 1;
}
if (ours)
jsonp_free(key);
next_token(s);
}
if (!s->has_error)
return object;
error:
json_decref(object);
return NULL;
}
static json_t *pack_array(scanner_t *s, va_list *ap) {
json_t *array = json_array();
next_token(s);
while (token(s) != ']') {
json_t *value;
char valueOptional;
if (!token(s)) {
set_error(s, "<format>", json_error_invalid_format,
"Unexpected end of format string");
/* Format string errors are unrecoverable. */
goto error;
}
next_token(s);
valueOptional = token(s);
prev_token(s);
value = pack(s, ap);
if (!value) {
if (valueOptional != '*') {
s->has_error = 1;
}
next_token(s);
continue;
}
if (s->has_error)
json_decref(value);
if (!s->has_error && json_array_append_new(array, value)) {
set_error(s, "<internal>", json_error_out_of_memory,
"Unable to append to array");
s->has_error = 1;
}
next_token(s);
}
if (!s->has_error)
return array;
error:
json_decref(array);
return NULL;
}
static json_t *pack_string(scanner_t *s, va_list *ap) {
char *str;
char t;
size_t len;
int ours;
int optional;
next_token(s);
t = token(s);
optional = t == '?' || t == '*';
if (!optional)
prev_token(s);
str = read_string(s, ap, "string", &len, &ours, optional);
if (!str)
return t == '?' && !s->has_error ? json_null() : NULL;
if (s->has_error) {
/* It's impossible to reach this point if ours != 0, do not free str. */
return NULL;
}
if (ours)
return jsonp_stringn_nocheck_own(str, len);
return json_stringn_nocheck(str, len);
}
static json_t *pack_object_inter(scanner_t *s, va_list *ap, int need_incref) {
json_t *json;
char ntoken;
next_token(s);
ntoken = token(s);
if (ntoken != '?' && ntoken != '*')
prev_token(s);
json = va_arg(*ap, json_t *);
if (json)
return need_incref ? json_incref(json) : json;
switch (ntoken) {
case '?':
return json_null();
case '*':
return NULL;
default:
break;
}
set_error(s, "<args>", json_error_null_value, "NULL object");
s->has_error = 1;
return NULL;
}
static json_t *pack_integer(scanner_t *s, json_int_t value) {
json_t *json = json_integer(value);
if (!json) {
set_error(s, "<internal>", json_error_out_of_memory, "Out of memory");
s->has_error = 1;
}
return json;
}
static json_t *pack_real(scanner_t *s, double value) {
/* Allocate without setting value so we can identify OOM error. */
json_t *json = json_real(0.0);
if (!json) {
set_error(s, "<internal>", json_error_out_of_memory, "Out of memory");
s->has_error = 1;
return NULL;
}
if (json_real_set(json, value)) {
json_decref(json);
set_error(s, "<args>", json_error_numeric_overflow,
"Invalid floating point value");
s->has_error = 1;
return NULL;
}
return json;
}
static json_t *pack(scanner_t *s, va_list *ap) {
switch (token(s)) {
case '{':
return pack_object(s, ap);
case '[':
return pack_array(s, ap);
case 's': /* string */
return pack_string(s, ap);
case 'n': /* null */
return json_null();
case 'b': /* boolean */
return va_arg(*ap, int) ? json_true() : json_false();
case 'i': /* integer from int */
return pack_integer(s, va_arg(*ap, int));
case 'I': /* integer from json_int_t */
return pack_integer(s, va_arg(*ap, json_int_t));
case 'f': /* real */
return pack_real(s, va_arg(*ap, double));
case 'O': /* a json_t object; increments refcount */
return pack_object_inter(s, ap, 1);
case 'o': /* a json_t object; doesn't increment refcount */
return pack_object_inter(s, ap, 0);
default:
set_error(s, "<format>", json_error_invalid_format,
"Unexpected format character '%c'", token(s));
s->has_error = 1;
return NULL;
}
}
static int unpack(scanner_t *s, json_t *root, va_list *ap);
static int unpack_object(scanner_t *s, json_t *root, va_list *ap) {
int ret = -1;
int strict = 0;
int gotopt = 0;
/* Use a set (emulated by a hashtable) to check that all object
keys are accessed. Checking that the correct number of keys
were accessed is not enough, as the same key can be unpacked
multiple times.
*/
hashtable_t key_set;
if (hashtable_init(&key_set)) {
set_error(s, "<internal>", json_error_out_of_memory, "Out of memory");
return -1;
}
if (root && !json_is_object(root)) {
set_error(s, "<validation>", json_error_wrong_type, "Expected object, got %s",
type_name(root));
goto out;
}
next_token(s);
while (token(s) != '}') {
const char *key;
json_t *value;
int opt = 0;
if (strict != 0) {
set_error(s, "<format>", json_error_invalid_format,
"Expected '}' after '%c', got '%c'", (strict == 1 ? '!' : '*'),
token(s));
goto out;
}
if (!token(s)) {
set_error(s, "<format>", json_error_invalid_format,
"Unexpected end of format string");
goto out;
}
if (token(s) == '!' || token(s) == '*') {
strict = (token(s) == '!' ? 1 : -1);
next_token(s);
continue;
}
if (token(s) != 's') {
set_error(s, "<format>", json_error_invalid_format,
"Expected format 's', got '%c'", token(s));
goto out;
}
key = va_arg(*ap, const char *);
if (!key) {
set_error(s, "<args>", json_error_null_value, "NULL object key");
goto out;
}
next_token(s);
if (token(s) == '?') {
opt = gotopt = 1;
next_token(s);
}
if (!root) {
/* skipping */
value = NULL;
} else {
value = json_object_get(root, key);
if (!value && !opt) {
set_error(s, "<validation>", json_error_item_not_found,
"Object item not found: %s", key);
goto out;
}
}
if (unpack(s, value, ap))
goto out;
hashtable_set(&key_set, key, strlen(key), json_null());
next_token(s);
}
if (strict == 0 && (s->flags & JSON_STRICT))
strict = 1;
if (root && strict == 1) {
/* We need to check that all non optional items have been parsed */
const char *key;
size_t key_len;
/* keys_res is 1 for uninitialized, 0 for success, -1 for error. */
int keys_res = 1;
strbuffer_t unrecognized_keys;
json_t *value;
long unpacked = 0;
if (gotopt || json_object_size(root) != key_set.size) {
json_object_keylen_foreach(root, key, key_len, value) {
if (!hashtable_get(&key_set, key, key_len)) {
unpacked++;
/* Save unrecognized keys for the error message */
if (keys_res == 1) {
keys_res = strbuffer_init(&unrecognized_keys);
} else if (!keys_res) {
keys_res = strbuffer_append_bytes(&unrecognized_keys, ", ", 2);
}
if (!keys_res)
keys_res =
strbuffer_append_bytes(&unrecognized_keys, key, key_len);
}
}
}
if (unpacked) {
set_error(s, "<validation>", json_error_end_of_input_expected,
"%li object item(s) left unpacked: %s", unpacked,
keys_res ? "<unknown>" : strbuffer_value(&unrecognized_keys));
strbuffer_close(&unrecognized_keys);
goto out;
}
}
ret = 0;
out:
hashtable_close(&key_set);
return ret;
}
static int unpack_array(scanner_t *s, json_t *root, va_list *ap) {
size_t i = 0;
int strict = 0;
if (root && !json_is_array(root)) {
set_error(s, "<validation>", json_error_wrong_type, "Expected array, got %s",
type_name(root));
return -1;
}
next_token(s);
while (token(s) != ']') {
json_t *value;
if (strict != 0) {
set_error(s, "<format>", json_error_invalid_format,
"Expected ']' after '%c', got '%c'", (strict == 1 ? '!' : '*'),
token(s));
return -1;
}
if (!token(s)) {
set_error(s, "<format>", json_error_invalid_format,
"Unexpected end of format string");
return -1;
}
if (token(s) == '!' || token(s) == '*') {
strict = (token(s) == '!' ? 1 : -1);
next_token(s);
continue;
}
if (!strchr(unpack_value_starters, token(s))) {
set_error(s, "<format>", json_error_invalid_format,
"Unexpected format character '%c'", token(s));
return -1;
}
if (!root) {
/* skipping */
value = NULL;
} else {
value = json_array_get(root, i);
if (!value) {
set_error(s, "<validation>", json_error_index_out_of_range,
"Array index %lu out of range", (unsigned long)i);
return -1;
}
}
if (unpack(s, value, ap))
return -1;
next_token(s);
i++;
}
if (strict == 0 && (s->flags & JSON_STRICT))
strict = 1;
if (root && strict == 1 && i != json_array_size(root)) {
long diff = (long)json_array_size(root) - (long)i;
set_error(s, "<validation>", json_error_end_of_input_expected,
"%li array item(s) left unpacked", diff);
return -1;
}
return 0;
}
static int unpack(scanner_t *s, json_t *root, va_list *ap) {
switch (token(s)) {
case '{':
return unpack_object(s, root, ap);
case '[':
return unpack_array(s, root, ap);
case 's':
if (root && !json_is_string(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected string, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
const char **str_target;
size_t *len_target = NULL;
str_target = va_arg(*ap, const char **);
if (!str_target) {
set_error(s, "<args>", json_error_null_value, "NULL string argument");
return -1;
}
next_token(s);
if (token(s) == '%') {
len_target = va_arg(*ap, size_t *);
if (!len_target) {
set_error(s, "<args>", json_error_null_value,
"NULL string length argument");
return -1;
}
} else
prev_token(s);
if (root) {
*str_target = json_string_value(root);
if (len_target)
*len_target = json_string_length(root);
}
}
return 0;
case 'i':
if (root && !json_is_integer(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected integer, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
int *target = va_arg(*ap, int *);
if (root)
*target = (int)json_integer_value(root);
}
return 0;
case 'I':
if (root && !json_is_integer(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected integer, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
json_int_t *target = va_arg(*ap, json_int_t *);
if (root)
*target = json_integer_value(root);
}
return 0;
case 'b':
if (root && !json_is_boolean(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected true or false, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
int *target = va_arg(*ap, int *);
if (root)
*target = json_is_true(root);
}
return 0;
case 'f':
if (root && !json_is_real(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected real, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
double *target = va_arg(*ap, double *);
if (root)
*target = json_real_value(root);
}
return 0;
case 'F':
if (root && !json_is_number(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected real or integer, got %s", type_name(root));
return -1;
}
if (!(s->flags & JSON_VALIDATE_ONLY)) {
double *target = va_arg(*ap, double *);
if (root)
*target = json_number_value(root);
}
return 0;
case 'O':
if (root && !(s->flags & JSON_VALIDATE_ONLY))
json_incref(root);
/* Fall through */
case 'o':
if (!(s->flags & JSON_VALIDATE_ONLY)) {
json_t **target = va_arg(*ap, json_t **);
if (root)
*target = root;
}
return 0;
case 'n':
/* Never assign, just validate */
if (root && !json_is_null(root)) {
set_error(s, "<validation>", json_error_wrong_type,
"Expected null, got %s", type_name(root));
return -1;
}
return 0;
default:
set_error(s, "<format>", json_error_invalid_format,
"Unexpected format character '%c'", token(s));
return -1;
}
}
json_t *json_vpack_ex(json_error_t *error, size_t flags, const char *fmt, va_list ap) {
scanner_t s;
va_list ap_copy;
json_t *value;
if (!fmt || !*fmt) {
jsonp_error_init(error, "<format>");
jsonp_error_set(error, -1, -1, 0, json_error_invalid_argument,
"NULL or empty format string");
return NULL;
}
jsonp_error_init(error, NULL);
scanner_init(&s, error, flags, fmt);
next_token(&s);
va_copy(ap_copy, ap);
value = pack(&s, &ap_copy);
va_end(ap_copy);
/* This will cover all situations where s.has_error is true */
if (!value)
return NULL;
next_token(&s);
if (token(&s)) {
json_decref(value);
set_error(&s, "<format>", json_error_invalid_format,
"Garbage after format string");
return NULL;
}
return value;
}
json_t *json_pack_ex(json_error_t *error, size_t flags, const char *fmt, ...) {
json_t *value;
va_list ap;
va_start(ap, fmt);
value = json_vpack_ex(error, flags, fmt, ap);
va_end(ap);
return value;
}
json_t *json_pack(const char *fmt, ...) {
json_t *value;
va_list ap;
va_start(ap, fmt);
value = json_vpack_ex(NULL, 0, fmt, ap);
va_end(ap);
return value;
}
int json_vunpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt,
va_list ap) {
scanner_t s;
va_list ap_copy;
if (!root) {
jsonp_error_init(error, "<root>");
jsonp_error_set(error, -1, -1, 0, json_error_null_value, "NULL root value");
return -1;
}
if (!fmt || !*fmt) {
jsonp_error_init(error, "<format>");
jsonp_error_set(error, -1, -1, 0, json_error_invalid_argument,
"NULL or empty format string");
return -1;
}
jsonp_error_init(error, NULL);
scanner_init(&s, error, flags, fmt);
next_token(&s);
va_copy(ap_copy, ap);
if (unpack(&s, root, &ap_copy)) {
va_end(ap_copy);
return -1;
}
va_end(ap_copy);
next_token(&s);
if (token(&s)) {
set_error(&s, "<format>", json_error_invalid_format,
"Garbage after format string");
return -1;
}
return 0;
}
int json_unpack_ex(json_t *root, json_error_t *error, size_t flags, const char *fmt,
...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = json_vunpack_ex(root, error, flags, fmt, ap);
va_end(ap);
return ret;
}
int json_unpack(json_t *root, const char *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = json_vunpack_ex(root, NULL, 0, fmt, ap);
va_end(ap);
return ret;
}

View file

@ -1,26 +1,29 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "strbuffer.h"
#include "jansson_private.h"
#include <stdlib.h>
#include <string.h>
#include "strbuffer.h"
#include "util.h"
#define STRBUFFER_MIN_SIZE 16
#define STRBUFFER_FACTOR 2
#define STRBUFFER_MIN_SIZE 16
#define STRBUFFER_FACTOR 2
#define STRBUFFER_SIZE_MAX ((size_t)(-1))
int strbuffer_init(strbuffer_t *strbuff)
{
int strbuffer_init(strbuffer_t *strbuff) {
strbuff->size = STRBUFFER_MIN_SIZE;
strbuff->length = 0;
strbuff->value = malloc(strbuff->size);
if(!strbuff->value)
strbuff->value = jsonp_malloc(strbuff->size);
if (!strbuff->value)
return -1;
/* initialize to empty */
@ -28,52 +31,54 @@ int strbuffer_init(strbuffer_t *strbuff)
return 0;
}
void strbuffer_close(strbuffer_t *strbuff)
{
free(strbuff->value);
void strbuffer_close(strbuffer_t *strbuff) {
if (strbuff->value)
jsonp_free(strbuff->value);
strbuff->size = 0;
strbuff->length = 0;
strbuff->value = NULL;
}
void strbuffer_clear(strbuffer_t *strbuff)
{
void strbuffer_clear(strbuffer_t *strbuff) {
strbuff->length = 0;
strbuff->value[0] = '\0';
}
const char *strbuffer_value(const strbuffer_t *strbuff)
{
return strbuff->value;
}
const char *strbuffer_value(const strbuffer_t *strbuff) { return strbuff->value; }
char *strbuffer_steal_value(strbuffer_t *strbuff)
{
char *strbuffer_steal_value(strbuffer_t *strbuff) {
char *result = strbuff->value;
strbuffer_init(strbuff);
strbuff->value = NULL;
return result;
}
int strbuffer_append(strbuffer_t *strbuff, const char *string)
{
return strbuffer_append_bytes(strbuff, string, strlen(string));
}
int strbuffer_append_byte(strbuffer_t *strbuff, char byte)
{
int strbuffer_append_byte(strbuffer_t *strbuff, char byte) {
return strbuffer_append_bytes(strbuff, &byte, 1);
}
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size)
{
if(strbuff->length + size >= strbuff->size)
{
strbuff->size = max(strbuff->size * STRBUFFER_FACTOR,
strbuff->length + size + 1);
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, size_t size) {
if (size >= strbuff->size - strbuff->length) {
size_t new_size;
char *new_value;
strbuff->value = realloc(strbuff->value, strbuff->size);
if(!strbuff->value)
/* avoid integer overflow */
if (strbuff->size > STRBUFFER_SIZE_MAX / STRBUFFER_FACTOR ||
size > STRBUFFER_SIZE_MAX - 1 ||
strbuff->length > STRBUFFER_SIZE_MAX - 1 - size)
return -1;
new_size = max(strbuff->size * STRBUFFER_FACTOR, strbuff->length + size + 1);
new_value = jsonp_malloc(new_size);
if (!new_value)
return -1;
memcpy(new_value, strbuff->value, strbuff->length);
jsonp_free(strbuff->value);
strbuff->value = new_value;
strbuff->size = new_size;
}
memcpy(strbuff->value + strbuff->length, data, size);
@ -83,13 +88,11 @@ int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size)
return 0;
}
char strbuffer_pop(strbuffer_t *strbuff)
{
if(strbuff->length > 0) {
char strbuffer_pop(strbuffer_t *strbuff) {
if (strbuff->length > 0) {
char c = strbuff->value[--strbuff->length];
strbuff->value[strbuff->length] = '\0';
return c;
}
else
} else
return '\0';
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
@ -8,23 +8,27 @@
#ifndef STRBUFFER_H
#define STRBUFFER_H
#include "jansson.h"
#include <stdlib.h>
typedef struct {
char *value;
int length; /* bytes used */
int size; /* bytes allocated */
size_t length; /* bytes used */
size_t size; /* bytes allocated */
} strbuffer_t;
int strbuffer_init(strbuffer_t *strbuff);
int strbuffer_init(strbuffer_t *strbuff) JANSSON_ATTRS((warn_unused_result));
void strbuffer_close(strbuffer_t *strbuff);
void strbuffer_clear(strbuffer_t *strbuff);
const char *strbuffer_value(const strbuffer_t *strbuff);
/* Steal the value and close the strbuffer */
char *strbuffer_steal_value(strbuffer_t *strbuff);
int strbuffer_append(strbuffer_t *strbuff, const char *string);
int strbuffer_append_byte(strbuffer_t *strbuff, char byte);
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size);
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, size_t size);
char strbuffer_pop(strbuffer_t *strbuff);

237
src/strconv.c Normal file
View file

@ -0,0 +1,237 @@
#include "jansson_private.h"
#include "strbuffer.h"
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
/* need jansson_private_config.h to get the correct snprintf */
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
/*
- This code assumes that the decimal separator is exactly one
character.
- If setlocale() is called by another thread between the call to
get_decimal_point() and the call to sprintf() or strtod(), the
result may be wrong. setlocale() is not thread-safe and should
not be used this way. Multi-threaded programs should use
uselocale() instead.
*/
static char get_decimal_point() {
char buf[3];
sprintf(buf, "%#.0f", 1.0); // "1." in the current locale
return buf[1];
}
static void to_locale(strbuffer_t *strbuffer) {
char point;
char *pos;
point = get_decimal_point();
if (point == '.') {
/* No conversion needed */
return;
}
pos = strchr(strbuffer->value, '.');
if (pos)
*pos = point;
}
int jsonp_strtod(strbuffer_t *strbuffer, double *out) {
double value;
char *end;
to_locale(strbuffer);
errno = 0;
value = strtod(strbuffer->value, &end);
assert(end == strbuffer->value + strbuffer->length);
if ((value == HUGE_VAL || value == -HUGE_VAL) && errno == ERANGE) {
/* Overflow */
return -1;
}
*out = value;
return 0;
}
#if DTOA_ENABLED
/* see dtoa.c */
char *dtoa_r(double dd, int mode, int ndigits, int *decpt, int *sign, char **rve,
char *buf, size_t blen);
int jsonp_dtostr(char *buffer, size_t size, double value, int precision) {
/* adapted from `format_float_short()` in
* https://github.com/python/cpython/blob/2cf18a44303b6d84faa8ecffaecc427b53ae121e/Python/pystrtod.c#L969
*/
char digits[25];
char *digits_end;
int mode = precision == 0 ? 0 : 2;
int decpt, sign, exp_len, exp = 0, use_exp = 0;
int digits_len, vdigits_start, vdigits_end;
char *p;
if (dtoa_r(value, mode, precision, &decpt, &sign, &digits_end, digits, 25) == NULL) {
// digits is too short => should not happen
return -1;
}
digits_len = digits_end - digits;
if (decpt <= -4 || decpt > 16) {
use_exp = 1;
exp = decpt - 1;
decpt = 1;
}
vdigits_start = decpt <= 0 ? decpt - 1 : 0;
vdigits_end = digits_len;
if (!use_exp) {
/* decpt + 1 to add ".0" if value is an integer */
vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1;
} else {
vdigits_end = vdigits_end > decpt ? vdigits_end : decpt;
}
if (
/* sign, decimal point and trailing 0 byte */
(size_t)(3 +
/* total digit count (including zero padding on both sides) */
(vdigits_end - vdigits_start) +
/* exponent "e+100", max 3 numerical digits */
(use_exp ? 5 : 0)) > size) {
/* buffer is too short */
return -1;
}
p = buffer;
if (sign == 1) {
*p++ = '-';
}
/* note that exactly one of the three 'if' conditions is true,
so we include exactly one decimal point */
/* Zero padding on left of digit string */
if (decpt <= 0) {
memset(p, '0', decpt - vdigits_start);
p += decpt - vdigits_start;
*p++ = '.';
memset(p, '0', 0 - decpt);
p += 0 - decpt;
} else {
memset(p, '0', 0 - vdigits_start);
p += 0 - vdigits_start;
}
/* Digits, with included decimal point */
if (0 < decpt && decpt <= digits_len) {
strncpy(p, digits, decpt - 0);
p += decpt - 0;
*p++ = '.';
strncpy(p, digits + decpt, digits_len - decpt);
p += digits_len - decpt;
} else {
strncpy(p, digits, digits_len);
p += digits_len;
}
/* And zeros on the right */
if (digits_len < decpt) {
memset(p, '0', decpt - digits_len);
p += decpt - digits_len;
*p++ = '.';
memset(p, '0', vdigits_end - decpt);
p += vdigits_end - decpt;
} else {
memset(p, '0', vdigits_end - digits_len);
p += vdigits_end - digits_len;
}
if (p[-1] == '.')
p--;
if (use_exp) {
*p++ = 'e';
exp_len = sprintf(p, "%d", exp);
p += exp_len;
}
*p = '\0';
return (int)(p - buffer);
}
#else /* DTOA_ENABLED == 0 */
static void from_locale(char *buffer) {
char point;
char *pos;
point = get_decimal_point();
if (point == '.') {
/* No conversion needed */
return;
}
pos = strchr(buffer, point);
if (pos)
*pos = '.';
}
int jsonp_dtostr(char *buffer, size_t size, double value, int precision) {
int ret;
char *start, *end;
size_t length;
if (precision == 0)
precision = 17;
ret = snprintf(buffer, size, "%.*g", precision, value);
if (ret < 0)
return -1;
length = (size_t)ret;
if (length >= size)
return -1;
from_locale(buffer);
/* Make sure there's a dot or 'e' in the output. Otherwise
a real is converted to an integer when decoding */
if (strchr(buffer, '.') == NULL && strchr(buffer, 'e') == NULL) {
if (length + 3 >= size) {
/* No space to append ".0" */
return -1;
}
buffer[length] = '.';
buffer[length + 1] = '0';
buffer[length + 2] = '\0';
length += 2;
}
/* Remove leading '+' from positive exponent. Also remove leading
zeros from exponents (added by some printf() implementations) */
start = strchr(buffer, 'e');
if (start) {
start++;
end = start + 1;
if (*start == '-')
start++;
while (*end == '0')
end++;
if (end != start) {
memmove(start, end, length - (size_t)(end - buffer));
length -= (size_t)(end - start);
}
}
return (int)length;
}
#endif

123
src/utf.c
View file

@ -1,111 +1,89 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <string.h>
#include "utf.h"
#include <string.h>
int utf8_encode(int32_t codepoint, char *buffer, int *size)
{
if(codepoint < 0)
int utf8_encode(int32_t codepoint, char *buffer, size_t *size) {
if (codepoint < 0)
return -1;
else if(codepoint < 0x80)
{
else if (codepoint < 0x80) {
buffer[0] = (char)codepoint;
*size = 1;
}
else if(codepoint < 0x800)
{
} else if (codepoint < 0x800) {
buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);
buffer[1] = 0x80 + ((codepoint & 0x03F));
*size = 2;
}
else if(codepoint < 0x10000)
{
} else if (codepoint < 0x10000) {
buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);
buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);
buffer[2] = 0x80 + ((codepoint & 0x003F));
*size = 3;
}
else if(codepoint <= 0x10FFFF)
{
} else if (codepoint <= 0x10FFFF) {
buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);
buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);
buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);
buffer[3] = 0x80 + ((codepoint & 0x00003F));
*size = 4;
}
else
} else
return -1;
return 0;
}
int utf8_check_first(char byte)
{
size_t utf8_check_first(char byte) {
unsigned char u = (unsigned char)byte;
if(u < 0x80)
if (u < 0x80)
return 1;
if(0x80 <= u && u <= 0xBF) {
if (0x80 <= u && u <= 0xBF) {
/* second, third or fourth byte of a multi-byte
sequence, i.e. a "continuation byte" */
return 0;
}
else if(u == 0xC0 || u == 0xC1) {
} else if (u == 0xC0 || u == 0xC1) {
/* overlong encoding of an ASCII byte */
return 0;
}
else if(0xC2 <= u && u <= 0xDF) {
} else if (0xC2 <= u && u <= 0xDF) {
/* 2-byte sequence */
return 2;
}
else if(0xE0 <= u && u <= 0xEF) {
else if (0xE0 <= u && u <= 0xEF) {
/* 3-byte sequence */
return 3;
}
else if(0xF0 <= u && u <= 0xF4) {
} else if (0xF0 <= u && u <= 0xF4) {
/* 4-byte sequence */
return 4;
}
else { /* u >= 0xF5 */
} else { /* u >= 0xF5 */
/* Restricted (start of 4-, 5- or 6-byte sequence) or invalid
UTF-8 */
return 0;
}
}
int utf8_check_full(const char *buffer, int size, int32_t *codepoint)
{
int i;
size_t utf8_check_full(const char *buffer, size_t size, int32_t *codepoint) {
size_t i;
int32_t value = 0;
unsigned char u = (unsigned char)buffer[0];
if(size == 2)
{
if (size == 2) {
value = u & 0x1F;
}
else if(size == 3)
{
} else if (size == 3) {
value = u & 0xF;
}
else if(size == 4)
{
} else if (size == 4) {
value = u & 0x7;
}
else
} else
return 0;
for(i = 1; i < size; i++)
{
for (i = 1; i < size; i++) {
u = (unsigned char)buffer[i];
if(u < 0x80 || u > 0xBF) {
if (u < 0x80 || u > 0xBF) {
/* not a continuation byte */
return 0;
}
@ -113,73 +91,64 @@ int utf8_check_full(const char *buffer, int size, int32_t *codepoint)
value = (value << 6) + (u & 0x3F);
}
if(value > 0x10FFFF) {
if (value > 0x10FFFF) {
/* not in Unicode range */
return 0;
}
else if(0xD800 <= value && value <= 0xDFFF) {
else if (0xD800 <= value && value <= 0xDFFF) {
/* invalid code point (UTF-16 surrogate halves) */
return 0;
}
else if((size == 2 && value < 0x80) ||
(size == 3 && value < 0x800) ||
(size == 4 && value < 0x10000)) {
else if ((size == 2 && value < 0x80) || (size == 3 && value < 0x800) ||
(size == 4 && value < 0x10000)) {
/* overlong encoding */
return 0;
}
if(codepoint)
if (codepoint)
*codepoint = value;
return 1;
}
const char *utf8_iterate(const char *buffer, int32_t *codepoint)
{
int count;
const char *utf8_iterate(const char *buffer, size_t bufsize, int32_t *codepoint) {
size_t count;
int32_t value;
if(!*buffer)
if (!bufsize)
return buffer;
count = utf8_check_first(buffer[0]);
if(count <= 0)
if (count <= 0)
return NULL;
if(count == 1)
if (count == 1)
value = (unsigned char)buffer[0];
else
{
if(!utf8_check_full(buffer, count, &value))
else {
if (count > bufsize || !utf8_check_full(buffer, count, &value))
return NULL;
}
if(codepoint)
if (codepoint)
*codepoint = value;
return buffer + count;
}
int utf8_check_string(const char *string, int length)
{
int i;
int utf8_check_string(const char *string, size_t length) {
size_t i;
if(length == -1)
length = strlen(string);
for(i = 0; i < length; i++)
{
int count = utf8_check_first(string[i]);
if(count == 0)
for (i = 0; i < length; i++) {
size_t count = utf8_check_first(string[i]);
if (count == 0)
return 0;
else if(count > 1)
{
if(i + count > length)
else if (count > 1) {
if (count > length - i)
return 0;
if(!utf8_check_full(&string[i], count, NULL))
if (!utf8_check_full(&string[i], count, NULL))
return 0;
i += count - 1;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
@ -8,21 +8,21 @@
#ifndef UTF_H
#define UTF_H
#include <config.h>
#ifdef HAVE_INTTYPES_H
/* inttypes.h includes stdint.h in a standard environment, so there's
no need to include stdint.h separately. If inttypes.h doesn't define
int32_t, it's defined in config.h. */
#include <inttypes.h>
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
int utf8_encode(int codepoint, char *buffer, int *size);
#include <stddef.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
int utf8_check_first(char byte);
int utf8_check_full(const char *buffer, int size, int32_t *codepoint);
const char *utf8_iterate(const char *buffer, int32_t *codepoint);
int utf8_encode(int32_t codepoint, char *buffer, size_t *size);
int utf8_check_string(const char *string, int length);
size_t utf8_check_first(char byte);
size_t utf8_check_full(const char *buffer, size_t size, int32_t *codepoint);
const char *utf8_iterate(const char *buffer, size_t size, int32_t *codepoint);
int utf8_check_string(const char *string, size_t length);
#endif

View file

@ -1,13 +0,0 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef UTIL_H
#define UTIL_H
#define max(a, b) ((a) > (b) ? (a) : (b))
#endif

File diff suppressed because it is too large Load diff

28
src/version.c Normal file
View file

@ -0,0 +1,28 @@
/*
* Copyright (c) 2019 Sean Bright <sean.bright@gmail.com>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "jansson.h"
const char *jansson_version_str(void) { return JANSSON_VERSION; }
int jansson_version_cmp(int major, int minor, int micro) {
int diff;
if ((diff = JANSSON_MAJOR_VERSION - major)) {
return diff;
}
if ((diff = JANSSON_MINOR_VERSION - minor)) {
return diff;
}
return JANSSON_MICRO_VERSION - micro;
}

14
test/.gitignore vendored
View file

@ -1,11 +1,21 @@
logs
bin/json_process
suites/api/test_array
suites/api/test_equal
suites/api/test_chaos
suites/api/test_copy
suites/api/test_cpp
suites/api/test_dump
suites/api/test_dump_callback
suites/api/test_equal
suites/api/test_fixed_size
suites/api/test_load
suites/api/test_load_callback
suites/api/test_loadb
suites/api/test_memory_funcs
suites/api/test_number
suites/api/test_object
suites/api/test_pack
suites/api/test_simple
suites/api/test_cpp
suites/api/test_sprintf
suites/api/test_unpack
suites/api/test_version

View file

@ -1,4 +1,4 @@
SUBDIRS = bin suites
SUBDIRS = bin suites ossfuzz
EXTRA_DIST = scripts run-suites
TESTS = run-suites

View file

@ -1,6 +1,5 @@
check_PROGRAMS = json_process
AM_CPPFLAGS = -I$(top_srcdir)/src
AM_CFLAGS = -Wall -Werror
AM_CPPFLAGS = -I$(top_builddir)/src -I$(top_srcdir)/src
LDFLAGS = -static # for speed and Valgrind
LDADD = $(top_builddir)/src/libjansson.la

View file

@ -1,72 +1,261 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
#include <ctype.h>
#include <jansson.h>
#include <stdio.h>
#include <stdlib.h>
#include <jansson.h>
#include <string.h>
static int getenv_int(const char *name)
{
char *value, *end;
long result;
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
value = getenv(name);
if(!value)
return 0;
#if _WIN32
#include <fcntl.h> /* for _O_BINARY */
#include <io.h> /* for _setmode() */
result = strtol(value, &end, 10);
if(*end != '\0')
return 0;
static const char dir_sep = '\\';
#else
static const char dir_sep = '/';
#endif
return (int)result;
struct config {
int indent;
int compact;
int preserve_order;
int ensure_ascii;
int sort_keys;
int strip;
int have_hashseed;
int hashseed;
int precision;
} conf;
#define l_isspace(c) ((c) == ' ' || (c) == '\n' || (c) == '\r' || (c) == '\t')
/* Return a pointer to the first non-whitespace character of str.
Modifies str so that all trailing whitespace characters are
replaced by '\0'. */
static const char *strip(char *str) {
size_t length;
char *result = str;
while (*result && l_isspace(*result))
result++;
length = strlen(result);
if (length == 0)
return result;
while (l_isspace(result[length - 1]))
result[--length] = '\0';
return result;
}
int main(int argc, char *argv[])
{
int indent = 0;
unsigned int flags = 0;
static char *loadfile(FILE *file) {
size_t fsize, ret;
char *buf;
fseek(file, 0, SEEK_END);
fsize = ftell(file);
fseek(file, 0, SEEK_SET);
buf = malloc(fsize + 1);
ret = fread(buf, 1, fsize, file);
if (ret != fsize)
exit(1);
buf[fsize] = '\0';
return buf;
}
static void read_conf(FILE *conffile) {
char *buffer, *line, *val;
conf.have_hashseed = 0;
buffer = loadfile(conffile);
for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) {
val = strchr(line, '=');
if (!val) {
printf("invalid configuration line\n");
break;
}
*val++ = '\0';
if (!strcmp(line, "JSON_INDENT"))
conf.indent = atoi(val);
if (!strcmp(line, "JSON_COMPACT"))
conf.compact = atoi(val);
if (!strcmp(line, "JSON_ENSURE_ASCII"))
conf.ensure_ascii = atoi(val);
if (!strcmp(line, "JSON_PRESERVE_ORDER"))
conf.preserve_order = atoi(val);
if (!strcmp(line, "JSON_SORT_KEYS"))
conf.sort_keys = atoi(val);
if (!strcmp(line, "JSON_REAL_PRECISION"))
conf.precision = atoi(val);
if (!strcmp(line, "STRIP"))
conf.strip = atoi(val);
if (!strcmp(line, "HASHSEED")) {
conf.have_hashseed = 1;
conf.hashseed = atoi(val);
}
}
free(buffer);
}
static int cmpfile(const char *str, const char *path, const char *fname) {
char filename[1024], *buffer;
int ret;
FILE *file;
sprintf(filename, "%s%c%s", path, dir_sep, fname);
file = fopen(filename, "rb");
if (!file) {
if (conf.strip)
strcat(filename, ".strip");
else
strcat(filename, ".normal");
file = fopen(filename, "rb");
}
if (!file) {
printf("Error: test result file could not be opened.\n");
exit(1);
}
buffer = loadfile(file);
if (strcmp(buffer, str) != 0) {
fprintf(stderr, "=== Expected %s ===\n", fname);
fprintf(stderr, "%s\n", buffer);
fprintf(stderr, "=== Actual %s ===\n", fname);
fprintf(stderr, "%s\n", str);
ret = 1;
} else {
ret = 0;
}
free(buffer);
fclose(file);
return ret;
}
int use_conf(char *test_path) {
int ret;
size_t flags = 0;
char filename[1024], errstr[1024];
char *buffer;
FILE *infile, *conffile;
json_t *json;
json_error_t error;
if(argc != 1) {
fprintf(stderr, "usage: %s\n", argv[0]);
sprintf(filename, "%s%cinput", test_path, dir_sep);
if (!(infile = fopen(filename, "rb"))) {
fprintf(stderr, "Could not open \"%s\"\n", filename);
return 2;
}
indent = getenv_int("JSON_INDENT");
if(indent < 0 || indent > 255) {
fprintf(stderr, "invalid value for JSON_INDENT: %d\n", indent);
return 2;
sprintf(filename, "%s%cenv", test_path, dir_sep);
conffile = fopen(filename, "rb");
if (conffile) {
read_conf(conffile);
fclose(conffile);
}
if(indent > 0)
flags |= JSON_INDENT(indent);
if (conf.indent < 0 || conf.indent > 31) {
fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent);
fclose(infile);
return 2;
}
if (conf.indent)
flags |= JSON_INDENT(conf.indent);
if(getenv_int("JSON_COMPACT") > 0)
if (conf.compact)
flags |= JSON_COMPACT;
if(getenv_int("JSON_ENSURE_ASCII"))
if (conf.ensure_ascii)
flags |= JSON_ENSURE_ASCII;
if(getenv_int("JSON_PRESERVE_ORDER"))
if (conf.preserve_order)
flags |= JSON_PRESERVE_ORDER;
if(getenv_int("JSON_SORT_KEYS"))
if (conf.sort_keys)
flags |= JSON_SORT_KEYS;
json = json_loadf(stdin, &error);
if(!json) {
fprintf(stderr, "%d\n%s\n", error.line, error.text);
return 1;
if (conf.precision < 0 || conf.precision > 31) {
fprintf(stderr, "invalid value for JSON_REAL_PRECISION: %d\n", conf.precision);
fclose(infile);
return 2;
}
if (conf.precision)
flags |= JSON_REAL_PRECISION(conf.precision);
if (conf.have_hashseed)
json_object_seed(conf.hashseed);
if (conf.strip) {
/* Load to memory, strip leading and trailing whitespace */
buffer = loadfile(infile);
json = json_loads(strip(buffer), 0, &error);
free(buffer);
} else {
json = json_loadf(infile, 0, &error);
}
json_dumpf(json, stdout, flags);
fclose(infile);
if (!json) {
sprintf(errstr, "%d %d %d\n%s\n", error.line, error.column, error.position,
error.text);
ret = cmpfile(errstr, test_path, "error");
return ret;
}
buffer = json_dumps(json, flags);
ret = cmpfile(buffer, test_path, "output");
free(buffer);
json_decref(json);
return 0;
return ret;
}
int main(int argc, char *argv[]) {
int i;
char *test_path = NULL;
#ifdef HAVE_SETLOCALE
setlocale(LC_ALL, "");
#endif
if (argc < 2) {
goto usage;
}
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--strip"))
conf.strip = 1;
else
test_path = argv[i];
}
if (!test_path) {
goto usage;
}
return use_conf(test_path);
usage:
fprintf(stderr, "usage: %s [--strip] test_dir\n", argv[0]);
return 2;
}

1
test/ossfuzz/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
json_load_dump_fuzzer

32
test/ossfuzz/Makefile.am Normal file
View file

@ -0,0 +1,32 @@
AM_CPPFLAGS = -I$(top_builddir)/src -I$(top_srcdir)/src
LDADD = $(top_builddir)/src/libjansson.la
if USE_OSSFUZZ_FLAG
FUZZ_FLAG = $(LIB_FUZZING_ENGINE)
else
if USE_OSSFUZZ_STATIC
LDADD += $(LIB_FUZZING_ENGINE)
FUZZ_FLAG =
else
LDADD += libstandaloneengine.a
FUZZ_FLAG =
endif
endif
noinst_PROGRAMS =
noinst_LIBRARIES =
if USE_OSSFUZZERS
noinst_PROGRAMS += \
json_load_dump_fuzzer
noinst_LIBRARIES += \
libstandaloneengine.a
endif
json_load_dump_fuzzer_SOURCES = json_load_dump_fuzzer.cc testinput.h
json_load_dump_fuzzer_CXXFLAGS = $(AM_CXXFLAGS) $(FUZZ_FLAG)
json_load_dump_fuzzer_LDFLAGS = $(AM_LDFLAGS) -static
libstandaloneengine_a_SOURCES = standaloneengine.cc
libstandaloneengine_a_CXXFLAGS = $(AM_CXXFLAGS)

View file

@ -0,0 +1,132 @@
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <inttypes.h>
#include "jansson.h"
static int enable_diags;
#define FUZZ_DEBUG(FMT, ...) \
if (enable_diags) \
{ \
fprintf(stderr, FMT, ##__VA_ARGS__); \
fprintf(stderr, "\n"); \
}
static int json_dump_counter(const char *buffer, size_t size, void *data)
{
uint64_t *counter = reinterpret_cast<uint64_t *>(data);
*counter += size;
return 0;
}
#define NUM_COMMAND_BYTES (sizeof(size_t) + sizeof(size_t) + 1)
#define FUZZ_DUMP_CALLBACK 0x00
#define FUZZ_DUMP_STRING 0x01
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
json_error_t error;
unsigned char dump_mode;
// Enable or disable diagnostics based on the FUZZ_VERBOSE environment flag.
enable_diags = (getenv("FUZZ_VERBOSE") != NULL);
FUZZ_DEBUG("Input data length: %zd", size);
if (size < NUM_COMMAND_BYTES)
{
return 0;
}
// Use the first sizeof(size_t) bytes as load flags.
size_t load_flags = *(const size_t*)data;
data += sizeof(size_t);
FUZZ_DEBUG("load_flags: 0x%zx\n"
"& JSON_REJECT_DUPLICATES = 0x%zx\n"
"& JSON_DECODE_ANY = 0x%zx\n"
"& JSON_DISABLE_EOF_CHECK = 0x%zx\n"
"& JSON_DECODE_INT_AS_REAL = 0x%zx\n"
"& JSON_ALLOW_NUL = 0x%zx\n",
load_flags,
load_flags & JSON_REJECT_DUPLICATES,
load_flags & JSON_DECODE_ANY,
load_flags & JSON_DISABLE_EOF_CHECK,
load_flags & JSON_DECODE_INT_AS_REAL,
load_flags & JSON_ALLOW_NUL);
// Use the next sizeof(size_t) bytes as dump flags.
size_t dump_flags = *(const size_t*)data;
data += sizeof(size_t);
FUZZ_DEBUG("dump_flags: 0x%zx\n"
"& JSON_MAX_INDENT = 0x%zx\n"
"& JSON_COMPACT = 0x%zx\n"
"& JSON_ENSURE_ASCII = 0x%zx\n"
"& JSON_SORT_KEYS = 0x%zx\n"
"& JSON_PRESERVE_ORDER = 0x%zx\n"
"& JSON_ENCODE_ANY = 0x%zx\n"
"& JSON_ESCAPE_SLASH = 0x%zx\n"
"& JSON_REAL_PRECISION = 0x%zx\n"
"& JSON_EMBED = 0x%zx\n",
dump_flags,
dump_flags & JSON_MAX_INDENT,
dump_flags & JSON_COMPACT,
dump_flags & JSON_ENSURE_ASCII,
dump_flags & JSON_SORT_KEYS,
dump_flags & JSON_PRESERVE_ORDER,
dump_flags & JSON_ENCODE_ANY,
dump_flags & JSON_ESCAPE_SLASH,
((dump_flags >> 11) & 0x1F) << 11,
dump_flags & JSON_EMBED);
// Use the next byte as the dump mode.
dump_mode = data[0];
data++;
FUZZ_DEBUG("dump_mode: 0x%x", (unsigned int)dump_mode);
// Remove the command bytes from the size total.
size -= NUM_COMMAND_BYTES;
// Attempt to load the remainder of the data with the given load flags.
const char* text = reinterpret_cast<const char *>(data);
json_t* jobj = json_loadb(text, size, load_flags, &error);
if (jobj == NULL)
{
return 0;
}
if (dump_mode & FUZZ_DUMP_STRING)
{
// Dump as a string. Remove indents so that we don't run out of memory.
char *out = json_dumps(jobj, dump_flags & ~JSON_MAX_INDENT);
if (out != NULL)
{
free(out);
}
}
else
{
// Default is callback mode.
//
// Attempt to dump the loaded json object with the given dump flags.
uint64_t counter = 0;
json_dump_callback(jobj, json_dump_counter, &counter, dump_flags);
FUZZ_DEBUG("Counter function counted %" PRIu64 " bytes.", counter);
}
if (jobj)
{
json_decref(jobj);
}
return 0;
}

30
test/ossfuzz/ossfuzz.sh Executable file
View file

@ -0,0 +1,30 @@
#!/bin/bash -eu
# This script is called by the oss-fuzz main project when compiling the fuzz
# targets. This script is regression tested by travisoss.sh.
# Save off the current folder as the build root.
export BUILD_ROOT=$PWD
echo "CC: $CC"
echo "CXX: $CXX"
echo "LIB_FUZZING_ENGINE: $LIB_FUZZING_ENGINE"
echo "CFLAGS: $CFLAGS"
echo "CXXFLAGS: $CXXFLAGS"
echo "OUT: $OUT"
export MAKEFLAGS+="-j$(nproc)"
# Install dependencies
apt-get -y install automake libtool
# Compile the fuzzer.
autoreconf -i
./configure --enable-ossfuzzers
make
# Copy the fuzzer to the output directory.
cp -v test/ossfuzz/json_load_dump_fuzzer $OUT/
# Zip up all input files to use as a test corpus
find test/suites -name "input" -print | zip $OUT/json_load_dump_fuzzer_seed_corpus.zip -@

View file

@ -0,0 +1,74 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "testinput.h"
/**
* Main procedure for standalone fuzzing engine.
*
* Reads filenames from the argument array. For each filename, read the file
* into memory and then call the fuzzing interface with the data.
*/
int main(int argc, char **argv)
{
int ii;
for(ii = 1; ii < argc; ii++)
{
FILE *infile;
printf("[%s] ", argv[ii]);
/* Try and open the file. */
infile = fopen(argv[ii], "rb");
if(infile)
{
uint8_t *buffer = NULL;
size_t buffer_len;
printf("Opened.. ");
/* Get the length of the file. */
fseek(infile, 0L, SEEK_END);
buffer_len = ftell(infile);
/* Reset the file indicator to the beginning of the file. */
fseek(infile, 0L, SEEK_SET);
/* Allocate a buffer for the file contents. */
buffer = (uint8_t *)calloc(buffer_len, sizeof(uint8_t));
if(buffer)
{
/* Read all the text from the file into the buffer. */
fread(buffer, sizeof(uint8_t), buffer_len, infile);
printf("Read %zu bytes, fuzzing.. ", buffer_len);
/* Call the fuzzer with the data. */
LLVMFuzzerTestOneInput(buffer, buffer_len);
printf("complete !!");
/* Free the buffer as it's no longer needed. */
free(buffer);
buffer = NULL;
}
else
{
fprintf(stderr,
"[%s] Failed to allocate %zu bytes \n",
argv[ii],
buffer_len);
}
/* Close the file as it's no longer needed. */
fclose(infile);
infile = NULL;
}
else
{
/* Failed to open the file. Maybe wrong name or wrong permissions? */
fprintf(stderr, "[%s] Open failed. \n", argv[ii]);
}
printf("\n");
}
}

3
test/ossfuzz/testinput.h Normal file
View file

@ -0,0 +1,3 @@
#include <inttypes.h>
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);

View file

@ -20,25 +20,29 @@ if [ -z "$SUITES" ]; then
done
fi
export suites_srcdir=$top_srcdir/test/suites
export suites_builddir=suites
export scriptdir=$top_srcdir/test/scripts
export logdir=logs
export bindir=bin
[ -z "$STOP" ] && STOP=0
suites_srcdir=$top_srcdir/test/suites
suites_builddir=suites
scriptdir=$top_srcdir/test/scripts
logdir=logs
bindir=bin
export suites_srcdir suites_builddir scriptdir logdir bindir
passed=0
failed=0
for suite in $SUITES; do
echo "Suite: $suite"
if $suites_srcdir/$suite/run $suite; then
passed=$(($passed+1))
passed=`expr $passed + 1`
else
failed=$(($failed+1))
failed=`expr $failed + 1`
[ $STOP -eq 1 ] && break
fi
done
if [ $failed -gt 0 ]; then
echo "$failed of $((passed+failed)) test suites failed"
echo "$failed of `expr $passed + $failed` test suites failed"
exit 1
else
echo "$passed test suites passed"

View file

@ -1,8 +1,20 @@
# Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
# Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
#
# Jansson is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.
die() {
echo "$1" >&2
exit 1
}
[ -n "$1" ] || die "Usage: $0 suite-name"
[ -n "$bindir" ] || die "Set bindir"
[ -n "$logdir" ] || die "Set logdir"
[ -n "$scriptdir" ] || die "Set scriptdir"
[ -n "$suites_srcdir" ] || die "Set suites_srcdir"
[ -n "$suites_builddir" ] || die "Set suites_builddir"
json_process=$bindir/json_process
suite_name=$1
@ -10,8 +22,8 @@ suite_srcdir=$suites_srcdir/$suite_name
suite_builddir=$suites_builddir/$suite_name
suite_log=$logdir/$suite_name
[ -z "$VERBOSE" ] && VERBOSE=0
[ -z "$STOP" ] && STOP=0
. $scriptdir/valgrind.sh
@ -29,29 +41,46 @@ for test_path in $suite_srcdir/*; do
rm -rf $test_log
mkdir -p $test_log
if [ $VERBOSE -eq 1 ]; then
echo -n "$test_name... "
printf '%s... ' "$test_name"
fi
if run_test; then
# Success
if [ $VERBOSE -eq 1 ]; then
echo "ok"
else
echo -n "."
fi
rm -rf $test_log
else
# Failure
if [ $VERBOSE -eq 1 ]; then
echo "FAILED"
else
echo -n "F"
fi
fi
run_test
case $? in
0)
# Success
if [ $VERBOSE -eq 1 ]; then
printf 'ok\n'
else
printf '.'
fi
rm -rf $test_log
;;
77)
# Skip
if [ $VERBOSE -eq 1 ]; then
printf 'skipped\n'
else
printf 'S'
fi
rm -rf $test_log
;;
*)
# Failure
if [ $VERBOSE -eq 1 ]; then
printf 'FAILED\n'
else
printf 'F'
fi
[ $STOP -eq 1 ] && break
;;
esac
done
if [ $VERBOSE -eq 0 ]; then
echo
printf '\n'
fi
if [ -n "$(ls -A $suite_log)" ]; then

View file

@ -1,4 +1,4 @@
# Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
# Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
#
# Jansson is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.

2
test/suites/.gitattributes vendored Normal file
View file

@ -0,0 +1,2 @@
api/ text=auto
* text eol=lf

View file

@ -1,2 +1,2 @@
SUBDIRS = api
EXTRA_DIST = invalid invalid-strip invalid-unicode valid valid-strip
EXTRA_DIST = invalid invalid-unicode valid

View file

@ -1,24 +1,42 @@
EXTRA_DIST = run
EXTRA_DIST = run check-exports
check_PROGRAMS = \
test_array \
test_equal \
test_chaos \
test_copy \
test_dump \
test_dump_callback \
test_equal \
test_fixed_size \
test_load \
test_simple \
test_load_callback \
test_loadb \
test_memory_funcs \
test_number \
test_object
test_object \
test_pack \
test_simple \
test_sprintf \
test_unpack \
test_version
test_array_SOURCES = test_array.c util.h
test_chaos_SOURCES = test_chaos.c util.h
test_copy_SOURCES = test_copy.c util.h
test_dump_SOURCES = test_dump.c util.h
test_dump_callback_SOURCES = test_dump_callback.c util.h
test_fixed_size_SOURCES = test_fixed_size.c util.h
test_load_SOURCES = test_load.c util.h
test_simple_SOURCES = test_simple.c util.h
test_loadb_SOURCES = test_loadb.c util.h
test_memory_funcs_SOURCES = test_memory_funcs.c util.h
test_number_SOURCES = test_number.c util.h
test_object_SOURCES = test_object.c util.h
test_pack_SOURCES = test_pack.c util.h
test_simple_SOURCES = test_simple.c util.h
test_sprintf_SOURCES = test_sprintf.c util.h
test_unpack_SOURCES = test_unpack.c util.h
test_version_SOURCES = test_version.c util.h
AM_CPPFLAGS = -I$(top_srcdir)/src
AM_CFLAGS = -Wall -Werror
AM_CPPFLAGS = -I$(top_builddir)/src -I$(top_srcdir)/src
LDFLAGS = -static # for speed and Valgrind
LDADD = $(top_builddir)/src/libjansson.la

View file

@ -1,88 +1,21 @@
#!/bin/sh
# This tests checks that the libjansson.so exports the correct
# symbols.
# The list of symbols that the shared object should export
sort >$test_log/exports <<EOF
json_delete
json_true
json_false
json_null
json_string
json_string_nocheck
json_string_value
json_string_set
json_string_set_nocheck
json_integer
json_integer_value
json_integer_set
json_real
json_real_value
json_real_set
json_number_value
json_array
json_array_size
json_array_get
json_array_set_new
json_array_append_new
json_array_insert_new
json_array_remove
json_array_clear
json_array_extend
json_object
json_object_size
json_object_get
json_object_set_new
json_object_set_new_nocheck
json_object_del
json_object_clear
json_object_update
json_object_iter
json_object_iter_at
json_object_iter_next
json_object_iter_key
json_object_iter_value
json_object_iter_set_new
json_dumps
json_dumpf
json_dump_file
json_loads
json_loadf
json_load_file
json_equal
json_copy
json_deep_copy
EOF
# The list of functions are not exported in the library because they
# are macros or static inline functions. This is only the make the
# list complete, there are not used by the test.
sort >$test_log/macros_or_inline <<EOF
json_typeof
json_incref
json_decref
json_is_object
json_is_object
json_is_array
json_is_string
json_is_integer
json_is_real
json_is_true
json_is_false
json_is_null
json_is_number
json_is_boolean
json_array_set
json_array_append
json_array_insert
json_object_set
json_object_set_nocheck
EOF
#
# This test checks that libjansson.so exports the correct symbols.
#
SOFILE="../src/.libs/libjansson.so"
nm -D $SOFILE | grep ' T ' | cut -d' ' -f3 | sort >$test_log/output
# The list of symbols, which the shared object should export, is read
# from the def file, which is used in Windows builds
grep 'json_\|jansson_' $top_srcdir/src/jansson.def \
| sed -e 's/ //g' \
| sort \
>$test_log/exports
nm -D $SOFILE >/dev/null >$test_log/symbols 2>/dev/null \
|| exit 77 # Skip if "nm -D" doesn't seem to work
grep ' [DT] ' $test_log/symbols | cut -d' ' -f3 | grep -v '^_' | sed 's/@@libjansson.*//' | sort >$test_log/output
if ! cmp -s $test_log/exports $test_log/output; then
diff -u $test_log/exports $test_log/output >&2

View file

@ -1,6 +1,6 @@
#!/bin/sh
#
# Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
# Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
#
# Jansson is free software; you can redistribute it and/or modify
# it under the terms of the MIT license. See LICENSE for details.

View file

@ -1,112 +1,111 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <jansson.h>
#include "util.h"
#include <jansson.h>
static void test_misc(void)
{
static void test_misc(void) {
json_t *array, *five, *seven, *value;
int i;
size_t i;
array = json_array();
five = json_integer(5);
seven = json_integer(7);
if(!array)
if (!array)
fail("unable to create array");
if(!five || !seven)
if (!five || !seven)
fail("unable to create integer");
if(json_array_size(array) != 0)
if (json_array_size(array) != 0)
fail("empty array has nonzero size");
if(!json_array_append(array, NULL))
if (!json_array_append(array, NULL))
fail("able to append NULL");
if(json_array_append(array, five))
if (json_array_append(array, five))
fail("unable to append");
if(json_array_size(array) != 1)
if (json_array_size(array) != 1)
fail("wrong array size");
value = json_array_get(array, 0);
if(!value)
if (!value)
fail("unable to get item");
if(value != five)
if (value != five)
fail("got wrong value");
if(json_array_append(array, seven))
if (json_array_append(array, seven))
fail("unable to append value");
if(json_array_size(array) != 2)
if (json_array_size(array) != 2)
fail("wrong array size");
value = json_array_get(array, 1);
if(!value)
if (!value)
fail("unable to get item");
if(value != seven)
if (value != seven)
fail("got wrong value");
if(json_array_set(array, 0, seven))
if (json_array_set(array, 0, seven))
fail("unable to set value");
if(!json_array_set(array, 0, NULL))
if (!json_array_set(array, 0, NULL))
fail("able to set NULL");
if(json_array_size(array) != 2)
if (json_array_size(array) != 2)
fail("wrong array size");
value = json_array_get(array, 0);
if(!value)
if (!value)
fail("unable to get item");
if(value != seven)
if (value != seven)
fail("got wrong value");
if(json_array_get(array, 2) != NULL)
if (json_array_get(array, 2) != NULL)
fail("able to get value out of bounds");
if(!json_array_set(array, 2, seven))
if (!json_array_set(array, 2, seven))
fail("able to set value out of bounds");
for(i = 2; i < 30; i++) {
if(json_array_append(array, seven))
for (i = 2; i < 30; i++) {
if (json_array_append(array, seven))
fail("unable to append value");
if(json_array_size(array) != i + 1)
if (json_array_size(array) != i + 1)
fail("wrong array size");
}
for(i = 0; i < 30; i++) {
for (i = 0; i < 30; i++) {
value = json_array_get(array, i);
if(!value)
if (!value)
fail("unable to get item");
if(value != seven)
if (value != seven)
fail("got wrong value");
}
if(json_array_set_new(array, 15, json_integer(123)))
if (json_array_set_new(array, 15, json_integer(123)))
fail("unable to set new value");
value = json_array_get(array, 15);
if(!json_is_integer(value) || json_integer_value(value) != 123)
if (!json_is_integer(value) || json_integer_value(value) != 123)
fail("json_array_set_new works incorrectly");
if(!json_array_set_new(array, 15, NULL))
if (!json_array_set_new(array, 15, NULL))
fail("able to set_new NULL value");
if(json_array_append_new(array, json_integer(321)))
if (json_array_append_new(array, json_integer(321)))
fail("unable to append new value");
value = json_array_get(array, json_array_size(array) - 1);
if(!json_is_integer(value) || json_integer_value(value) != 321)
if (!json_is_integer(value) || json_integer_value(value) != 321)
fail("json_array_append_new works incorrectly");
if(!json_array_append_new(array, NULL))
if (!json_array_append_new(array, NULL))
fail("able to append_new NULL value");
json_decref(five);
@ -114,8 +113,7 @@ static void test_misc(void)
json_decref(array);
}
static void test_insert(void)
{
static void test_insert(void) {
json_t *array, *five, *seven, *eleven, *value;
int i;
@ -124,77 +122,71 @@ static void test_insert(void)
seven = json_integer(7);
eleven = json_integer(11);
if(!array)
if (!array)
fail("unable to create array");
if(!five || !seven || !eleven)
if (!five || !seven || !eleven)
fail("unable to create integer");
if(!json_array_insert(array, 1, five))
if (!json_array_insert(array, 1, five))
fail("able to insert value out of bounds");
if(json_array_insert(array, 0, five))
if (json_array_insert(array, 0, five))
fail("unable to insert value in an empty array");
if(json_array_get(array, 0) != five)
if (json_array_get(array, 0) != five)
fail("json_array_insert works incorrectly");
if(json_array_size(array) != 1)
if (json_array_size(array) != 1)
fail("array size is invalid after insertion");
if(json_array_insert(array, 1, seven))
if (json_array_insert(array, 1, seven))
fail("unable to insert value at the end of an array");
if(json_array_get(array, 0) != five)
if (json_array_get(array, 0) != five)
fail("json_array_insert works incorrectly");
if(json_array_get(array, 1) != seven)
if (json_array_get(array, 1) != seven)
fail("json_array_insert works incorrectly");
if(json_array_size(array) != 2)
if (json_array_size(array) != 2)
fail("array size is invalid after insertion");
if(json_array_insert(array, 1, eleven))
if (json_array_insert(array, 1, eleven))
fail("unable to insert value in the middle of an array");
if(json_array_get(array, 0) != five)
if (json_array_get(array, 0) != five)
fail("json_array_insert works incorrectly");
if(json_array_get(array, 1) != eleven)
if (json_array_get(array, 1) != eleven)
fail("json_array_insert works incorrectly");
if(json_array_get(array, 2) != seven)
if (json_array_get(array, 2) != seven)
fail("json_array_insert works incorrectly");
if(json_array_size(array) != 3)
if (json_array_size(array) != 3)
fail("array size is invalid after insertion");
if(json_array_insert_new(array, 2, json_integer(123)))
if (json_array_insert_new(array, 2, json_integer(123)))
fail("unable to insert value in the middle of an array");
value = json_array_get(array, 2);
if(!json_is_integer(value) || json_integer_value(value) != 123)
if (!json_is_integer(value) || json_integer_value(value) != 123)
fail("json_array_insert_new works incorrectly");
if(json_array_size(array) != 4)
if (json_array_size(array) != 4)
fail("array size is invalid after insertion");
for(i = 0; i < 20; i++) {
if(json_array_insert(array, 0, seven))
fail("unable to insert value at the begining of an array");
for (i = 0; i < 20; i++) {
if (json_array_insert(array, 0, seven))
fail("unable to insert value at the beginning of an array");
}
for(i = 0; i < 20; i++) {
if(json_array_get(array, i) != seven)
for (i = 0; i < 20; i++) {
if (json_array_get(array, i) != seven)
fail("json_aray_insert works incorrectly");
}
if(json_array_size(array) != 24)
if (json_array_size(array) != 24)
fail("array size is invalid after loop insertion");
json_decref(five);
@ -203,63 +195,7 @@ static void test_insert(void)
json_decref(array);
}
static void test_remove(void)
{
json_t *array, *five, *seven;
array = json_array();
five = json_integer(5);
seven = json_integer(7);
if(!array)
fail("unable to create array");
if(!five)
fail("unable to create integer");
if(!seven)
fail("unable to create integer");
if(!json_array_remove(array, 0))
fail("able to remove an unexisting index");
if(json_array_append(array, five))
fail("unable to append");
if(!json_array_remove(array, 1))
fail("able to remove an unexisting index");
if(json_array_remove(array, 0))
fail("unable to remove");
if(json_array_size(array) != 0)
fail("array size is invalid after removing");
if(json_array_append(array, five) ||
json_array_append(array, seven) ||
json_array_append(array, five) ||
json_array_append(array, seven))
fail("unable to append");
if(json_array_remove(array, 2))
fail("unable to remove");
if(json_array_size(array) != 3)
fail("array size is invalid after removing");
if(json_array_get(array, 0) != five ||
json_array_get(array, 1) != seven ||
json_array_get(array, 2) != seven)
fail("remove works incorrectly");
json_decref(five);
json_decref(seven);
json_decref(array);
}
static void test_clear(void)
{
static void test_remove(void) {
json_t *array, *five, *seven;
int i;
@ -267,27 +203,89 @@ static void test_clear(void)
five = json_integer(5);
seven = json_integer(7);
if(!array)
if (!array)
fail("unable to create array");
if(!five || !seven)
if (!five)
fail("unable to create integer");
if (!seven)
fail("unable to create integer");
for(i = 0; i < 10; i++) {
if(json_array_append(array, five))
if (!json_array_remove(array, 0))
fail("able to remove an unexisting index");
if (json_array_append(array, five))
fail("unable to append");
if (!json_array_remove(array, 1))
fail("able to remove an unexisting index");
if (json_array_remove(array, 0))
fail("unable to remove");
if (json_array_size(array) != 0)
fail("array size is invalid after removing");
if (json_array_append(array, five) || json_array_append(array, seven) ||
json_array_append(array, five) || json_array_append(array, seven))
fail("unable to append");
if (json_array_remove(array, 2))
fail("unable to remove");
if (json_array_size(array) != 3)
fail("array size is invalid after removing");
if (json_array_get(array, 0) != five || json_array_get(array, 1) != seven ||
json_array_get(array, 2) != seven)
fail("remove works incorrectly");
json_decref(array);
array = json_array();
for (i = 0; i < 4; i++) {
json_array_append(array, five);
json_array_append(array, seven);
}
if (json_array_size(array) != 8)
fail("unable to append 8 items to array");
/* Remove an element from a "full" array. */
json_array_remove(array, 5);
json_decref(five);
json_decref(seven);
json_decref(array);
}
static void test_clear(void) {
json_t *array, *five, *seven;
int i;
array = json_array();
five = json_integer(5);
seven = json_integer(7);
if (!array)
fail("unable to create array");
if (!five || !seven)
fail("unable to create integer");
for (i = 0; i < 10; i++) {
if (json_array_append(array, five))
fail("unable to append");
}
for(i = 0; i < 10; i++) {
if(json_array_append(array, seven))
for (i = 0; i < 10; i++) {
if (json_array_append(array, seven))
fail("unable to append");
}
if(json_array_size(array) != 20)
if (json_array_size(array) != 20)
fail("array size is invalid after appending");
if(json_array_clear(array))
if (json_array_clear(array))
fail("unable to clear");
if(json_array_size(array) != 0)
if (json_array_size(array) != 0)
fail("array size is invalid after clearing");
json_decref(five);
@ -295,8 +293,7 @@ static void test_clear(void)
json_decref(array);
}
static void test_extend(void)
{
static void test_extend(void) {
json_t *array1, *array2, *five, *seven;
int i;
@ -305,32 +302,32 @@ static void test_extend(void)
five = json_integer(5);
seven = json_integer(7);
if(!array1 || !array2)
if (!array1 || !array2)
fail("unable to create array");
if(!five || !seven)
if (!five || !seven)
fail("unable to create integer");
for(i = 0; i < 10; i++) {
if(json_array_append(array1, five))
for (i = 0; i < 10; i++) {
if (json_array_append(array1, five))
fail("unable to append");
}
for(i = 0; i < 10; i++) {
if(json_array_append(array2, seven))
for (i = 0; i < 10; i++) {
if (json_array_append(array2, seven))
fail("unable to append");
}
if(json_array_size(array1) != 10 || json_array_size(array2) != 10)
if (json_array_size(array1) != 10 || json_array_size(array2) != 10)
fail("array size is invalid after appending");
if(json_array_extend(array1, array2))
if (json_array_extend(array1, array2))
fail("unable to extend");
for(i = 0; i < 10; i++) {
if(json_array_get(array1, i) != five)
for (i = 0; i < 10; i++) {
if (json_array_get(array1, i) != five)
fail("invalid array contents after extending");
}
for(i = 10; i < 20; i++) {
if(json_array_get(array1, i) != seven)
for (i = 10; i < 20; i++) {
if (json_array_get(array1, i) != seven)
fail("invalid array contents after extending");
}
@ -340,44 +337,41 @@ static void test_extend(void)
json_decref(array2);
}
static void test_circular()
{
static void test_circular() {
json_t *array1, *array2;
/* the simple cases are checked */
array1 = json_array();
if(!array1)
if (!array1)
fail("unable to create array");
if(json_array_append(array1, array1) == 0)
if (json_array_append(array1, array1) == 0)
fail("able to append self");
if(json_array_insert(array1, 0, array1) == 0)
if (json_array_insert(array1, 0, array1) == 0)
fail("able to insert self");
if(json_array_append_new(array1, json_true()))
if (json_array_append_new(array1, json_true()))
fail("failed to append true");
if(json_array_set(array1, 0, array1) == 0)
if (json_array_set(array1, 0, array1) == 0)
fail("able to set self");
json_decref(array1);
/* create circular references */
array1 = json_array();
array2 = json_array();
if(!array1 || !array2)
if (!array1 || !array2)
fail("unable to create array");
if(json_array_append(array1, array2) ||
json_array_append(array2, array1))
if (json_array_append(array1, array2) || json_array_append(array2, array1))
fail("unable to append");
/* circularity is detected when dumping */
if(json_dumps(array1, 0) != NULL)
if (json_dumps(array1, 0) != NULL)
fail("able to dump circulars");
/* decref twice to deal with the circular references */
@ -386,15 +380,105 @@ static void test_circular()
json_decref(array1);
}
static void test_array_foreach() {
size_t index;
json_t *array1, *array2, *value;
int main()
{
array1 = json_pack("[sisisi]", "foo", 1, "bar", 2, "baz", 3);
array2 = json_array();
json_array_foreach(array1, index, value) { json_array_append(array2, value); }
if (!json_equal(array1, array2))
fail("json_array_foreach failed to iterate all elements");
json_decref(array1);
json_decref(array2);
}
static void test_bad_args(void) {
json_t *arr = json_array();
json_t *num = json_integer(1);
if (!arr || !num)
fail("failed to create required objects");
if (json_array_size(NULL) != 0)
fail("NULL array has nonzero size");
if (json_array_size(num) != 0)
fail("non-array has nonzero array size");
if (json_array_get(NULL, 0))
fail("json_array_get did not return NULL for non-array");
if (json_array_get(num, 0))
fail("json_array_get did not return NULL for non-array");
if (!json_array_set_new(NULL, 0, json_incref(num)))
fail("json_array_set_new did not return error for non-array");
if (!json_array_set_new(num, 0, json_incref(num)))
fail("json_array_set_new did not return error for non-array");
if (!json_array_set_new(arr, 0, NULL))
fail("json_array_set_new did not return error for NULL value");
if (!json_array_set_new(arr, 0, json_incref(arr)))
fail("json_array_set_new did not return error for value == array");
if (!json_array_remove(NULL, 0))
fail("json_array_remove did not return error for non-array");
if (!json_array_remove(num, 0))
fail("json_array_remove did not return error for non-array");
if (!json_array_clear(NULL))
fail("json_array_clear did not return error for non-array");
if (!json_array_clear(num))
fail("json_array_clear did not return error for non-array");
if (!json_array_append_new(NULL, json_incref(num)))
fail("json_array_append_new did not return error for non-array");
if (!json_array_append_new(num, json_incref(num)))
fail("json_array_append_new did not return error for non-array");
if (!json_array_append_new(arr, NULL))
fail("json_array_append_new did not return error for NULL value");
if (!json_array_append_new(arr, json_incref(arr)))
fail("json_array_append_new did not return error for value == array");
if (!json_array_insert_new(NULL, 0, json_incref(num)))
fail("json_array_insert_new did not return error for non-array");
if (!json_array_insert_new(num, 0, json_incref(num)))
fail("json_array_insert_new did not return error for non-array");
if (!json_array_insert_new(arr, 0, NULL))
fail("json_array_insert_new did not return error for NULL value");
if (!json_array_insert_new(arr, 0, json_incref(arr)))
fail("json_array_insert_new did not return error for value == array");
if (!json_array_extend(NULL, arr))
fail("json_array_extend did not return error for first argument "
"non-array");
if (!json_array_extend(num, arr))
fail("json_array_extend did not return error for first argument "
"non-array");
if (!json_array_extend(arr, NULL))
fail("json_array_extend did not return error for second argument "
"non-array");
if (!json_array_extend(arr, num))
fail("json_array_extend did not return error for second argument "
"non-array");
if (num->refcount != 1)
fail("unexpected reference count on num");
if (arr->refcount != 1)
fail("unexpected reference count on arr");
json_decref(num);
json_decref(arr);
}
static void run_tests() {
test_misc();
test_insert();
test_remove();
test_clear();
test_extend();
test_circular();
return 0;
test_array_foreach();
test_bad_args();
}

View file

@ -0,0 +1,168 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "util.h"
#include <jansson.h>
#include <stdio.h>
#include <string.h>
static int chaos_pos = 0;
static int chaos_fail = 0;
#define CHAOS_MAX_FAILURE 100
void *chaos_malloc(size_t size) {
if (chaos_pos == chaos_fail)
return NULL;
chaos_pos++;
return malloc(size);
}
void chaos_free(void *obj) { free(obj); }
/* Test all potential allocation failures. */
#define chaos_loop(condition, code, cleanup) \
{ \
chaos_pos = chaos_fail = 0; \
while (condition) { \
if (chaos_fail > CHAOS_MAX_FAILURE) \
fail("too many chaos failures"); \
code chaos_pos = 0; \
chaos_fail++; \
} \
cleanup \
}
#define chaos_loop_new_value(json, initcall) \
chaos_loop(!json, json = initcall;, json_decref(json); json = NULL;)
int test_unpack() {
int ret = -1;
int v1;
int v2;
json_error_t error;
json_t *root = json_pack("{s:i, s:i, s:i, s:i}", "n1", 1, "n2", 2, "n3", 3, "n4", 4);
if (!root)
return -1;
if (!json_unpack_ex(root, &error, JSON_STRICT, "{s:i, s:i}", "n1", &v1, "n2", &v2))
fail("Unexpected success");
if (json_error_code(&error) != json_error_end_of_input_expected) {
if (json_error_code(&error) != json_error_out_of_memory)
fail("Unexpected error code");
goto out;
}
if (strcmp(error.text, "2 object item(s) left unpacked: n3, n4"))
goto out;
ret = 0;
out:
json_decref(root);
return ret;
}
int dump_chaos_callback(const char *buffer, size_t size, void *data) {
json_t *obj = json_object();
(void)buffer;
(void)size;
(void)data;
if (!obj)
return -1;
json_decref(obj);
return 0;
}
static void test_chaos() {
json_malloc_t orig_malloc;
json_free_t orig_free;
json_t *json = NULL;
json_t *obj = json_object();
json_t *arr1 = json_array();
json_t *arr2 = json_array();
json_t *txt = json_string("test");
json_t *intnum = json_integer(1);
json_t *dblnum = json_real(0.5);
char *dumptxt = NULL;
json_t *dumpobj = json_pack("{s:[iiis], s:s}", "key1", 1, 2, 3, "txt", "key2", "v2");
int keyno;
if (!obj || !arr1 || !arr2 || !txt || !intnum || !dblnum || !dumpobj)
fail("failed to allocate basic objects");
json_get_alloc_funcs(&orig_malloc, &orig_free);
json_set_alloc_funcs(chaos_malloc, chaos_free);
chaos_loop_new_value(json, json_pack("{s:s}", "key", "value"));
chaos_loop_new_value(json, json_pack("{s:[]}", "key"));
chaos_loop_new_value(json, json_pack("[biIf]", 1, 1, (json_int_t)1, 1.0));
chaos_loop_new_value(json, json_pack("[s*,s*]", "v1", "v2"));
chaos_loop_new_value(json, json_pack("o", json_incref(txt)));
chaos_loop_new_value(json, json_pack("O", txt));
chaos_loop_new_value(json, json_pack("s++", "a", "long string to force realloc",
"another long string to force yet another "
"reallocation of the string because "
"that's what we are testing."));
chaos_loop(test_unpack(), , );
chaos_loop(json_dump_callback(dumpobj, dump_chaos_callback, NULL, JSON_INDENT(1)),
, );
chaos_loop(json_dump_callback(dumpobj, dump_chaos_callback, NULL,
JSON_INDENT(1) | JSON_SORT_KEYS),
, );
chaos_loop(!dumptxt, dumptxt = json_dumps(dumpobj, JSON_COMPACT);, free(dumptxt);
dumptxt = NULL;);
chaos_loop_new_value(json, json_copy(obj));
chaos_loop_new_value(json, json_deep_copy(obj));
chaos_loop_new_value(json, json_copy(arr1));
chaos_loop_new_value(json, json_deep_copy(arr1));
chaos_loop_new_value(json, json_copy(txt));
chaos_loop_new_value(json, json_copy(intnum));
chaos_loop_new_value(json, json_copy(dblnum));
#define JSON_LOAD_TXT "{\"n\":[1,2,3,4,5,6,7,8,9,10]}"
chaos_loop_new_value(json, json_loads(JSON_LOAD_TXT, 0, NULL));
chaos_loop_new_value(json, json_loadb(JSON_LOAD_TXT, strlen(JSON_LOAD_TXT), 0, NULL));
chaos_loop_new_value(json, json_sprintf("%s", "string"));
for (keyno = 0; keyno < 100; ++keyno) {
#if !defined(_MSC_VER) || _MSC_VER >= 1900
/* Skip this test on old Windows compilers. */
char testkey[10];
snprintf(testkey, sizeof(testkey), "test%d", keyno);
chaos_loop(json_object_set_new_nocheck(obj, testkey, json_object()), , );
#endif
chaos_loop(json_array_append_new(arr1, json_null()), , );
chaos_loop(json_array_insert_new(arr2, 0, json_null()), , );
}
chaos_loop(json_array_extend(arr1, arr2), , );
chaos_loop(json_string_set_nocheck(txt, "test"), , );
json_set_alloc_funcs(orig_malloc, orig_free);
json_decref(obj);
json_decref(arr1);
json_decref(arr2);
json_decref(txt);
json_decref(intnum);
json_decref(dblnum);
json_decref(dumpobj);
}
static void run_tests() { test_chaos(); }

View file

@ -1,25 +1,24 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <string.h>
#include <jansson.h>
#include "util.h"
#include <jansson.h>
#include <string.h>
static void test_copy_simple(void)
{
static void test_copy_simple(void) {
json_t *value, *copy;
if(json_copy(NULL))
if (json_copy(NULL))
fail("copying NULL doesn't return NULL");
/* true */
value = json_true();
copy = json_copy(value);
if(value != copy)
if (value != copy)
fail("copying true failed");
json_decref(value);
json_decref(copy);
@ -27,7 +26,7 @@ static void test_copy_simple(void)
/* false */
value = json_false();
copy = json_copy(value);
if(value != copy)
if (value != copy)
fail("copying false failed");
json_decref(value);
json_decref(copy);
@ -35,71 +34,70 @@ static void test_copy_simple(void)
/* null */
value = json_null();
copy = json_copy(value);
if(value != copy)
if (value != copy)
fail("copying null failed");
json_decref(value);
json_decref(copy);
/* string */
value = json_string("foo");
if(!value)
if (!value)
fail("unable to create a string");
copy = json_copy(value);
if(!copy)
if (!copy)
fail("unable to copy a string");
if(copy == value)
if (copy == value)
fail("copying a string doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("copying a string produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
/* integer */
value = json_integer(543);
if(!value)
if (!value)
fail("unable to create an integer");
copy = json_copy(value);
if(!copy)
if (!copy)
fail("unable to copy an integer");
if(copy == value)
if (copy == value)
fail("copying an integer doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("copying an integer produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
/* real */
value = json_real(123e9);
if(!value)
if (!value)
fail("unable to create a real");
copy = json_copy(value);
if(!copy)
if (!copy)
fail("unable to copy a real");
if(copy == value)
if (copy == value)
fail("copying a real doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("copying a real produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
}
static void test_deep_copy_simple(void)
{
static void test_deep_copy_simple(void) {
json_t *value, *copy;
if(json_deep_copy(NULL))
if (json_deep_copy(NULL))
fail("deep copying NULL doesn't return NULL");
/* true */
value = json_true();
copy = json_deep_copy(value);
if(value != copy)
if (value != copy)
fail("deep copying true failed");
json_decref(value);
json_decref(copy);
@ -107,7 +105,7 @@ static void test_deep_copy_simple(void)
/* false */
value = json_false();
copy = json_deep_copy(value);
if(value != copy)
if (value != copy)
fail("deep copying false failed");
json_decref(value);
json_decref(copy);
@ -115,82 +113,80 @@ static void test_deep_copy_simple(void)
/* null */
value = json_null();
copy = json_deep_copy(value);
if(value != copy)
if (value != copy)
fail("deep copying null failed");
json_decref(value);
json_decref(copy);
/* string */
value = json_string("foo");
if(!value)
if (!value)
fail("unable to create a string");
copy = json_deep_copy(value);
if(!copy)
if (!copy)
fail("unable to deep copy a string");
if(copy == value)
if (copy == value)
fail("deep copying a string doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("deep copying a string produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
/* integer */
value = json_integer(543);
if(!value)
if (!value)
fail("unable to create an integer");
copy = json_deep_copy(value);
if(!copy)
if (!copy)
fail("unable to deep copy an integer");
if(copy == value)
if (copy == value)
fail("deep copying an integer doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("deep copying an integer produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
/* real */
value = json_real(123e9);
if(!value)
if (!value)
fail("unable to create a real");
copy = json_deep_copy(value);
if(!copy)
if (!copy)
fail("unable to deep copy a real");
if(copy == value)
if (copy == value)
fail("deep copying a real doesn't copy");
if(!json_equal(copy, value))
if (!json_equal(copy, value))
fail("deep copying a real produces an inequal copy");
if(value->refcount != 1 || copy->refcount != 1)
if (value->refcount != 1 || copy->refcount != 1)
fail("invalid refcounts");
json_decref(value);
json_decref(copy);
}
static void test_copy_array(void)
{
static void test_copy_array(void) {
const char *json_array_text = "[1, \"foo\", 3.141592, {\"foo\": \"bar\"}]";
json_t *array, *copy;
unsigned int i;
size_t i;
array = json_loads(json_array_text, NULL);
if(!array)
array = json_loads(json_array_text, 0, NULL);
if (!array)
fail("unable to parse an array");
copy = json_copy(array);
if(!copy)
if (!copy)
fail("unable to copy an array");
if(copy == array)
if (copy == array)
fail("copying an array doesn't copy");
if(!json_equal(copy, array))
if (!json_equal(copy, array))
fail("copying an array produces an inequal copy");
for(i = 0; i < json_array_size(copy); i++)
{
if(json_array_get(array, i) != json_array_get(copy, i))
for (i = 0; i < json_array_size(copy); i++) {
if (json_array_get(array, i) != json_array_get(copy, i))
fail("copying an array modifies its elements");
}
@ -198,28 +194,26 @@ static void test_copy_array(void)
json_decref(copy);
}
static void test_deep_copy_array(void)
{
static void test_deep_copy_array(void) {
const char *json_array_text = "[1, \"foo\", 3.141592, {\"foo\": \"bar\"}]";
json_t *array, *copy;
unsigned int i;
size_t i;
array = json_loads(json_array_text, NULL);
if(!array)
array = json_loads(json_array_text, 0, NULL);
if (!array)
fail("unable to parse an array");
copy = json_deep_copy(array);
if(!copy)
if (!copy)
fail("unable to deep copy an array");
if(copy == array)
if (copy == array)
fail("deep copying an array doesn't copy");
if(!json_equal(copy, array))
if (!json_equal(copy, array))
fail("deep copying an array produces an inequal copy");
for(i = 0; i < json_array_size(copy); i++)
{
if(json_array_get(array, i) == json_array_get(copy, i))
for (i = 0; i < json_array_size(copy); i++) {
if (json_array_get(array, i) == json_array_get(copy, i))
fail("deep copying an array doesn't copy its elements");
}
@ -227,29 +221,31 @@ static void test_deep_copy_array(void)
json_decref(copy);
}
static void test_copy_object(void)
{
static void test_copy_object(void) {
const char *json_object_text =
"{\"foo\": \"bar\", \"a\": 1, \"b\": 3.141592, \"c\": [1,2,3,4]}";
const char *keys[] = {"foo", "a", "b", "c"};
int i;
json_t *object, *copy;
void *iter;
object = json_loads(json_object_text, NULL);
if(!object)
object = json_loads(json_object_text, 0, NULL);
if (!object)
fail("unable to parse an object");
copy = json_copy(object);
if(!copy)
if (!copy)
fail("unable to copy an object");
if(copy == object)
if (copy == object)
fail("copying an object doesn't copy");
if(!json_equal(copy, object))
if (!json_equal(copy, object))
fail("copying an object produces an inequal copy");
i = 0;
iter = json_object_iter(object);
while(iter)
{
while (iter) {
const char *key;
json_t *value1, *value2;
@ -257,39 +253,45 @@ static void test_copy_object(void)
value1 = json_object_iter_value(iter);
value2 = json_object_get(copy, key);
if(value1 != value2)
fail("deep copying an object modifies its items");
if (value1 != value2)
fail("copying an object modifies its items");
if (strcmp(key, keys[i]) != 0)
fail("copying an object doesn't preserve key order");
iter = json_object_iter_next(object, iter);
i++;
}
json_decref(object);
json_decref(copy);
}
static void test_deep_copy_object(void)
{
static void test_deep_copy_object(void) {
const char *json_object_text =
"{\"foo\": \"bar\", \"a\": 1, \"b\": 3.141592, \"c\": [1,2,3,4]}";
const char *keys[] = {"foo", "a", "b", "c"};
int i;
json_t *object, *copy;
void *iter;
object = json_loads(json_object_text, NULL);
if(!object)
object = json_loads(json_object_text, 0, NULL);
if (!object)
fail("unable to parse an object");
copy = json_deep_copy(object);
if(!copy)
if (!copy)
fail("unable to deep copy an object");
if(copy == object)
if (copy == object)
fail("deep copying an object doesn't copy");
if(!json_equal(copy, object))
if (!json_equal(copy, object))
fail("deep copying an object produces an inequal copy");
i = 0;
iter = json_object_iter(object);
while(iter)
{
while (iter) {
const char *key;
json_t *value1, *value2;
@ -297,23 +299,77 @@ static void test_deep_copy_object(void)
value1 = json_object_iter_value(iter);
value2 = json_object_get(copy, key);
if(value1 == value2)
if (value1 == value2)
fail("deep copying an object doesn't copy its items");
if (strcmp(key, keys[i]) != 0)
fail("deep copying an object doesn't preserve key order");
iter = json_object_iter_next(object, iter);
i++;
}
json_decref(object);
json_decref(copy);
}
int main()
{
static void test_deep_copy_circular_references(void) {
/* Construct a JSON object/array with a circular reference:
object: {"a": {"b": {"c": <circular reference to $.a>}}}
array: [[[<circular reference to the $[0] array>]]]
Deep copy it, remove the circular reference and deep copy again.
*/
json_t *json;
json_t *copy;
json = json_object();
json_object_set_new(json, "a", json_object());
json_object_set_new(json_object_get(json, "a"), "b", json_object());
json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
json_object_get(json, "a"));
copy = json_deep_copy(json);
if (copy)
fail("json_deep_copy copied a circular reference!");
json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");
copy = json_deep_copy(json);
if (!copy)
fail("json_deep_copy failed!");
json_decref(copy);
json_decref(json);
json = json_array();
json_array_append_new(json, json_array());
json_array_append_new(json_array_get(json, 0), json_array());
json_array_append(json_array_get(json_array_get(json, 0), 0),
json_array_get(json, 0));
copy = json_deep_copy(json);
if (copy)
fail("json_deep_copy copied a circular reference!");
json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);
copy = json_deep_copy(json);
if (!copy)
fail("json_deep_copy failed!");
json_decref(copy);
json_decref(json);
}
static void run_tests() {
test_copy_simple();
test_deep_copy_simple();
test_copy_array();
test_deep_copy_array();
test_copy_object();
test_deep_copy_object();
return 0;
test_deep_copy_circular_references();
}

View file

@ -1,49 +1,87 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "jansson_private_config.h"
#include <jansson.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "util.h"
#ifdef __MINGW32__
#include <fcntl.h>
#define pipe(fds) _pipe(fds, 1024, _O_BINARY)
#endif
static int encode_null_callback(const char *buffer, size_t size, void *data) {
(void)buffer;
(void)size;
(void)data;
return 0;
}
static void encode_null() {
if (json_dumps(NULL, JSON_ENCODE_ANY) != NULL)
fail("json_dumps didn't fail for NULL");
if (json_dumpb(NULL, NULL, 0, JSON_ENCODE_ANY) != 0)
fail("json_dumpb didn't fail for NULL");
if (json_dumpf(NULL, stderr, JSON_ENCODE_ANY) != -1)
fail("json_dumpf didn't fail for NULL");
#ifdef HAVE_UNISTD_H
if (json_dumpfd(NULL, STDERR_FILENO, JSON_ENCODE_ANY) != -1)
fail("json_dumpfd didn't fail for NULL");
#endif
/* Don't test json_dump_file to avoid creating a file */
if (json_dump_callback(NULL, encode_null_callback, NULL, JSON_ENCODE_ANY) != -1)
fail("json_dump_callback didn't fail for NULL");
}
static void encode_twice() {
/* Encode an empty object/array, add an item, encode again */
int main()
{
json_t *json;
char *result;
/* Encode an empty object/array, add an item, encode again */
json = json_object();
result = json_dumps(json, 0);
if(!result || strcmp(result, "{}"))
fail("json_dumps failed");
if (!result || strcmp(result, "{}"))
fail("json_dumps failed");
free(result);
json_object_set_new(json, "foo", json_integer(5));
result = json_dumps(json, 0);
if(!result || strcmp(result, "{\"foo\": 5}"))
fail("json_dumps failed");
if (!result || strcmp(result, "{\"foo\": 5}"))
fail("json_dumps failed");
free(result);
json_decref(json);
json = json_array();
result = json_dumps(json, 0);
if(!result || strcmp(result, "[]"))
fail("json_dumps failed");
if (!result || strcmp(result, "[]"))
fail("json_dumps failed");
free(result);
json_array_append_new(json, json_integer(5));
result = json_dumps(json, 0);
if(!result || strcmp(result, "[5]"))
fail("json_dumps failed");
if (!result || strcmp(result, "[5]"))
fail("json_dumps failed");
free(result);
json_decref(json);
}
static void circular_references() {
/* Construct a JSON object/array with a circular reference:
object: {"a": {"b": {"c": <circular reference to $.a>}}}
@ -51,19 +89,23 @@ int main()
Encode it, remove the circular reference and encode again.
*/
json_t *json;
char *result;
json = json_object();
json_object_set_new(json, "a", json_object());
json_object_set_new(json_object_get(json, "a"), "b", json_object());
json_object_set(json_object_get(json_object_get(json, "a"), "b"), "c",
json_object_get(json, "a"));
if(json_dumps(json, 0))
if (json_dumps(json, 0))
fail("json_dumps encoded a circular reference!");
json_object_del(json_object_get(json_object_get(json, "a"), "b"), "c");
result = json_dumps(json, 0);
if(!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
if (!result || strcmp(result, "{\"a\": {\"b\": {}}}"))
fail("json_dumps failed!");
free(result);
@ -75,17 +117,195 @@ int main()
json_array_append(json_array_get(json_array_get(json, 0), 0),
json_array_get(json, 0));
if(json_dumps(json, 0))
if (json_dumps(json, 0))
fail("json_dumps encoded a circular reference!");
json_array_remove(json_array_get(json_array_get(json, 0), 0), 0);
result = json_dumps(json, 0);
if(!result || strcmp(result, "[[[]]]"))
if (!result || strcmp(result, "[[[]]]"))
fail("json_dumps failed!");
free(result);
json_decref(json);
return 0;
}
static void encode_other_than_array_or_object() {
/* Encoding anything other than array or object should only
* succeed if the JSON_ENCODE_ANY flag is used */
json_t *json;
char *result;
json = json_string("foo");
if (json_dumps(json, 0) != NULL)
fail("json_dumps encoded a string!");
if (json_dumpf(json, NULL, 0) == 0)
fail("json_dumpf encoded a string!");
if (json_dumpfd(json, -1, 0) == 0)
fail("json_dumpfd encoded a string!");
result = json_dumps(json, JSON_ENCODE_ANY);
if (!result || strcmp(result, "\"foo\"") != 0)
fail("json_dumps failed to encode a string with JSON_ENCODE_ANY");
free(result);
json_decref(json);
json = json_integer(42);
if (json_dumps(json, 0) != NULL)
fail("json_dumps encoded an integer!");
if (json_dumpf(json, NULL, 0) == 0)
fail("json_dumpf encoded an integer!");
if (json_dumpfd(json, -1, 0) == 0)
fail("json_dumpfd encoded an integer!");
result = json_dumps(json, JSON_ENCODE_ANY);
if (!result || strcmp(result, "42") != 0)
fail("json_dumps failed to encode an integer with JSON_ENCODE_ANY");
free(result);
json_decref(json);
}
static void escape_slashes() {
/* Test dump escaping slashes */
json_t *json;
char *result;
json = json_object();
json_object_set_new(json, "url", json_string("https://github.com/akheron/jansson"));
result = json_dumps(json, 0);
if (!result || strcmp(result, "{\"url\": \"https://github.com/akheron/jansson\"}"))
fail("json_dumps failed to not escape slashes");
free(result);
result = json_dumps(json, JSON_ESCAPE_SLASH);
if (!result ||
strcmp(result, "{\"url\": \"https:\\/\\/github.com\\/akheron\\/jansson\"}"))
fail("json_dumps failed to escape slashes");
free(result);
json_decref(json);
}
static void encode_nul_byte() {
json_t *json;
char *result;
json = json_stringn("nul byte \0 in string", 20);
result = json_dumps(json, JSON_ENCODE_ANY);
if (!result || memcmp(result, "\"nul byte \\u0000 in string\"", 27))
fail("json_dumps failed to dump an embedded NUL byte");
free(result);
json_decref(json);
}
static void dump_file() {
json_t *json;
int result;
result = json_dump_file(NULL, "", 0);
if (result != -1)
fail("json_dump_file succeeded with invalid args");
json = json_object();
result = json_dump_file(json, "json_dump_file.json", 0);
if (result != 0)
fail("json_dump_file failed");
json_decref(json);
remove("json_dump_file.json");
}
static void dumpb() {
char buf[2];
json_t *obj;
size_t size;
obj = json_object();
size = json_dumpb(obj, buf, sizeof(buf), 0);
if (size != 2 || strncmp(buf, "{}", 2))
fail("json_dumpb failed");
json_decref(obj);
obj = json_pack("{s:s}", "foo", "bar");
size = json_dumpb(obj, buf, sizeof(buf), JSON_COMPACT);
if (size != 13)
fail("json_dumpb size check failed");
json_decref(obj);
}
static void dumpfd() {
#ifdef HAVE_UNISTD_H
int fds[2] = {-1, -1};
json_t *a, *b;
if (pipe(fds))
fail("pipe() failed");
a = json_pack("{s:s}", "foo", "bar");
if (json_dumpfd(a, fds[1], 0))
fail("json_dumpfd() failed");
close(fds[1]);
b = json_loadfd(fds[0], 0, NULL);
if (!b)
fail("json_loadfd() failed");
close(fds[0]);
if (!json_equal(a, b))
fail("json_equal() failed for fd test");
json_decref(a);
json_decref(b);
#endif
}
static void embed() {
static const char *plains[] = {"{\"bar\":[],\"foo\":{}}", "[[],{}]", "{}", "[]",
NULL};
size_t i;
for (i = 0; plains[i]; i++) {
const char *plain = plains[i];
json_t *parse = NULL;
char *embed = NULL;
size_t psize = 0;
size_t esize = 0;
psize = strlen(plain) - 2;
embed = calloc(1, psize);
parse = json_loads(plain, 0, NULL);
esize =
json_dumpb(parse, embed, psize, JSON_COMPACT | JSON_SORT_KEYS | JSON_EMBED);
json_decref(parse);
if (esize != psize)
fail("json_dumpb(JSON_EMBED) returned an invalid size");
if (strncmp(plain + 1, embed, esize) != 0)
fail("json_dumps(JSON_EMBED) returned an invalid value");
free(embed);
}
}
static void run_tests() {
encode_null();
encode_twice();
circular_references();
encode_other_than_array_or_object();
escape_slashes();
encode_nul_byte();
dump_file();
dumpb();
dumpfd();
embed();
}

View file

@ -0,0 +1,82 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <stdlib.h>
#include <string.h>
struct my_sink {
char *buf;
size_t off;
size_t cap;
};
static int my_writer(const char *buffer, size_t len, void *data) {
struct my_sink *s = data;
if (len > s->cap - s->off) {
return -1;
}
memcpy(s->buf + s->off, buffer, len);
s->off += len;
return 0;
}
static void run_tests() {
struct my_sink s;
json_t *json;
const char str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
char *dumped_to_string;
json = json_loads(str, 0, NULL);
if (!json) {
fail("json_loads failed");
}
dumped_to_string = json_dumps(json, 0);
if (!dumped_to_string) {
json_decref(json);
fail("json_dumps failed");
}
s.off = 0;
s.cap = strlen(dumped_to_string);
s.buf = malloc(s.cap);
if (!s.buf) {
json_decref(json);
free(dumped_to_string);
fail("malloc failed");
}
if (json_dump_callback(json, my_writer, &s, 0) == -1) {
json_decref(json);
free(dumped_to_string);
free(s.buf);
fail("json_dump_callback failed on an exact-length sink buffer");
}
if (strncmp(dumped_to_string, s.buf, s.off) != 0) {
json_decref(json);
free(dumped_to_string);
free(s.buf);
fail("json_dump_callback and json_dumps did not produce identical "
"output");
}
s.off = 1;
if (json_dump_callback(json, my_writer, &s, 0) != -1) {
json_decref(json);
free(dumped_to_string);
free(s.buf);
fail("json_dump_callback succeeded on a short buffer when it should "
"have failed");
}
json_decref(json);
free(dumped_to_string);
free(s.buf);
}

View file

@ -1,42 +1,41 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <jansson.h>
#include "util.h"
#include <jansson.h>
static void test_equal_simple()
{
static void test_equal_simple() {
json_t *value1, *value2;
if(json_equal(NULL, NULL))
if (json_equal(NULL, NULL))
fail("json_equal fails for two NULLs");
value1 = json_true();
if(json_equal(value1, NULL) || json_equal(NULL, value1))
if (json_equal(value1, NULL) || json_equal(NULL, value1))
fail("json_equal fails for NULL");
/* this covers true, false and null as they are singletons */
if(!json_equal(value1, value1))
if (!json_equal(value1, value1))
fail("identical objects are not equal");
json_decref(value1);
/* integer */
value1 = json_integer(1);
value2 = json_integer(1);
if(!value1 || !value2)
if (!value1 || !value2)
fail("unable to create integers");
if(!json_equal(value1, value2))
if (!json_equal(value1, value2))
fail("json_equal fails for two equal integers");
json_decref(value2);
value2 = json_integer(2);
if(!value2)
if (!value2)
fail("unable to create an integer");
if(json_equal(value1, value2))
if (json_equal(value1, value2))
fail("json_equal fails for two inequal integers");
json_decref(value1);
@ -45,16 +44,16 @@ static void test_equal_simple()
/* real */
value1 = json_real(1.2);
value2 = json_real(1.2);
if(!value1 || !value2)
if (!value1 || !value2)
fail("unable to create reals");
if(!json_equal(value1, value2))
if (!json_equal(value1, value2))
fail("json_equal fails for two equal reals");
json_decref(value2);
value2 = json_real(3.141592);
if(!value2)
if (!value2)
fail("unable to create an real");
if(json_equal(value1, value2))
if (json_equal(value1, value2))
fail("json_equal fails for two inequal reals");
json_decref(value1);
@ -63,32 +62,38 @@ static void test_equal_simple()
/* string */
value1 = json_string("foo");
value2 = json_string("foo");
if(!value1 || !value2)
if (!value1 || !value2)
fail("unable to create strings");
if(!json_equal(value1, value2))
if (!json_equal(value1, value2))
fail("json_equal fails for two equal strings");
json_decref(value2);
value2 = json_string("bar");
if(!value2)
if (!value2)
fail("unable to create an string");
if(json_equal(value1, value2))
if (json_equal(value1, value2))
fail("json_equal fails for two inequal strings");
json_decref(value2);
value2 = json_string("bar2");
if (!value2)
fail("unable to create an string");
if (json_equal(value1, value2))
fail("json_equal fails for two inequal length strings");
json_decref(value1);
json_decref(value2);
}
static void test_equal_array()
{
static void test_equal_array() {
json_t *array1, *array2;
array1 = json_array();
array2 = json_array();
if(!array1 || !array2)
if (!array1 || !array2)
fail("unable to create arrays");
if(!json_equal(array1, array2))
if (!json_equal(array1, array2))
fail("json_equal fails for two empty arrays");
json_array_append_new(array1, json_integer(1));
@ -97,31 +102,30 @@ static void test_equal_array()
json_array_append_new(array2, json_string("foo"));
json_array_append_new(array1, json_integer(2));
json_array_append_new(array2, json_integer(2));
if(!json_equal(array1, array2))
if (!json_equal(array1, array2))
fail("json_equal fails for two equal arrays");
json_array_remove(array2, 2);
if(json_equal(array1, array2))
if (json_equal(array1, array2))
fail("json_equal fails for two inequal arrays");
json_array_append_new(array2, json_integer(3));
if(json_equal(array1, array2))
if (json_equal(array1, array2))
fail("json_equal fails for two inequal arrays");
json_decref(array1);
json_decref(array2);
}
static void test_equal_object()
{
static void test_equal_object() {
json_t *object1, *object2;
object1 = json_object();
object2 = json_object();
if(!object1 || !object2)
if (!object1 || !object2)
fail("unable to create objects");
if(!json_equal(object1, object2))
if (!json_equal(object1, object2))
fail("json_equal fails for two empty objects");
json_object_set_new(object1, "a", json_integer(1));
@ -130,61 +134,69 @@ static void test_equal_object()
json_object_set_new(object2, "b", json_string("foo"));
json_object_set_new(object1, "c", json_integer(2));
json_object_set_new(object2, "c", json_integer(2));
if(!json_equal(object1, object2))
if (!json_equal(object1, object2))
fail("json_equal fails for two equal objects");
json_object_del(object2, "c");
if(json_equal(object1, object2))
if (json_equal(object1, object2))
fail("json_equal fails for two inequal objects");
json_object_set_new(object2, "c", json_integer(3));
if(json_equal(object1, object2))
if (json_equal(object1, object2))
fail("json_equal fails for two inequal objects");
json_object_del(object2, "c");
json_object_set_new(object2, "d", json_integer(2));
if(json_equal(object1, object2))
if (json_equal(object1, object2))
fail("json_equal fails for two inequal objects");
json_decref(object1);
json_decref(object2);
}
static void test_equal_complex()
{
json_t *value1, *value2;
static void test_equal_complex() {
json_t *value1, *value2, *value3;
const char *complex_json =
"{"
" \"integer\": 1, "
" \"real\": 3.141592, "
" \"string\": \"foobar\", "
" \"true\": true, "
" \"object\": {"
" \"array-in-object\": [1,true,\"foo\",{}],"
" \"object-in-object\": {\"foo\": \"bar\"}"
" },"
" \"array\": [\"foo\", false, null, 1.234]"
"}";
const char *complex_json = "{"
" \"integer\": 1, "
" \"real\": 3.141592, "
" \"string\": \"foobar\", "
" \"true\": true, "
" \"object\": {"
" \"array-in-object\": [1,true,\"foo\",{}],"
" \"object-in-object\": {\"foo\": \"bar\"}"
" },"
" \"array\": [\"foo\", false, null, 1.234]"
"}";
value1 = json_loads(complex_json, NULL);
value2 = json_loads(complex_json, NULL);
if(!value1 || !value2)
value1 = json_loads(complex_json, 0, NULL);
value2 = json_loads(complex_json, 0, NULL);
value3 = json_loads(complex_json, 0, NULL);
if (!value1 || !value2)
fail("unable to parse JSON");
if(!json_equal(value1, value2))
fail("json_equal fails for two inequal strings");
if (!json_equal(value1, value2))
fail("json_equal fails for two equal objects");
json_array_set_new(
json_object_get(json_object_get(value2, "object"), "array-in-object"), 1,
json_false());
if (json_equal(value1, value2))
fail("json_equal fails for two inequal objects");
json_object_set_new(
json_object_get(json_object_get(value3, "object"), "object-in-object"), "foo",
json_string("baz"));
if (json_equal(value1, value3))
fail("json_equal fails for two inequal objects");
json_decref(value1);
json_decref(value2);
/* TODO: There's no negative test case here */
json_decref(value3);
}
int main()
{
static void run_tests() {
test_equal_simple();
test_equal_array();
test_equal_object();
test_equal_complex();
return 0;
}

View file

@ -0,0 +1,228 @@
/*
* Copyright (c) 2020 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <string.h>
static void test_keylen_iterator(json_t *object) {
const char key1[] = {'t', 'e', 's', 't', '1'};
const char key2[] = {'t', 'e', 's', 't'};
const char key3[] = {'t', 'e', 's', '\0', 't'};
const char key4[] = {'t', 'e', 's', 't', '\0'};
const char *reference_keys[] = {key1, key2, key3, key4};
const size_t reference_keys_len[] = {sizeof(key1), sizeof(key2), sizeof(key3),
sizeof(key4)};
size_t index = 0;
json_t *value;
const char *key;
size_t keylen;
json_object_keylen_foreach(object, key, keylen, value) {
if (keylen != reference_keys_len[index])
fail("invalid key len in iterator");
if (memcmp(key, reference_keys[index], reference_keys_len[index]) != 0)
fail("invalid key in iterator");
index++;
}
}
static void test_keylen(void) {
json_t *obj = json_object();
const char key[] = {'t', 'e', 's', 't', '1'};
const char key2[] = {'t', 'e', 's', 't'};
const char key3[] = {'t', 'e', 's', '\0', 't'};
const char key4[] = {'t', 'e', 's', 't', '\0'};
if (json_object_size(obj) != 0)
fail("incorrect json");
json_object_set_new_nocheck(obj, "test1", json_true());
if (json_object_size(obj) != 1)
fail("incorrect json");
if (json_object_getn(obj, key, sizeof(key)) != json_true())
fail("json_object_getn failed");
if (json_object_getn(obj, key2, sizeof(key2)) != NULL)
fail("false positive json_object_getn by key2");
if (json_object_setn_nocheck(obj, key2, sizeof(key2), json_false()))
fail("json_object_setn_nocheck for key2 failed");
if (json_object_size(obj) != 2)
fail("incorrect json");
if (json_object_get(obj, "test") != json_false())
fail("json_object_setn_nocheck for key2 failed");
if (json_object_getn(obj, key2, sizeof(key2)) != json_false())
fail("json_object_getn by key 2 failed");
if (json_object_getn(obj, key3, sizeof(key3)) != NULL)
fail("false positive json_object_getn by key3");
if (json_object_setn_nocheck(obj, key3, sizeof(key3), json_false()))
fail("json_object_setn_nocheck for key3 failed");
if (json_object_size(obj) != 3)
fail("incorrect json");
if (json_object_getn(obj, key3, sizeof(key3)) != json_false())
fail("json_object_getn by key 3 failed");
if (json_object_getn(obj, key4, sizeof(key4)) != NULL)
fail("false positive json_object_getn by key3");
if (json_object_setn_nocheck(obj, key4, sizeof(key4), json_false()))
fail("json_object_setn_nocheck for key3 failed");
if (json_object_size(obj) != 4)
fail("incorrect json");
test_keylen_iterator(obj);
if (json_object_getn(obj, key4, sizeof(key4)) != json_false())
fail("json_object_getn by key 3 failed");
if (json_object_size(obj) != 4)
fail("incorrect json");
if (json_object_deln(obj, key4, sizeof(key4)))
fail("json_object_deln failed");
if (json_object_getn(obj, key4, sizeof(key4)) != NULL)
fail("json_object_deln failed");
if (json_object_size(obj) != 3)
fail("incorrect json");
if (json_object_deln(obj, key3, sizeof(key3)))
fail("json_object_deln failed");
if (json_object_getn(obj, key3, sizeof(key3)) != NULL)
fail("json_object_deln failed");
if (json_object_size(obj) != 2)
fail("incorrect json");
if (json_object_deln(obj, key2, sizeof(key2)))
fail("json_object_deln failed");
if (json_object_getn(obj, key2, sizeof(key2)) != NULL)
fail("json_object_deln failed");
if (json_object_size(obj) != 1)
fail("incorrect json");
if (json_object_deln(obj, key, sizeof(key)))
fail("json_object_deln failed");
if (json_object_getn(obj, key, sizeof(key)) != NULL)
fail("json_object_deln failed");
if (json_object_size(obj) != 0)
fail("incorrect json");
json_decref(obj);
}
static void test_invalid_keylen(void) {
json_t *obj = json_object();
json_t *empty_obj = json_object();
const char key[] = {'t', 'e', 's', 't', '1'};
json_object_set_new_nocheck(obj, "test1", json_true());
if (json_object_getn(NULL, key, sizeof(key)) != NULL)
fail("json_object_getn on NULL failed");
if (json_object_getn(obj, NULL, sizeof(key)) != NULL)
fail("json_object_getn on NULL failed");
if (json_object_getn(obj, key, 0) != NULL)
fail("json_object_getn on NULL failed");
if (!json_object_setn_new(obj, NULL, sizeof(key), json_true()))
fail("json_object_setn_new with NULL key failed");
if (!json_object_setn_new_nocheck(obj, NULL, sizeof(key), json_true()))
fail("json_object_setn_new_nocheck with NULL key failed");
if (!json_object_del(obj, NULL))
fail("json_object_del with NULL failed");
if (!json_object_deln(empty_obj, key, sizeof(key)))
fail("json_object_deln with empty object failed");
if (!json_object_deln(obj, key, sizeof(key) - 1))
fail("json_object_deln with incomplete key failed");
json_decref(obj);
json_decref(empty_obj);
}
static void test_binary_keys(void) {
json_t *obj = json_object();
int key1 = 0;
int key2 = 1;
json_object_setn_nocheck(obj, (const char *)&key1, sizeof(key1), json_true());
json_object_setn_nocheck(obj, (const char *)&key2, sizeof(key2), json_true());
if (!json_is_true(json_object_getn(obj, (const char *)&key1, sizeof(key1))))
fail("cannot get integer key1");
if (!json_is_true(json_object_getn(obj, (const char *)&key1, sizeof(key2))))
fail("cannot get integer key2");
if (json_object_size(obj) != 2)
fail("binary object size missmatch");
if (json_object_deln(obj, (const char *)&key1, sizeof(key1)))
fail("cannot del integer key1");
if (json_object_size(obj) != 1)
fail("binary object size missmatch");
if (json_object_deln(obj, (const char *)&key2, sizeof(key2)))
fail("cannot del integer key2");
if (json_object_size(obj) != 0)
fail("binary object size missmatch");
json_decref(obj);
}
static void test_dump_order(void) {
json_t *obj = json_object();
char key1[] = {'k', '\0', '-', '2'};
char key2[] = {'k', '\0', '-', '1'};
const char expected_sorted_str[] =
"{\"k\\u0000-1\": \"first\", \"k\\u0000-2\": \"second\"}";
const char expected_nonsorted_str[] =
"{\"k\\u0000-2\": \"second\", \"k\\u0000-1\": \"first\"}";
char *out;
json_object_setn_new_nocheck(obj, key1, sizeof(key1), json_string("second"));
json_object_setn_new_nocheck(obj, key2, sizeof(key2), json_string("first"));
out = malloc(512);
json_dumpb(obj, out, 512, 0);
if (memcmp(expected_nonsorted_str, out, sizeof(expected_nonsorted_str) - 1) != 0)
fail("preserve order failed");
json_dumpb(obj, out, 512, JSON_SORT_KEYS);
if (memcmp(expected_sorted_str, out, sizeof(expected_sorted_str) - 1) != 0)
fail("utf-8 sort failed");
free(out);
json_decref(obj);
}
static void run_tests() {
test_keylen();
test_invalid_keylen();
test_binary_keys();
test_dump_order();
}

View file

@ -1,24 +1,238 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <string.h>
#include "util.h"
int main()
{
static void file_not_found() {
json_t *json;
json_error_t error;
char *pos;
json = json_load_file("/path/to/nonexistent/file.json", 0, &error);
if (json)
fail("json_load_file returned non-NULL for a nonexistent file");
if (error.line != -1)
fail("json_load_file returned an invalid line number");
/* The error message is locale specific, only check the beginning
of the error message. */
pos = strchr(error.text, ':');
if (!pos)
fail("json_load_file returne an invalid error message");
*pos = '\0';
if (strcmp(error.text, "unable to open /path/to/nonexistent/file.json") != 0)
fail("json_load_file returned an invalid error message");
if (json_error_code(&error) != json_error_cannot_open_file)
fail("json_load_file returned an invalid error code");
}
static void very_long_file_name() {
json_t *json;
json_error_t error;
json = json_load_file("/path/to/nonexistent/file.json", &error);
if(error.line != -1)
json = json_load_file("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
0, &error);
if (json)
fail("json_load_file returned non-NULL for a nonexistent file");
if (error.line != -1)
fail("json_load_file returned an invalid line number");
if(strcmp(error.text, "unable to open /path/to/nonexistent/file.json: No such file or directory") != 0)
fail("json_load_file returned an invalid error message");
return 0;
if (strncmp(error.source, "...aaa", 6) != 0)
fail("error source was set incorrectly");
if (json_error_code(&error) != json_error_cannot_open_file)
fail("error code was set incorrectly");
}
static void reject_duplicates() {
json_error_t error;
if (json_loads("{\"foo\": 1, \"foo\": 2}", JSON_REJECT_DUPLICATES, &error))
fail("json_loads did not detect a duplicate key");
check_error(json_error_duplicate_key, "duplicate object key near '\"foo\"'",
"<string>", 1, 16, 16);
}
static void disable_eof_check() {
json_error_t error;
json_t *json;
const char *text = "{\"foo\": 1} garbage";
if (json_loads(text, 0, &error))
fail("json_loads did not detect garbage after JSON text");
check_error(json_error_end_of_input_expected, "end of file expected near 'garbage'",
"<string>", 1, 18, 18);
json = json_loads(text, JSON_DISABLE_EOF_CHECK, &error);
if (!json)
fail("json_loads failed with JSON_DISABLE_EOF_CHECK");
json_decref(json);
}
static void decode_any() {
json_t *json;
json_error_t error;
json = json_loads("\"foo\"", JSON_DECODE_ANY, &error);
if (!json || !json_is_string(json))
fail("json_load decoded any failed - string");
json_decref(json);
json = json_loads("42", JSON_DECODE_ANY, &error);
if (!json || !json_is_integer(json))
fail("json_load decoded any failed - integer");
json_decref(json);
json = json_loads("true", JSON_DECODE_ANY, &error);
if (!json || !json_is_true(json))
fail("json_load decoded any failed - boolean");
json_decref(json);
json = json_loads("null", JSON_DECODE_ANY, &error);
if (!json || !json_is_null(json))
fail("json_load decoded any failed - null");
json_decref(json);
}
static void decode_int_as_real() {
json_t *json;
json_error_t error;
#if JSON_INTEGER_IS_LONG_LONG
const char *imprecise;
json_int_t expected;
#endif
char big[311];
json = json_loads("42", JSON_DECODE_INT_AS_REAL | JSON_DECODE_ANY, &error);
if (!json || !json_is_real(json) || json_real_value(json) != 42.0)
fail("json_load decode int as real failed - int");
json_decref(json);
#if JSON_INTEGER_IS_LONG_LONG
/* This number cannot be represented exactly by a double */
imprecise = "9007199254740993";
expected = 9007199254740992ll;
json = json_loads(imprecise, JSON_DECODE_INT_AS_REAL | JSON_DECODE_ANY, &error);
if (!json || !json_is_real(json) || expected != (json_int_t)json_real_value(json))
fail("json_load decode int as real failed - expected imprecision");
json_decref(json);
#endif
/* 1E309 overflows. Here we create 1E309 as a decimal number, i.e.
1000...(309 zeroes)...0. */
big[0] = '1';
memset(big + 1, '0', 309);
big[310] = '\0';
json = json_loads(big, JSON_DECODE_INT_AS_REAL | JSON_DECODE_ANY, &error);
if (json || strcmp(error.text, "real number overflow") != 0 ||
json_error_code(&error) != json_error_numeric_overflow)
fail("json_load decode int as real failed - expected overflow");
json_decref(json);
}
static void allow_nul() {
const char *text = "\"nul byte \\u0000 in string\"";
const char *expected = "nul byte \0 in string";
size_t len = 20;
json_t *json;
json = json_loads(text, JSON_ALLOW_NUL | JSON_DECODE_ANY, NULL);
if (!json || !json_is_string(json))
fail("unable to decode embedded NUL byte");
if (json_string_length(json) != len)
fail("decoder returned wrong string length");
if (memcmp(json_string_value(json), expected, len + 1))
fail("decoder returned wrong string content");
json_decref(json);
}
static void load_wrong_args() {
json_t *json;
json_error_t error;
json = json_loads(NULL, 0, &error);
if (json)
fail("json_loads should return NULL if the first argument is NULL");
json = json_loadb(NULL, 0, 0, &error);
if (json)
fail("json_loadb should return NULL if the first argument is NULL");
json = json_loadf(NULL, 0, &error);
if (json)
fail("json_loadf should return NULL if the first argument is NULL");
json = json_loadfd(-1, 0, &error);
if (json)
fail("json_loadfd should return NULL if the first argument is < 0");
json = json_load_file(NULL, 0, &error);
if (json)
fail("json_load_file should return NULL if the first argument is NULL");
}
static void position() {
json_t *json;
size_t flags = JSON_DISABLE_EOF_CHECK;
json_error_t error;
json = json_loads("{\"foo\": \"bar\"}", 0, &error);
if (error.position != 14)
fail("json_loads returned a wrong position");
json_decref(json);
json = json_loads("{\"foo\": \"bar\"} baz quux", flags, &error);
if (error.position != 14)
fail("json_loads returned a wrong position");
json_decref(json);
}
static void error_code() {
json_error_t error;
json_t *json = json_loads("[123] garbage", 0, &error);
if (json != NULL)
fail("json_loads returned not NULL");
if (strlen(error.text) >= JSON_ERROR_TEXT_LENGTH)
fail("error.text longer than expected");
if (json_error_code(&error) != json_error_end_of_input_expected)
fail("json_loads returned incorrect error code");
json = json_loads("{\"foo\": ", 0, &error);
if (json != NULL)
fail("json_loads returned not NULL");
if (strlen(error.text) >= JSON_ERROR_TEXT_LENGTH)
fail("error.text longer than expected");
if (json_error_code(&error) != json_error_premature_end_of_input)
fail("json_loads returned incorrect error code");
}
static void run_tests() {
file_not_found();
very_long_file_name();
reject_duplicates();
disable_eof_check();
decode_any();
decode_int_as_real();
allow_nul();
load_wrong_args();
position();
error_code();
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2009-2011 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <stdlib.h>
#include <string.h>
struct my_source {
const char *buf;
size_t off;
size_t cap;
};
static const char my_str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
static size_t greedy_reader(void *buf, size_t buflen, void *arg) {
struct my_source *s = arg;
if (buflen > s->cap - s->off)
buflen = s->cap - s->off;
if (buflen > 0) {
memcpy(buf, s->buf + s->off, buflen);
s->off += buflen;
return buflen;
} else {
return 0;
}
}
static void run_tests() {
struct my_source s;
json_t *json;
json_error_t error;
s.off = 0;
s.cap = strlen(my_str);
s.buf = my_str;
json = json_load_callback(greedy_reader, &s, 0, &error);
if (!json)
fail("json_load_callback failed on a valid callback");
json_decref(json);
s.off = 0;
s.cap = strlen(my_str) - 1;
s.buf = my_str;
json = json_load_callback(greedy_reader, &s, 0, &error);
if (json) {
json_decref(json);
fail("json_load_callback should have failed on an incomplete stream, "
"but it didn't");
}
if (strcmp(error.source, "<callback>") != 0) {
fail("json_load_callback returned an invalid error source");
}
if (strcmp(error.text, "']' expected near end of file") != 0) {
fail("json_load_callback returned an invalid error message for an "
"unclosed top-level array");
}
json = json_load_callback(NULL, NULL, 0, &error);
if (json) {
json_decref(json);
fail("json_load_callback should have failed on NULL load callback, but "
"it didn't");
}
if (strcmp(error.text, "wrong arguments") != 0) {
fail("json_load_callback returned an invalid error message for a NULL "
"load callback");
}
}

View file

@ -0,0 +1,37 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <string.h>
static void run_tests() {
json_t *json;
json_error_t error;
const char str[] = "[\"A\", {\"B\": \"C\"}, 1, 2, 3]garbage";
size_t len = strlen(str) - strlen("garbage");
json = json_loadb(str, len, 0, &error);
if (!json) {
fail("json_loadb failed on a valid JSON buffer");
}
json_decref(json);
json = json_loadb(str, len - 1, 0, &error);
if (json) {
json_decref(json);
fail("json_loadb should have failed on an incomplete buffer, but it "
"didn't");
}
if (error.line != 1) {
fail("json_loadb returned an invalid line number on fail");
}
if (strcmp(error.text, "']' expected near end of file") != 0) {
fail("json_loadb returned an invalid error message for an unclosed "
"top-level array");
}
}

View file

@ -0,0 +1,115 @@
#include <jansson.h>
#include <string.h>
#include "util.h"
static int malloc_called = 0;
static int free_called = 0;
static size_t malloc_used = 0;
/* helpers */
static void create_and_free_complex_object() {
json_t *obj;
obj = json_pack("{s:i,s:n,s:b,s:b,s:{s:s},s:[i,i,i]}", "foo", 42, "bar", "baz", 1,
"qux", 0, "alice", "bar", "baz", "bob", 9, 8, 7);
json_decref(obj);
}
static void create_and_free_object_with_oom() {
int i;
char key[4];
json_t *obj = json_object();
for (i = 0; i < 10; i++) {
snprintf(key, sizeof key, "%d", i);
json_object_set_new(obj, key, json_integer(i));
}
json_decref(obj);
}
static void *my_malloc(size_t size) {
malloc_called = 1;
return malloc(size);
}
static void my_free(void *ptr) {
free_called = 1;
free(ptr);
}
static void test_simple() {
json_malloc_t mfunc = NULL;
json_free_t ffunc = NULL;
json_set_alloc_funcs(my_malloc, my_free);
json_get_alloc_funcs(&mfunc, &ffunc);
create_and_free_complex_object();
if (malloc_called != 1 || free_called != 1 || mfunc != my_malloc || ffunc != my_free)
fail("Custom allocation failed");
}
static void *oom_malloc(size_t size) {
if (malloc_used + size > 800)
return NULL;
malloc_used += size;
return malloc(size);
}
static void oom_free(void *ptr) {
free_called++;
free(ptr);
}
static void test_oom() {
free_called = 0;
json_set_alloc_funcs(oom_malloc, oom_free);
create_and_free_object_with_oom();
if (free_called == 0)
fail("Allocation with OOM failed");
}
/*
Test the secure memory functions code given in the API reference
documentation, but by using plain memset instead of
guaranteed_memset().
*/
static void *secure_malloc(size_t size) {
/* Store the memory area size in the beginning of the block */
void *ptr = malloc(size + 8);
*((size_t *)ptr) = size;
return (char *)ptr + 8;
}
static void secure_free(void *ptr) {
size_t size;
ptr = (char *)ptr - 8;
size = *((size_t *)ptr);
/*guaranteed_*/ memset(ptr, 0, size + 8);
free(ptr);
}
static void test_secure_funcs(void) {
json_set_alloc_funcs(secure_malloc, secure_free);
create_and_free_complex_object();
}
static void test_bad_args(void) {
/* The result of this test is not crashing. */
json_get_alloc_funcs(NULL, NULL);
}
static void run_tests() {
test_simple();
test_secure_funcs();
test_oom();
test_bad_args();
}

View file

@ -1,44 +1,123 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <jansson.h>
#include "util.h"
#include <jansson.h>
#include <math.h>
int main()
{
#ifdef INFINITY
// This test triggers "warning C4756: overflow in constant arithmetic"
// in Visual Studio. This warning is triggered here by design, so disable it.
// (This can only be done on function level so we keep these tests separate)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4756)
#endif
static void test_inifity() {
json_t *real = json_real(INFINITY);
if (real != NULL)
fail("could construct a real from Inf");
real = json_real(1.0);
if (json_real_set(real, INFINITY) != -1)
fail("could set a real to Inf");
if (json_real_value(real) != 1.0)
fail("real value changed unexpectedly");
json_decref(real);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
#endif // INFINITY
static void test_bad_args(void) {
json_t *txt = json_string("test");
if (json_integer_value(NULL) != 0)
fail("json_integer_value did not return 0 for non-integer");
if (json_integer_value(txt) != 0)
fail("json_integer_value did not return 0 for non-integer");
if (!json_integer_set(NULL, 0))
fail("json_integer_set did not return error for non-integer");
if (!json_integer_set(txt, 0))
fail("json_integer_set did not return error for non-integer");
if (json_real_value(NULL) != 0.0)
fail("json_real_value did not return 0.0 for non-real");
if (json_real_value(txt) != 0.0)
fail("json_real_value did not return 0.0 for non-real");
if (!json_real_set(NULL, 0.0))
fail("json_real_set did not return error for non-real");
if (!json_real_set(txt, 0.0))
fail("json_real_set did not return error for non-real");
if (json_number_value(NULL) != 0.0)
fail("json_number_value did not return 0.0 for non-numeric");
if (json_number_value(txt) != 0.0)
fail("json_number_value did not return 0.0 for non-numeric");
if (txt->refcount != 1)
fail("unexpected reference count for txt");
json_decref(txt);
}
static void run_tests() {
json_t *integer, *real;
int i;
json_int_t i;
double d;
integer = json_integer(5);
real = json_real(100.1);
if(!integer)
if (!integer)
fail("unable to create integer");
if(!real)
if (!real)
fail("unable to create real");
i = json_integer_value(integer);
if(i != 5)
if (i != 5)
fail("wrong integer value");
d = json_real_value(real);
if(d != 100.1)
if (d != 100.1)
fail("wrong real value");
d = json_number_value(integer);
if(d != 5.0)
if (d != 5.0)
fail("wrong number value");
d = json_number_value(real);
if(d != 100.1)
if (d != 100.1)
fail("wrong number value");
json_decref(integer);
json_decref(real);
return 0;
#ifdef NAN
real = json_real(NAN);
if (real != NULL)
fail("could construct a real from NaN");
real = json_real(1.0);
if (json_real_set(real, NAN) != -1)
fail("could set a real to NaN");
if (json_real_value(real) != 1.0)
fail("real value changed unexpectedly");
json_decref(real);
#endif
#ifdef INFINITY
test_inifity();
#endif
test_bad_args();
}

View file

@ -1,47 +1,43 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <string.h>
#include "util.h"
static void test_clear()
{
static void test_clear() {
json_t *object, *ten;
object = json_object();
ten = json_integer(10);
if(!object)
if (!object)
fail("unable to create object");
if(!ten)
if (!ten)
fail("unable to create integer");
if(json_object_set(object, "a", ten) ||
json_object_set(object, "b", ten) ||
json_object_set(object, "c", ten) ||
json_object_set(object, "d", ten) ||
json_object_set(object, "e", ten))
if (json_object_set(object, "a", ten) || json_object_set(object, "b", ten) ||
json_object_set(object, "c", ten) || json_object_set(object, "d", ten) ||
json_object_set(object, "e", ten))
fail("unable to set value");
if(json_object_size(object) != 5)
if (json_object_size(object) != 5)
fail("invalid size");
json_object_clear(object);
if(json_object_size(object) != 0)
if (json_object_size(object) != 0)
fail("invalid size after clear");
json_decref(ten);
json_decref(object);
}
static void test_update()
{
static void test_update() {
json_t *object, *other, *nine, *ten;
object = json_object();
@ -50,115 +46,303 @@ static void test_update()
nine = json_integer(9);
ten = json_integer(10);
if(!object || !other)
if (!object || !other)
fail("unable to create object");
if(!nine || !ten)
if (!nine || !ten)
fail("unable to create integer");
/* update an empty object with an empty object */
if(json_object_update(object, other))
fail("unable to update an emtpy object with an empty object");
if (json_object_update(object, other))
fail("unable to update an empty object with an empty object");
if(json_object_size(object) != 0)
if (json_object_size(object) != 0)
fail("invalid size after update");
if(json_object_size(other) != 0)
if (json_object_size(other) != 0)
fail("invalid size for updater after update");
/* update an empty object with a nonempty object */
if(json_object_set(other, "a", ten) ||
json_object_set(other, "b", ten) ||
json_object_set(other, "c", ten) ||
json_object_set(other, "d", ten) ||
json_object_set(other, "e", ten))
if (json_object_set(other, "a", ten) || json_object_set(other, "b", ten) ||
json_object_set(other, "c", ten) || json_object_set(other, "d", ten) ||
json_object_set(other, "e", ten))
fail("unable to set value");
if(json_object_update(object, other))
if (json_object_update(object, other))
fail("unable to update an empty object");
if(json_object_size(object) != 5)
if (json_object_size(object) != 5)
fail("invalid size after update");
if(json_object_get(object, "a") != ten ||
json_object_get(object, "b") != ten ||
json_object_get(object, "c") != ten ||
json_object_get(object, "d") != ten ||
json_object_get(object, "e") != ten)
if (json_object_get(object, "a") != ten || json_object_get(object, "b") != ten ||
json_object_get(object, "c") != ten || json_object_get(object, "d") != ten ||
json_object_get(object, "e") != ten)
fail("update works incorrectly");
/* perform the same update again */
if(json_object_update(object, other))
fail("unable to update an empty object");
if (json_object_update(object, other))
fail("unable to update a non-empty object");
if(json_object_size(object) != 5)
if (json_object_size(object) != 5)
fail("invalid size after update");
if(json_object_get(object, "a") != ten ||
json_object_get(object, "b") != ten ||
json_object_get(object, "c") != ten ||
json_object_get(object, "d") != ten ||
json_object_get(object, "e") != ten)
if (json_object_get(object, "a") != ten || json_object_get(object, "b") != ten ||
json_object_get(object, "c") != ten || json_object_get(object, "d") != ten ||
json_object_get(object, "e") != ten)
fail("update works incorrectly");
/* update a nonempty object with a nonempty object with both old
and new keys */
if(json_object_clear(other))
if (json_object_clear(other))
fail("clear failed");
if(json_object_set(other, "a", nine) ||
json_object_set(other, "b", nine) ||
json_object_set(other, "f", nine) ||
json_object_set(other, "g", nine) ||
json_object_set(other, "h", nine))
if (json_object_set(other, "a", nine) || json_object_set(other, "b", nine) ||
json_object_set(other, "f", nine) || json_object_set(other, "g", nine) ||
json_object_set(other, "h", nine))
fail("unable to set value");
if(json_object_update(object, other))
if (json_object_update(object, other))
fail("unable to update a nonempty object");
if(json_object_size(object) != 8)
if (json_object_size(object) != 8)
fail("invalid size after update");
if(json_object_get(object, "a") != nine ||
json_object_get(object, "b") != nine ||
json_object_get(object, "f") != nine ||
json_object_get(object, "g") != nine ||
json_object_get(object, "h") != nine)
if (json_object_get(object, "a") != nine || json_object_get(object, "b") != nine ||
json_object_get(object, "f") != nine || json_object_get(object, "g") != nine ||
json_object_get(object, "h") != nine)
fail("update works incorrectly");
/* update_new check */
if (json_object_clear(object))
fail("clear failed");
if (json_object_set(object, "a", ten) || json_object_set(object, "b", ten) ||
json_object_set(object, "c", ten) || json_object_set(object, "d", ten) ||
json_object_set(object, "e", ten))
fail("unable to set value");
if (json_object_update_new(
object, json_pack("{s:O, s:O, s:O}", "b", nine, "f", nine, "g", nine)))
fail("unable to update_new a nonempty object");
if (json_object_size(object) != 7)
fail("invalid size after update_new");
if (json_object_get(object, "a") != ten || json_object_get(object, "b") != nine ||
json_object_get(object, "c") != ten || json_object_get(object, "d") != ten ||
json_object_get(object, "e") != ten || json_object_get(object, "f") != nine ||
json_object_get(object, "g") != nine)
fail("update_new works incorrectly");
json_decref(nine);
json_decref(ten);
json_decref(other);
json_decref(object);
}
static void test_circular()
{
static void test_set_many_keys() {
json_t *object, *value;
const char *keys = "abcdefghijklmnopqrstuvwxyz";
char buf[2];
size_t i;
object = json_object();
if (!object)
fail("unable to create object");
value = json_string("a");
if (!value)
fail("unable to create string");
buf[1] = '\0';
for (i = 0; i < strlen(keys); i++) {
buf[0] = keys[i];
if (json_object_set(object, buf, value))
fail("unable to set object key");
}
json_decref(object);
json_decref(value);
}
static void test_conditional_updates() {
json_t *object, *other;
object = json_pack("{sisi}", "foo", 1, "bar", 2);
other = json_pack("{sisi}", "foo", 3, "baz", 4);
if (json_object_update_existing(object, other))
fail("json_object_update_existing failed");
if (json_object_size(object) != 2)
fail("json_object_update_existing added new items");
if (json_integer_value(json_object_get(object, "foo")) != 3)
fail("json_object_update_existing failed to update existing key");
if (json_integer_value(json_object_get(object, "bar")) != 2)
fail("json_object_update_existing updated wrong key");
json_decref(object);
/* json_object_update_existing_new check */
object = json_pack("{sisi}", "foo", 1, "bar", 2);
if (json_object_update_existing_new(object, json_pack("{sisi}", "foo", 3, "baz", 4)))
fail("json_object_update_existing_new failed");
if (json_object_size(object) != 2)
fail("json_object_update_existing_new added new items");
if (json_integer_value(json_object_get(object, "foo")) != 3)
fail("json_object_update_existing_new failed to update existing key");
if (json_integer_value(json_object_get(object, "bar")) != 2)
fail("json_object_update_existing_new updated wrong key");
json_decref(object);
object = json_pack("{sisi}", "foo", 1, "bar", 2);
if (json_object_update_missing(object, other))
fail("json_object_update_missing failed");
if (json_object_size(object) != 3)
fail("json_object_update_missing didn't add new items");
if (json_integer_value(json_object_get(object, "foo")) != 1)
fail("json_object_update_missing updated existing key");
if (json_integer_value(json_object_get(object, "bar")) != 2)
fail("json_object_update_missing updated wrong key");
if (json_integer_value(json_object_get(object, "baz")) != 4)
fail("json_object_update_missing didn't add new items");
json_decref(object);
/* json_object_update_missing_new check */
object = json_pack("{sisi}", "foo", 1, "bar", 2);
if (json_object_update_missing_new(object, json_pack("{sisi}", "foo", 3, "baz", 4)))
fail("json_object_update_missing_new failed");
if (json_object_size(object) != 3)
fail("json_object_update_missing_new didn't add new items");
if (json_integer_value(json_object_get(object, "foo")) != 1)
fail("json_object_update_missing_new updated existing key");
if (json_integer_value(json_object_get(object, "bar")) != 2)
fail("json_object_update_missing_new updated wrong key");
if (json_integer_value(json_object_get(object, "baz")) != 4)
fail("json_object_update_missing_new didn't add new items");
json_decref(object);
json_decref(other);
}
static void test_recursive_updates() {
json_t *invalid, *object, *other, *barBefore, *barAfter;
invalid = json_integer(42);
object = json_pack("{sis{si}}", "foo", 1, "bar", "baz", 2);
other = json_pack("{sisisi}", "foo", 3, "bar", 4, "baz", 5);
if (!json_object_update_recursive(invalid, other))
fail("json_object_update_recursive accepted non-object argument");
json_decref(invalid);
if (json_object_update_recursive(object, other))
fail("json_object_update_recursive failed");
if (json_object_size(object) != 3)
fail("invalid size after update");
if (json_integer_value(json_object_get(object, "foo")) != 3)
fail("json_object_update_recursive failed to update existing key");
if (json_integer_value(json_object_get(object, "bar")) != 4)
fail("json_object_update_recursive failed to overwrite object");
if (json_integer_value(json_object_get(object, "baz")) != 5)
fail("json_object_update_recursive didn't add new item");
json_decref(object);
json_decref(other);
object = json_pack("{sis{si}}", "foo", 1, "bar", "baz", 2);
other = json_pack("{s{si}}", "bar", "baz", 3);
barBefore = json_object_get(object, "bar");
if (!barBefore)
fail("can't get bar object before json_object_update_recursive");
if (json_object_update_recursive(object, other))
fail("json_object_update_recursive failed");
if (json_object_size(object) != 2)
fail("invalid size after update");
if (!json_object_get(object, "foo"))
fail("json_object_update_recursive removed existing key");
if (json_integer_value(json_object_get(json_object_get(object, "bar"), "baz")) != 3)
fail("json_object_update_recursive failed to update nested value");
barAfter = json_object_get(object, "bar");
if (!barAfter)
fail("can't get bar object after json_object_update_recursive");
if (barBefore != barAfter)
fail("bar object reference changed after json_object_update_recursive");
json_decref(object);
json_decref(other);
/* check circular reference */
object = json_pack("{s{s{s{si}}}}", "foo", "bar", "baz", "xxx", 2);
other = json_pack("{s{s{si}}}", "foo", "bar", "baz", 2);
json_object_set(json_object_get(json_object_get(other, "foo"), "bar"), "baz",
json_object_get(other, "foo"));
if (!json_object_update_recursive(object, other))
fail("json_object_update_recursive update a circular reference!");
json_object_set_new(json_object_get(json_object_get(other, "foo"), "bar"), "baz",
json_integer(1));
if (json_object_update_recursive(object, other))
fail("json_object_update_recursive failed!");
json_decref(object);
json_decref(other);
}
static void test_circular() {
json_t *object1, *object2;
object1 = json_object();
object2 = json_object();
if(!object1 || !object2)
if (!object1 || !object2)
fail("unable to create object");
/* the simple case is checked */
if(json_object_set(object1, "a", object1) == 0)
if (json_object_set(object1, "a", object1) == 0)
fail("able to set self");
/* create circular references */
if(json_object_set(object1, "a", object2) ||
json_object_set(object2, "a", object1))
if (json_object_set(object1, "a", object2) || json_object_set(object2, "a", object1))
fail("unable to set value");
/* circularity is detected when dumping */
if(json_dumps(object1, 0) != NULL)
if (json_dumps(object1, 0) != NULL)
fail("able to dump circulars");
/* decref twice to deal with the circular references */
@ -167,125 +351,114 @@ static void test_circular()
json_decref(object1);
}
static void test_set_nocheck()
{
static void test_set_nocheck() {
json_t *object, *string;
object = json_object();
string = json_string("bar");
if(!object)
if (!object)
fail("unable to create object");
if(!string)
if (!string)
fail("unable to create string");
if(json_object_set_nocheck(object, "foo", string))
if (json_object_set_nocheck(object, "foo", string))
fail("json_object_set_nocheck failed");
if(json_object_get(object, "foo") != string)
if (json_object_get(object, "foo") != string)
fail("json_object_get after json_object_set_nocheck failed");
/* invalid UTF-8 in key */
if(json_object_set_nocheck(object, "a\xefz", string))
if (json_object_set_nocheck(object, "a\xefz", string))
fail("json_object_set_nocheck failed for invalid UTF-8");
if(json_object_get(object, "a\xefz") != string)
if (json_object_get(object, "a\xefz") != string)
fail("json_object_get after json_object_set_nocheck failed");
if(json_object_set_new_nocheck(object, "bax", json_integer(123)))
if (json_object_set_new_nocheck(object, "bax", json_integer(123)))
fail("json_object_set_new_nocheck failed");
if(json_integer_value(json_object_get(object, "bax")) != 123)
if (json_integer_value(json_object_get(object, "bax")) != 123)
fail("json_object_get after json_object_set_new_nocheck failed");
/* invalid UTF-8 in key */
if(json_object_set_new_nocheck(object, "asdf\xfe", json_integer(321)))
if (json_object_set_new_nocheck(object, "asdf\xfe", json_integer(321)))
fail("json_object_set_new_nocheck failed for invalid UTF-8");
if(json_integer_value(json_object_get(object, "asdf\xfe")) != 321)
if (json_integer_value(json_object_get(object, "asdf\xfe")) != 321)
fail("json_object_get after json_object_set_new_nocheck failed");
json_decref(string);
json_decref(object);
}
static void test_iterators()
{
static void test_iterators() {
json_t *object, *foo, *bar, *baz;
void *iter;
if(json_object_iter(NULL))
if (json_object_iter(NULL))
fail("able to iterate over NULL");
if(json_object_iter_next(NULL, NULL))
if (json_object_iter_next(NULL, NULL))
fail("able to increment an iterator on a NULL object");
object = json_object();
foo = json_string("foo");
bar = json_string("bar");
baz = json_string("baz");
if(!object || !foo || !bar || !bar)
if (!object || !foo || !bar || !baz)
fail("unable to create values");
if(json_object_iter_next(object, NULL))
if (json_object_iter_next(object, NULL))
fail("able to increment a NULL iterator");
if(json_object_set(object, "a", foo) ||
json_object_set(object, "b", bar) ||
json_object_set(object, "c", baz))
if (json_object_set(object, "a", foo) || json_object_set(object, "b", bar) ||
json_object_set(object, "c", baz))
fail("unable to populate object");
iter = json_object_iter(object);
if(!iter)
if (!iter)
fail("unable to get iterator");
if(strcmp(json_object_iter_key(iter), "a"))
fail("iterating failed: wrong key");
if(json_object_iter_value(iter) != foo)
fail("iterating failed: wrong value");
if (strcmp(json_object_iter_key(iter), "a") != 0)
fail("iterating doesn't yield keys in order");
if (json_object_iter_value(iter) != foo)
fail("iterating doesn't yield values in order");
iter = json_object_iter_next(object, iter);
if(!iter)
if (!iter)
fail("unable to increment iterator");
if(strcmp(json_object_iter_key(iter), "b"))
fail("iterating failed: wrong key");
if(json_object_iter_value(iter) != bar)
fail("iterating failed: wrong value");
if (strcmp(json_object_iter_key(iter), "b") != 0)
fail("iterating doesn't yield keys in order");
if (json_object_iter_value(iter) != bar)
fail("iterating doesn't yield values in order");
iter = json_object_iter_next(object, iter);
if(!iter)
if (!iter)
fail("unable to increment iterator");
if(strcmp(json_object_iter_key(iter), "c"))
fail("iterating failed: wrong key");
if(json_object_iter_value(iter) != baz)
fail("iterating failed: wrong value");
if (strcmp(json_object_iter_key(iter), "c") != 0)
fail("iterating doesn't yield keys in order");
if (json_object_iter_value(iter) != baz)
fail("iterating doesn't yield values in order");
if(json_object_iter_next(object, iter) != NULL)
if (json_object_iter_next(object, iter) != NULL)
fail("able to iterate over the end");
if(json_object_iter_at(object, "foo"))
if (json_object_iter_at(object, "foo"))
fail("json_object_iter_at() succeeds for non-existent key");
iter = json_object_iter_at(object, "b");
if(!iter)
if (!iter)
fail("json_object_iter_at() fails for an existing key");
if(strcmp(json_object_iter_key(iter), "b"))
if (strcmp(json_object_iter_key(iter), "b"))
fail("iterating failed: wrong key");
if(json_object_iter_value(iter) != bar)
if (json_object_iter_value(iter) != bar)
fail("iterating failed: wrong value");
iter = json_object_iter_next(object, iter);
if(!iter)
fail("unable to increment iterator");
if(strcmp(json_object_iter_key(iter), "c"))
fail("iterating failed: wrong key");
if(json_object_iter_value(iter) != baz)
fail("iterating failed: wrong value");
if(json_object_iter_set(object, iter, bar))
if (json_object_iter_set(object, iter, baz))
fail("unable to set value at iterator");
if(strcmp(json_object_iter_key(iter), "c"))
if (strcmp(json_object_iter_key(iter), "b"))
fail("json_object_iter_key() fails after json_object_iter_set()");
if(json_object_iter_value(iter) != bar)
if (json_object_iter_value(iter) != baz)
fail("json_object_iter_value() fails after json_object_iter_set()");
if(json_object_get(object, "c") != bar)
if (json_object_get(object, "b") != baz)
fail("json_object_get() fails after json_object_iter_set()");
json_decref(object);
@ -294,107 +467,109 @@ static void test_iterators()
json_decref(baz);
}
static void test_misc()
{
static void test_misc() {
json_t *object, *string, *other_string, *value;
object = json_object();
string = json_string("test");
other_string = json_string("other");
if(!object)
if (!object)
fail("unable to create object");
if(!string || !other_string)
if (!string || !other_string)
fail("unable to create string");
if(json_object_get(object, "a"))
if (json_object_get(object, "a"))
fail("value for nonexisting key");
if(json_object_set(object, "a", string))
if (json_object_set(object, "a", string))
fail("unable to set value");
if(!json_object_set(object, NULL, string))
if (!json_object_set(object, NULL, string))
fail("able to set NULL key");
if(!json_object_set(object, "a", NULL))
if (json_object_del(object, "a"))
fail("unable to del the only key");
if (json_object_set(object, "a", string))
fail("unable to set value");
if (!json_object_set(object, "a", NULL))
fail("able to set NULL value");
/* invalid UTF-8 in key */
if(!json_object_set(object, "a\xefz", string))
if (!json_object_set(object, "a\xefz", string))
fail("able to set invalid unicode key");
value = json_object_get(object, "a");
if(!value)
if (!value)
fail("no value for existing key");
if(value != string)
if (value != string)
fail("got different value than what was added");
/* "a", "lp" and "px" collide in a five-bucket hashtable */
if(json_object_set(object, "b", string) ||
json_object_set(object, "lp", string) ||
json_object_set(object, "px", string))
if (json_object_set(object, "b", string) || json_object_set(object, "lp", string) ||
json_object_set(object, "px", string))
fail("unable to set value");
value = json_object_get(object, "a");
if(!value)
if (!value)
fail("no value for existing key");
if(value != string)
if (value != string)
fail("got different value than what was added");
if(json_object_set(object, "a", other_string))
if (json_object_set(object, "a", other_string))
fail("unable to replace an existing key");
value = json_object_get(object, "a");
if(!value)
if (!value)
fail("no value for existing key");
if(value != other_string)
if (value != other_string)
fail("got different value than what was set");
if(!json_object_del(object, "nonexisting"))
if (!json_object_del(object, "nonexisting"))
fail("able to delete a nonexisting key");
if(json_object_del(object, "px"))
if (json_object_del(object, "px"))
fail("unable to delete an existing key");
if(json_object_del(object, "a"))
if (json_object_del(object, "a"))
fail("unable to delete an existing key");
if(json_object_del(object, "lp"))
if (json_object_del(object, "lp"))
fail("unable to delete an existing key");
/* add many keys to initiate rehashing */
if(json_object_set(object, "a", string))
if (json_object_set(object, "a", string))
fail("unable to set value");
if(json_object_set(object, "lp", string))
if (json_object_set(object, "lp", string))
fail("unable to set value");
if(json_object_set(object, "px", string))
if (json_object_set(object, "px", string))
fail("unable to set value");
if(json_object_set(object, "c", string))
if (json_object_set(object, "c", string))
fail("unable to set value");
if(json_object_set(object, "d", string))
if (json_object_set(object, "d", string))
fail("unable to set value");
if(json_object_set(object, "e", string))
if (json_object_set(object, "e", string))
fail("unable to set value");
if(json_object_set_new(object, "foo", json_integer(123)))
if (json_object_set_new(object, "foo", json_integer(123)))
fail("unable to set new value");
value = json_object_get(object, "foo");
if(!json_is_integer(value) || json_integer_value(value) != 123)
if (!json_is_integer(value) || json_integer_value(value) != 123)
fail("json_object_set_new works incorrectly");
if(!json_object_set_new(object, NULL, json_integer(432)))
if (!json_object_set_new(object, NULL, json_integer(432)))
fail("able to set_new NULL key");
if(!json_object_set_new(object, "foo", NULL))
if (!json_object_set_new(object, "foo", NULL))
fail("able to set_new NULL value");
json_decref(string);
@ -402,12 +577,12 @@ static void test_misc()
json_decref(object);
}
static void test_preserve_order()
{
static void test_preserve_order() {
json_t *object;
char *result;
const char *expected = "{\"foobar\": 1, \"bazquux\": 6, \"lorem ipsum\": 3, \"sit amet\": 5, \"helicopter\": 7}";
const char *expected = "{\"foobar\": 1, \"bazquux\": 6, \"lorem ipsum\": "
"3, \"sit amet\": 5, \"helicopter\": 7}";
object = json_object();
@ -428,7 +603,7 @@ static void test_preserve_order()
result = json_dumps(object, JSON_PRESERVE_ORDER);
if(strcmp(expected, result) != 0) {
if (strcmp(expected, result) != 0) {
fprintf(stderr, "%s != %s", expected, result);
fail("JSON_PRESERVE_ORDER doesn't work");
}
@ -437,15 +612,186 @@ static void test_preserve_order()
json_decref(object);
}
int main()
{
static void test_object_foreach() {
const char *key;
json_t *object1, *object2, *value;
object1 = json_pack("{sisisi}", "foo", 1, "bar", 2, "baz", 3);
object2 = json_object();
json_object_foreach(object1, key, value) json_object_set(object2, key, value);
if (!json_equal(object1, object2))
fail("json_object_foreach failed to iterate all key-value pairs");
json_decref(object1);
json_decref(object2);
}
static void test_object_foreach_safe() {
const char *key;
void *tmp;
json_t *object, *value;
object = json_pack("{sisisi}", "foo", 1, "bar", 2, "baz", 3);
json_object_foreach_safe(object, tmp, key, value) { json_object_del(object, key); }
if (json_object_size(object) != 0)
fail("json_object_foreach_safe failed to iterate all key-value pairs");
json_decref(object);
}
static void test_bad_args(void) {
json_t *obj = json_object();
json_t *num = json_integer(1);
void *iter;
if (!obj || !num)
fail("failed to allocate test objects");
if (json_object_set(obj, "testkey", json_null()))
fail("failed to set testkey on object");
iter = json_object_iter(obj);
if (!iter)
fail("failed to retrieve test iterator");
if (json_object_size(NULL) != 0)
fail("json_object_size with non-object argument returned non-zero");
if (json_object_size(num) != 0)
fail("json_object_size with non-object argument returned non-zero");
if (json_object_get(NULL, "test") != NULL)
fail("json_object_get with non-object argument returned non-NULL");
if (json_object_get(num, "test") != NULL)
fail("json_object_get with non-object argument returned non-NULL");
if (json_object_get(obj, NULL) != NULL)
fail("json_object_get with NULL key returned non-NULL");
if (!json_object_set_new_nocheck(NULL, "test", json_null()))
fail("json_object_set_new_nocheck with non-object argument did not "
"return error");
if (!json_object_set_new_nocheck(num, "test", json_null()))
fail("json_object_set_new_nocheck with non-object argument did not "
"return error");
if (!json_object_set_new_nocheck(obj, "test", json_incref(obj)))
fail("json_object_set_new_nocheck with object == value did not return "
"error");
if (!json_object_set_new_nocheck(obj, NULL, json_object()))
fail("json_object_set_new_nocheck with NULL key did not return error");
if (!json_object_del(NULL, "test"))
fail("json_object_del with non-object argument did not return error");
if (!json_object_del(num, "test"))
fail("json_object_del with non-object argument did not return error");
if (!json_object_del(obj, NULL))
fail("json_object_del with NULL key did not return error");
if (!json_object_clear(NULL))
fail("json_object_clear with non-object argument did not return error");
if (!json_object_clear(num))
fail("json_object_clear with non-object argument did not return error");
if (!json_object_update(NULL, obj))
fail("json_object_update with non-object first argument did not return "
"error");
if (!json_object_update(num, obj))
fail("json_object_update with non-object first argument did not return "
"error");
if (!json_object_update(obj, NULL))
fail("json_object_update with non-object second argument did not "
"return error");
if (!json_object_update(obj, num))
fail("json_object_update with non-object second argument did not "
"return error");
if (!json_object_update_existing(NULL, obj))
fail("json_object_update_existing with non-object first argument did "
"not return error");
if (!json_object_update_existing(num, obj))
fail("json_object_update_existing with non-object first argument did "
"not return error");
if (!json_object_update_existing(obj, NULL))
fail("json_object_update_existing with non-object second argument did "
"not return error");
if (!json_object_update_existing(obj, num))
fail("json_object_update_existing with non-object second argument did "
"not return error");
if (!json_object_update_missing(NULL, obj))
fail("json_object_update_missing with non-object first argument did "
"not return error");
if (!json_object_update_missing(num, obj))
fail("json_object_update_missing with non-object first argument did "
"not return error");
if (!json_object_update_missing(obj, NULL))
fail("json_object_update_missing with non-object second argument did "
"not return error");
if (!json_object_update_missing(obj, num))
fail("json_object_update_missing with non-object second argument did "
"not return error");
if (json_object_iter(NULL) != NULL)
fail("json_object_iter with non-object argument returned non-NULL");
if (json_object_iter(num) != NULL)
fail("json_object_iter with non-object argument returned non-NULL");
if (json_object_iter_at(NULL, "test") != NULL)
fail("json_object_iter_at with non-object argument returned non-NULL");
if (json_object_iter_at(num, "test") != NULL)
fail("json_object_iter_at with non-object argument returned non-NULL");
if (json_object_iter_at(obj, NULL) != NULL)
fail("json_object_iter_at with NULL iter returned non-NULL");
if (json_object_iter_next(obj, NULL) != NULL)
fail("json_object_iter_next with NULL iter returned non-NULL");
if (json_object_iter_next(num, iter) != NULL)
fail("json_object_iter_next with non-object argument returned non-NULL");
if (json_object_iter_key(NULL) != NULL)
fail("json_object_iter_key with NULL iter returned non-NULL");
if (json_object_key_to_iter(NULL) != NULL)
fail("json_object_key_to_iter with NULL iter returned non-NULL");
if (json_object_iter_value(NULL) != NULL)
fail("json_object_iter_value with NULL iter returned non-NULL");
if (!json_object_iter_set_new(NULL, iter, json_incref(num)))
fail("json_object_iter_set_new with non-object argument did not return "
"error");
if (!json_object_iter_set_new(num, iter, json_incref(num)))
fail("json_object_iter_set_new with non-object argument did not return "
"error");
if (!json_object_iter_set_new(obj, NULL, json_incref(num)))
fail("json_object_iter_set_new with NULL iter did not return error");
if (!json_object_iter_set_new(obj, iter, NULL))
fail("json_object_iter_set_new with NULL value did not return error");
if (obj->refcount != 1)
fail("unexpected reference count for obj");
if (num->refcount != 1)
fail("unexpected reference count for num");
json_decref(obj);
json_decref(num);
}
static void run_tests() {
test_misc();
test_clear();
test_update();
test_set_many_keys();
test_conditional_updates();
test_recursive_updates();
test_circular();
test_set_nocheck();
test_iterators();
test_preserve_order();
return 0;
test_object_foreach();
test_object_foreach_safe();
test_bad_args();
}

547
test/suites/api/test_pack.c Normal file
View file

@ -0,0 +1,547 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2010-2012 Graeme Smecher <graeme.smecher@mail.mcgill.ca>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifdef HAVE_CONFIG_H
#include <jansson_private_config.h>
#endif
#include <jansson_config.h>
#include "util.h"
#include <jansson.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifdef INFINITY
// This test triggers "warning C4756: overflow in constant arithmetic"
// in Visual Studio. This warning is triggered here by design, so disable it.
// (This can only be done on function level so we keep these tests separate)
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4756)
#endif
static void test_inifity() {
json_error_t error;
if (json_pack_ex(&error, 0, "f", INFINITY))
fail("json_pack infinity incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
1, 1);
if (json_pack_ex(&error, 0, "[f]", INFINITY))
fail("json_pack infinity array element incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
2, 2);
if (json_pack_ex(&error, 0, "{s:f}", "key", INFINITY))
fail("json_pack infinity object value incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
4, 4);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
#endif // INFINITY
static void run_tests() {
json_t *value;
int i;
char buffer[4] = {'t', 'e', 's', 't'};
json_error_t error;
/*
* Simple, valid json_pack cases
*/
/* true */
value = json_pack("b", 1);
if (!json_is_true(value))
fail("json_pack boolean failed");
if (value->refcount != (size_t)-1)
fail("json_pack boolean refcount failed");
json_decref(value);
/* false */
value = json_pack("b", 0);
if (!json_is_false(value))
fail("json_pack boolean failed");
if (value->refcount != (size_t)-1)
fail("json_pack boolean refcount failed");
json_decref(value);
/* null */
value = json_pack("n");
if (!json_is_null(value))
fail("json_pack null failed");
if (value->refcount != (size_t)-1)
fail("json_pack null refcount failed");
json_decref(value);
/* integer */
value = json_pack("i", 1);
if (!json_is_integer(value) || json_integer_value(value) != 1)
fail("json_pack integer failed");
if (value->refcount != (size_t)1)
fail("json_pack integer refcount failed");
json_decref(value);
/* integer from json_int_t */
value = json_pack("I", (json_int_t)555555);
if (!json_is_integer(value) || json_integer_value(value) != 555555)
fail("json_pack json_int_t failed");
if (value->refcount != (size_t)1)
fail("json_pack integer refcount failed");
json_decref(value);
/* real */
value = json_pack("f", 1.0);
if (!json_is_real(value) || json_real_value(value) != 1.0)
fail("json_pack real failed");
if (value->refcount != (size_t)1)
fail("json_pack real refcount failed");
json_decref(value);
/* string */
value = json_pack("s", "test");
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string failed");
if (value->refcount != (size_t)1)
fail("json_pack string refcount failed");
json_decref(value);
/* nullable string (defined case) */
value = json_pack("s?", "test");
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack nullable string (defined case) failed");
if (value->refcount != (size_t)1)
fail("json_pack nullable string (defined case) refcount failed");
json_decref(value);
/* nullable string (NULL case) */
value = json_pack("s?", NULL);
if (!json_is_null(value))
fail("json_pack nullable string (NULL case) failed");
if (value->refcount != (size_t)-1)
fail("json_pack nullable string (NULL case) refcount failed");
json_decref(value);
/* nullable string concatenation */
if (json_pack_ex(&error, 0, "s?+", "test", "ing"))
fail("json_pack failed to catch invalid format 's?+'");
check_error(json_error_invalid_format, "Cannot use '+' on optional strings",
"<format>", 1, 2, 2);
/* nullable string with integer length */
if (json_pack_ex(&error, 0, "s?#", "test", 4))
fail("json_pack failed to catch invalid format 's?#'");
check_error(json_error_invalid_format, "Cannot use '#' on optional strings",
"<format>", 1, 2, 2);
/* string and length (int) */
value = json_pack("s#", "test asdf", 4);
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string and length failed");
if (value->refcount != (size_t)1)
fail("json_pack string and length refcount failed");
json_decref(value);
/* string and length (size_t) */
value = json_pack("s%", "test asdf", (size_t)4);
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string and length failed");
if (value->refcount != (size_t)1)
fail("json_pack string and length refcount failed");
json_decref(value);
/* string and length (int), non-NUL terminated string */
value = json_pack("s#", buffer, 4);
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string and length (int) failed");
if (value->refcount != (size_t)1)
fail("json_pack string and length (int) refcount failed");
json_decref(value);
/* string and length (size_t), non-NUL terminated string */
value = json_pack("s%", buffer, (size_t)4);
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string and length (size_t) failed");
if (value->refcount != (size_t)1)
fail("json_pack string and length (size_t) refcount failed");
json_decref(value);
/* string concatenation */
if (json_pack("s+", "test", NULL))
fail("json_pack string concatenation succeeded with NULL string");
value = json_pack("s++", "te", "st", "ing");
if (!json_is_string(value) || strcmp("testing", json_string_value(value)))
fail("json_pack string concatenation failed");
if (value->refcount != (size_t)1)
fail("json_pack string concatenation refcount failed");
json_decref(value);
/* string concatenation and length (int) */
value = json_pack("s#+#+", "test", 1, "test", 2, "test");
if (!json_is_string(value) || strcmp("ttetest", json_string_value(value)))
fail("json_pack string concatenation and length (int) failed");
if (value->refcount != (size_t)1)
fail("json_pack string concatenation and length (int) refcount failed");
json_decref(value);
/* string concatenation and length (size_t) */
value = json_pack("s%+%+", "test", (size_t)1, "test", (size_t)2, "test");
if (!json_is_string(value) || strcmp("ttetest", json_string_value(value)))
fail("json_pack string concatenation and length (size_t) failed");
if (value->refcount != (size_t)1)
fail("json_pack string concatenation and length (size_t) refcount "
"failed");
json_decref(value);
/* empty object */
value = json_pack("{}", 1.0);
if (!json_is_object(value) || json_object_size(value) != 0)
fail("json_pack empty object failed");
if (value->refcount != (size_t)1)
fail("json_pack empty object refcount failed");
json_decref(value);
/* empty list */
value = json_pack("[]", 1.0);
if (!json_is_array(value) || json_array_size(value) != 0)
fail("json_pack empty list failed");
if (value->refcount != (size_t)1)
fail("json_pack empty list failed");
json_decref(value);
/* non-incref'd object */
value = json_pack("o", json_integer(1));
if (!json_is_integer(value) || json_integer_value(value) != 1)
fail("json_pack object failed");
if (value->refcount != (size_t)1)
fail("json_pack integer refcount failed");
json_decref(value);
/* non-incref'd nullable object (defined case) */
value = json_pack("o?", json_integer(1));
if (!json_is_integer(value) || json_integer_value(value) != 1)
fail("json_pack nullable object (defined case) failed");
if (value->refcount != (size_t)1)
fail("json_pack nullable object (defined case) refcount failed");
json_decref(value);
/* non-incref'd nullable object (NULL case) */
value = json_pack("o?", NULL);
if (!json_is_null(value))
fail("json_pack nullable object (NULL case) failed");
if (value->refcount != (size_t)-1)
fail("json_pack nullable object (NULL case) refcount failed");
json_decref(value);
/* incref'd object */
value = json_pack("O", json_integer(1));
if (!json_is_integer(value) || json_integer_value(value) != 1)
fail("json_pack object failed");
if (value->refcount != (size_t)2)
fail("json_pack integer refcount failed");
json_decref(value);
json_decref(value);
/* incref'd nullable object (defined case) */
value = json_pack("O?", json_integer(1));
if (!json_is_integer(value) || json_integer_value(value) != 1)
fail("json_pack incref'd nullable object (defined case) failed");
if (value->refcount != (size_t)2)
fail("json_pack incref'd nullable object (defined case) refcount "
"failed");
json_decref(value);
json_decref(value);
/* incref'd nullable object (NULL case) */
value = json_pack("O?", NULL);
if (!json_is_null(value))
fail("json_pack incref'd nullable object (NULL case) failed");
if (value->refcount != (size_t)-1)
fail("json_pack incref'd nullable object (NULL case) refcount failed");
/* simple object */
value = json_pack("{s:[]}", "foo");
if (!json_is_object(value) || json_object_size(value) != 1)
fail("json_pack array failed");
if (!json_is_array(json_object_get(value, "foo")))
fail("json_pack array failed");
if (json_object_get(value, "foo")->refcount != (size_t)1)
fail("json_pack object refcount failed");
json_decref(value);
/* object with complex key */
value = json_pack("{s+#+: []}", "foo", "barbar", 3, "baz");
if (!json_is_object(value) || json_object_size(value) != 1)
fail("json_pack array failed");
if (!json_is_array(json_object_get(value, "foobarbaz")))
fail("json_pack array failed");
if (json_object_get(value, "foobarbaz")->refcount != (size_t)1)
fail("json_pack object refcount failed");
json_decref(value);
/* object with optional members */
value = json_pack("{s:s,s:o,s:O}", "a", NULL, "b", NULL, "c", NULL);
if (value)
fail("json_pack object optional incorrectly succeeded");
value = json_pack("{s:**}", "a", NULL);
if (value)
fail("json_pack object optional invalid incorrectly succeeded");
if (json_pack_ex(&error, 0, "{s:i*}", "a", 1))
fail("json_pack object optional invalid incorrectly succeeded");
check_error(json_error_invalid_format, "Expected format 's', got '*'", "<format>", 1,
5, 5);
value = json_pack("{s:s*,s:o*,s:O*}", "a", NULL, "b", NULL, "c", NULL);
if (!json_is_object(value) || json_object_size(value) != 0)
fail("json_pack object optional failed");
json_decref(value);
value = json_pack("{s:s*}", "key", "\xff\xff");
if (value)
fail("json_pack object optional with invalid UTF-8 incorrectly "
"succeeded");
if (json_pack_ex(&error, 0, "{s: s*#}", "key", "test", 1))
fail("json_pack failed to catch invalid format 's*#'");
check_error(json_error_invalid_format, "Cannot use '#' on optional strings",
"<format>", 1, 6, 6);
if (json_pack_ex(&error, 0, "{s: s*+}", "key", "test", "ing"))
fail("json_pack failed to catch invalid format 's*+'");
check_error(json_error_invalid_format, "Cannot use '+' on optional strings",
"<format>", 1, 6, 6);
/* simple array */
value = json_pack("[i,i,i]", 0, 1, 2);
if (!json_is_array(value) || json_array_size(value) != 3)
fail("json_pack object failed");
for (i = 0; i < 3; i++) {
if (!json_is_integer(json_array_get(value, i)) ||
json_integer_value(json_array_get(value, i)) != i)
fail("json_pack integer array failed");
}
json_decref(value);
/* simple array with optional members */
value = json_pack("[s,o,O]", NULL, NULL, NULL);
if (value)
fail("json_pack array optional incorrectly succeeded");
if (json_pack_ex(&error, 0, "[i*]", 1))
fail("json_pack array optional invalid incorrectly succeeded");
check_error(json_error_invalid_format, "Unexpected format character '*'", "<format>",
1, 3, 3);
value = json_pack("[**]", NULL);
if (value)
fail("json_pack array optional invalid incorrectly succeeded");
value = json_pack("[s*,o*,O*]", NULL, NULL, NULL);
if (!json_is_array(value) || json_array_size(value) != 0)
fail("json_pack array optional failed");
json_decref(value);
#ifdef NAN
/* Invalid float values */
if (json_pack_ex(&error, 0, "f", NAN))
fail("json_pack NAN incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
1, 1);
if (json_pack_ex(&error, 0, "[f]", NAN))
fail("json_pack NAN array element incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
2, 2);
if (json_pack_ex(&error, 0, "{s:f}", "key", NAN))
fail("json_pack NAN object value incorrectly succeeded");
check_error(json_error_numeric_overflow, "Invalid floating point value", "<args>", 1,
4, 4);
#endif
#ifdef INFINITY
test_inifity();
#endif
/* Whitespace; regular string */
value = json_pack(" s\t ", "test");
if (!json_is_string(value) || strcmp("test", json_string_value(value)))
fail("json_pack string (with whitespace) failed");
json_decref(value);
/* Whitespace; empty array */
value = json_pack("[ ]");
if (!json_is_array(value) || json_array_size(value) != 0)
fail("json_pack empty array (with whitespace) failed");
json_decref(value);
/* Whitespace; array */
value = json_pack("[ i , i, i ] ", 1, 2, 3);
if (!json_is_array(value) || json_array_size(value) != 3)
fail("json_pack array (with whitespace) failed");
json_decref(value);
/*
* Invalid cases
*/
/* newline in format string */
if (json_pack_ex(&error, 0, "{\n\n1"))
fail("json_pack failed to catch invalid format '1'");
check_error(json_error_invalid_format, "Expected format 's', got '1'", "<format>", 3,
1, 4);
/* mismatched open/close array/object */
if (json_pack_ex(&error, 0, "[}"))
fail("json_pack failed to catch mismatched '}'");
check_error(json_error_invalid_format, "Unexpected format character '}'", "<format>",
1, 2, 2);
if (json_pack_ex(&error, 0, "{]"))
fail("json_pack failed to catch mismatched ']'");
check_error(json_error_invalid_format, "Expected format 's', got ']'", "<format>", 1,
2, 2);
/* missing close array */
if (json_pack_ex(&error, 0, "["))
fail("json_pack failed to catch missing ']'");
check_error(json_error_invalid_format, "Unexpected end of format string", "<format>",
1, 2, 2);
/* missing close object */
if (json_pack_ex(&error, 0, "{"))
fail("json_pack failed to catch missing '}'");
check_error(json_error_invalid_format, "Unexpected end of format string", "<format>",
1, 2, 2);
/* garbage after format string */
if (json_pack_ex(&error, 0, "[i]a", 42))
fail("json_pack failed to catch garbage after format string");
check_error(json_error_invalid_format, "Garbage after format string", "<format>", 1,
4, 4);
if (json_pack_ex(&error, 0, "ia", 42))
fail("json_pack failed to catch garbage after format string");
check_error(json_error_invalid_format, "Garbage after format string", "<format>", 1,
2, 2);
/* NULL string */
if (json_pack_ex(&error, 0, "s", NULL))
fail("json_pack failed to catch null argument string");
check_error(json_error_null_value, "NULL string", "<args>", 1, 1, 1);
/* + on its own */
if (json_pack_ex(&error, 0, "+", NULL))
fail("json_pack failed to a lone +");
check_error(json_error_invalid_format, "Unexpected format character '+'", "<format>",
1, 1, 1);
/* Empty format */
if (json_pack_ex(&error, 0, ""))
fail("json_pack failed to catch empty format string");
check_error(json_error_invalid_argument, "NULL or empty format string", "<format>",
-1, -1, 0);
/* NULL format */
if (json_pack_ex(&error, 0, NULL))
fail("json_pack failed to catch NULL format string");
check_error(json_error_invalid_argument, "NULL or empty format string", "<format>",
-1, -1, 0);
/* NULL key */
if (json_pack_ex(&error, 0, "{s:i}", NULL, 1))
fail("json_pack failed to catch NULL key");
check_error(json_error_null_value, "NULL object key", "<args>", 1, 2, 2);
/* NULL value followed by object still steals the object's ref */
value = json_incref(json_object());
if (json_pack_ex(&error, 0, "{s:s,s:o}", "badnull", NULL, "dontleak", value))
fail("json_pack failed to catch NULL value");
check_error(json_error_null_value, "NULL string", "<args>", 1, 4, 4);
if (value->refcount != (size_t)1)
fail("json_pack failed to steal reference after error.");
json_decref(value);
/* More complicated checks for row/columns */
if (json_pack_ex(&error, 0, "{ {}: s }", "foo"))
fail("json_pack failed to catch object as key");
check_error(json_error_invalid_format, "Expected format 's', got '{'", "<format>", 1,
3, 3);
/* Complex object */
if (json_pack_ex(&error, 0, "{ s: {}, s:[ii{} }", "foo", "bar", 12, 13))
fail("json_pack failed to catch missing ]");
check_error(json_error_invalid_format, "Unexpected format character '}'", "<format>",
1, 19, 19);
/* Complex array */
if (json_pack_ex(&error, 0, "[[[[[ [[[[[ [[[[ }]]]] ]]]] ]]]]]"))
fail("json_pack failed to catch extra }");
check_error(json_error_invalid_format, "Unexpected format character '}'", "<format>",
1, 21, 21);
/* Invalid UTF-8 in object key */
if (json_pack_ex(&error, 0, "{s:i}", "\xff\xff", 42))
fail("json_pack failed to catch invalid UTF-8 in an object key");
check_error(json_error_invalid_utf8, "Invalid UTF-8 object key", "<args>", 1, 2, 2);
/* Invalid UTF-8 in a string */
if (json_pack_ex(&error, 0, "{s:s}", "foo", "\xff\xff"))
fail("json_pack failed to catch invalid UTF-8 in a string");
check_error(json_error_invalid_utf8, "Invalid UTF-8 string", "<args>", 1, 4, 4);
/* Invalid UTF-8 in an optional '?' string */
if (json_pack_ex(&error, 0, "{s:s?}", "foo", "\xff\xff"))
fail("json_pack failed to catch invalid UTF-8 in an optional '?' "
"string");
check_error(json_error_invalid_utf8, "Invalid UTF-8 string", "<args>", 1, 5, 5);
/* Invalid UTF-8 in an optional '*' string */
if (json_pack_ex(&error, 0, "{s:s*}", "foo", "\xff\xff"))
fail("json_pack failed to catch invalid UTF-8 in an optional '*' "
"string");
check_error(json_error_invalid_utf8, "Invalid UTF-8 string", "<args>", 1, 5, 5);
/* Invalid UTF-8 in a concatenated key */
if (json_pack_ex(&error, 0, "{s+:i}", "\xff\xff", "concat", 42))
fail("json_pack failed to catch invalid UTF-8 in an object key");
check_error(json_error_invalid_utf8, "Invalid UTF-8 object key", "<args>", 1, 3, 3);
if (json_pack_ex(&error, 0, "{s:o}", "foo", NULL))
fail("json_pack failed to catch nullable object");
check_error(json_error_null_value, "NULL object", "<args>", 1, 4, 4);
if (json_pack_ex(&error, 0, "{s:O}", "foo", NULL))
fail("json_pack failed to catch nullable incref object");
check_error(json_error_null_value, "NULL object", "<args>", 1, 4, 4);
if (json_pack_ex(&error, 0, "{s+:o}", "foo", "bar", NULL))
fail("json_pack failed to catch non-nullable object value");
check_error(json_error_null_value, "NULL object", "<args>", 1, 5, 5);
if (json_pack_ex(&error, 0, "[1s", "Hi"))
fail("json_pack failed to catch invalid format");
check_error(json_error_invalid_format, "Unexpected format character '1'", "<format>",
1, 2, 2);
if (json_pack_ex(&error, 0, "[1s+", "Hi", "ya"))
fail("json_pack failed to catch invalid format");
check_error(json_error_invalid_format, "Unexpected format character '1'", "<format>",
1, 2, 2);
if (json_pack_ex(&error, 0, "[so]", NULL, json_object()))
fail("json_pack failed to catch NULL value");
check_error(json_error_null_value, "NULL string", "<args>", 1, 2, 2);
}

View file

@ -1,185 +1,287 @@
/*
* Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <string.h>
#include <jansson.h>
#include "util.h"
#include <jansson.h>
#include <string.h>
static void test_bad_args(void) {
json_t *num = json_integer(1);
json_t *txt = json_string("test");
if (!num || !txt)
fail("failed to allocate test objects");
if (json_string_nocheck(NULL) != NULL)
fail("json_string_nocheck with NULL argument did not return NULL");
if (json_stringn_nocheck(NULL, 0) != NULL)
fail("json_stringn_nocheck with NULL argument did not return NULL");
if (json_string(NULL) != NULL)
fail("json_string with NULL argument did not return NULL");
if (json_stringn(NULL, 0) != NULL)
fail("json_stringn with NULL argument did not return NULL");
if (json_string_length(NULL) != 0)
fail("json_string_length with non-string argument did not return 0");
if (json_string_length(num) != 0)
fail("json_string_length with non-string argument did not return 0");
if (json_string_value(NULL) != NULL)
fail("json_string_value with non-string argument did not return NULL");
if (json_string_value(num) != NULL)
fail("json_string_value with non-string argument did not return NULL");
if (!json_string_setn_nocheck(NULL, "", 0))
fail("json_string_setn with non-string argument did not return error");
if (!json_string_setn_nocheck(num, "", 0))
fail("json_string_setn with non-string argument did not return error");
if (!json_string_setn_nocheck(txt, NULL, 0))
fail("json_string_setn_nocheck with NULL value did not return error");
if (!json_string_set_nocheck(txt, NULL))
fail("json_string_set_nocheck with NULL value did not return error");
if (!json_string_set(txt, NULL))
fail("json_string_set with NULL value did not return error");
if (!json_string_setn(txt, NULL, 0))
fail("json_string_setn with NULL value did not return error");
if (num->refcount != 1)
fail("unexpected reference count for num");
if (txt->refcount != 1)
fail("unexpected reference count for txt");
json_decref(num);
json_decref(txt);
}
/* Call the simple functions not covered by other tests of the public API */
int main()
{
static void run_tests() {
json_t *value;
value = json_boolean(1);
if (!json_is_true(value))
fail("json_boolean(1) failed");
json_decref(value);
value = json_boolean(-123);
if (!json_is_true(value))
fail("json_boolean(-123) failed");
json_decref(value);
value = json_boolean(0);
if (!json_is_false(value))
fail("json_boolean(0) failed");
if (json_boolean_value(value) != 0)
fail("json_boolean_value failed");
json_decref(value);
value = json_integer(1);
if(json_typeof(value) != JSON_INTEGER)
if (json_typeof(value) != JSON_INTEGER)
fail("json_typeof failed");
if(json_is_object(value))
if (json_is_object(value))
fail("json_is_object failed");
if(json_is_array(value))
if (json_is_array(value))
fail("json_is_array failed");
if(json_is_string(value))
if (json_is_string(value))
fail("json_is_string failed");
if(!json_is_integer(value))
if (!json_is_integer(value))
fail("json_is_integer failed");
if(json_is_real(value))
if (json_is_real(value))
fail("json_is_real failed");
if(!json_is_number(value))
if (!json_is_number(value))
fail("json_is_number failed");
if(json_is_true(value))
if (json_is_true(value))
fail("json_is_true failed");
if(json_is_false(value))
if (json_is_false(value))
fail("json_is_false failed");
if(json_is_boolean(value))
if (json_is_boolean(value))
fail("json_is_boolean failed");
if(json_is_null(value))
if (json_is_null(value))
fail("json_is_null failed");
json_decref(value);
value = json_string("foo");
if(!value)
if (!value)
fail("json_string failed");
if(strcmp(json_string_value(value), "foo"))
if (strcmp(json_string_value(value), "foo"))
fail("invalid string value");
if (json_string_length(value) != 3)
fail("invalid string length");
if(json_string_set(value, "bar"))
if (json_string_set(value, "barr"))
fail("json_string_set failed");
if(strcmp(json_string_value(value), "bar"))
if (strcmp(json_string_value(value), "barr"))
fail("invalid string value");
if (json_string_length(value) != 4)
fail("invalid string length");
if (json_string_setn(value, "hi\0ho", 5))
fail("json_string_set failed");
if (memcmp(json_string_value(value), "hi\0ho\0", 6))
fail("invalid string value");
if (json_string_length(value) != 5)
fail("invalid string length");
json_decref(value);
value = json_string(NULL);
if(value)
if (value)
fail("json_string(NULL) failed");
/* invalid UTF-8 */
value = json_string("a\xefz");
if(value)
if (value)
fail("json_string(<invalid utf-8>) failed");
value = json_string_nocheck("foo");
if(!value)
if (!value)
fail("json_string_nocheck failed");
if(strcmp(json_string_value(value), "foo"))
if (strcmp(json_string_value(value), "foo"))
fail("invalid string value");
if (json_string_length(value) != 3)
fail("invalid string length");
if(json_string_set_nocheck(value, "bar"))
if (json_string_set_nocheck(value, "barr"))
fail("json_string_set_nocheck failed");
if(strcmp(json_string_value(value), "bar"))
if (strcmp(json_string_value(value), "barr"))
fail("invalid string value");
if (json_string_length(value) != 4)
fail("invalid string length");
if (json_string_setn_nocheck(value, "hi\0ho", 5))
fail("json_string_set failed");
if (memcmp(json_string_value(value), "hi\0ho\0", 6))
fail("invalid string value");
if (json_string_length(value) != 5)
fail("invalid string length");
json_decref(value);
/* invalid UTF-8 */
value = json_string_nocheck("qu\xff");
if(!value)
if (!value)
fail("json_string_nocheck failed");
if(strcmp(json_string_value(value), "qu\xff"))
if (strcmp(json_string_value(value), "qu\xff"))
fail("invalid string value");
if (json_string_length(value) != 3)
fail("invalid string length");
if(json_string_set_nocheck(value, "\xfd\xfe\xff"))
if (json_string_set_nocheck(value, "\xfd\xfe\xff"))
fail("json_string_set_nocheck failed");
if(strcmp(json_string_value(value), "\xfd\xfe\xff"))
if (strcmp(json_string_value(value), "\xfd\xfe\xff"))
fail("invalid string value");
if (json_string_length(value) != 3)
fail("invalid string length");
json_decref(value);
value = json_integer(123);
if(!value)
if (!value)
fail("json_integer failed");
if(json_integer_value(value) != 123)
if (json_integer_value(value) != 123)
fail("invalid integer value");
if(json_number_value(value) != 123.0)
if (json_number_value(value) != 123.0)
fail("invalid number value");
if(json_integer_set(value, 321))
if (json_integer_set(value, 321))
fail("json_integer_set failed");
if(json_integer_value(value) != 321)
if (json_integer_value(value) != 321)
fail("invalid integer value");
if(json_number_value(value) != 321.0)
if (json_number_value(value) != 321.0)
fail("invalid number value");
json_decref(value);
value = json_real(123.123);
if(!value)
if (!value)
fail("json_real failed");
if(json_real_value(value) != 123.123)
if (json_real_value(value) != 123.123)
fail("invalid integer value");
if(json_number_value(value) != 123.123)
if (json_number_value(value) != 123.123)
fail("invalid number value");
if(json_real_set(value, 321.321))
if (json_real_set(value, 321.321))
fail("json_real_set failed");
if(json_real_value(value) != 321.321)
if (json_real_value(value) != 321.321)
fail("invalid real value");
if(json_number_value(value) != 321.321)
if (json_number_value(value) != 321.321)
fail("invalid number value");
json_decref(value);
value = json_true();
if(!value)
if (!value)
fail("json_true failed");
json_decref(value);
value = json_false();
if(!value)
if (!value)
fail("json_false failed");
json_decref(value);
value = json_null();
if(!value)
if (!value)
fail("json_null failed");
json_decref(value);
/* Test reference counting on singletons (true, false, null) */
value = json_true();
if(value->refcount != (unsigned int)-1)
fail("refcounting true works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting true works incorrectly");
json_decref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting true works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting true works incorrectly");
json_incref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting true works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting true works incorrectly");
value = json_false();
if(value->refcount != (unsigned int)-1)
fail("refcounting false works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting false works incorrectly");
json_decref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting false works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting false works incorrectly");
json_incref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting false works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting false works incorrectly");
value = json_null();
if(value->refcount != (unsigned int)-1)
fail("refcounting null works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting null works incorrectly");
json_decref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting null works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting null works incorrectly");
json_incref(value);
if(value->refcount != (unsigned int)-1)
fail("refcounting null works incorrectly");
if (value->refcount != (size_t)-1)
fail("refcounting null works incorrectly");
return 0;
#ifdef json_auto_t
value = json_string("foo");
{
json_auto_t *test = json_incref(value);
/* Use test so GCC doesn't complain it is unused. */
if (!json_is_string(test))
fail("value type check failed");
}
if (value->refcount != 1)
fail("automatic decrement failed");
json_decref(value);
#endif
test_bad_args();
}

View file

@ -0,0 +1,29 @@
#include "util.h"
#include <jansson.h>
#include <string.h>
static void test_sprintf() {
json_t *s = json_sprintf("foo bar %d", 42);
if (!s)
fail("json_sprintf returned NULL");
if (!json_is_string(s))
fail("json_sprintf didn't return a JSON string");
if (strcmp(json_string_value(s), "foo bar 42"))
fail("json_sprintf generated an unexpected string");
json_decref(s);
s = json_sprintf("%s", "");
if (!s)
fail("json_sprintf returned NULL");
if (!json_is_string(s))
fail("json_sprintf didn't return a JSON string");
if (json_string_length(s) != 0)
fail("string is not empty");
json_decref(s);
if (json_sprintf("%s", "\xff\xff"))
fail("json_sprintf unexpected success with invalid UTF");
}
static void run_tests() { test_sprintf(); }

View file

@ -0,0 +1,431 @@
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
* Copyright (c) 2010-2012 Graeme Smecher <graeme.smecher@mail.mcgill.ca>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "util.h"
#include <jansson.h>
#include <stdio.h>
#include <string.h>
static void run_tests() {
json_t *j, *j2;
int i1, i2, i3;
json_int_t I1;
int rv;
size_t z;
double f;
char *s;
json_error_t error;
/*
* Simple, valid json_pack cases
*/
/* true */
rv = json_unpack(json_true(), "b", &i1);
if (rv || !i1)
fail("json_unpack boolean failed");
/* false */
rv = json_unpack(json_false(), "b", &i1);
if (rv || i1)
fail("json_unpack boolean failed");
/* null */
if (json_unpack(json_null(), "n"))
fail("json_unpack null failed");
/* integer */
j = json_integer(42);
rv = json_unpack(j, "i", &i1);
if (rv || i1 != 42)
fail("json_unpack integer failed");
json_decref(j);
/* json_int_t */
j = json_integer(5555555);
rv = json_unpack(j, "I", &I1);
if (rv || I1 != 5555555)
fail("json_unpack json_int_t failed");
json_decref(j);
/* real */
j = json_real(1.7);
rv = json_unpack(j, "f", &f);
if (rv || f != 1.7)
fail("json_unpack real failed");
json_decref(j);
/* number */
j = json_integer(12345);
rv = json_unpack(j, "F", &f);
if (rv || f != 12345.0)
fail("json_unpack (real or) integer failed");
json_decref(j);
j = json_real(1.7);
rv = json_unpack(j, "F", &f);
if (rv || f != 1.7)
fail("json_unpack real (or integer) failed");
json_decref(j);
/* string */
j = json_string("foo");
rv = json_unpack(j, "s", &s);
if (rv || strcmp(s, "foo"))
fail("json_unpack string failed");
json_decref(j);
/* string with length (size_t) */
j = json_string("foo");
rv = json_unpack(j, "s%", &s, &z);
if (rv || strcmp(s, "foo") || z != 3)
fail("json_unpack string with length (size_t) failed");
json_decref(j);
/* empty object */
j = json_object();
if (json_unpack(j, "{}"))
fail("json_unpack empty object failed");
json_decref(j);
/* empty list */
j = json_array();
if (json_unpack(j, "[]"))
fail("json_unpack empty list failed");
json_decref(j);
/* non-incref'd object */
j = json_object();
rv = json_unpack(j, "o", &j2);
if (rv || j2 != j || j->refcount != 1)
fail("json_unpack object failed");
json_decref(j);
/* incref'd object */
j = json_object();
rv = json_unpack(j, "O", &j2);
if (rv || j2 != j || j->refcount != 2)
fail("json_unpack object failed");
json_decref(j);
json_decref(j);
/* simple object */
j = json_pack("{s:i}", "foo", 42);
rv = json_unpack(j, "{s:i}", "foo", &i1);
if (rv || i1 != 42)
fail("json_unpack simple object failed");
json_decref(j);
/* simple array */
j = json_pack("[iii]", 1, 2, 3);
rv = json_unpack(j, "[i,i,i]", &i1, &i2, &i3);
if (rv || i1 != 1 || i2 != 2 || i3 != 3)
fail("json_unpack simple array failed");
json_decref(j);
/* object with many items & strict checking */
j = json_pack("{s:i, s:i, s:i}", "a", 1, "b", 2, "c", 3);
rv = json_unpack(j, "{s:i, s:i, s:i}", "a", &i1, "b", &i2, "c", &i3);
if (rv || i1 != 1 || i2 != 2 || i3 != 3)
fail("json_unpack object with many items failed");
json_decref(j);
/*
* Invalid cases
*/
j = json_integer(42);
if (!json_unpack_ex(j, &error, 0, "z"))
fail("json_unpack succeeded with invalid format character");
check_error(json_error_invalid_format, "Unexpected format character 'z'", "<format>",
1, 1, 1);
if (!json_unpack_ex(NULL, &error, 0, "[i]"))
fail("json_unpack succeeded with NULL root");
check_error(json_error_null_value, "NULL root value", "<root>", -1, -1, 0);
json_decref(j);
/* mismatched open/close array/object */
j = json_pack("[]");
if (!json_unpack_ex(j, &error, 0, "[}"))
fail("json_unpack failed to catch mismatched ']'");
check_error(json_error_invalid_format, "Unexpected format character '}'", "<format>",
1, 2, 2);
json_decref(j);
j = json_pack("{}");
if (!json_unpack_ex(j, &error, 0, "{]"))
fail("json_unpack failed to catch mismatched '}'");
check_error(json_error_invalid_format, "Expected format 's', got ']'", "<format>", 1,
2, 2);
json_decref(j);
/* missing close array */
j = json_pack("[]");
if (!json_unpack_ex(j, &error, 0, "["))
fail("json_unpack failed to catch missing ']'");
check_error(json_error_invalid_format, "Unexpected end of format string", "<format>",
1, 2, 2);
json_decref(j);
/* missing close object */
j = json_pack("{}");
if (!json_unpack_ex(j, &error, 0, "{"))
fail("json_unpack failed to catch missing '}'");
check_error(json_error_invalid_format, "Unexpected end of format string", "<format>",
1, 2, 2);
json_decref(j);
/* garbage after format string */
j = json_pack("[i]", 42);
if (!json_unpack_ex(j, &error, 0, "[i]a", &i1))
fail("json_unpack failed to catch garbage after format string");
check_error(json_error_invalid_format, "Garbage after format string", "<format>", 1,
4, 4);
json_decref(j);
j = json_integer(12345);
if (!json_unpack_ex(j, &error, 0, "ia", &i1))
fail("json_unpack failed to catch garbage after format string");
check_error(json_error_invalid_format, "Garbage after format string", "<format>", 1,
2, 2);
json_decref(j);
/* NULL format string */
j = json_pack("[]");
if (!json_unpack_ex(j, &error, 0, NULL))
fail("json_unpack failed to catch null format string");
check_error(json_error_invalid_argument, "NULL or empty format string", "<format>",
-1, -1, 0);
json_decref(j);
/* NULL string pointer */
j = json_string("foobie");
if (!json_unpack_ex(j, &error, 0, "s", NULL))
fail("json_unpack failed to catch null string pointer");
check_error(json_error_null_value, "NULL string argument", "<args>", 1, 1, 1);
json_decref(j);
/* invalid types */
j = json_integer(42);
j2 = json_string("foo");
if (!json_unpack_ex(j, &error, 0, "s"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected string, got integer", "<validation>", 1,
1, 1);
if (!json_unpack_ex(j, &error, 0, "n"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected null, got integer", "<validation>", 1, 1,
1);
if (!json_unpack_ex(j, &error, 0, "b"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected true or false, got integer",
"<validation>", 1, 1, 1);
if (!json_unpack_ex(j2, &error, 0, "i"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected integer, got string", "<validation>", 1,
1, 1);
if (!json_unpack_ex(j2, &error, 0, "I"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected integer, got string", "<validation>", 1,
1, 1);
if (!json_unpack_ex(j, &error, 0, "f"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected real, got integer", "<validation>", 1, 1,
1);
if (!json_unpack_ex(j2, &error, 0, "F"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected real or integer, got string",
"<validation>", 1, 1, 1);
if (!json_unpack_ex(j, &error, 0, "[i]"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected array, got integer", "<validation>", 1,
1, 1);
if (!json_unpack_ex(j, &error, 0, "{si}", "foo"))
fail("json_unpack failed to catch invalid type");
check_error(json_error_wrong_type, "Expected object, got integer", "<validation>", 1,
1, 1);
json_decref(j);
json_decref(j2);
/* Array index out of range */
j = json_pack("[i]", 1);
if (!json_unpack_ex(j, &error, 0, "[ii]", &i1, &i2))
fail("json_unpack failed to catch index out of array bounds");
check_error(json_error_index_out_of_range, "Array index 1 out of range",
"<validation>", 1, 3, 3);
json_decref(j);
/* NULL object key */
j = json_pack("{si}", "foo", 42);
if (!json_unpack_ex(j, &error, 0, "{si}", NULL, &i1))
fail("json_unpack failed to catch null string pointer");
check_error(json_error_null_value, "NULL object key", "<args>", 1, 2, 2);
json_decref(j);
/* Object key not found */
j = json_pack("{si}", "foo", 42);
if (!json_unpack_ex(j, &error, 0, "{si}", "baz", &i1))
fail("json_unpack failed to catch null string pointer");
check_error(json_error_item_not_found, "Object item not found: baz", "<validation>",
1, 3, 3);
json_decref(j);
/*
* Strict validation
*/
j = json_pack("[iii]", 1, 2, 3);
rv = json_unpack(j, "[iii!]", &i1, &i2, &i3);
if (rv || i1 != 1 || i2 != 2 || i3 != 3)
fail("json_unpack array with strict validation failed");
json_decref(j);
j = json_pack("[iii]", 1, 2, 3);
if (!json_unpack_ex(j, &error, 0, "[ii!]", &i1, &i2))
fail("json_unpack array with strict validation failed");
check_error(json_error_end_of_input_expected, "1 array item(s) left unpacked",
"<validation>", 1, 5, 5);
json_decref(j);
/* Like above, but with JSON_STRICT instead of '!' format */
j = json_pack("[iii]", 1, 2, 3);
if (!json_unpack_ex(j, &error, JSON_STRICT, "[ii]", &i1, &i2))
fail("json_unpack array with strict validation failed");
check_error(json_error_end_of_input_expected, "1 array item(s) left unpacked",
"<validation>", 1, 4, 4);
json_decref(j);
j = json_pack("{s:s, s:i}", "foo", "bar", "baz", 42);
rv = json_unpack(j, "{sssi!}", "foo", &s, "baz", &i1);
if (rv || strcmp(s, "bar") != 0 || i1 != 42)
fail("json_unpack object with strict validation failed");
json_decref(j);
/* Unpack the same item twice */
j = json_pack("{s:s, s:i, s:b}", "foo", "bar", "baz", 42, "quux", 1);
if (!json_unpack_ex(j, &error, 0, "{s:s,s:s!}", "foo", &s, "foo", &s))
fail("json_unpack object with strict validation failed");
{
const char *possible_errors[] = {"2 object item(s) left unpacked: baz, quux",
"2 object item(s) left unpacked: quux, baz"};
check_errors(json_error_end_of_input_expected, possible_errors, 2, "<validation>",
1, 10, 10);
}
json_decref(j);
j = json_pack("[i,{s:i,s:n},[i,i]]", 1, "foo", 2, "bar", 3, 4);
if (json_unpack_ex(j, NULL, JSON_STRICT | JSON_VALIDATE_ONLY, "[i{sisn}[ii]]", "foo",
"bar"))
fail("json_unpack complex value with strict validation failed");
json_decref(j);
/* ! and * must be last */
j = json_pack("[ii]", 1, 2);
if (!json_unpack_ex(j, &error, 0, "[i!i]", &i1, &i2))
fail("json_unpack failed to catch ! in the middle of an array");
check_error(json_error_invalid_format, "Expected ']' after '!', got 'i'", "<format>",
1, 4, 4);
if (!json_unpack_ex(j, &error, 0, "[i*i]", &i1, &i2))
fail("json_unpack failed to catch * in the middle of an array");
check_error(json_error_invalid_format, "Expected ']' after '*', got 'i'", "<format>",
1, 4, 4);
json_decref(j);
j = json_pack("{sssi}", "foo", "bar", "baz", 42);
if (!json_unpack_ex(j, &error, 0, "{ss!si}", "foo", &s, "baz", &i1))
fail("json_unpack failed to catch ! in the middle of an object");
check_error(json_error_invalid_format, "Expected '}' after '!', got 's'", "<format>",
1, 5, 5);
if (!json_unpack_ex(j, &error, 0, "{ss*si}", "foo", &s, "baz", &i1))
fail("json_unpack failed to catch ! in the middle of an object");
check_error(json_error_invalid_format, "Expected '}' after '*', got 's'", "<format>",
1, 5, 5);
json_decref(j);
/* Error in nested object */
j = json_pack("{s{snsn}}", "foo", "bar", "baz");
if (!json_unpack_ex(j, &error, 0, "{s{sn!}}", "foo", "bar"))
fail("json_unpack nested object with strict validation failed");
check_error(json_error_end_of_input_expected, "1 object item(s) left unpacked: baz",
"<validation>", 1, 7, 7);
json_decref(j);
/* Error in nested array */
j = json_pack("[[ii]]", 1, 2);
if (!json_unpack_ex(j, &error, 0, "[[i!]]", &i1))
fail("json_unpack nested array with strict validation failed");
check_error(json_error_end_of_input_expected, "1 array item(s) left unpacked",
"<validation>", 1, 5, 5);
json_decref(j);
/* Optional values */
j = json_object();
i1 = 0;
if (json_unpack(j, "{s?i}", "foo", &i1))
fail("json_unpack failed for optional key");
if (i1 != 0)
fail("json_unpack unpacked an optional key");
json_decref(j);
i1 = 0;
j = json_pack("{si}", "foo", 42);
if (json_unpack(j, "{s?i}", "foo", &i1))
fail("json_unpack failed for an optional value");
if (i1 != 42)
fail("json_unpack failed to unpack an optional value");
json_decref(j);
j = json_object();
i1 = i2 = i3 = 0;
if (json_unpack(j, "{s?[ii]s?{s{si}}}", "foo", &i1, &i2, "bar", "baz", "quux", &i3))
fail("json_unpack failed for complex optional values");
if (i1 != 0 || i2 != 0 || i3 != 0)
fail("json_unpack unexpectedly unpacked something");
json_decref(j);
j = json_pack("{s{si}}", "foo", "bar", 42);
if (json_unpack(j, "{s?{s?i}}", "foo", "bar", &i1))
fail("json_unpack failed for complex optional values");
if (i1 != 42)
fail("json_unpack failed to unpack");
json_decref(j);
/* Combine ? and ! */
j = json_pack("{si}", "foo", 42);
i1 = i2 = 0;
if (json_unpack(j, "{sis?i!}", "foo", &i1, "bar", &i2))
fail("json_unpack failed for optional values with strict mode");
if (i1 != 42)
fail("json_unpack failed to unpack");
if (i2 != 0)
fail("json_unpack failed to unpack");
json_decref(j);
/* But don't compensate a missing key with an optional one. */
j = json_pack("{sisi}", "foo", 42, "baz", 43);
i1 = i2 = i3 = 0;
if (!json_unpack_ex(j, &error, 0, "{sis?i!}", "foo", &i1, "bar", &i2))
fail("json_unpack failed for optional values with strict mode and "
"compensation");
check_error(json_error_end_of_input_expected, "1 object item(s) left unpacked: baz",
"<validation>", 1, 8, 8);
json_decref(j);
}

Some files were not shown because too many files have changed in this diff Show more