提交 12790a40 编写于 作者: J jp9000

Subtree merged in deps/jansson

上级 71890e03
*~
*.o
*.a
.libs
.deps
Makefile
Makefile.in
aclocal.m4
autom4te.cache
config.guess
config.h
config.h.in
config.log
config.status
config.sub
configure
depcomp
install-sh
libtool
ltmain.sh
missing
*.lo
*.la
stamp-h1
*.pyc
*.pc
/src/jansson_config.h
*.exe
language: c
compiler:
- gcc
- clang
script: autoreconf -f -i && CFLAGS=-Werror ./configure && make check
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/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
LOCAL_MODULE:= libjansson
include $(BUILD_SHARED_LIBRARY)
Version 2.6 (in development)
============================
Released XXXX-XX-XX
* New features:
- `json_pack()` and friends: Add format specifiers ``s%`` and ``+%``
for a size_t string length.
- `json_unpack()` and friends: Add format specifier ``s%`` for
unpacking the string length along with the string itself.
- 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()`.
- Support ``\u0000`` escapes in the decoder. The support can be
enabled by using the ``JSON_ALLOW_NUL`` decoding flag.
* Bug fixes:
- Some malformed ``\uNNNN`` escapes could crash the decoder with an
assertion failure.
* Other changes:
- ``\uNNNN`` escapes are now encoded in upper case for better
readability.
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
compatiblity.
* 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
keys.
* Bug fixes:
- Fix an error that occured when an array or object was first
encoded as empty, then populated with some data, and then
re-encoded
- Fix the situation like above, but when the first encoding resulted
in an error
* Documentation:
- Clarify the documentation on reference stealing, providing an
example usage pattern
Version 1.2.1
=============
Released 2010-04-03
* Bug fixes:
- Fix reference counting on ``true``, ``false`` and ``null``
- Estimate real number underflows in decoder with 0.0 instead of
issuing an error
* Portability:
- Make ``int32_t`` available on all systems
- Support compilers that don't have the ``inline`` keyword
- Require Autoconf 2.60 (for ``int32_t``)
* Tests:
- Print test names correctly when ``VERBOSE=1``
- ``test/suites/api``: Fail when a test fails
- Enhance tests for iterators
- Enhance tests for decoding texts that contain null bytes
* Documentation:
- Don't remove ``changes.rst`` in ``make clean``
- Add a chapter on RFC conformance
Version 1.2
===========
Released 2010-01-21
* New functions:
- `json_equal()`: Test whether two JSON values are equal
- `json_copy()` and `json_deep_copy()`: Make shallow and deep copies
of JSON values
- Add a version of all functions taking a string argument that
doesn't check for valid UTF-8: `json_string_nocheck()`,
`json_string_set_nocheck()`, `json_object_set_nocheck()`,
`json_object_set_new_nocheck()`
* New encoding flags:
- ``JSON_SORT_KEYS``: Sort objects by key
- ``JSON_ENSURE_ASCII``: Escape all non-ASCII Unicode characters
- ``JSON_COMPACT``: Use a compact representation with all unneeded
whitespace stripped
* Bug fixes:
- Revise and unify whitespace usage in encoder: Add spaces between
array and object items, never append newline to output.
- Remove const qualifier from the ``json_t`` parameter in
`json_string_set()`, `json_integer_set()` and `json_real_set`.
- Use ``int32_t`` internally for representing Unicode code points
(int is not enough on all platforms)
* Other changes:
- Convert ``CHANGES`` (this file) to reStructured text and add it to
HTML documentation
- The test system has been refactored. Python is no longer required
to run the tests.
- Documentation can now be built by invoking ``make html``
- Support for pkg-config
Version 1.1.3
=============
Released 2009-12-18
* Encode reals correctly, so that first encoding and then decoding a
real always produces the same value
* Don't export private symbols in ``libjansson.so``
Version 1.1.2
=============
Released 2009-11-08
* Fix a bug where an error message was not produced if the input file
could not be opened in `json_load_file()`
* Fix an assertion failure in decoder caused by a minus sign without a
digit after it
* Remove an unneeded include of ``stdint.h`` in ``jansson.h``
Version 1.1.1
=============
Released 2009-10-26
* All documentation files were not distributed with v1.1; build
documentation in make distcheck to prevent this in the future
* Fix v1.1 release date in ``CHANGES``
Version 1.1
===========
Released 2009-10-20
* API additions and improvements:
- Extend array and object APIs
- Add functions to modify integer, real and string values
- Improve argument validation
- Use unsigned int instead of ``uint32_t`` for encoding flags
* Enhance documentation
- Add getting started guide and tutorial
- Fix some typos
- General clarifications and cleanup
* Check for integer and real overflows and underflows in decoder
* Make singleton values thread-safe (``true``, ``false`` and ``null``)
* Enhance circular reference handling
* Don't define ``-std=c99`` in ``AM_CFLAGS``
* Add C++ guards to ``jansson.h``
* Minor performance and portability improvements
* Expand test coverage
Version 1.0.4
=============
Released 2009-10-11
* Relax Autoconf version requirement to 2.59
* Make Jansson compile on platforms where plain ``char`` is unsigned
* Fix API tests for object
Version 1.0.3
=============
Released 2009-09-14
* Check for integer and real overflows and underflows in decoder
* Use the Python json module for tests, or simplejson if the json
module is not found
* Distribute changelog (this file)
Version 1.0.2
=============
Released 2009-09-08
* Handle EOF correctly in decoder
Version 1.0.1
=============
Released 2009-09-04
* Fixed broken `json_is_boolean()`
Version 1.0
===========
Released 2009-08-25
* Initial release
# Notes:
#
# Author: Paul Harris, June 2012
# Additions: Joakim Soderberg, Febuary 2013
#
# Supports: building static/shared, release/debug/etc, can also build html docs
# and some of the tests.
# Note that its designed for out-of-tree builds, so it will not pollute your
# source tree.
#
# TODO 1: Finish implementing tests. api tests are working, but the valgrind
# variants are not flagging problems.
#
# TODO 2: There is a check_exports script that would try and incorporate.
#
# TODO 3: Consolidate version numbers, currently the version number is written
# into: * cmake (here) * autotools (the configure) * source code header files.
# Should not be written directly into header files, autotools/cmake can do
# that job.
#
# Brief intro on how to use cmake:
# > mkdir build (somewhere - we do out-of-tree builds)
# > use cmake, ccmake, or cmake-gui to configure the project. for linux, you
# can only choose one variant: release,debug,etc... and static or shared.
# >> example:
# >> cd build
# >> ccmake -i ../path_to_jansson_dir
# >> inside, configure your options. press C until there are no lines
# with * next to them.
# >> note, I like to configure the 'install' path to ../install, so I get
# self-contained clean installs I can point other projects to.
# >> press G to 'generate' the project files.
# >> make (to build the project)
# >> make install
# >> make test (to run the tests, if you enabled them)
#
# Brief description on how it works:
# There is a small heirachy of CMakeLists.txt files which define how the
# project is built.
# Header file detection etc is done, and the results are written into config.h
# and jansson_config.h, which are generated from the corresponding
# config.h.cmake and jansson_config.h.cmake template files.
# The generated header files end up in the build directory - not in
# the source directory.
# The rest is down to the usual make process.
cmake_minimum_required (VERSION 2.8)
# required for exports? cmake_minimum_required (VERSION 2.8.6)
project (jansson C)
# Options
OPTION (BUILD_SHARED_LIBS "Build shared libraries." OFF)
if (MSVC)
# This option must match the settings used in your program, in particular if you
# are linking statically
OPTION( STATIC_CRT "Link the static CRT libraries" OFF )
endif ()
# Set some nicer output dirs.
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
# 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)
SET (CMAKE_DEBUG_POSTFIX "_d")
else (WIN32)
endif (WIN32)
# This is how I thought it should go
# set (JANSSON_VERSION "2.3.1")
# set (JANSSON_SOVERSION 2)
set(JANSSON_DISPLAY_VERSION "2.5")
# This is what is required to match the same numbers as automake's
set (JANSSON_VERSION "4.5.0")
set (JANSSON_SOVERSION 4)
# for CheckFunctionKeywords
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include (CheckFunctionExists)
include (CheckFunctionKeywords)
include (CheckIncludeFiles)
include (CheckTypeSize)
if (MSVC)
# Turn off Microsofts "security" warnings.
add_definitions( "/W3 /D_CRT_SECURE_NO_WARNINGS /wd4005 /wd4996 /nologo" )
if (STATIC_CRT)
set(CMAKE_C_FLAGS_RELEASE "/MT")
set(CMAKE_C_FLAGS_DEBUG "/MTd")
endif()
endif()
if (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_C_FLAGS "-fPIC")
endif()
# Check for the int-type includes
check_include_files (sys/types.h HAVE_SYS_TYPES_H)
check_include_files (inttypes.h HAVE_INTTYPES_H)
check_include_files (stdint.h HAVE_STDINT_H)
# 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 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 for ssize_t and SSIZE_T existance.
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)
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 ()
# If locale.h and localeconv() are available, define to 1, otherwise to 0.
check_include_files (locale.h HAVE_LOCALE_H)
check_function_exists (localeconv HAVE_LOCALECONV)
if (HAVE_LOCALECONV AND HAVE_LOCALE_H)
set (JSON_HAVE_LOCALECONV 1)
else ()
set (JSON_HAVE_LOCALECONV 0)
endif ()
# check if we have setlocale
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 (HAVE_INLINE)
# no inline on this platform
set (JSON_INLINE)
endif (HAVE_INLINE)
# Find our snprintf
check_function_exists (snprintf HAVE_SNPRINTF)
check_function_exists (_snprintf HAVE__SNPRINTF)
if (HAVE_SNPRINTF)
set (JSON_SNPRINTF snprintf)
elseif (HAVE__SNPRINTF)
set (JSON_SNPRINTF _snprintf)
endif ()
# Create pkg-conf file.
# (We use the same files as ./configure does, so we
# have to defined the same variables used there).
if(NOT DEFINED CMAKE_INSTALL_LIBDIR)
set(CMAKE_INSTALL_LIBDIR lib)
endif(NOT DEFINED CMAKE_INSTALL_LIBDIR)
set(prefix ${CMAKE_INSTALL_PREFIX})
set(exec_prefix ${CMAKE_INSTALL_PREFIX})
set(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR})
set(VERSION ${JANSSON_DISPLAY_VERSION})
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/jansson.pc.in
${CMAKE_CURRENT_BINARY_DIR}/jansson.pc @ONLY)
# 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/config.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/private_include/config.h)
# and tell the source code to include it
add_definitions (-DHAVE_CONFIG_H)
include_directories (${CMAKE_CURRENT_BINARY_DIR}/include)
include_directories (${CMAKE_CURRENT_BINARY_DIR}/private_include)
# Add the lib sources.
file (GLOB C_FILES src/*.c)
if (BUILD_SHARED_LIBS)
add_library (jansson SHARED ${C_FILES} src/jansson.def)
set_target_properties (jansson PROPERTIES
VERSION ${JANSSON_VERSION}
SOVERSION ${JANSSON_SOVERSION})
else ()
add_library (jansson ${C_FILES})
endif ()
# LIBRARY for linux
# RUNTIME for windows (when building shared)
install (TARGETS jansson
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION bin
)
install (FILES
${CMAKE_CURRENT_BINARY_DIR}/include/jansson_config.h
${CMAKE_CURRENT_SOURCE_DIR}/src/jansson.h
DESTINATION include)
install (FILES
${CMAKE_CURRENT_BINARY_DIR}/jansson.pc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
# For building Documentation (uses Sphinx)
OPTION (BUILD_DOCS "Build documentation (uses python-sphinx)." ON)
if (BUILD_DOCS)
find_package(Sphinx)
if (NOT SPHINX_FOUND)
message(WARNING "Sphinx not found. Cannot generate documentation!
Set -DBUILD_DOCS=0 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(BUILD_MAN "Create a target for building man pages." ON)
if (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(BUILD_LATEX "Create a target for building latex docs (to create PDF)." OFF)
if (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 (WITHOUT_TESTS "Don't build tests ('make test' to execute tests)" OFF)
if (NOT WITHOUT_TESTS)
OPTION (TEST_WITH_VALGRIND "Enable valgrind tests." OFF)
ENABLE_TESTING()
if (TEST_WITH_VALGRIND)
# TODO: Add FindValgrind.cmake instead of having a hardcoded path.
# enable valgrind
set(CMAKE_MEMORYCHECK_COMMAND valgrind)
set(CMAKE_MEMORYCHECK_COMMAND_OPTIONS
"--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 -Werror)
endif ()
set(api_tests
test_array
test_copy
test_dump
test_dump_callback
test_equal
test_load
test_loadb
test_number
test_object
test_pack
test_simple
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} ${PROJECT_SOURCE_DIR}/test/suites/api)
add_test(${test} ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${test})
if (TEST_WITH_VALGRIND)
add_test(memcheck_${test} ${MEMCHECK_COMMAND}
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${test})
endif ()
endforeach ()
# Test harness for the suites tests.
build_testprog(json_process ${PROJECT_SOURCE_DIR}/test/bin)
set(SUITES encoding-flags valid invalid invalid-unicode)
foreach (SUITE ${SUITES})
file(GLOB TESTDIRS ${jansson_SOURCE_DIR}/test/suites/${SUITE}/*)
foreach (TESTDIR ${TESTDIRS})
if (IS_DIRECTORY ${TESTDIR})
get_filename_component(TNAME ${TESTDIR} NAME)
add_test(${SUITE}__${TNAME}
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/json_process ${TESTDIR})
if ((${SUITE} STREQUAL "valid" OR ${SUITE} STREQUAL "invalid") AND NOT EXISTS ${TESTDIR}/nostrip)
add_test(${SUITE}__${TNAME}__strip
${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/json_process --strip ${TESTDIR})
endif ()
endif ()
endforeach ()
endforeach ()
add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND}
DEPENDS json_process ${api_tests})
endif ()
# 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
# ************************************************
Copyright (c) 2009-2013 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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
EXTRA_DIST = CHANGES LICENSE README.rst win32
SUBDIRS = doc src test
# "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
if GCC
# These flags are gcc specific
export AM_CFLAGS = -Wall -Wextra -Wdeclaration-after-statement
endif
Jansson README
==============
.. image:: https://travis-ci.org/akheron/jansson.png
:alt: Build status
:target: https://travis-ci.org/akheron/jansson
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
- No dependencies on other libraries
- Full Unicode support (UTF-8)
- Extensive test suite
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::
$ ./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
-------------
Prebuilt HTML documentation is available at
http://www.digip.org/jansson/doc/.
The documentation source is in the ``doc/`` subdirectory. To generate
HTML documentation, invoke::
$ make html
Then, point your browser to ``doc/_build/html/index.html``. Sphinx_
1.0 or newer is required to generate the documentation.
.. _Jansson: http://www.digip.org/jansson/
.. _`MIT license`: http://www.opensource.org/licenses/mit-license.php
.. _Sphinx: http://sphinx.pocoo.org/
/*
* Copyright (c) 2010-2013 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
/* If locale.h and localeconv() are available, define to 1,
otherwise to 0. */
#define JSON_HAVE_LOCALECONV 0
#endif
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)
#
# 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
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}" -h
OUTPUT_VARIABLE _Sphinx_VERSION
ERROR_VARIABLE _Sphinx_VERSION
)
elseif (UNIX)
execute_process (
COMMAND "${Sphinx-build_EXECUTABLE}" -h
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" so we cannot just split on "."
if (_Sphinx_VERSION MATCHES "Sphinx v([0-9]+\\.[0-9]+(\\.|b)[0-9]+)")
set (Sphinx_VERSION_STRING "${CMAKE_MATCH_1}")
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()
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)
\ No newline at end of file
/* Reduced down to the defines that are actually used in the code */
/* Define to 1 if you have the <inttypes.h> (and friends) header file. */
#cmakedefine HAVE_INTTYPES_H 1
#cmakedefine HAVE_STDINT_H 1
#cmakedefine HAVE_SYS_TYPES_H 1
/* We must include this here, as in (eg) utf.h it will want to use
the integer type, which in MSVC2010 will be in stdint.h
(there is no inttypes.h in MSVC2010) */
#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
/* Define to 1 if you have the <locale.h> header file. */
#cmakedefine HAVE_LOCALE_H 1
/* Define to 1 if you have the 'setlocale' function. */
#cmakedefine HAVE_SETLOCALE 1
/* Define to the type of a signed integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
#cmakedefine HAVE_INT32_T 1
#ifndef HAVE_INT32_T
# define int32_t @JSON_INT32@
#endif
#cmakedefine HAVE_SSIZE_T 1
#ifndef HAVE_SSIZE_T
# define ssize_t @JSON_SSIZE@
#endif
#cmakedefine HAVE_SNPRINTF 1
#ifndef HAVE_SNPRINTF
# define snprintf @JSON_SNPRINTF@
#endif
#cmakedefine HAVE_VSNPRINTF
/*
* Copyright (c) 2010-2013 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 */
#define JANSSON_USING_CMAKE
/* Note: when using cmake, JSON_INTEGER_IS_LONG_LONG is not defined nor used,
* as we will also check for __int64 etc types.
* (the definition was used in the automake system) */
/* 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 locale.h and localeconv() are available, define to 1, otherwise to 0. */
#define JSON_HAVE_LOCALECONV @JSON_HAVE_LOCALECONV@
#endif
AC_PREREQ([2.60])
AC_INIT([jansson], [2.5], [petri@digip.org])
AM_INIT_AUTOMAKE([1.10 foreign])
AC_CONFIG_SRCDIR([src/value.c])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CC
AC_PROG_LIBTOOL
AM_CONDITIONAL([GCC], [test x$GCC = xyes])
# Checks for libraries.
# Checks for header files.
AC_CHECK_HEADERS([locale.h])
# Checks for typedefs, structures, and compiler characteristics.
AC_TYPE_INT32_T
AC_TYPE_LONG_LONG_INT
AC_C_INLINE
case $ac_cv_c_inline in
yes) json_inline=inline;;
no) json_inline=;;
*) json_inline=$ac_cv_c_inline;;
esac
AC_SUBST([json_inline])
# Checks for library functions.
AC_CHECK_FUNCS([strtoll localeconv])
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])
case "$ac_cv_header_locale_h$ac_cv_func_localeconv" in
yesyes) json_have_localeconv=1;;
*) json_have_localeconv=0;;
esac
AC_SUBST([json_have_localeconv])
AC_CONFIG_FILES([
jansson.pc
Makefile
doc/Makefile
src/Makefile
src/jansson_config.h
test/Makefile
test/bin/Makefile
test/suites/Makefile
test/suites/api/Makefile
])
AC_OUTPUT
EXTRA_DIST = conf.py apiref.rst changes.rst conformance.rst \
gettingstarted.rst github_commits.c index.rst portability.rst \
tutorial.rst upgrading.rst ext/refcounting.py
SPHINXBUILD = sphinx-build
SPHINXOPTS = -d _build/doctrees $(SPHINXOPTS_EXTRA)
html-local:
$(SPHINXBUILD) -b html $(SPHINXOPTS) $(srcdir) _build/html
install-html-local: html
mkdir -p $(DESTDIR)$(htmldir)
cp -r _build/html $(DESTDIR)$(htmldir)
uninstall-local:
rm -rf $(DESTDIR)$(htmldir)
clean-local:
rm -rf _build
rm -f ext/refcounting.pyc
To build the documentation, invoke
make html
Then point your browser to _build/html/index.html.
此差异已折叠。
******************
Changes in Jansson
******************
.. include:: ../CHANGES
# -*- coding: utf-8 -*-
#
# Jansson documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 5 21:47:20 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# 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.insert(0, os.path.abspath('ext'))
# -- 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']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jansson'
copyright = u'2009-2013, 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 = '2.5'
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# 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 = 'c:func'
primary_domain = 'c'
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# 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 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".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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 = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# 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 = ''
# 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 --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('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
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# 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 = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#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)
]
.. _rfc-conformance:
***************
RFC Conformance
***************
JSON is specified in :rfc:`4627`, *"The application/json Media Type
for JavaScript Object Notation (JSON)"*.
Character Encoding
==================
Jansson only supports UTF-8 encoded JSON texts. It does not support or
auto-detect any of the other encodings mentioned in the RFC, namely
UTF-16LE, UTF-16BE, UTF-32LE or UTF-32BE. Pure ASCII is supported, as
it's a subset of UTF-8.
Strings
=======
JSON strings are mapped to C-style null-terminated character arrays,
and UTF-8 encoding is used internally.
All Unicode codepoints U+0000 through U+10FFFF are allowed in string
values. However, U+0000 is not allowed in object keys because of API
restrictions.
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 ``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). With the ``JSON_DECODE_INT_AS_REAL``
decoder flag set all numbers are interpreted as real.
All other JSON numbers are considered integers.
When encoding to JSON, real values are always represented
with a fractional part; e.g., the ``double`` value 3.0 will be
represented in JSON as ``3.0``, not ``3``.
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
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`` 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 ``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
rounded approximate value is silently used. Thus the JSON number
1.000000000000000005 may, depending on platform, result in the
``double`` value 1.0.
Signed zeros
------------
JSON makes no statement about what a number means; however Javascript
(ECMAscript) does state that +0.0 and -0.0 must be treated as being
distinct values, i.e. -0.0 |not-equal| 0.0. Jansson relies on the
underlying floating point library in the C environment in which it is
compiled. Therefore it is platform-dependent whether 0.0 and -0.0 will
be distinct values. Most platforms that use the IEEE 754
floating-point standard will support signed zeros.
Note that this only applies to floating-point; neither JSON, C, or
IEEE support the concept of signed integer zeros.
.. |not-equal| unicode:: U+2260
Types
-----
No support is provided in Jansson for any C numeric types other than
``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.
"""
refcounting
~~~~~~~~~~~
Reference count annotations for C API functions. Has the same
result as the sphinx.ext.refcounting extension but works for all
functions regardless of the signature, and the reference counting
information is written inline with the documentation instead of a
separate file.
Adds a new directive "refcounting". The directive has no content
and one required positional parameter:: "new" or "borrow".
Example:
.. cfunction:: json_t *json_object(void)
.. refcounting:: new
<description of the json_object function>
:copyright: Copyright (c) 2009-2013 Petri Lehtinen <petri@digip.org>
:license: MIT, see LICENSE for details.
"""
from docutils import nodes
class refcounting(nodes.emphasis): pass
def visit(self, node):
self.visit_emphasis(node)
def depart(self, node):
self.depart_emphasis(node)
def html_visit(self, node):
self.body.append(self.starttag(node, 'em', '', CLASS='refcount'))
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')
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))
***************
Getting Started
***************
.. highlight:: c
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::
bunzip2 -c jansson-|release|.tar.bz2 | tar xf -
cd jansson-|release|
The source uses GNU Autotools (autoconf_, automake_, libtool_), so
compiling and installing is extremely simple::
./configure
make
make check
make install
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.)
The command ``make check`` runs the test suite distributed with
Jansson. This step is not strictly necessary, but it may find possible
problems that Jansson has on your platform. If any problems are found,
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, the build system needs to be
bootstrapped. There are many ways to do this, but the easiest one is
to use ``autoreconf``::
autoreconf -vi
This command creates the ``./configure`` script, which can then be
used as described above.
.. _autoconf: http://www.gnu.org/software/autoconf/
.. _automake: http://www.gnu.org/software/automake/
.. _libtool: http://www.gnu.org/software/libtool/
.. _build-cmake:
CMake (various platforms, including Windows)
--------------------------------------------
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.
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.
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 10" ..
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 ..
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 -DBUILD_SHARED=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.
Windows
-------
**This method is deprecated**. Using :ref:`CMake <build-cmake>` is now
preferred.
Jansson can be built with Visual Studio 2010 (and probably newer
versions, too). The solution and project files are in the
``win32/vs2010/`` 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
--------------------------
(This subsection describes how to build the HTML documentation you are
currently reading, so it can be safely skipped.)
Documentation is in the ``doc/`` subdirectory. It's written in
reStructuredText_ with Sphinx_ annotations. To generate the HTML
documentation, invoke::
make html
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
===================================
Jansson involves one C header file, :file:`jansson.h`, so it's enough
to put the line
::
#include <jansson.h>
in the beginning of every source file that uses Jansson.
There's also just one library to link with, ``libjansson``. Compile and
link the program as follows::
cc -o prog prog.c -ljansson
Starting from version 1.2, there's also support for pkg-config_::
cc -o prog prog.c `pkg-config --cflags --libs jansson`
.. _pkg-config: http://pkg-config.freedesktop.org/
/*
* Copyright (c) 2009-2013 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 <stdlib.h>
#include <string.h>
#include <jansson.h>
#include <curl/curl.h>
#define BUFFER_SIZE (256 * 1024) /* 256 KB */
#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)
{
const char *newline = strchr(text, '\n');
if(!newline)
return strlen(text);
else
return (int)(newline - text);
}
struct write_result
{
char *data;
int pos;
};
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)
{
fprintf(stderr, "error: too small buffer\n");
return 0;
}
memcpy(result->data + result->pos, ptr, size * nmemb);
result->pos += size * nmemb;
return size * nmemb;
}
static char *request(const char *url)
{
CURL *curl = NULL;
CURLcode status;
char *data = NULL;
long code;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(!curl)
goto error;
data = malloc(BUFFER_SIZE);
if(!data)
goto error;
struct write_result write_result = {
.data = data,
.pos = 0
};
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);
status = curl_easy_perform(curl);
if(status != 0)
{
fprintf(stderr, "error: unable to request data from %s:\n", url);
fprintf(stderr, "%s\n", curl_easy_strerror(status));
goto error;
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if(code != 200)
{
fprintf(stderr, "error: server responded with code %ld\n", code);
goto error;
}
curl_easy_cleanup(curl);
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);
curl_global_cleanup();
return NULL;
}
int main(int argc, char *argv[])
{
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;
}
snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);
text = request(url);
if(!text)
return 1;
root = json_loads(text, 0, &error);
free(text);
if(!root)
{
fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
return 1;
}
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(root); i++)
{
json_t *data, *sha, *commit, *message;
const char *message_text;
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;
}
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));
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", (int)(i + 1));
json_decref(root);
return 1;
}
message_text = json_string_value(message);
printf("%.8s %.*s\n",
json_string_value(sha),
newline_offset(message_text),
message_text);
}
json_decref(root);
return 0;
}
Jansson Documentation
=====================
This is the documentation for Jansson_ |release|, last updated |today|.
Introduction
------------
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
- No dependencies on other libraries
- Full Unicode support (UTF-8)
- Extensive test suite
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/
Contents
--------
.. toctree::
:maxdepth: 2
gettingstarted
upgrading
tutorial
conformance
portability
apiref
changes
Indices and Tables
==================
* :ref:`genindex`
* :ref:`search`
***********
Portability
***********
Thread safety
-------------
Jansson is thread safe and has no mutable global state. The only
exception are the memory allocation functions, that should be set at
most once, and only on program startup. See
:ref:`apiref-custom-memory-allocation`.
There's no locking performed inside Jansson's code, so a multithreaded
program must perform its own locking if JSON values are shared by
multiple threads. Jansson's reference counting semantics may make this
a bit harder than it seems, as it's possible to have a reference to a
value that's also stored inside a list or object. Modifying the
container (adding or removing values) may trigger concurrent access to
such values, as containers manage the reference count of their
contained values. Bugs involving concurrent incrementing or
decrementing of deference counts may be hard to track.
The encoding functions (:func:`json_dumps()` and friends) track
reference loops by modifying the internal state of objects and arrays.
For this reason, encoding functions must not be run on the same JSON
values in two separate threads at the same time. As already noted
above, be especially careful if two arrays or objects share their
contained values with another array or object.
If you want to make sure that two JSON value hierarchies do not
contain shared values, use :func:`json_deep_copy()` to make copies.
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.
.. _tutorial:
********
Tutorial
********
.. highlight:: c
In this tutorial, we create a program that fetches the latest commits
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
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
gcc), use the following command::
gcc -o github_commits github_commits.c -ljansson -lcurl
libcurl_ is used to communicate over the web, so it is required to
compile the program.
The command line syntax is::
github_commits USER REPOSITORY
``USER`` is a GitHub user ID and ``REPOSITORY`` is the repository
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: https://github.com/
.. _GitHub API: http://developer.github.com/
.. _libcurl: http://curl.haxx.se/
.. _tutorial-github-commits-api:
The GitHub Repo Commits API
===========================
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 array of the following form:
.. code-block:: none
[
{
"sha": "<the commit ID>",
"commit": {
"message": "<the commit message>",
<more fields, not important to this tutorial...>
},
<more fields...>
},
{
"sha": "<the commit ID>",
"commit": {
"message": "<the commit message>",
<more fields...>
},
<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
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 Repo Commits API: http://developer.github.com/v3/repos/commits/
.. _tutorial-the-program:
The Program
===========
First the includes::
#include <string.h>
#include <jansson.h>
Like all the programs using Jansson, we need to include
:file:`jansson.h`.
The following definitions are used to build the GitHub API request
URL::
#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
first newline in the commit message::
/* 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)
{
const char *newline = strchr(text, '\n');
if(!newline)
return strlen(text);
else
return (int)(newline - text);
}
The main function follows. In the beginning, we first declare a bunch
of variables and check the command line parameters::
int main(int argc, char *argv[])
{
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::
snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);
This uses the ``URL_SIZE`` and ``URL_FORMAT`` constants defined above.
Now we're ready to actually request the JSON data over the web::
text = request(url);
if(!text)
return 1;
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 :func:`json_loads()` to decode the JSON text we got
as a response::
root = json_loads(text, 0, &error);
free(text);
if(!root)
{
fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
return 1;
}
We don't need the JSON text anymore, so we can free the ``text``
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.
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`.
We check that the returned value really is an array::
if(!json_is_array(root))
{
fprintf(stderr, "error: root is not an array\n");
json_decref(root);
return 1;
}
Then we proceed to loop over all the commits in the array::
for(i = 0; i < json_array_size(root); i++)
{
json_t *data, *sha, *commit, *message;
const char *message_text;
data = json_array_get(root, i);
if(!json_is_object(data))
{
fprintf(stderr, "error: commit data %d is not an object\n", i + 1);
json_decref(root);
return 1;
}
...
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 ``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 (a hexadecimal SHA-1 sum),
intermediate commit info object, and the commit message from that
object. We also do proper type checks::
sha = json_object_get(data, "sha");
if(!json_is_string(sha))
{
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;
}
message = json_object_get(commit, "message");
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 :func:`json_string_value()`::
message_text = json_string_value(message);
printf("%.8s %.*s\n",
json_string_value(id),
newline_offset(message_text),
message_text);
}
After sending the HTTP request, we decoded the JSON text using
: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 :func:`json_decref()`. This way
Jansson can release the resources::
json_decref(root);
return 0;
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::
$ ./github_commits akheron jansson
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 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
:ref:`apiref` to explore all features of Jansson.
.. 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
:type:`int` to the widest available signed integer type, i.e.
:type:`long long` or :type:`long`, depending on whether
:type:`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. :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
:type:`unsigned int` and :type:`unsigned long` have been replaced
with :type:`size_t`. This includes flags, container sizes, etc.
This should not require source code changes, as both
:type:`unsigned int` and :type:`unsigned long` are usually
compatible with :type:`size_t`.
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=${prefix}/include
Name: Jansson
Description: Library for encoding, decoding and manipulating JSON data
Version: @VERSION@
Libs: -L${libdir} -ljansson
Cflags: -I${includedir}
#!/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"
EXTRA_DIST = jansson.def
include_HEADERS = jansson.h jansson_config.h
lib_LTLIBRARIES = libjansson.la
libjansson_la_SOURCES = \
dump.c \
error.c \
hashtable.c \
hashtable.h \
jansson_private.h \
load.c \
memory.c \
pack_unpack.c \
strbuffer.c \
strbuffer.h \
strconv.c \
utf.c \
utf.h \
value.c
libjansson_la_LDFLAGS = \
-no-undefined \
-export-symbols-regex '^json_' \
-version-info 9:0:5
此差异已折叠。
#include <string.h>
#include "jansson_private.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)
strcpy(error->source, source);
else {
size_t extra = length - JSON_ERROR_SOURCE_LENGTH + 4;
strcpy(error->source, "...");
strcpy(error->source + 3, source + extra);
}
}
void jsonp_error_set(json_error_t *error, int line, int column,
size_t position, const char *msg, ...)
{
va_list ap;
va_start(ap, msg);
jsonp_error_vset(error, line, column, position, msg, ap);
va_end(ap);
}
void jsonp_error_vset(json_error_t *error, int line, int column,
size_t position, 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 = position;
vsnprintf(error->text, JSON_ERROR_TEXT_LENGTH, msg, ap);
error->text[JSON_ERROR_TEXT_LENGTH - 1] = '\0';
}
此差异已折叠。
此差异已折叠。
EXPORTS
json_delete
json_true
json_false
json_null
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_set_new
json_object_set_new_nocheck
json_object_del
json_object_clear
json_object_update
json_object_update_existing
json_object_update_missing
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_object_key_to_iter
json_dumps
json_dumpf
json_dump_file
json_dump_callback
json_loads
json_loadb
json_loadf
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
此差异已折叠。
/*
* Copyright (c) 2010-2013 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 locale.h and localeconv() are available, define to 1,
otherwise to 0. */
#define JSON_HAVE_LOCALECONV @json_have_localeconv@
#endif
此差异已折叠。
此差异已折叠。
/*
* Copyright (c) 2009-2013 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;
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
SUBDIRS = api
EXTRA_DIST = invalid invalid-unicode valid
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册