Import libcbor at 'contrib/libcbor/'

git-subtree-dir: contrib/libcbor
git-subtree-mainline: 293663f4da
git-subtree-split: 5b2defbd2a
(cherry picked from commit 10ff414c14)
This commit is contained in:
Ed Maste 2021-10-06 20:26:10 -04:00
parent bc49561db7
commit f55904f2f6
151 changed files with 16202 additions and 0 deletions

View File

@ -0,0 +1,151 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
CanonicalDelimiter: ''
BasedOnStyle: google
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseTab: Never
...

View File

@ -0,0 +1,23 @@
name: CIFuzz
on: [pull_request]
jobs:
Fuzzing:
runs-on: ubuntu-latest
steps:
- name: Build Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
with:
oss-fuzz-project-name: 'libcbor'
dry-run: false
- name: Run Fuzzers
uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
with:
oss-fuzz-project-name: 'libcbor'
fuzz-seconds: 600
dry-run: false
- name: Upload Crash
uses: actions/upload-artifact@v1
if: failure()
with:
name: artifacts
path: ./out/artifacts

8
contrib/libcbor/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
build
*~
nbproject
.idea
doxygen_docs
*/*.out
cmake-build-debug
venv

View File

@ -0,0 +1,66 @@
language: c
matrix:
include:
- arch: amd64
os: linux
dist: bionic
compiler: clang
env: TRAVIS_ARCH="amd64"
- arch: amd64
os: linux
dist: bionic
compiler: gcc
env: TRAVIS_ARCH="amd64"
- arch: arm64
os: linux
dist: bionic
compiler: gcc
env: TRAVIS_ARCH="arm64"
- arch: ppc64le
os: linux
dist: bionic
compiler: gcc
env: TRAVIS_ARCH="ppc64le"
- arch: amd64
os: osx
compiler: gcc
env: TRAVIS_ARCH="amd64"
before_install:
- pushd ${HOME}
- git clone https://gitlab.com/cmocka/cmocka.git
- cd cmocka && mkdir build && cd build
- cmake .. && make -j2 && sudo make install
- cd .. && popd
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get update -qq; sudo apt-get install -y clang-format-8 cppcheck; fi
- if [ "$TRAVIS_OS_NAME" = "linux" -a "$CC" = "gcc" -a "$TRAVIS_ARCH" = "amd64" ]; then pip install --user codecov; export CFLAGS="-coverage"; fi
script:
- >
if [ "$TRAVIS_OS_NAME" = "linux" ]; then
cppcheck . --error-exitcode=1
# Fail if re-formatting creates diffs (implying bad formatting)
/clang-format.sh --verbose
git diff-index --quiet HEAD
fi;
- mkdir build && cd build
- cmake -DWITH_TESTS=ON
-DCBOR_CUSTOM_ALLOC=ON
-DCMAKE_BUILD_TYPE=Debug
-DSANITIZE=OFF
..
- make VERBOSE=1
- ctest -VV
- ctest -T memcheck | tee memcheck.out
- >
if grep -q 'Memory Leak\|IPW\|Uninitialized Memory Conditional\|Uninitialized Memory Read' memcheck.out; then
exit 1
fi;
after_success:
- if [ "$TRAVIS_OS_NAME" = "linux" -a "$CC" = "gcc" -a "$TRAVIS_ARCH" = "amd64" ]; then codecov; fi
notifications:
email: false

View File

@ -0,0 +1,109 @@
Next
---------------------
0.8.0 (2020-09-20)
---------------------
- BUILD BREAKING: Use BUILD_SHARED_LIBS to determine how to build libraries (fixed Windows linkage) [[#148]](https://github.com/PJK/libcbor/pull/148) (by [intelligide@](https://github.com/intelligide))
- BREAKING: Fix `cbor_tag_item` not increasing the reference count on the tagged item reference it returns [[Fixes #109](https://github.com/PJK/libcbor/issues/109)] (discovered bt [JohnGilmour](https://github.com/JohnGilmour))
- If you have previously relied on the broken behavior, you can use `cbor_move` to emulate as long as the returned handle is an "rvalue"
- BREAKING: [`CBOR_DECODER_EBUFFER` removed from `cbor_decoder_status`](https://github.com/PJK/libcbor/pull/156)
- `cbor_stream_decode` will set `CBOR_DECODER_NEDATA` instead if the input buffer is empty
- [Fix `cbor_stream_decode`](https://github.com/PJK/libcbor/pull/156) to set `cbor_decoder_result.required` to the minimum number of input bytes necessary to receive the next callback (as long as at least one byte was passed) (discovered by [woefulwabbit](https://github.com/woefulwabbit))
- Fixed several minor manpage issues [[#159]](https://github.com/PJK/libcbor/pull/159) (discovered by [kloczek@](https://github.com/kloczek))
0.7.0 (2020-04-25)
---------------------
- Fix bad encoding of NaN half-floats [[Fixes #53]](https://github.com/PJK/libcbor/issues/53) (discovered by [BSipos-RKF](https://github.com/BSipos-RKF))
- **Warning**: Previous versions encoded NaNs as `0xf9e700` instead of `0xf97e00`; if you rely on the broken behavior, this will be a breaking change
- Fix potentially bad encoding of negative half-float with exponent < -14 [[Fixes #112]](https://github.com/PJK/libcbor/issues/112) (discovered by [yami36](https://github.com/yami36))
- BREAKING: Improved bool support [[Fixes #63]](https://github.com/PJK/libcbor/issues/63)
- Rename `cbor_ctrl_is_bool` to `cbor_get_bool` and fix the behavior
- Add `cbor_set_bool`
- Fix memory_allocation_test breaking the build without CBOR_CUSTOM_ALLOC [[Fixes #128]](https://github.com/PJK/libcbor/issues/128) (by [panlinux](https://github.com/panlinux))
- [Fix a potential build issue where cJSON includes may be misconfigured](https://github.com/PJK/libcbor/pull/132)
- Breaking: [Add a limit on the size of the decoding context stack](https://github.com/PJK/libcbor/pull/138) (by [James-ZHANG](https://github.com/James-ZHANG))
- If your usecase requires parsing very deeply nested structures, you might need to increase the default 2k limit via `CBOR_MAX_STACK_SIZE`
- Enable LTO/IPO based on [CheckIPOSupported](https://cmake.org/cmake/help/latest/module/CheckIPOSupported.html#module:CheckIPOSupported) [[#143]](https://github.com/PJK/libcbor/pull/143) (by [xanderlent](https://github.com/xanderlent))
- If you rely on LTO being enabled and use CMake version older than 3.9, you will need to re-enable it manually or upgrade your CMake
0.6.1 (2020-03-26)
---------------------
- [Fix bad shared library version number](https://github.com/PJK/libcbor/pull/131)
- **Warning**: Shared library built from the 0.6.0 release is erroneously marked as version "0.6.0", which makes it incompatible with future releases *including the v0.6.X line* even though they may be compatible API/ABI-wise. Refer to the documentation for the new SO versioning scheme.
0.6.0 (2020-03-15)
---------------------
- Correctly set .so version [[Fixes #52]](https://github.com/PJK/libcbor/issues/52).
- **Warning**: All previous releases will be identified as 0.0 by the linker.
- Fix & prevent heap overflow error in example code [[#74]](https://github.com/PJK/libcbor/pull/74) [[#76]](https://github.com/PJK/libcbor/pull/76) (by @nevun)
- Correctly set OSX dynamic library version [[Fixes #75]](https://github.com/PJK/libcbor/issues/75)
- [Fix misplaced 0xFF bytes in maps possibly causing memory corruption](https://github.com/PJK/libcbor/pull/82)
- BREAKING: Fix handling & cleanup of failed memory allocation in constructor
and builder helper functions [[Fixes #84]](https://github.com/PJK/libcbor/issues/84)
- All cbor_new_* and cbor_build_* functions will now explicitly return NULL when memory allocation fails
- It is up to the client to handle such cases
- Globally enforced code style [[Fixes #83]](https://github.com/PJK/libcbor/issues/83)
- Fix issue possible memory corruption bug on repeated
cbor_(byte)string_add_chunk calls with intermittently failing realloc calls
- Fix possibly misaligned reads and writes when endian.h is uses or when
running on a big-endian machine [[Fixes #99](https://github.com/PJK/libcbor/issues/99), [#100](https://github.com/PJK/libcbor/issues/100)]
- [Improved CI setup with Travis-native arm64 support](https://github.com/PJK/libcbor/pull/116)
- [Docs migrated to Sphinx 2.4 and Python3](https://github.com/PJK/libcbor/pull/117)
0.5.0 (2017-02-06)
---------------------
- Remove cmocka from the subtree (always rely on system or user-provided version)
- Windows CI
- Only build tests if explicitly enabled (`-DWITH_TESTS=ON`)
- Fixed static header declarations (by cedric-d)
- Improved documentation (by Michael Richardson)
- Improved `examples/readfile.c`
- Reworked (re)allocation to handle huge inputs and overflows in size_t [[Fixes #16]](https://github.com/PJK/libcbor/issues/16)
- Improvements to C++ linkage (corrected `cbor_empty_callbacks`, fixed `restrict` pointers) (by Dennis Bijwaard)
- Fixed Linux installation directory depending on architecture [[Fixes #34]](https://github.com/PJK/libcbor/issues/34) (by jvymazal)
- Improved 32-bit support [[Fixes #35]](https://github.com/PJK/libcbor/issues/35)
- Fixed MSVC compatibility [[Fixes #31]](https://github.com/PJK/libcbor/issues/31)
- Fixed and improved half-float encoding [[Fixes #5](https://github.com/PJK/libcbor/issues/5), [#11](https://github.com/PJK/libcbor/issues/11)]
0.4.0 (2015-12-25)
---------------------
Breaks build & header compatibility due to:
- Improved build configuration and feature check macros
- Endianess configuration fixes (by Erwin Kroon and David Grigsby)
- pkg-config compatibility (by Vincent Bernat)
- enable use of versioned SONAME (by Vincent Bernat)
- better fuzzer (wasn't random until now, ooops)
0.3.1 (2015-05-21)
---------------------
- documentation and comments improvements, mostly for the API reference
0.3.0 (2015-05-21)
---------------------
- Fixes, polishing, niceties across the code base
- Updated examples
- `cbor_copy`
- `cbor_build_negint8`, 16, 32, 64, matching asserts
- `cbor_build_stringn`
- `cbor_build_tag`
- `cbor_build_float2`, ...
0.2.1 (2015-05-17)
---------------------
- C99 support
0.2.0 (2015-05-17)
---------------------
- `cbor_ctrl_bool` -> `cbor_ctrl_is_bool`
- Added `cbor_array_allocated` & map equivalent
- Overhauled endianess conversion - ARM now works as expected
- 'sort.c' example added
- Significantly improved and doxyfied documentation
0.1.0 (2015-05-06)
---------------------
The initial release, yay!

View File

@ -0,0 +1,159 @@
cmake_minimum_required(VERSION 2.8)
project(libcbor)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMakeModules/")
include(CTest)
SET(CBOR_VERSION_MAJOR "0")
SET(CBOR_VERSION_MINOR "8")
SET(CBOR_VERSION_PATCH "0")
SET(CBOR_VERSION ${CBOR_VERSION_MAJOR}.${CBOR_VERSION_MINOR}.${CBOR_VERSION_PATCH})
set(CMAKE_SKIP_INSTALL_ALL_DEPENDENCY true)
include(CheckIncludeFiles)
include(TestBigEndian)
test_big_endian(BIG_ENDIAN)
if(BIG_ENDIAN)
add_definitions(-DIS_BIG_ENDIAN)
endif()
option(CBOR_CUSTOM_ALLOC "Custom, dynamically defined allocator support" OFF)
option(CBOR_PRETTY_PRINTER "Include a pretty-printing routine" ON)
set(CBOR_BUFFER_GROWTH "2" CACHE STRING "Factor for buffer growth & shrinking")
set(CBOR_MAX_STACK_SIZE "2048" CACHE STRING "maximum size for decoding context stack")
option(WITH_TESTS "[TEST] Build unit tests (requires CMocka)" OFF)
if(WITH_TESTS)
add_definitions(-DWITH_TESTS)
endif(WITH_TESTS)
option(WITH_EXAMPLES "Build examples" ON)
option(HUGE_FUZZ "[TEST] Fuzz through 8GB of data in the test. Do not use with memory instrumentation!" OFF)
if(HUGE_FUZZ)
add_definitions(-DHUGE_FUZZ)
endif(HUGE_FUZZ)
option(SANE_MALLOC "[TEST] Assume that malloc will not allocate multi-GB blocks. Tests only, platform specific" OFF)
if(SANE_MALLOC)
add_definitions(-DSANE_MALLOC)
endif(SANE_MALLOC)
option(PRINT_FUZZ "[TEST] Print the fuzzer input" OFF)
if(PRINT_FUZZ)
add_definitions(-DPRINT_FUZZ)
endif(PRINT_FUZZ)
option(SANITIZE "Enable ASan & a few compatible sanitizers in Debug mode" ON)
set(CPACK_GENERATOR "DEB" "TGZ" "RPM")
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64")
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Pavel Kalvoda")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6")
set(CPACK_PACKAGE_VERSION_MAJOR ${CBOR_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${CBOR_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${CBOR_VERSION_PATCH})
include(CPack)
if(MINGW)
# https://github.com/PJK/libcbor/issues/13
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99")
elseif(NOT MSVC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -pedantic")
endif()
if(MSVC)
# This just doesn't work right -- https://msdn.microsoft.com/en-us/library/5ft82fed.aspx
set(CBOR_RESTRICT_SPECIFIER "")
else()
set(CBOR_RESTRICT_SPECIFIER "restrict")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0 -Wall -g -ggdb -DDEBUG=true")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3 -Wall -DNDEBUG")
if(SANITIZE)
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} \
-fsanitize=undefined -fsanitize=address \
-fsanitize=bounds -fsanitize=alignment")
endif()
endif()
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "-g")
include(CheckTypeSize)
check_type_size("size_t" SIZEOF_SIZE_T)
if(SIZEOF_SIZE_T LESS 8)
message(WARNING "Your size_t is less than 8 bytes. Long items with 64b length specifiers might not work as expected. Make sure to run the tests!")
else()
add_definitions(-DEIGHT_BYTE_SIZE_T)
endif()
enable_testing()
set(CTEST_MEMORYCHECK_COMMAND "/usr/bin/valgrind")
set(MEMORYCHECK_COMMAND_OPTIONS "--tool=memcheck --track-origins=yes --leak-check=full --error-exitcode=1")
add_custom_target(coverage
COMMAND ctest
COMMAND lcov --capture --directory . --output-file coverage.info
COMMAND genhtml coverage.info --highlight --legend --output-directory coverage_html
COMMAND echo "Coverage report ready: file://${CMAKE_CURRENT_BINARY_DIR}/coverage_html/index.html")
include_directories(src)
option(COVERAGE "Enable code coverage instrumentation" OFF)
if (COVERAGE)
message("Configuring code coverage instrumentation")
if(NOT CMAKE_C_COMPILER MATCHES "gcc")
message(WARNING "Gcov instrumentation only works with GCC")
endif()
# https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -fprofile-arcs -ftest-coverage --coverage")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -g -fprofile-arcs -ftest-coverage --coverage")
endif (COVERAGE)
# We want to generate configuration.h from the template and make it so that it is accessible using the same
# path during both library build and installed header use, without littering the source dir.
# Using cbor/configuration.h in the build dir works b/c headers will be installed to <prefix>/cbor
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/cbor/configuration.h.in ${PROJECT_BINARY_DIR}/cbor/configuration.h)
install(FILES ${PROJECT_BINARY_DIR}/cbor/configuration.h DESTINATION include/cbor)
# Make the header visible at compile time
include_directories(${PROJECT_BINARY_DIR})
# CMake >= 3.9.0 enables LTO for GCC and Clang with INTERPROCEDURAL_OPTIMIZATION
# Policy CMP0069 enables this behavior when we set the minimum CMake version < 3.9.0
# Checking for LTO support before setting INTERPROCEDURAL_OPTIMIZATION is mandatory with CMP0069 set to NEW.
set(use_lto FALSE)
if(${CMAKE_VERSION} VERSION_GREATER "3.9.0" OR ${CMAKE_VERSION} VERSION_EQUAL "3.9.0")
cmake_policy(SET CMP0069 NEW)
# Require LTO support to build libcbor with newer CMake versions
include(CheckIPOSupported)
check_ipo_supported(RESULT use_lto)
endif(${CMAKE_VERSION} VERSION_GREATER "3.9.0" OR ${CMAKE_VERSION} VERSION_EQUAL "3.9.0")
if(use_lto)
message(STATUS "LTO is enabled")
else()
message(STATUS "LTO is not enabled")
endif(use_lto)
subdirs(src)
if(use_lto)
set_property(DIRECTORY src PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif(use_lto)
if (WITH_TESTS)
subdirs(test)
if(use_lto)
set_property(DIRECTORY test PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif(use_lto)
endif (WITH_TESTS)
if (WITH_EXAMPLES)
subdirs(examples)
if(use_lto)
set_property(DIRECTORY examples PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif(use_lto)
endif (WITH_EXAMPLES)

View File

@ -0,0 +1,9 @@
include (LibFindMacros)
find_path(CJSON_INCLUDE_DIR NAMES cjson/cJSON.h)
find_library(CJSON_LIBRARY NAMES cjson)
set(CJSON_PROCESS_INCLUDES CJSON_INCLUDE_DIR)
set(CJSON_PROCESS_LIBS CJSON_LIBRARY)
libfind_process(CJSON)

View File

@ -0,0 +1,49 @@
# - Try to find CMocka
# Once done this will define
#
# CMOCKA_ROOT_DIR - Set this variable to the root installation of CMocka
#
# Read-Only variables:
# CMOCKA_FOUND - system has CMocka
# CMOCKA_INCLUDE_DIR - the CMocka include directory
# CMOCKA_LIBRARIES - Link these to use CMocka
# CMOCKA_DEFINITIONS - Compiler switches required for using CMocka
#
#=============================================================================
# Copyright (c) 2011-2012 Andreas Schneider <asn@cryptomilk.org>
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
#
find_path(CMOCKA_INCLUDE_DIR
NAMES
cmocka.h
PATHS
${CMOCKA_ROOT_DIR}/include
)
find_library(CMOCKA_LIBRARY
NAMES
cmocka cmocka_shared
PATHS
${CMOCKA_ROOT_DIR}/include
)
if (CMOCKA_LIBRARY)
set(CMOCKA_LIBRARIES
${CMOCKA_LIBRARIES}
${CMOCKA_LIBRARY}
)
endif (CMOCKA_LIBRARY)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(CMocka DEFAULT_MSG CMOCKA_LIBRARIES CMOCKA_INCLUDE_DIR)
# show the CMOCKA_INCLUDE_DIR and CMOCKA_LIBRARIES variables only in the advanced view
mark_as_advanced(CMOCKA_INCLUDE_DIR CMOCKA_LIBRARIES)

View File

@ -0,0 +1,120 @@
# Fetched from https://github.com/JonathanSalwan/Triton/blob/master/CMakeModules/LibFindMacros.cmake
#
# Copyright:
#
# * Jonathan Salwan (Quarkslab)
# * Pierrick Brunet (Quarkslab)
# * Romain Thomas (Quarkslab)
# * Florent Saudel (Bordeaux University)
#
# 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
#
# https://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.
# Works the same as find_package, but forwards the "REQUIRED" and "QUIET" arguments
# used for the current package. For this to work, the first parameter must be the
# prefix of the current package, then the prefix of the new package etc, which are
# passed to find_package.
macro (libfind_package PREFIX)
set (LIBFIND_PACKAGE_ARGS ${ARGN})
if (${PREFIX}_FIND_QUIETLY)
set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} QUIET)
endif (${PREFIX}_FIND_QUIETLY)
if (${PREFIX}_FIND_REQUIRED)
set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} REQUIRED)
endif (${PREFIX}_FIND_REQUIRED)
find_package(${LIBFIND_PACKAGE_ARGS})
endmacro (libfind_package)
# CMake developers made the UsePkgConfig system deprecated in the same release (2.6)
# where they added pkg_check_modules. Consequently I need to support both in my scripts
# to avoid those deprecated warnings. Here's a helper that does just that.
# Works identically to pkg_check_modules, except that no checks are needed prior to use.
macro (libfind_pkg_check_modules PREFIX PKGNAME)
if (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
include(UsePkgConfig)
pkgconfig(${PKGNAME} ${PREFIX}_INCLUDE_DIRS ${PREFIX}_LIBRARY_DIRS ${PREFIX}_LDFLAGS ${PREFIX}_CFLAGS)
else (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
find_package(PkgConfig)
if (PKG_CONFIG_FOUND)
pkg_check_modules(${PREFIX} ${PKGNAME})
endif (PKG_CONFIG_FOUND)
endif (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
endmacro (libfind_pkg_check_modules)
# Do the final processing once the paths have been detected.
# If include dirs are needed, ${PREFIX}_PROCESS_INCLUDES should be set to contain
# all the variables, each of which contain one include directory.
# Ditto for ${PREFIX}_PROCESS_LIBS and library files.
# Will set ${PREFIX}_FOUND, ${PREFIX}_INCLUDE_DIRS and ${PREFIX}_LIBRARIES.
# Also handles errors in case library detection was required, etc.
macro (libfind_process PREFIX)
# Skip processing if already processed during this run
if (NOT ${PREFIX}_FOUND)
# Start with the assumption that the library was found
set (${PREFIX}_FOUND TRUE)
# Process all includes and set _FOUND to false if any are missing
foreach (i ${${PREFIX}_PROCESS_INCLUDES})
if (${i})
set (${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIRS} ${${i}})
mark_as_advanced(${i})
else (${i})
set (${PREFIX}_FOUND FALSE)
endif (${i})
endforeach (i)
# Process all libraries and set _FOUND to false if any are missing
foreach (i ${${PREFIX}_PROCESS_LIBS})
if (${i})
set (${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARIES} ${${i}})
mark_as_advanced(${i})
else (${i})
set (${PREFIX}_FOUND FALSE)
endif (${i})
endforeach (i)
# Print message and/or exit on fatal error
if (${PREFIX}_FOUND)
if (NOT ${PREFIX}_FIND_QUIETLY)
message (STATUS "Found ${PREFIX} include directory: ${${PREFIX}_INCLUDE_DIR}")
message (STATUS "Found ${PREFIX} library: ${${PREFIX}_LIBRARY}")
endif (NOT ${PREFIX}_FIND_QUIETLY)
else (${PREFIX}_FOUND)
if (${PREFIX}_FIND_REQUIRED)
foreach (i ${${PREFIX}_PROCESS_INCLUDES} ${${PREFIX}_PROCESS_LIBS})
message("${i}=${${i}}")
endforeach (i)
message (FATAL_ERROR "Required library ${PREFIX} NOT FOUND.\nInstall the library (dev version) and try again. If the library is already installed, use ccmake to set the missing variables manually.")
endif (${PREFIX}_FIND_REQUIRED)
endif (${PREFIX}_FOUND)
endif (NOT ${PREFIX}_FOUND)
endmacro (libfind_process)
macro(libfind_library PREFIX basename)
set(TMP "")
if(MSVC80)
set(TMP -vc80)
endif(MSVC80)
if(MSVC90)
set(TMP -vc90)
endif(MSVC90)
set(${PREFIX}_LIBNAMES ${basename}${TMP})
if(${ARGC} GREATER 2)
set(${PREFIX}_LIBNAMES ${basename}${TMP}-${ARGV2})
string(REGEX REPLACE "\\." "_" TMP ${${PREFIX}_LIBNAMES})
set(${PREFIX}_LIBNAMES ${${PREFIX}_LIBNAMES} ${TMP})
endif(${ARGC} GREATER 2)
find_library(${PREFIX}_LIBRARY
NAMES ${${PREFIX}_LIBNAMES}
PATHS ${${PREFIX}_PKGCONF_LIBRARY_DIRS}
)
endmacro(libfind_library)

2417
contrib/libcbor/Doxyfile Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2014-2017 Pavel Kalvoda
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.

122
contrib/libcbor/README.md Normal file
View File

@ -0,0 +1,122 @@
# [libcbor](https://github.com/PJK/libcbor)
[![Build Status](https://travis-ci.org/PJK/libcbor.svg?branch=master)](https://travis-ci.org/PJK/libcbor)
[![Build status](https://ci.appveyor.com/api/projects/status/8kkmvmefelsxp5u2?svg=true)](https://ci.appveyor.com/project/PJK/libcbor)
[![Documentation Status](https://readthedocs.org/projects/libcbor/badge/?version=latest)](https://readthedocs.org/projects/libcbor/?badge=latest)
[![latest packaged version(s)](https://repology.org/badge/latest-versions/libcbor.svg)](https://repology.org/project/libcbor/versions)
[![codecov](https://codecov.io/gh/PJK/libcbor/branch/master/graph/badge.svg)](https://codecov.io/gh/PJK/libcbor)
**libcbor** is a C library for parsing and generating [CBOR](http://tools.ietf.org/html/rfc7049), the general-purpose schema-less binary data format.
## Main features
- Complete RFC conformance
- Robust C99 implementation
- Layered architecture offers both control and convenience
- Flexible memory management
- No shared global state - threading friendly
- Proper handling of UTF-8
- Full support for streams & incremental processing
- Extensive documentation and test suite
- No runtime dependencies, small footprint
## Getting started
### Compile from source
```bash
git clone https://github.com/PJK/libcbor
cmake -DCMAKE_BUILD_TYPE=Release -DCBOR_CUSTOM_ALLOC=ON libcbor
make
make install
```
### Homebrew
```bash
brew install libcbor
```
### Ubuntu 18.04 and above
```bash
sudo add-apt-repository universe
sudo apt-get install libcbor-dev
```
### Fedora & RPM friends
```bash
yum install libcbor-devel
```
### Others
<details>
<summary>Packaged libcbor is available from 15+ major repositories. Click here for more detail</summary>
[![Packaging status](https://repology.org/badge/vertical-allrepos/libcbor.svg)](https://repology.org/project/libcbor/versions)
</details>
## Usage example
```c
#include <cbor.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
/* Preallocate the map structure */
cbor_item_t * root = cbor_new_definite_map(2);
/* Add the content */
cbor_map_add(root, (struct cbor_pair) {
.key = cbor_move(cbor_build_string("Is CBOR awesome?")),
.value = cbor_move(cbor_build_bool(true))
});
cbor_map_add(root, (struct cbor_pair) {
.key = cbor_move(cbor_build_uint8(42)),
.value = cbor_move(cbor_build_string("Is the answer"))
});
/* Output: `length` bytes of data in the `buffer` */
unsigned char * buffer;
size_t buffer_size,
length = cbor_serialize_alloc(root, &buffer, &buffer_size);
fwrite(buffer, 1, length, stdout);
free(buffer);
fflush(stdout);
cbor_decref(&root);
}
```
## Documentation
Get the latest documentation at [libcbor.readthedocs.org](http://libcbor.readthedocs.org/)
## Contributions
All bug reports and contributions are welcome. Please see https://github.com/PJK/libcbor for more info.
Kudos to all the [contributors](https://github.com/PJK/libcbor/graphs/contributors)!
## License
The MIT License (MIT)
Copyright (c) Pavel Kalvoda, 2014-2020
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.

View File

@ -0,0 +1,27 @@
image: Visual Studio 2015
version: '{build}'
branches:
except:
- gh-pages
platform: x64
environment:
matrix:
- CMAKE_GENERATOR: "Visual Studio 14 2015 Win64"
# Via https://github.com/apitrace/apitrace/blob/master/appveyor.yml
before_build:
- cmake -H. -Bbuild -G "%CMAKE_GENERATOR%"
- C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\x86_amd64\CL.exe /?
build_script:
- if "%APPVEYOR_REPO_TAG%"=="true" (set CONFIGURATION=RelWithDebInfo) else (set CONFIGURATION=Debug)
- cmake --build build --config "%CONFIGURATION%"
# TODO enable CMocka tests, maybe package the binaries
# TODO add MinGW
# TODO add older MSVC

17
contrib/libcbor/clang-format.sh Executable file
View File

@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Usage: ./clang-format.sh <extra arguments>
DIRS="src test examples"
SOURCES=$(find ${DIRS} -name "*.c")
SOURCES+=" $(find ${DIRS} -name "*.h")"
SOURCES+=" $(find ${DIRS} -name "*.cpp")"
# TravisCI workaround to use new clang-format while avoiding painful aliasing
# into the subshell
if which clang-format-8; then
clang-format-8 $@ -style=file -i ${SOURCES}
else
clang-format $@ -style=file -i ${SOURCES}
fi

View File

@ -0,0 +1,2 @@
ignore:
- "test/stream_expectations.c" # Function pointers are not resolved correctly

View File

@ -0,0 +1,180 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/libcbor.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/libcbor.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/libcbor"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/libcbor"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
livehtml: html
sphinx-autobuild -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html

View File

@ -0,0 +1,37 @@
This is the development reference of [libcbor](https://github.com/PJK/libcbor). Looking for the [user documentation](https://libcbor.readthedocs.io/)?
# Where to start
A couple of pointers for you to start with: `0x00000000`, `0xDEADBEEF`.
If you just want to peek under the hood, have a look at:
- \ref src/cbor/common.h
- \ref src/cbor/encoding.h
- \ref src/cbor.h
If you want to implement your own decoder or see how the default one is made:
- \ref src/cbor/internal/builder_callbacks.h
- \ref src/cbor/internal/stack.h
For details on encoding and packing (could be useful when porting to exotic platforms):
- \ref src/cbor/internal/encoders.h
- \ref src/cbor/internal/loaders.h
Streaming driver:
- \ref src/cbor/streaming.h
Manipulation routines for particular types:
- \ref src/cbor/ints.h
- \ref src/cbor/bytestrings.h
- \ref src/cbor/strings.h
- \ref src/cbor/arrays.h
- \ref src/cbor/maps.h
- \ref src/cbor/tags.h
- \ref src/cbor/floats_ctrls.h
# How to contribute
Please refer to [the repository](https://github.com/PJK/libcbor)

View File

@ -0,0 +1,242 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\libcbor.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\libcbor.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end

View File

@ -0,0 +1,39 @@
API
=======
The data API is centered around :type:`cbor_item_t`, a generic handle for any CBOR item. There are functions to
- create items,
- set items' data,
- parse serialized data into items,
- manage, move, and links item together.
The single most important thing to keep in mind is: :type:`cbor_item_t` **is an opaque type and should only be manipulated using the appropriate functions!** Think of it as an object.
The *libcbor* API closely follows the semantics outlined by `CBOR standard <http://tools.ietf.org/html/rfc7049>`_. This part of the documentation provides a short overview of the CBOR constructs, as well as a general introduction to the *libcbor* API. Remaining reference can be found in the following files structured by data types.
The API is designed to allow both very tight control & flexibility and general convenience with sane defaults. [#]_ For example, client with very specific requirements (constrained environment, custom application protocol built on top of CBOR, etc.) may choose to take full control (and responsibility) of memory and data structures management by interacting directly with the decoder. Other clients might want to take control of specific aspects (streamed collections, hash maps storage), but leave other responsibilities to *libcbor*. More general clients might prefer to be abstracted away from all aforementioned details and only be presented complete data structures.
*libcbor* provides
- stateless encoders and decoders
- encoding and decoding *drivers*, routines that coordinate encoding and decoding of complex structures
- data structures to represent and transform CBOR structures
- routines for building and manipulating these structures
- utilities for inspection and debugging
.. toctree::
api/item_types
api/item_reference_counting
api/decoding
api/encoding
api/type_0_1
api/type_2
api/type_3
api/type_4
api/type_5
api/type_6
api/type_7
.. [#] http://softwareengineering.vazexqi.com/files/pattern.html

View File

@ -0,0 +1,53 @@
Decoding
=============================
The following diagram illustrates the relationship among different parts of libcbor from the decoding standpoint.
::
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ │
│ Client application │
│ │
│ ┌────────────────────────────────────────────┘
│ │ ↕
│ │ ┌──────────────────────────────────────────┐
│ │ │ │
│ │ │ Manipulation routines │
│ │ │ │
│ ┌─────────────────────────────────────┘ └──────────────────────────────────────────┘
│ │ ↑ ↑ ↑ ↑
│ │ │ │ ┌─────────────╫──────────┬───────────────────┴─┐
│ │ │ CDS │ ║ │ │
│ │ │ │ PDS ║ PDS PDS
│ │ ↓ ↓ ↓ ↓ ↓ ↓
│ │ ┌─────────────────┐ ┌────────────────────┐ ┌────────────────────────────┐
│ │ │ │ │ │ │ │
│ │ │ Custom driver │ ↔ │ Streaming driver │ ↔ │ Default driver │ ↔ CD
│ │ │ │ │ │ │ │
└───────────┘ └─────────────────┘ └────────────────────┘ └────────────────────────────┘
↕ ↕ ↕ ↕
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ │
│ Stateless event─driven decoder │
│ │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
(PSD = Provided Data Structures, CDS = Custom Data Structures)
This section will deal with the API that is labeled as the "Default driver" in the diagram. That is, routines that
decode complete libcbor data items
.. doxygenfunction:: cbor_load
Associated data structures
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenenum:: cbor_error_code
.. doxygenstruct:: cbor_load_result
:members:
.. doxygenstruct:: cbor_error
:members:

View File

@ -0,0 +1,23 @@
Encoding
=============================
The easiest way to encode data items is using the :func:`cbor_serialize` or :func:`cbor_serialize_alloc` functions:
.. doxygenfunction:: cbor_serialize
.. doxygenfunction:: cbor_serialize_alloc
Type-specific serializers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In case you know the type of the item you want to serialize beforehand, you can use one
of the type-specific serializers.
.. note:: Unless compiled in debug mode, these do not verify the type. Passing an incorrect item will result in an undefined behavior.
.. doxygenfunction:: cbor_serialize_uint
.. doxygenfunction:: cbor_serialize_negint
.. doxygenfunction:: cbor_serialize_bytestring
.. doxygenfunction:: cbor_serialize_string
.. doxygenfunction:: cbor_serialize_array
.. doxygenfunction:: cbor_serialize_map
.. doxygenfunction:: cbor_serialize_tag
.. doxygenfunction:: cbor_serialize_float_ctrl

View File

@ -0,0 +1,41 @@
Memory management and reference counting
===============================================
Due to the nature of its domain, *libcbor* will need to work with heap memory. The stateless decoder and encoder don't allocate any memory.
If you have specific requirements, you should consider rolling your own driver for the stateless API.
Using custom allocator
^^^^^^^^^^^^^^^^^^^^^^^^
*libcbor* gives you with the ability to provide your own implementations of ``malloc``, ``realloc``, and ``free``. This can be useful if you are using a custom allocator throughout your application, or if you want to implement custom policies (e.g. tighter restrictions on the amount of allocated memory).
In order to use this feature, *libcbor* has to be compiled with the :doc:`appropriate flags </getting_started>`. You can verify the configuration using the ``CBOR_CUSTOM_ALLOC`` macro. A simple usage might be as follows:
.. code-block:: c
#if CBOR_CUSTOM_ALLOC
cbor_set_allocs(malloc, realloc, free);
#else
#error "libcbor built with support for custom allocation is required"
#endif
.. doxygenfunction:: cbor_set_allocs
Reference counting
^^^^^^^^^^^^^^^^^^^^^
As CBOR items may require complex cleanups at the end of their lifetime, there is a reference counting mechanism in place. This also enables very simple GC when integrating *libcbor* into managed environment. Every item starts its life (by either explicit creation, or as a result of parsing) with reference count set to 1. When the refcount reaches zero, it will be destroyed.
Items containing nested items will be destroyed recursively - refcount of every nested item will be decreased by one.
The destruction is synchronous and renders any pointers to items with refcount zero invalid immediately after calling the :func:`cbor_decref`.
.. doxygenfunction:: cbor_incref
.. doxygenfunction:: cbor_decref
.. doxygenfunction:: cbor_intermediate_decref
.. doxygenfunction:: cbor_refcount
.. doxygenfunction:: cbor_move
.. doxygenfunction:: cbor_copy

View File

@ -0,0 +1,41 @@
Types of items
===============================================
Every :type:`cbor_item_t` has a :type:`cbor_type` associated with it - these constants correspond to the types specified by the `CBOR standard <http://tools.ietf.org/html/rfc7049>`_:
.. doxygenenum:: cbor_type
To find out the type of an item, one can use
.. doxygenfunction:: cbor_typeof
Please note the distinction between functions like :func:`cbor_isa_uint()` and :func:`cbor_is_int()`. The following functions work solely with the major type value.
Binary queries
------------------------
Alternatively, there are functions to query each particular type.
.. warning:: Passing an invalid :type:`cbor_item_t` reference to any of these functions results in undefined behavior.
.. doxygenfunction:: cbor_isa_uint
.. doxygenfunction:: cbor_isa_negint
.. doxygenfunction:: cbor_isa_bytestring
.. doxygenfunction:: cbor_isa_string
.. doxygenfunction:: cbor_isa_array
.. doxygenfunction:: cbor_isa_map
.. doxygenfunction:: cbor_isa_tag
.. doxygenfunction:: cbor_isa_float_ctrl
Logical queries
------------------------
These functions provide information about the item type from a more high-level perspective
.. doxygenfunction:: cbor_is_int
.. doxygenfunction:: cbor_is_float
.. doxygenfunction:: cbor_is_bool
.. doxygenfunction:: cbor_is_null
.. doxygenfunction:: cbor_is_undef

View File

@ -0,0 +1,91 @@
Types 0 & 1 Positive and negative integers
===============================================
*CBOR* has two types of integers positive (which may be effectively regarded as unsigned), and negative. There are four possible widths for an integer 1, 2, 4, or 8 bytes. These are represented by
.. doxygenenum:: cbor_int_width
Type 0 - positive integers
--------------------------
================================== =========================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_UINT``
Number of allocations One per lifetime
Storage requirements ``sizeof(cbor_item_t) + sizeof(uint*_t)``
================================== =========================================
**Note:** once a positive integer has been created, its width *cannot* be changed.
Type 1 - negative integers
--------------------------
================================== =========================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_NEGINT``
Number of allocations One per lifetime
Storage requirements ``sizeof(cbor_item_t) + sizeof(uint*_t)``
================================== =========================================
**Note:** once a positive integer has been created, its width *cannot* be changed.
Type 0 & 1
-------------
Due to their largely similar semantics, the following functions can be used for both Type 0 and Type 1 items. One can convert between them freely using `the conversion functions <#dealing-with-signedness>`_.
Actual Type of the integer can be checked using :doc:`item types API <item_types>`.
An integer item is created with one of the four widths. Because integers' `storage is bundled together with the handle </internal#c.cbor_item_t.data>`_, the width cannot be changed over its lifetime.
.. warning::
Due to the fact that CBOR negative integers represent integers in the range :math:`[-1, -2^N]`, ``cbor_set_uint`` API is somewhat counter-intuitive as the resulting logical value is 1 less. This behavior is necessary in order to permit uniform manipulation with the full range of permitted values. For example, the following snippet
.. code-block:: c
cbor_item_t * item = cbor_new_int8();
cbor_mark_negint(item);
cbor_set_uint8(0);
will produce an item with the logical value of :math:`-1`. There is, however, an upside to this as well: There is only one representation of zero.
Building new items
------------------------
.. doxygenfunction:: cbor_build_uint8
.. doxygenfunction:: cbor_build_uint16
.. doxygenfunction:: cbor_build_uint32
.. doxygenfunction:: cbor_build_uint64
Retrieving values
------------------------
.. doxygenfunction:: cbor_get_uint8
.. doxygenfunction:: cbor_get_uint16
.. doxygenfunction:: cbor_get_uint32
.. doxygenfunction:: cbor_get_uint64
Setting values
------------------------
.. doxygenfunction:: cbor_set_uint8
.. doxygenfunction:: cbor_set_uint16
.. doxygenfunction:: cbor_set_uint32
.. doxygenfunction:: cbor_set_uint64
Dealing with width
---------------------
.. doxygenfunction:: cbor_int_get_width
Dealing with signedness
--------------------------
.. doxygenfunction:: cbor_mark_uint
.. doxygenfunction:: cbor_mark_negint
Creating new items
------------------------
.. doxygenfunction:: cbor_new_int8
.. doxygenfunction:: cbor_new_int16
.. doxygenfunction:: cbor_new_int32
.. doxygenfunction:: cbor_new_int64

View File

@ -0,0 +1,66 @@
Type 2 Byte strings
=============================
CBOR byte strings are just (ordered) series of bytes without further interpretation (unless there is a :doc:`tag <type_6>`). Byte string's length may or may not be known during encoding. These two kinds of byte strings can be distinguished using :func:`cbor_bytestring_is_definite` and :func:`cbor_bytestring_is_indefinite` respectively.
In case a byte string is indefinite, it is encoded as a series of definite byte strings. These are called "chunks". For example, the encoded item
::
0xf5 Start indefinite byte string
0x41 Byte string (1B long)
0x00
0x41 Byte string (1B long)
0xff
0xff "Break" control token
represents two bytes, ``0x00`` and ``0xff``. This on one hand enables streaming messages even before they are fully generated, but on the other hand it adds more complexity to the client code.
================================== ======================================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_BYTESTRING``
Number of allocations (definite) One plus any manipulations with the data
Number of allocations (indefinite) One plus logarithmically many
reallocations relative to chunk count
Storage requirements (definite) ``sizeof(cbor_item_t) + length(handle)``
Storage requirements (indefinite) ``sizeof(cbor_item_t) * (1 + chunk_count) + chunks``
================================== ======================================================
Streaming indefinite byte strings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to :doc:`/streaming`.
Getting metadata
~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_bytestring_length
.. doxygenfunction:: cbor_bytestring_is_definite
.. doxygenfunction:: cbor_bytestring_is_indefinite
.. doxygenfunction:: cbor_bytestring_chunk_count
Reading data
~~~~~~~~~~~~~
.. doxygenfunction:: cbor_bytestring_handle
.. doxygenfunction:: cbor_bytestring_chunks_handle
Creating new items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_new_definite_bytestring
.. doxygenfunction:: cbor_new_indefinite_bytestring
Building items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_build_bytestring
Manipulating existing items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_bytestring_set_handle
.. doxygenfunction:: cbor_bytestring_add_chunk

View File

@ -0,0 +1,55 @@
Type 3 UTF-8 strings
=============================
CBOR strings work in much the same ways as :doc:`type_2`.
================================== ======================================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_STRING``
Number of allocations (definite) One plus any manipulations with the data
Number of allocations (indefinite) One plus logarithmically many
reallocations relative to chunk count
Storage requirements (definite) ``sizeof(cbor_item_t) + length(handle)``
Storage requirements (indefinite) ``sizeof(cbor_item_t) * (1 + chunk_count) + chunks``
================================== ======================================================
Streaming indefinite strings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to :doc:`/streaming`.
UTF-8 encoding validation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
*libcbor* considers UTF-8 encoding validity to be a part of the well-formedness notion of CBOR and therefore invalid UTF-8 strings will be rejected by the parser. Strings created by the user are not checked.
Getting metadata
~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_string_length
.. doxygenfunction:: cbor_string_is_definite
.. doxygenfunction:: cbor_string_is_indefinite
.. doxygenfunction:: cbor_string_chunk_count
Reading data
~~~~~~~~~~~~~
.. doxygenfunction:: cbor_string_handle
.. doxygenfunction:: cbor_string_chunks_handle
Creating new items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_new_definite_string
.. doxygenfunction:: cbor_new_indefinite_string
Building items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_build_string
Manipulating existing items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_string_set_handle
.. doxygenfunction:: cbor_string_add_chunk

View File

@ -0,0 +1,62 @@
Type 4 Arrays
=============================
CBOR arrays, just like :doc:`byte strings <type_2>` and :doc:`strings <type_3>`, can be encoded either as definite, or as indefinite.
================================== =====================================================================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_ARRAY``
Number of allocations (definite) Two plus any manipulations with the data
Number of allocations (indefinite) Two plus logarithmically many
reallocations relative to additions
Storage requirements (definite) ``(sizeof(cbor_item_t) + 1) * size``
Storage requirements (indefinite) ``<= sizeof(cbor_item_t) + sizeof(cbor_item_t) * size * BUFFER_GROWTH``
================================== =====================================================================================
Examples
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::
0x9f Start indefinite array
0x01 Unsigned integer 1
0xff "Break" control token
::
0x9f Start array, 1B length follows
0x20 Unsigned integer 32
... 32 items follow
Streaming indefinite arrays
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to :doc:`/streaming`.
Getting metadata
~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_array_size
.. doxygenfunction:: cbor_array_allocated
.. doxygenfunction:: cbor_array_is_definite
.. doxygenfunction:: cbor_array_is_indefinite
Reading data
~~~~~~~~~~~~~
.. doxygenfunction:: cbor_array_handle
.. doxygenfunction:: cbor_array_get
Creating new items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_new_definite_array
.. doxygenfunction:: cbor_new_indefinite_array
Modifying items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_array_push
.. doxygenfunction:: cbor_array_replace
.. doxygenfunction:: cbor_array_set

View File

@ -0,0 +1,44 @@
Type 5 Maps
=============================
CBOR maps are the plain old associate hash maps known from JSON and many other formats and languages, with one exception: any CBOR data item can be a key, not just strings. This is somewhat unusual and you, as an application developer, should keep that in mind.
Maps can be either definite or indefinite, in much the same way as :doc:`type_4`.
================================== =====================================================================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_MAP``
Number of allocations (definite) Two plus any manipulations with the data
Number of allocations (indefinite) Two plus logarithmically many
reallocations relative to additions
Storage requirements (definite) ``sizeof(cbor_pair) * size + sizeof(cbor_item_t)``
Storage requirements (indefinite) ``<= sizeof(cbor_item_t) + sizeof(cbor_pair) * size * BUFFER_GROWTH``
================================== =====================================================================================
Streaming maps
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to :doc:`/streaming`.
Getting metadata
~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_map_size
.. doxygenfunction:: cbor_map_allocated
.. doxygenfunction:: cbor_map_is_definite
.. doxygenfunction:: cbor_map_is_indefinite
Reading data
~~~~~~~~~~~~~
.. doxygenfunction:: cbor_map_handle
Creating new items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_new_definite_map
.. doxygenfunction:: cbor_new_indefinite_map
Modifying items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_map_add

View File

@ -0,0 +1,21 @@
Type 6 Semantic tags
=============================
Tag are additional metadata that can be used to extend or specialize the meaning or interpretation of the other data items.
For example, one might tag an array of numbers to communicate that it should be interpreted as a vector.
Please consult the official `IANA repository of CBOR tags <https://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml>`_ before inventing new ones.
================================== ======================================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_TAG``
Number of allocations One plus any manipulations with the data
reallocations relative to chunk count
Storage requirements ``sizeof(cbor_item_t) + the tagged item``
================================== ======================================================
.. doxygenfunction:: cbor_new_tag
.. doxygenfunction:: cbor_tag_item
.. doxygenfunction:: cbor_tag_value
.. doxygenfunction:: cbor_tag_set_item

View File

@ -0,0 +1,75 @@
Type 7 Floats & control tokens
=================================
This type combines two completely unrelated types of items -- floating point numbers and special values such as true, false, null, etc. We refer to these special values as 'control values' or 'ctrls' for short throughout the code.
Just like integers, they have different possible width (resulting in different value ranges and precisions).
.. doxygenenum:: cbor_float_width
================================== =========================================
Corresponding :type:`cbor_type` ``CBOR_TYPE_FLOAT_CTRL``
Number of allocations One per lifetime
Storage requirements ``sizeof(cbor_item_t) + 1/4/8``
================================== =========================================
Getting metadata
~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_float_ctrl_is_ctrl
.. doxygenfunction:: cbor_float_get_width
Reading data
~~~~~~~~~~~~~
.. doxygenfunction:: cbor_float_get_float2
.. doxygenfunction:: cbor_float_get_float4
.. doxygenfunction:: cbor_float_get_float8
.. doxygenfunction:: cbor_float_get_float
.. doxygenfunction:: cbor_ctrl_value
.. doxygenfunction:: cbor_get_bool
Creating new items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_new_ctrl
.. doxygenfunction:: cbor_new_float2
.. doxygenfunction:: cbor_new_float4
.. doxygenfunction:: cbor_new_float8
.. doxygenfunction:: cbor_new_null
.. doxygenfunction:: cbor_new_undef
Building items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_build_bool
.. doxygenfunction:: cbor_build_ctrl
.. doxygenfunction:: cbor_build_float2
.. doxygenfunction:: cbor_build_float4
.. doxygenfunction:: cbor_build_float8
Manipulating existing items
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygenfunction:: cbor_set_ctrl
.. doxygenfunction:: cbor_set_bool
.. doxygenfunction:: cbor_set_float2
.. doxygenfunction:: cbor_set_float4
.. doxygenfunction:: cbor_set_float8
.. _api_type_7_hard_floats:
Half floats
~~~~~~~~~~~~
CBOR supports two `bytes wide ("half-precision") <https://en.wikipedia.org/wiki/Half-precision_floating-point_format>`_
floats which are not supported by the C language. *libcbor* represents them using `float <https://en.cppreference.com/w/c/language/type>` values throughout the API, which has important implications when manipulating these values.
In particular, if a user uses some of the manipulation APIs
(e.g. :func:`cbor_set_float2`, :func:`cbor_new_float2`)
to introduce a value that doesn't have an exect half-float representation,
the encoding semantics are given by :func:`cbor_encode_half` as follows:
.. doxygenfunction:: cbor_encode_half

View File

@ -0,0 +1,4 @@
Changelog
==============
.. include:: ../../CHANGELOG.md

View File

@ -0,0 +1,296 @@
# -*- coding: utf-8 -*-
#
# libcbor documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 8 13:27:19 2014.
#
# 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
import 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('.'))
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
# -- 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 = [
'breathe',
'sphinx.ext.mathjax',
'sphinx.ext.autodoc',
'sphinx.ext.ifconfig'
]
import subprocess, os
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
print(subprocess.check_output('cd ../..; mkdir doc/build; doxygen', shell=True))
if on_rtd:
print(subprocess.check_output('cd ../..; mkdir doc/build; doxygen', shell=True))
print(os.getcwd())
print(os.getcwd() + '/../build/doxygen/xml')
breathe_projects = {
'libcbor': '../build/doxygen/xml'
}
breathe_default_project = "libcbor"
# 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 = 'libcbor'
copyright = '2014 - 2020, Pavel Kalvoda'
# 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 = '0.8'
release = '0.8.0'
# 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.
# https://github.com/michaeljones/breathe/issues/197
exclude_patterns = ['breathe/*']
# The reST default role (used for this markup: `text`) to use for all
# documents.
breathe_domain_by_extension = {
"h" : "C",
}
#default_role = 'c:func'
primary_domain = "cpp"
# 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 = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- 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 = []
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# 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 = 'libcbordoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'libcbor.tex', 'libcbor Documentation',
'Pavel Kalvoda', '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
# 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', 'libcbor', 'libcbor Documentation',
['Pavel Kalvoda'], 3)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'libcbor', 'libcbor Documentation',
'Pavel Kalvoda', 'libcbor', 'C library for parsing and generating CBOR.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# otherwise, readthedocs.org uses their theme by default, so no need to specify it

View File

@ -0,0 +1,143 @@
Development
==========================
Vision and principles
---------------------------
Consistency and coherence are one of the key characteristics of good software.
While the reality is never black and white, it is important libcbor
contributors are working towards the same high-level goal. This document
attempts to set out the basic principles of libcbor and the rationale behind
them. If you are contributing to libcbor or looking to evaluate whether libcbor
is the right choice for your project, it might be worthwhile to skim through the
section below.
Mission statement
~~~~~~~~~~~~~~~~~~~~~~
*libcbor* is the compact, full-featured, and safe CBOR library that works
everywhere.
Goals
~~~~~~~~~~~~~~~~~~~~~~
RFC-conformance and full feature support
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Anything the standard allows, libcbor can do.
**Why?** Because conformance and interoperability is the point of defining
standards. Clients expect the support to be feature-complete and
there is no significant complexity reduction that can be achieved by slightly
cutting corners, which means that the incremental cost of full RFC support is
comparatively small over "almost-conformance" seen in many alternatives.
Safety
^^^^^^^^^^^^^^^^^^^^^^
Untrusted bytes from the network are the typical input.
**Why?** Because it is the client expectation. Vast majority of security
vulnerabilities are violations of contracts -- in other words, bugs -- anyway.
Self-containment
^^^^^^^^^^^^^^^^^^^^^^
libcbor has no runtime dependencies.
**Why?** Because any constraint imposed on libcbor has to be enforced
transitively, which is difficult and leads to incompatibilities and
distribution issues, especially in IoT applications.
Portability
^^^^^^^^^^^^^^^^^^^^^^
If you can compile C for it, libcbor will work there.
**Why?** Lowest-common-denominator solution for system-level and IoT software
was the original niche of libcbor. Users who rely on libcbor expect future
updates to work on their target platform.
Stable and predictable API
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
libcbor will not break without a warning.
**Why?** `Industry-standard <https://semver.org/>`_ versioning is a basic
requirement for production-quality software. This is especially relevant in IoT
environments where updates may be costly.
Performance
^^^^^^^^^^^^^^^^^^^^^^
libcbor is fast and resource-efficient by design
**Why?** Because the main maintainer is an avid hater of slow bloated software.
Who wouldn't want more bang per their electricity buck?
Non-goals
~~~~~~~~~~~~~~~~~~~~~~
- Convenience -- libcbor only provides the minimum surface to make it usable
- FFI/SWIG/interop support -- libcbor is primarily a C library for C clients
- One-off usecases support -- although there are primitives to reuse, the
basic
assumption is that most clients want most of CBOR features
Development dependencies
---------------------------
- `CMocka <http://cmocka.org/>`_ (testing)
- `Python <https://www.python.org/>`_ and `pip <https://pypi.python.org/pypi/pip>`_ (Sphinx platform)
- `Doxygen <http://www.stack.nl/~dimitri/doxygen/>`_
- `Sphinx <http://sphinx-doc.org/>`_ (documentation)
- There are some `Ruby <https://www.ruby-lang.org/en/>`_ scripts in ``misc``
- `Valgrind <http://valgrind.org/>`_ (memory correctness & profiling)
- `GCOV/LCOV <http://ltp.sourceforge.net/coverage/lcov.php>`_ (test coverage)
- `clang-format`
Installing *sphinx*
~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
pip install sphinx
pip install sphinx_rtd_theme
pip install breathe
pip install https://github.com/lepture/python-livereload/archive/master.zip
pip install sphinx-autobuild
Further instructions on configuring advanced features can be found at `<http://read-the-docs.readthedocs.org/en/latest/install.html>`_.
Live preview of docs
~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
cd doc
make livehtml
Set up git hooks
~~~~~~~~~~~~~~~~~
A catch-all git hook that runs clang-format and automatically refreshes the `GH
pages <https://pages.github.com/>`_ contents located in ``docs`` can be
symlinked:
.. code-block:: bash
ln -sf $(pwd)/misc/hooks/pre-commit .git/hooks
Testing and code coverage
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please refer to :doc:`tests`

View File

@ -0,0 +1,190 @@
Getting started
==========================
Pre-built Linux packages are available in most mainstream distributions
**Ubuntu, Debian, etc.**:
.. code-block:: bash
apt-get install libcbor-dev
**Fedora, openSUSE, etc.**:
.. code-block:: bash
yum install libcbor-devel
**OS X** users can use `Homebrew <http://brew.sh/>`_:
.. code-block:: bash
brew install libcbor
For other platforms, you will need to compile it from source.
Building & installing libcbor
------------------------------
Prerequisites:
- C99 compiler
- CMake_ 2.8 or newer (might also be called ``cmakesetup``, ``cmake-gui`` or ``ccmake`` depending on the installed version and system)
- C build system CMake can target (make, Apple Xcode, MinGW, ...)
.. _CMake: http://cmake.org/
**Configuration options**
A handful of configuration flags can be passed to `cmake`. The following table lists libcbor compile-time directives and several important generic flags.
======================== ======================================================= ====================== =====================================================================================================================
Option Meaning Default Possible values
------------------------ ------------------------------------------------------- ---------------------- ---------------------------------------------------------------------------------------------------------------------
``CMAKE_C_COMPILER`` C compiler to use ``cc`` ``gcc``, ``clang``, ``clang-3.5``, ...
``CMAKE_INSTALL_PREFIX`` Installation prefix System-dependent ``/usr/local/lib``, ...
``BUILD_SHARED_LIBS`` Build as a shared library ``OFF`` ``ON``, ``OFF``
``HUGE_FUZZ`` :doc:`Fuzz test </tests>` with 8GB of data ``OFF`` ``ON``, ``OFF``
``SANE_MALLOC`` Assume ``malloc`` will refuse unreasonable allocations ``OFF`` ``ON``, ``OFF``
``COVERAGE`` Generate test coverage instrumentation ``OFF`` ``ON``, ``OFF``
``WITH_TESTS`` Build unit tests (see :doc:`development`) ``OFF`` ``ON``, ``OFF``
======================== ======================================================= ====================== =====================================================================================================================
The following configuration options will also be defined as macros[#]_ in ``<cbor/common.h>`` and can therefore be used in client code:
======================== ======================================================= ====================== =====================================================================================================================
Option Meaning Default Possible values
------------------------ ------------------------------------------------------- ---------------------- ---------------------------------------------------------------------------------------------------------------------
``CBOR_CUSTOM_ALLOC`` Enable custom allocator support ``OFF`` ``ON``, ``OFF``
``CBOR_PRETTY_PRINTER`` Include a pretty-printing routine ``ON`` ``ON``, ``OFF``
``CBOR_BUFFER_GROWTH`` Factor for buffer growth & shrinking ``2`` Decimals > 1
======================== ======================================================= ====================== =====================================================================================================================
.. [#] ``ON`` & ``OFF`` will be translated to ``1`` and ``0`` using `cmakedefine <https://cmake.org/cmake/help/v3.2/command/configure_file.html?highlight=cmakedefine>`_.
If you want to pass other custom configuration options, please refer to `<http://www.cmake.org/Wiki/CMake_Useful_Variables>`_.
**Building using make**
CMake will generate a Makefile and other configuration files for the build. As a rule of thumb, you should configure the
build *outside of the source tree* in order to keep different configurations isolated. If you are unsure where to
execute the build, just use a temporary directory:
.. code-block:: bash
cd $(mktemp -d /tmp/cbor_build.XXXX)
Now, assuming you are in the directory where you want to build, build libcbor as a **static library**:
.. code-block:: bash
cmake -DCMAKE_BUILD_TYPE=Release path_to_libcbor_dir
make cbor
... or as a **dynamic library**:
.. code-block:: bash
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON path_to_libcbor_dir
make cbor
To install locally:
.. code-block:: bash
make install
Root permissions are required on most systems when using the default installation prefix.
**Portability**
libcbor is highly portable and works on both little- and big-endian systems regardless of the operating system. After building
on an exotic platform, you might wish to verify the result by running the :doc:`test suite </tests>`. If you encounter any problems, please
report them to the `issue tracker <https://github.com/PJK/libcbor/issues>`_.
libcbor is known to successfully work on ARM Android devices. Cross-compilation is possible with ``arm-linux-gnueabi-gcc``.
Linking with libcbor
---------------------
If you include and linker paths include the directories to which libcbor has been installed, compiling programs that uses libcbor requires
no extra considerations.
You can verify that everything has been set up properly by creating a file with the following contents
.. code-block:: c
#include <cbor.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
printf("Hello from libcbor %s\n", CBOR_VERSION);
}
and compiling it
.. code-block:: bash
cc hello_cbor.c -lcbor -o hello_cbor
libcbor also comes with `pkg-config <https://wiki.freedesktop.org/www/Software/pkg-config/>`_ support. If you install libcbor with a custom prefix, you can use pkg-config to resolve the headers and objects:
.. code-block:: bash
cc $(pkg-config --cflags libcbor) hello_cbor.c $(pkg-config --libs libcbor) -o hello_cbor
**A note on linkage**
libcbor is primarily intended to be linked statically. The shared library versioning scheme generally follows `SemVer <https://semver.org/>`_, but is irregular for the 0.X.Y development branch for historical reasons. The following version identifiers are used as a part of the SONAME (Linux) or the dylib `"Compatibility version" <https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/CreatingDynamicLibraries.html>`_ (OS X):
- 0.Y for the 0.Y.Z branch. Patches are backwards compatible, minor releases are generally not and require re-compilation of any dependent code.
- X for the X.Y.Z stable versions starting 1.X.Y. All minor release of the major version are backwards compatible.
.. warning:: Please note that releases up to and including v0.6.0 `may export misleading .so/.dylib version number <https://github.com/PJK/libcbor/issues/52>`_.
Troubleshooting
---------------------
**cbor.h not found**: The headers directory is probably not in your include path. First, verify the installation
location by checking the installation log. If you used make, it will look something like
.. code-block:: text
...
-- Installing: /usr/local/include/cbor
-- Installing: /usr/local/include/cbor/callbacks.h
-- Installing: /usr/local/include/cbor/encoding.h
...
Make sure that ``CMAKE_INSTALL_PREFIX`` (if you provided it) was correct. Including the path path during compilation should suffice, e.g.:
.. code-block:: bash
cc -I/usr/local/include hello_cbor.c -lcbor -o hello_cbor
**cannot find -lcbor during linking**: Most likely the same problem as before. Include the installation directory in the
linker shared path using ``-R``, e.g.:
.. code-block:: bash
cc -Wl,-rpath,/usr/local/lib -lcbor -o hello_cbor
**shared library missing during execution**: Verify the linkage using ``ldd``, ``otool``, or similar and adjust the compilation directives accordingly:
.. code-block:: text
⇒ ldd hello_cbor
linux-vdso.so.1 => (0x00007ffe85585000)
libcbor.so => /usr/local/lib/libcbor.so (0x00007f9af69da000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9af65eb000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9af6be9000)
**compilation failed**: If your compiler supports C99 yet the compilation has failed, please report the issue to the `issue tracker <https://github.com/PJK/libcbor/issues>`_.

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,40 @@
libcbor
===================================
Documentation for version |release|, updated on |today|.
Overview
--------
*libcbor* is a C library for parsing and generating CBOR_, the general-purpose schema-less binary data format.
Main features
- Complete RFC conformance [#]_
- Robust C99 implementation
- Layered architecture offers both control and convenience
- Flexible memory management
- No shared global state - threading friendly [#]_
- Proper handling of UTF-8
- Full support for streams & incremental processing
- Extensive documentation and test suite
- No runtime dependencies, small footprint
.. [#] See :doc:`rfc_conformance`
.. [#] With the exception of custom memory allocators (see :doc:`api/item_reference_counting`)
Contents
----------
.. toctree::
getting_started
using
api
streaming
tests
rfc_conformance
internal
changelog
development
.. _CBOR: http://tools.ietf.org/html/rfc7049

View File

@ -0,0 +1,128 @@
Internal mechanics
==========================
Internal workings of *libcbor* are mostly derived from the specification. The purpose of this document is to describe technical choices made during design & implementation and to explicate the reasoning behind those choices.
Terminology
---------------
=== ====================== ========================================================================================================================================
MTB Major Type Byte http://tools.ietf.org/html/rfc7049#section-2.1
--- ---------------------- ----------------------------------------------------------------------------------------------------------------------------------------
DST Dynamically Sized Type Type whose storage requirements cannot be determined
during compilation (originated in the `Rust <http://www.rust-lang.org/>`_ community)
=== ====================== ========================================================================================================================================
Conventions
--------------
API symbols start with ``cbor_`` or ``CBOR_`` prefix, internal symbols have ``_cbor_`` or ``_CBOR_`` prefix.
Inspiration & related projects
-------------------------------
Most of the API is largely modelled after existing JSON libraries, including
- `Jansson <http://www.digip.org/jansson/>`_
- `json-c <https://github.com/json-c/json-c>`_
- Gnome's `JsonGlib <https://wiki.gnome.org/action/show/Projects/JsonGlib?action=show&redirect=JsonGlib>`_
and also borrowing from
- `msgpack-c <https://github.com/msgpack/msgpack-c>`_
- `Google Protocol Buffers <http://code.google.com/p/protobuf/>`_.
General notes on the API design
--------------------------------
The API design has two main driving priciples:
1. Let the client manage the memory as much as possible
2. Behave exactly as specified by the standard
Combining these two principles in practice turns out to be quite difficult. Indefinite-length strings, arrays, and maps require client to handle every fixed-size chunk explicitly in order to
- ensure the client never runs out of memory due to *libcbor*
- use :func:`realloc` sparsely and predictably [#]_
- provide strong guarantees about its usage (to prevent latency spikes)
- provide APIs to avoid :func:`realloc` altogether
- allow proper handling of (streamed) data bigger than available memory
.. [#] Reasonable handling of DSTs requires reallocation if the API is to remain sane.
Coding style
-------------
This code loosely follows the `Linux kernel coding style <https://www.kernel.org/doc/Documentation/CodingStyle>`_. Tabs are tabs, and they are 4 characters wide.
Memory layout
---------------
CBOR is very dynamic in the sense that it contains many data elements of variable length, sometimes even indefinite length. This section describes internal representation of all CBOR data types.
Generally speaking, data items consist of three parts:
- a generic :type:`handle <cbor_item_t>`,
- the associated :type:`metadata <cbor_item_metadata>`,
- and the actual data
.. type:: cbor_item_t
Represents the item. Used as an opaque type
.. member:: cbor_type type
Type discriminator
.. member:: size_t refcount
Reference counter. Used by :func:`cbor_decref`, :func:`cbor_incref`
.. member:: union cbor_item_metadata metadata
Union discriminated by :member:`type`. Contains type-specific metadata
.. member:: unsigned char * data
Contains pointer to the actual data. Small, fixed size items (:doc:`api/type_0_1`, :doc:`api/type_6`, :doc:`api/type_7`) are allocated as a single memory block.
Consider the following snippet
.. code-block:: c
cbor_item_t * item = cbor_new_int8();
then the memory is laid out as follows
::
+-----------+---------------+---------------+-----------------------------------++-----------+
| | | | || |
| type | refcount | metadata | data || uint8_t |
| | | | (= item + sizeof(cbor_item_t)) || |
+-----------+---------------+---------------+-----------------------------------++-----------+
^ ^
| |
+--- item +--- item->data
Dynamically sized types (:doc:`api/type_2`, :doc:`api/type_3`, :doc:`api/type_4`, :doc:`api/type_5`) may store handle and data in separate locations. This enables creating large items (e.g :doc:`byte strings <api/type_2>`) without :func:`realloc` or copying large blocks of memory. One simply attaches the correct pointer to the handle.
.. type:: cbor_item_metadata
Union type of the following members, based on the item type:
.. member:: struct _cbor_int_metadata int_metadata
Used both by both :doc:`api/type_0_1`
.. member:: struct _cbor_bytestring_metadata bytestring_metadata
.. member:: struct _cbor_string_metadata string_metadata
.. member:: struct _cbor_array_metadata array_metadata
.. member:: struct _cbor_map_metadata map_metadata
.. member:: struct _cbor_tag_metadata tag_metadata
.. member:: struct _cbor_float_ctrl_metadata float_ctrl_metadata
Decoding
---------
As outlined in :doc:`api`, there decoding is based on the streaming decoder Essentially, the decoder is a custom set of callbacks for the streaming decoder.

View File

@ -0,0 +1,39 @@
alabaster==0.7.12
argh==0.26.2
Babel==2.8.0
breathe==4.14.1
certifi==2019.11.28
chardet==3.0.4
Click==7.0
docutils==0.16
Flask==1.1.1
idna==2.9
imagesize==1.2.0
itsdangerous==1.1.0
Jinja2==2.10.1
livereload==2.6.1
MarkupSafe==1.1.1
packaging==20.3
pathtools==0.1.2
port-for==0.3.1
Pygments==2.6.1
pyparsing==2.4.6
pytz==2019.3
PyYAML==5.3
requests==2.23.0
six==1.14.0
snowballstemmer==2.0.0
sortedcontainers==2.1.0
Sphinx==2.4.4
sphinx-autobuild==0.7.1
sphinx-rtd-theme==0.4.3
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==1.0.3
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.4
tornado==6.0.4
urllib3==1.25.8
watchdog==0.10.2
Werkzeug==0.15.5

View File

@ -0,0 +1,17 @@
RFC conformance
=========================
*libcbor* is, generally speaking, very faithful implementation of `RFC 7049 <http://tools.ietf.org/html/rfc7049>`_. There are, however, some limitations imposed by technical constraints.
Bytestring length
-------------------
There is no explicit limitation of indefinite length byte strings. [#]_ *libcbor* will not handle byte strings with more chunks than the maximum value of :type:`size_t`. On any sane platform, such string would not fit in the memory anyway. It is, however, possible to process arbitrarily long strings and byte strings using the streaming decoder.
.. [#] http://tools.ietf.org/html/rfc7049#section-2.2.2
"Half-precision" IEEE 754 floats
---------------------------------
As of C99 and even C11, there is no standard implementation for 2 bytes floats. *libcbor* packs them as a `float <https://en.cppreference.com/w/c/language/type>`. When encoding, *libcbor* selects the appropriate wire representation based on metadata and the actual value. This applies both to canonical and normal mode.
For more information on half-float serialization, please refer to the section on :ref:`api_type_7_hard_floats`.

View File

@ -0,0 +1,13 @@
Streaming & indefinite items
=============================
CBOR :doc:`strings <api/type_2>`, :doc:`byte strings <api/type_3>`, :doc:`arrays <api/type_4>`, and :doc:`maps <api/type_5>` can be encoded as *indefinite*, meaning their length or size is not specified. Instead, they are divided into *chunks* (:doc:`strings <api/type_2>`, :doc:`byte strings <api/type_3>`), or explicitly terminated (:doc:`arrays <api/type_4>`, :doc:`maps <api/type_5>`).
This is one of the most important (and due to poor implementations, underutilized) features of CBOR. It enables low-overhead streaming just about anywhere without dealing with channels or pub/sub mechanism. It is, however, important to recognize that CBOR streaming is not a substitute for Websockets [#]_ and similar technologies.
.. [#] :RFC:`6455`
.. toctree::
streaming/decoding
streaming/encoding

View File

@ -0,0 +1,40 @@
Decoding
=============================
Another way to decode data using libcbor is to specify a callbacks that will be invoked when upon finding certain items in the input. This API is provided by
.. doxygenfunction:: cbor_stream_decode
Usage example: https://github.com/PJK/libcbor/blob/master/examples/streaming_parser.c
The callbacks are defined by
.. doxygenstruct:: cbor_callbacks
:members:
When building custom sets of callbacks, feel free to start from
.. doxygenvariable:: cbor_empty_callbacks
Related structures
~~~~~~~~~~~~~~~~~~~~~
.. doxygenenum:: cbor_decoder_status
.. doxygenstruct:: cbor_decoder_result
:members:
Callback types definition
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. doxygentypedef:: cbor_int8_callback
.. doxygentypedef:: cbor_int16_callback
.. doxygentypedef:: cbor_int32_callback
.. doxygentypedef:: cbor_int64_callback
.. doxygentypedef:: cbor_simple_callback
.. doxygentypedef:: cbor_string_callback
.. doxygentypedef:: cbor_collection_callback
.. doxygentypedef:: cbor_float_callback
.. doxygentypedef:: cbor_double_callback
.. doxygentypedef:: cbor_bool_callback

View File

@ -0,0 +1,4 @@
Encoding
=============================
TODO

View File

@ -0,0 +1,39 @@
Tests
=============
Unit tests
--------------
There is a comprehensive test suite employing CMocka_. You can run all of them using ``ctest`` in the build directory. Individual tests are themselves runnable. Please refer to `CTest <http://www.cmake.org/Wiki/CMake/Testing_With_CTest>`_ documentation for detailed information on how to specify particular subset of tests.
.. _CMocka: http://cmocka.org/
Testing for memory leaks
------------------------
Every release is tested for memory correctness. You can run these tests by passing the ``-T memcheck`` flag to ``ctest``. [#]_
.. [#] Project should be configured with ``-DCMAKE_BUILD_TYPE=Debug`` to obtain meaningful description of location of the leak. You might also need ``--dsymutil=yes`` on OS X.
Code coverage
-------------------
Every release is inspected using `GCOV/LCOV <http://ltp.sourceforge.net/coverage/lcov.php>`_. Platform-independent code should be fully covered by the test suite. Simply run
.. code-block:: bash
make coverage
or alternatively run ``lcov`` by hand using
.. code-block:: bash
lcov --capture --directory . --output-file coverage.info
genhtml coverage.info --output-directory out
Fuzz testing
-----------------
Every release is tested using a fuzz test. In this test, a huge buffer filled with random data is passed to the decoder. We require that it either succeeds or fail with a sensible error, without leaking any memory. This is intended to simulate real-world situations where data received from the network are CBOR-decoded before any further processing.

View File

@ -0,0 +1,173 @@
Usage & preliminaries
=======================
Version information
--------------------
libcbor exports its version using three self-explanatory macros:
- ``CBOR_MAJOR_VERSION``
- ``CBOR_MINOR_VERSION``
- ``CBOR_PATCH_VERSION``
The ``CBOR_VERSION`` is a string concatenating these three identifiers into one (e.g. ``0.2.0``).
In order to simplify version comparisons, the version is also exported as
.. code-block:: c
#define CBOR_HEX_VERSION ((CBOR_MAJOR_VERSION << 16) | (CBOR_MINOR_VERSION << 8) | CBOR_PATCH_VERSION)
Since macros are difficult to work with through FFIs, the same information is also available through three ``uint8_t`` constants,
namely
- ``cbor_major_version``
- ``cbor_minor_version``
- ``cbor_patch_version``
Headers to include
---------------------
The ``cbor.h`` header includes all the symbols. If, for any reason, you don't want to include all the exported symbols,
feel free to use just some of the ``cbor/*.h`` headers:
- ``cbor/arrays.h`` - :doc:`api/type_4`
- ``cbor/bytestrings.h`` - :doc:`api/type_2`
- ``cbor/callbacks.h`` - Callbacks used for :doc:`streaming/decoding`
- ``cbor/common.h`` - Common utilities - always transitively included
- ``cbor/data.h`` - Data types definitions - always transitively included
- ``cbor/encoding.h`` - Streaming encoders for :doc:`streaming/encoding`
- ``cbor/floats_ctrls.h`` - :doc:`api/type_7`
- ``cbor/ints.h`` - :doc:`api/type_0_1`
- ``cbor/maps.h`` - :doc:`api/type_5`
- ``cbor/serialization.h`` - High level serialization such as :func:`cbor_serialize`
- ``cbor/streaming.h`` - Home of :func:`cbor_stream_decode`
- ``cbor/strings.h`` - :doc:`api/type_3`
- ``cbor/tags.h`` - :doc:`api/type_6`
Using libcbor
--------------
If you want to get more familiar with CBOR, we recommend the `cbor.io <http://cbor.io/>`_ website. Once you get the grasp
of what is it CBOR does, the examples (located in the ``examples`` directory) should give you a good feel of the API. The
:doc:`API documentation <api>` should then provide with all the information you may need.
**Creating and serializing items**
.. code-block:: c
#include "cbor.h"
#include <stdio.h>
int main(int argc, char * argv[])
{
/* Preallocate the map structure */
cbor_item_t * root = cbor_new_definite_map(2);
/* Add the content */
cbor_map_add(root, (struct cbor_pair) {
.key = cbor_move(cbor_build_string("Is CBOR awesome?")),
.value = cbor_move(cbor_build_bool(true))
});
cbor_map_add(root, (struct cbor_pair) {
.key = cbor_move(cbor_build_uint8(42)),
.value = cbor_move(cbor_build_string("Is the answer"))
});
/* Output: `length` bytes of data in the `buffer` */
unsigned char * buffer;
size_t buffer_size, length = cbor_serialize_alloc(root, &buffer, &buffer_size);
fwrite(buffer, 1, length, stdout);
free(buffer);
fflush(stdout);
cbor_decref(&root);
}
**Reading serialized data**
.. code-block:: c
#include "cbor.h"
#include <stdio.h>
/*
* Reads data from a file. Example usage:
* $ ./examples/readfile examples/data/nested_array.cbor
*/
int main(int argc, char * argv[])
{
FILE * f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
size_t length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char * buffer = malloc(length);
fread(buffer, length, 1, f);
/* Assuming `buffer` contains `info.st_size` bytes of input data */
struct cbor_load_result result;
cbor_item_t * item = cbor_load(buffer, length, &result);
/* Pretty-print the result */
cbor_describe(item, stdout);
fflush(stdout);
/* Deallocate the result */
cbor_decref(&item);
fclose(f);
}
**Using the streaming parser**
.. code-block:: c
#include "cbor.h"
#include <stdio.h>
#include <string.h>
/*
* Illustrates how one might skim through a map (which is assumed to have
* string keys and values only), looking for the value of a specific key
*
* Use the examples/data/map.cbor input to test this.
*/
const char * key = "a secret key";
bool key_found = false;
void find_string(void * _ctx, cbor_data buffer, size_t len)
{
if (key_found) {
printf("Found the value: %*s\n", (int) len, buffer);
key_found = false;
} else if (len == strlen(key)) {
key_found = (memcmp(key, buffer, len) == 0);
}
}
int main(int argc, char * argv[])
{
FILE * f = fopen(argv[1], "rb");
fseek(f, 0, SEEK_END);
size_t length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char * buffer = malloc(length);
fread(buffer, length, 1, f);
struct cbor_callbacks callbacks = cbor_empty_callbacks;
struct cbor_decoder_result decode_result;
size_t bytes_read = 0;
callbacks.string = find_string;
while (bytes_read < length) {
decode_result = cbor_stream_decode(buffer + bytes_read,
length - bytes_read,
&callbacks, NULL);
bytes_read += decode_result.read;
}
fclose(f);
}

View File

@ -0,0 +1,25 @@
add_executable(readfile readfile.c)
target_link_libraries(readfile cbor)
add_executable(create_items create_items.c)
target_link_libraries(create_items cbor)
add_executable(streaming_parser streaming_parser.c)
target_link_libraries(streaming_parser cbor)
add_executable(sort sort.c)
target_link_libraries(sort cbor)
add_executable(hello hello.c)
target_link_libraries(hello cbor)
find_package(CJSON)
if(CJSON_FOUND)
add_executable(cjson2cbor cjson2cbor.c)
target_include_directories(cjson2cbor PUBLIC ${CJSON_INCLUDE_DIRS})
target_link_libraries(cjson2cbor cbor ${CJSON_LIBRARY})
endif()
file(COPY data DESTINATION .)

View File

@ -0,0 +1,145 @@
/*
* Contributed by Jacob Teplitsky <jacob.teplitsky@ericsson.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
/**
* This code demonstrates how cJSON (https://github.com/DaveGamble/cJSON)
* callbacks can be used in conjuction with the streaming parser to translate
* JSON to CBOR. Please note that cbor_builder_* APIs are internal and thus
* subject to change.
*
* The example will only be compiled when cJSON is available
*/
#include <cjson/cJSON.h>
#include <float.h>
#include <math.h>
#include <string.h>
#include "cbor.h"
#include "cbor/internal/builder_callbacks.h"
#include "cbor/internal/loaders.h"
typedef void (*cbor_load_callback_t)(cJSON *, const struct cbor_callbacks *,
void *);
cbor_item_t *cjson_cbor_load(void *source,
cbor_load_callback_t cbor_load_callback) {
static struct cbor_callbacks callbacks = {
.uint64 = &cbor_builder_uint64_callback,
.negint64 = &cbor_builder_negint64_callback,
.string = &cbor_builder_string_callback,
.array_start = &cbor_builder_array_start_callback,
.map_start = &cbor_builder_map_start_callback,
.null = &cbor_builder_null_callback,
.boolean = &cbor_builder_boolean_callback,
.float4 = &cbor_builder_float4_callback,
};
/* Context stack */
struct _cbor_stack stack = _cbor_stack_init();
/* Target for callbacks */
struct _cbor_decoder_context context = (struct _cbor_decoder_context){
.stack = &stack,
};
cbor_load_callback(source, &callbacks, &context);
return context.root;
}
void cjson_cbor_stream_decode(cJSON *source,
const struct cbor_callbacks *callbacks,
void *context) {
switch (source->type) {
case cJSON_False: {
callbacks->boolean(context, false);
return;
}
case cJSON_True: {
callbacks->boolean(context, true);
return;
}
case cJSON_NULL: {
callbacks->null(context);
return;
}
case cJSON_Number: {
// This is stupid -- ints and doubles cannot are not distinguished
if (fabs(source->valuedouble - source->valueint) > DBL_EPSILON) {
callbacks->float4(context, source->valuedouble);
} else {
// XXX: This is not portable
if (source->valueint >= 0) {
callbacks->uint64(context, source->valueint);
} else {
callbacks->negint64(context, source->valueint + 1);
}
}
return;
}
case cJSON_String: {
// XXX: Assume cJSON handled unicode correctly
callbacks->string(context, (unsigned char *)source->valuestring,
strlen(source->valuestring));
return;
}
case cJSON_Array: {
callbacks->array_start(context, cJSON_GetArraySize(source));
cJSON *item = source->child;
while (item != NULL) {
cjson_cbor_stream_decode(item, callbacks, context);
item = item->next;
}
return;
}
case cJSON_Object: {
callbacks->map_start(context, cJSON_GetArraySize(source));
cJSON *item = source->child;
while (item != NULL) {
callbacks->string(context, (unsigned char *)item->string,
strlen(item->string));
cjson_cbor_stream_decode(item, callbacks, context);
item = item->next;
}
return;
}
}
}
void usage() {
printf("Usage: cjson [input JSON file]\n");
exit(1);
}
int main(int argc, char *argv[]) {
if (argc != 2) usage();
FILE *f = fopen(argv[1], "rb");
if (f == NULL) usage();
/* Read input file into a buffer (cJSON doesn't work with streams) */
fseek(f, 0, SEEK_END);
size_t length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
char *json_buffer = malloc(length + 1);
fread(json_buffer, length, 1, f);
json_buffer[length] = '\0';
/* Convert between JSON and CBOR */
cJSON *json = cJSON_Parse(json_buffer);
cbor_item_t *cbor = cjson_cbor_load(json, cjson_cbor_stream_decode);
/* Print out CBOR bytes */
unsigned char *buffer;
size_t buffer_size,
cbor_length = cbor_serialize_alloc(cbor, &buffer, &buffer_size);
fwrite(buffer, 1, cbor_length, stdout);
free(buffer);
fflush(stdout);
cJSON_Delete(json);
cbor_decref(&cbor);
}

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include "cbor.h"
int main(int argc, char* argv[]) {
/* Preallocate the map structure */
cbor_item_t* root = cbor_new_definite_map(2);
/* Add the content */
cbor_map_add(root,
(struct cbor_pair){
.key = cbor_move(cbor_build_string("Is CBOR awesome?")),
.value = cbor_move(cbor_build_bool(true))});
cbor_map_add(root,
(struct cbor_pair){
.key = cbor_move(cbor_build_uint8(42)),
.value = cbor_move(cbor_build_string("Is the answer"))});
/* Output: `length` bytes of data in the `buffer` */
unsigned char* buffer;
size_t buffer_size,
length = cbor_serialize_alloc(root, &buffer, &buffer_size);
fwrite(buffer, 1, length, stdout);
free(buffer);
fflush(stdout);
cbor_decref(&root);
}

Binary file not shown.

View File

@ -0,0 +1 @@
eHellofworld!ÿ

View File

@ -0,0 +1 @@
*

View File

@ -0,0 +1,6 @@
{
"a": [1, 2.2, -1, "žluťoučký kůň!!!"],
"b": {
"c": [true, false, null]
}
}

Binary file not shown.

View File

@ -0,0 +1 @@
<EFBFBD><02><03><05>

View File

@ -0,0 +1 @@
Àt2013-03-21T20:04:00Z

View File

@ -0,0 +1,16 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include "cbor.h"
int main(int argc, char* argv[]) {
printf("Hello from libcbor %s\n", CBOR_VERSION);
printf("Custom allocation support: %s\n", CBOR_CUSTOM_ALLOC ? "yes" : "no");
printf("Pretty-printer support: %s\n", CBOR_PRETTY_PRINTER ? "yes" : "no");
printf("Buffer growth factor: %f\n", (float)CBOR_BUFFER_GROWTH);
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include "cbor.h"
void usage() {
printf("Usage: readfile [input file]\n");
exit(1);
}
/*
* Reads data from a file. Example usage:
* $ ./examples/readfile examples/data/nested_array.cbor
*/
int main(int argc, char* argv[]) {
if (argc != 2) usage();
FILE* f = fopen(argv[1], "rb");
if (f == NULL) usage();
fseek(f, 0, SEEK_END);
size_t length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char* buffer = malloc(length);
fread(buffer, length, 1, f);
/* Assuming `buffer` contains `length` bytes of input data */
struct cbor_load_result result;
cbor_item_t* item = cbor_load(buffer, length, &result);
if (result.error.code != CBOR_ERR_NONE) {
printf(
"There was an error while reading the input near byte %zu (read %zu "
"bytes in total): ",
result.error.position, result.read);
switch (result.error.code) {
case CBOR_ERR_MALFORMATED: {
printf("Malformed data\n");
break;
}
case CBOR_ERR_MEMERROR: {
printf("Memory error -- perhaps the input is too large?\n");
break;
}
case CBOR_ERR_NODATA: {
printf("The input is empty\n");
break;
}
case CBOR_ERR_NOTENOUGHDATA: {
printf("Data seem to be missing -- is the input complete?\n");
break;
}
case CBOR_ERR_SYNTAXERROR: {
printf(
"Syntactically malformed data -- see "
"http://tools.ietf.org/html/rfc7049\n");
break;
}
case CBOR_ERR_NONE: {
// GCC's cheap dataflow analysis gag
break;
}
}
exit(1);
}
/* Pretty-print the result */
cbor_describe(item, stdout);
fflush(stdout);
/* Deallocate the result */
cbor_decref(&item);
fclose(f);
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include "cbor.h"
/*
* Illustrates how to use the contiguous storage of nested items with
* standard library functions.
*/
int comparUint(const void *a, const void *b) {
uint8_t av = cbor_get_uint8(*(cbor_item_t **)a),
bv = cbor_get_uint8(*(cbor_item_t **)b);
if (av < bv)
return -1;
else if (av == bv)
return 0;
else
return 1;
}
int main(int argc, char *argv[]) {
cbor_item_t *array = cbor_new_definite_array(4);
cbor_array_push(array, cbor_move(cbor_build_uint8(4)));
cbor_array_push(array, cbor_move(cbor_build_uint8(3)));
cbor_array_push(array, cbor_move(cbor_build_uint8(1)));
cbor_array_push(array, cbor_move(cbor_build_uint8(2)));
qsort(cbor_array_handle(array), cbor_array_size(array), sizeof(cbor_item_t *),
comparUint);
cbor_describe(array, stdout);
fflush(stdout);
}

View File

@ -0,0 +1,58 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include <string.h>
#include "cbor.h"
void usage() {
printf("Usage: streaming_parser [input file]\n");
exit(1);
}
/*
* Illustrates how one might skim through a map (which is assumed to have
* string keys and values only), looking for the value of a specific key
*
* Use the examples/data/map.cbor input to test this.
*/
const char* key = "a secret key";
bool key_found = false;
void find_string(void* _ctx, cbor_data buffer, size_t len) {
if (key_found) {
printf("Found the value: %.*s\n", (int)len, buffer);
key_found = false;
} else if (len == strlen(key)) {
key_found = (memcmp(key, buffer, len) == 0);
}
}
int main(int argc, char* argv[]) {
if (argc != 2) usage();
FILE* f = fopen(argv[1], "rb");
if (f == NULL) usage();
fseek(f, 0, SEEK_END);
size_t length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char* buffer = malloc(length);
fread(buffer, length, 1, f);
struct cbor_callbacks callbacks = cbor_empty_callbacks;
struct cbor_decoder_result decode_result;
size_t bytes_read = 0;
callbacks.string = find_string;
while (bytes_read < length) {
decode_result = cbor_stream_decode(buffer + bytes_read, length - bytes_read,
&callbacks, NULL);
bytes_read += decode_result.read;
}
free(buffer);
fclose(f);
}

3
contrib/libcbor/misc/bytes.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
puts $*[0][2..-1].split('').each_slice(2).map {|_| '0x%02X' % _.join.to_i(16) }.join(', ')

View File

@ -0,0 +1,5 @@
#!/usr/bin/env ruby
lst = (ARGV.empty? ? STDIN.read : IO.binread(ARGV[0])).bytes.map {|_| '0x%02X' % _ }
puts lst.size
puts lst.join(', ')

View File

@ -0,0 +1,18 @@
#!/bin/sh
set -e
# Run clang-format and add modified files
MODIFIED_UNSTAGED=$(git -C . diff --name-only)
MODIFIED_STAGED=$(git -C . diff --name-only --cached --diff-filter=d)
./clang-format.sh
git add ${MODIFIED_STAGED}
if [[ ${MODIFIED_UNSTAGED} != $(git -C . diff --name-only) ]]; then
echo "WARNING: Non-staged files were reformatted. Please review and/or add" \
"them"
fi

3
contrib/libcbor/misc/repeat.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
(Integer($*[0])..Integer($*[1])).each {|i| puts "case 0x%02X:" % i}

3
contrib/libcbor/misc/seq.rb Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env ruby
Integer($*[0]).times {|i| print "0x%02X, " % ((Integer($*[1]) + i) % 0xFF) }

View File

@ -0,0 +1,38 @@
import sys, re
from datetime import date
version = sys.argv[1]
release_date = date.today().strftime('%Y-%m-%d')
major, minor, patch = version.split('.')
def replace(file_path, pattern, replacement):
updated = re.sub(pattern, replacement, open(file_path).read())
with open(file_path, 'w') as f:
f.write(updated)
# Update changelog
SEP = '---------------------'
NEXT = f'Next\n{SEP}'
changelog_header = f'{NEXT}\n\n{version} ({release_date})\n{SEP}'
replace('CHANGELOG.md', NEXT, changelog_header)
# Update Doxyfile
DOXY_VERSION = 'PROJECT_NUMBER = '
replace('Doxyfile', DOXY_VERSION + '.*', DOXY_VERSION + version)
# Update CMakeLists.txt
replace('CMakeLists.txt',
'''SET\\(CBOR_VERSION_MAJOR "0"\\)
SET\\(CBOR_VERSION_MINOR "7"\\)
SET\\(CBOR_VERSION_PATCH "0"\\)''',
f'''SET(CBOR_VERSION_MAJOR "{major}")
SET(CBOR_VERSION_MINOR "{minor}")
SET(CBOR_VERSION_PATCH "{patch}")''')
# Update Sphinx
replace('doc/source/conf.py',
"""version = '.*'
release = '.*'""",
f"""version = '{major}.{minor}'
release = '{major}.{minor}.{patch}'""")

View File

@ -0,0 +1,28 @@
#!/bin/bash -eu
# Copyright 2019 Google Inc.
#
# 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.
#
################################################################################
mkdir build
cd build
# We disable libcbor's default sanitizers since we'll be configuring them ourselves via CFLAGS.
cmake -D CMAKE_BUILD_TYPE=Debug -D CMAKE_INSTALL_PREFIX="$WORK" -D CBOR_CUSTOM_ALLOC=ON -D SANITIZE=OFF ..
make "-j$(nproc)"
make install
$CXX $CXXFLAGS -std=c++11 "-I$WORK/include" \
../oss-fuzz/cbor_load_fuzzer.cc -o "$OUT/cbor_load_fuzzer" \
$LIB_FUZZING_ENGINE src/libcbor.a

View File

@ -0,0 +1,37 @@
#include <cstdint>
#include <cstdio>
#include "cbor.h"
void *limited_malloc(size_t size) {
if (size > 1 << 24) {
return nullptr;
}
return malloc(size);
}
struct State {
FILE* fout;
State() : fout(fopen("/dev/null", "r")) {
cbor_set_allocs(limited_malloc, realloc, free);
}
};
static State kState;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
cbor_load_result result;
cbor_item_t *item = cbor_load(Data, Size, &result);
if (result.error.code == CBOR_ERR_NONE) {
cbor_describe(item, kState.fout);
unsigned char *buffer;
size_t buffer_size;
cbor_serialize_alloc(item, &buffer, &buffer_size);
free(buffer);
cbor_item_t *copied = cbor_copy(item);
cbor_decref(&copied);
cbor_decref(&item);
}
return 0;
}

75
contrib/libcbor/release.sh Executable file
View File

@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Guides my forgetful self through the release process.
# Usage release.sh VERSION
set -e
function prompt() {
echo "$1 Confirm with 'Yes'"
read check
if [ "$check" != "Yes" ]; then
echo "Aborting..."
exit 1
fi
}
# http://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUTDIR=$(mktemp -d)
TAG_NAME="v$1"
cd $DIR
python3 misc/update_version.py "$1"
echo ">>>>> Checking changelog"
grep -A 5 -F "$1" CHANGELOG.md || true
prompt "Is the changelog correct and complete?"
echo ">>>>> Checking Doxyfile"
grep PROJECT_NUMBER Doxyfile
prompt "Is the Doxyfile version correct?"
echo ">>>>> Checking CMakeLists"
grep -A 2 'SET(CBOR_VERSION_MAJOR' CMakeLists.txt
prompt "Is the CMake version correct?"
echo ">>>>> Checking docs"
grep 'version =\|release =' doc/source/conf.py
prompt "Are the versions correct?"
set -x
pushd doc
make clean
popd
doxygen
cd doc
make html
cd build
cp -r html libcbor_docs_html
tar -zcf libcbor_docs.tar.gz libcbor_docs_html
cp -r doxygen/html libcbor_api_docs_html
tar -zcf libcbor_api_docs.tar.gz libcbor_api_docs_html
mv libcbor_docs.tar.gz libcbor_api_docs.tar.gz "$OUTDIR"
pushd "$OUTDIR"
cmake "$DIR" -DCMAKE_BUILD_TYPE=Release -DWITH_TESTS=ON
make
ctest
popd
prompt "Will proceed to tag the release with $TAG_NAME."
git tag "$TAG_NAME"
git push --tags
set +x
echo "Release ready in $OUTDIR"
echo "Add the release to GitHub at https://github.com/PJK/libcbor/releases/new *now*"
prompt "Have you added the release to https://github.com/PJK/libcbor/releases/tag/$TAG_NAME?"
echo "Update the Hombrew formula (https://github.com/Homebrew/homebrew-core/blob/master/Formula/libcbor.rb) *now*"
echo "HOWTO: https://github.com/Linuxbrew/brew/blob/master/docs/How-To-Open-a-Homebrew-Pull-Request.md"
prompt "Have you updated the formula?"

View File

@ -0,0 +1,45 @@
set(SOURCES cbor.c cbor/streaming.c cbor/internal/encoders.c cbor/internal/builder_callbacks.c cbor/internal/loaders.c cbor/internal/memory_utils.c cbor/internal/stack.c cbor/internal/unicode.c cbor/encoding.c cbor/serialization.c cbor/arrays.c cbor/common.c cbor/floats_ctrls.c cbor/bytestrings.c cbor/callbacks.c cbor/strings.c cbor/maps.c cbor/tags.c cbor/ints.c)
include(GNUInstallDirs)
set(CMAKE_SKIP_BUILD_RPATH FALSE)
if (CBOR_CUSTOM_ALLOC)
LIST(APPEND SOURCES allocators.c)
endif(CBOR_CUSTOM_ALLOC)
if (NOT DEFINED CMAKE_MACOSX_RPATH)
set(CMAKE_MACOSX_RPATH 0)
endif()
add_library(cbor ${SOURCES})
target_include_directories(cbor PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
include(GenerateExportHeader)
generate_export_header(cbor EXPORT_FILE_NAME ${CMAKE_CURRENT_BINARY_DIR}/cbor/cbor_export.h)
target_include_directories(cbor PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cbor/cbor_export.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/cbor)
if (NOT ${CBOR_VERSION_MAJOR} EQUAL 0)
MESSAGE(FATAL_ERROR "Change the shared library version scheme to reflect https://github.com/PJK/libcbor/issues/52.")
endif()
set_target_properties(cbor PROPERTIES
VERSION ${CBOR_VERSION}
MACHO_COMPATIBILITY_VERSION ${CBOR_VERSION_MAJOR}.${CBOR_VERSION_MINOR}.0
SOVERSION ${CBOR_VERSION_MAJOR}.${CBOR_VERSION_MINOR})
configure_file(libcbor.pc.in libcbor.pc @ONLY)
# http://www.cmake.org/Wiki/CMake:Install_Commands
install(TARGETS cbor
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY cbor DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
FILES_MATCHING PATTERN "*.h")
install(FILES cbor.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libcbor.pc"
DESTINATION "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}/pkgconfig")

View File

@ -0,0 +1,19 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "cbor/common.h"
CBOR_EXPORT _cbor_malloc_t _cbor_malloc = malloc;
CBOR_EXPORT _cbor_realloc_t _cbor_realloc = realloc;
CBOR_EXPORT _cbor_free_t _cbor_free = free;
void cbor_set_allocs(_cbor_malloc_t custom_malloc,
_cbor_realloc_t custom_realloc, _cbor_free_t custom_free) {
_cbor_malloc = custom_malloc;
_cbor_realloc = custom_realloc;
_cbor_free = custom_free;
}

345
contrib/libcbor/src/cbor.c Normal file
View File

@ -0,0 +1,345 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "cbor.h"
#include "cbor/internal/builder_callbacks.h"
#include "cbor/internal/loaders.h"
cbor_item_t *cbor_load(cbor_data source, size_t source_size,
struct cbor_load_result *result) {
/* Context stack */
static struct cbor_callbacks callbacks = {
.uint8 = &cbor_builder_uint8_callback,
.uint16 = &cbor_builder_uint16_callback,
.uint32 = &cbor_builder_uint32_callback,
.uint64 = &cbor_builder_uint64_callback,
.negint8 = &cbor_builder_negint8_callback,
.negint16 = &cbor_builder_negint16_callback,
.negint32 = &cbor_builder_negint32_callback,
.negint64 = &cbor_builder_negint64_callback,
.byte_string = &cbor_builder_byte_string_callback,
.byte_string_start = &cbor_builder_byte_string_start_callback,
.string = &cbor_builder_string_callback,
.string_start = &cbor_builder_string_start_callback,
.array_start = &cbor_builder_array_start_callback,
.indef_array_start = &cbor_builder_indef_array_start_callback,
.map_start = &cbor_builder_map_start_callback,
.indef_map_start = &cbor_builder_indef_map_start_callback,
.tag = &cbor_builder_tag_callback,
.null = &cbor_builder_null_callback,
.undefined = &cbor_builder_undefined_callback,
.boolean = &cbor_builder_boolean_callback,
.float2 = &cbor_builder_float2_callback,
.float4 = &cbor_builder_float4_callback,
.float8 = &cbor_builder_float8_callback,
.indef_break = &cbor_builder_indef_break_callback};
if (source_size == 0) {
result->error.code = CBOR_ERR_NODATA;
return NULL;
}
struct _cbor_stack stack = _cbor_stack_init();
/* Target for callbacks */
struct _cbor_decoder_context context = (struct _cbor_decoder_context){
.stack = &stack, .creation_failed = false, .syntax_error = false};
struct cbor_decoder_result decode_result;
*result =
(struct cbor_load_result){.read = 0, .error = {.code = CBOR_ERR_NONE}};
do {
if (source_size > result->read) { /* Check for overflows */
decode_result =
cbor_stream_decode(source + result->read, source_size - result->read,
&callbacks, &context);
} else {
result->error = (struct cbor_error){.code = CBOR_ERR_NOTENOUGHDATA,
.position = result->read};
goto error;
}
switch (decode_result.status) {
case CBOR_DECODER_FINISHED:
/* Everything OK */
{
result->read += decode_result.read;
break;
}
case CBOR_DECODER_NEDATA:
/* Data length doesn't match MTB expectation */
{
result->error.code = CBOR_ERR_NOTENOUGHDATA;
goto error;
}
case CBOR_DECODER_ERROR:
/* Reserved/malformated item */
{
result->error.code = CBOR_ERR_MALFORMATED;
goto error;
}
}
if (context.creation_failed) {
/* Most likely unsuccessful allocation - our callback has failed */
result->error.code = CBOR_ERR_MEMERROR;
goto error;
} else if (context.syntax_error) {
result->error.code = CBOR_ERR_SYNTAXERROR;
goto error;
}
} while (stack.size > 0);
/* Move the result before free */
cbor_item_t *result_item = context.root;
return result_item;
error:
result->error.position = result->read;
// debug_print("Failed with decoder error %d at %d\n", result->error.code,
// result->error.position); cbor_describe(stack.top->item, stdout);
/* Free the stack */
while (stack.size > 0) {
cbor_decref(&stack.top->item);
_cbor_stack_pop(&stack);
}
return NULL;
}
static cbor_item_t *_cbor_copy_int(cbor_item_t *item, bool negative) {
cbor_item_t *res;
switch (cbor_int_get_width(item)) {
case CBOR_INT_8:
res = cbor_build_uint8(cbor_get_uint8(item));
break;
case CBOR_INT_16:
res = cbor_build_uint16(cbor_get_uint16(item));
break;
case CBOR_INT_32:
res = cbor_build_uint32(cbor_get_uint32(item));
break;
case CBOR_INT_64:
res = cbor_build_uint64(cbor_get_uint64(item));
break;
default:
return NULL;
}
if (negative) cbor_mark_negint(res);
return res;
}
static cbor_item_t *_cbor_copy_float_ctrl(cbor_item_t *item) {
switch (cbor_float_get_width(item)) {
case CBOR_FLOAT_0:
return cbor_build_ctrl(cbor_ctrl_value(item));
case CBOR_FLOAT_16:
return cbor_build_float2(cbor_float_get_float2(item));
case CBOR_FLOAT_32:
return cbor_build_float4(cbor_float_get_float4(item));
case CBOR_FLOAT_64:
return cbor_build_float8(cbor_float_get_float8(item));
}
return NULL;
}
cbor_item_t *cbor_copy(cbor_item_t *item) {
switch (cbor_typeof(item)) {
case CBOR_TYPE_UINT:
return _cbor_copy_int(item, false);
case CBOR_TYPE_NEGINT:
return _cbor_copy_int(item, true);
case CBOR_TYPE_BYTESTRING:
if (cbor_bytestring_is_definite(item)) {
return cbor_build_bytestring(cbor_bytestring_handle(item),
cbor_bytestring_length(item));
} else {
cbor_item_t *res = cbor_new_indefinite_bytestring();
for (size_t i = 0; i < cbor_bytestring_chunk_count(item); i++)
cbor_bytestring_add_chunk(
res,
cbor_move(cbor_copy(cbor_bytestring_chunks_handle(item)[i])));
return res;
}
case CBOR_TYPE_STRING:
if (cbor_string_is_definite(item)) {
return cbor_build_stringn((const char *)cbor_string_handle(item),
cbor_string_length(item));
} else {
cbor_item_t *res = cbor_new_indefinite_string();
for (size_t i = 0; i < cbor_string_chunk_count(item); i++)
cbor_string_add_chunk(
res, cbor_move(cbor_copy(cbor_string_chunks_handle(item)[i])));
return res;
}
case CBOR_TYPE_ARRAY: {
cbor_item_t *res;
if (cbor_array_is_definite(item))
res = cbor_new_definite_array(cbor_array_size(item));
else
res = cbor_new_indefinite_array();
for (size_t i = 0; i < cbor_array_size(item); i++)
cbor_array_push(
res, cbor_move(cbor_copy(cbor_move(cbor_array_get(item, i)))));
return res;
}
case CBOR_TYPE_MAP: {
cbor_item_t *res;
if (cbor_map_is_definite(item))
res = cbor_new_definite_map(cbor_map_size(item));
else
res = cbor_new_indefinite_map();
struct cbor_pair *it = cbor_map_handle(item);
for (size_t i = 0; i < cbor_map_size(item); i++)
cbor_map_add(res, (struct cbor_pair){
.key = cbor_move(cbor_copy(it[i].key)),
.value = cbor_move(cbor_copy(it[i].value))});
return res;
}
case CBOR_TYPE_TAG:
return cbor_build_tag(
cbor_tag_value(item),
cbor_move(cbor_copy(cbor_move(cbor_tag_item(item)))));
case CBOR_TYPE_FLOAT_CTRL:
return _cbor_copy_float_ctrl(item);
}
return NULL;
}
#if CBOR_PRETTY_PRINTER
#include <inttypes.h>
#include <locale.h>
#include <stdlib.h>
#include <wchar.h>
#define __STDC_FORMAT_MACROS
static int _pow(int b, int ex) {
if (ex == 0) return 1;
int res = b;
while (--ex > 0) res *= b;
return res;
}
static void _cbor_nested_describe(cbor_item_t *item, FILE *out, int indent) {
setlocale(LC_ALL, "");
switch (cbor_typeof(item)) {
case CBOR_TYPE_UINT: {
fprintf(out, "%*s[CBOR_TYPE_UINT] ", indent, " ");
fprintf(out, "Width: %dB, ", _pow(2, cbor_int_get_width(item)));
fprintf(out, "Value: %" PRIu64 "\n", cbor_get_int(item));
break;
};
case CBOR_TYPE_NEGINT: {
fprintf(out, "%*s[CBOR_TYPE_NEGINT] ", indent, " ");
fprintf(out, "Width: %dB, ", _pow(2, cbor_int_get_width(item)));
fprintf(out, "Value: -%" PRIu64 " -1\n", cbor_get_int(item));
break;
};
case CBOR_TYPE_BYTESTRING: {
fprintf(out, "%*s[CBOR_TYPE_BYTESTRING] ", indent, " ");
if (cbor_bytestring_is_indefinite(item)) {
fprintf(out, "Indefinite, with %zu chunks:\n",
cbor_bytestring_chunk_count(item));
for (size_t i = 0; i < cbor_bytestring_chunk_count(item); i++)
_cbor_nested_describe(cbor_bytestring_chunks_handle(item)[i], out,
indent + 4);
} else {
fprintf(out, "Definite, length %zuB\n", cbor_bytestring_length(item));
}
break;
};
case CBOR_TYPE_STRING: {
fprintf(out, "%*s[CBOR_TYPE_STRING] ", indent, " ");
if (cbor_string_is_indefinite(item)) {
fprintf(out, "Indefinite, with %zu chunks:\n",
cbor_string_chunk_count(item));
for (size_t i = 0; i < cbor_string_chunk_count(item); i++)
_cbor_nested_describe(cbor_string_chunks_handle(item)[i], out,
indent + 4);
} else {
fprintf(out, "Definite, length %zuB, %zu codepoints\n",
cbor_string_length(item), cbor_string_codepoint_count(item));
/* Careful - this doesn't support multibyte characters! */
/* Printing those is out of the scope of this demo :) */
/* libICU is your friend */
fprintf(out, "%*s", indent + 4, " ");
/* XXX: no null at the end -> confused vprintf */
fwrite(cbor_string_handle(item), (int)cbor_string_length(item), 1, out);
fprintf(out, "\n");
}
break;
};
case CBOR_TYPE_ARRAY: {
fprintf(out, "%*s[CBOR_TYPE_ARRAY] ", indent, " ");
if (cbor_array_is_definite(item)) {
fprintf(out, "Definite, size: %zu\n", cbor_array_size(item));
} else {
fprintf(out, "Indefinite, size: %zu\n", cbor_array_size(item));
}
for (size_t i = 0; i < cbor_array_size(item); i++)
_cbor_nested_describe(cbor_array_handle(item)[i], out, indent + 4);
break;
};
case CBOR_TYPE_MAP: {
fprintf(out, "%*s[CBOR_TYPE_MAP] ", indent, " ");
if (cbor_map_is_definite(item)) {
fprintf(out, "Definite, size: %zu\n", cbor_map_size(item));
} else {
fprintf(out, "Indefinite, size: %zu\n", cbor_map_size(item));
}
for (size_t i = 0; i < cbor_map_size(item); i++) {
_cbor_nested_describe(cbor_map_handle(item)[i].key, out, indent + 4);
_cbor_nested_describe(cbor_map_handle(item)[i].value, out, indent + 4);
}
break;
};
case CBOR_TYPE_TAG: {
fprintf(out, "%*s[CBOR_TYPE_TAG] ", indent, " ");
fprintf(out, "Value: %" PRIu64 "\n", cbor_tag_value(item));
_cbor_nested_describe(cbor_move(cbor_tag_item(item)), out, indent + 4);
break;
};
case CBOR_TYPE_FLOAT_CTRL: {
fprintf(out, "%*s[CBOR_TYPE_FLOAT_CTRL] ", indent, " ");
if (cbor_float_ctrl_is_ctrl(item)) {
if (cbor_is_bool(item))
fprintf(out, "Bool: %s\n", cbor_get_bool(item) ? "true" : "false");
else if (cbor_is_undef(item))
fprintf(out, "Undefined\n");
else if (cbor_is_null(item))
fprintf(out, "Null\n");
else
fprintf(out, "Simple value %d\n", cbor_ctrl_value(item));
} else {
fprintf(out, "Width: %dB, ", _pow(2, cbor_float_get_width(item)));
fprintf(out, "value: %lf\n", cbor_float_get_float(item));
}
break;
};
}
}
void cbor_describe(cbor_item_t *item, FILE *out) {
_cbor_nested_describe(item, out, 0);
}
#endif

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_H_
#define LIBCBOR_H_
#include "cbor/common.h"
#include "cbor/data.h"
#include "cbor/arrays.h"
#include "cbor/bytestrings.h"
#include "cbor/floats_ctrls.h"
#include "cbor/ints.h"
#include "cbor/maps.h"
#include "cbor/strings.h"
#include "cbor/tags.h"
#include "cbor/callbacks.h"
#include "cbor/cbor_export.h"
#include "cbor/encoding.h"
#include "cbor/serialization.h"
#include "cbor/streaming.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* ============================================================================
* High level decoding
* ============================================================================
*/
/** Loads data item from a buffer
*
* @param source The buffer
* @param source_size
* @param result[out] Result indicator. #CBOR_ERR_NONE on success
* @return **new** CBOR item or `NULL` on failure. In that case, \p result
* contains location and description of the error.
*/
CBOR_EXPORT cbor_item_t* cbor_load(cbor_data source, size_t source_size,
struct cbor_load_result* result);
/** Deep copy of an item
*
* All the reference counts in the new structure are set to one.
*
* @param item[borrow] item to copy
* @return **new** CBOR deep copy
*/
CBOR_EXPORT cbor_item_t* cbor_copy(cbor_item_t* item);
#if CBOR_PRETTY_PRINTER
#include <stdio.h>
CBOR_EXPORT void cbor_describe(cbor_item_t* item, FILE* out);
#endif
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_H_

View File

@ -0,0 +1,135 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "arrays.h"
#include <string.h>
#include "internal/memory_utils.h"
size_t cbor_array_size(const cbor_item_t *item) {
assert(cbor_isa_array(item));
return item->metadata.array_metadata.end_ptr;
}
size_t cbor_array_allocated(const cbor_item_t *item) {
assert(cbor_isa_array(item));
return item->metadata.array_metadata.allocated;
}
cbor_item_t *cbor_array_get(const cbor_item_t *item, size_t index) {
return cbor_incref(((cbor_item_t **)item->data)[index]);
}
bool cbor_array_set(cbor_item_t *item, size_t index, cbor_item_t *value) {
if (index == item->metadata.array_metadata.end_ptr) {
return cbor_array_push(item, value);
} else if (index < item->metadata.array_metadata.end_ptr) {
return cbor_array_replace(item, index, value);
} else {
return false;
}
// TODO: This is unreachable and the index checking logic above seems
// suspicious -- out of bounds index is a caller error. Figure out & fix.
return true;
}
bool cbor_array_replace(cbor_item_t *item, size_t index, cbor_item_t *value) {
if (index >= item->metadata.array_metadata.end_ptr) return false;
/* We cannot use cbor_array_get as that would increase the refcount */
cbor_intermediate_decref(((cbor_item_t **)item->data)[index]);
((cbor_item_t **)item->data)[index] = cbor_incref(value);
return true;
}
bool cbor_array_push(cbor_item_t *array, cbor_item_t *pushee) {
assert(cbor_isa_array(array));
struct _cbor_array_metadata *metadata =
(struct _cbor_array_metadata *)&array->metadata;
cbor_item_t **data = (cbor_item_t **)array->data;
if (cbor_array_is_definite(array)) {
/* Do not reallocate definite arrays */
if (metadata->end_ptr >= metadata->allocated) {
return false;
}
data[metadata->end_ptr++] = pushee;
} else {
/* Exponential realloc */
if (metadata->end_ptr >= metadata->allocated) {
// Check for overflows first
// TODO: Explicitly test this
if (!_cbor_safe_to_multiply(CBOR_BUFFER_GROWTH, metadata->allocated)) {
return false;
}
size_t new_allocation = metadata->allocated == 0
? 1
: CBOR_BUFFER_GROWTH * metadata->allocated;
unsigned char *new_data = _cbor_realloc_multiple(
array->data, sizeof(cbor_item_t *), new_allocation);
if (new_data == NULL) {
return false;
}
array->data = new_data;
metadata->allocated = new_allocation;
}
((cbor_item_t **)array->data)[metadata->end_ptr++] = pushee;
}
cbor_incref(pushee);
return true;
}
bool cbor_array_is_definite(const cbor_item_t *item) {
assert(cbor_isa_array(item));
return item->metadata.array_metadata.type == _CBOR_METADATA_DEFINITE;
}
bool cbor_array_is_indefinite(const cbor_item_t *item) {
assert(cbor_isa_array(item));
return item->metadata.array_metadata.type == _CBOR_METADATA_INDEFINITE;
}
cbor_item_t **cbor_array_handle(const cbor_item_t *item) {
assert(cbor_isa_array(item));
return (cbor_item_t **)item->data;
}
cbor_item_t *cbor_new_definite_array(size_t size) {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t));
_CBOR_NOTNULL(item);
cbor_item_t **data = _cbor_alloc_multiple(sizeof(cbor_item_t *), size);
_CBOR_DEPENDENT_NOTNULL(item, data);
for (size_t i = 0; i < size; i++) {
data[i] = NULL;
}
*item = (cbor_item_t){
.refcount = 1,
.type = CBOR_TYPE_ARRAY,
.metadata = {.array_metadata = {.type = _CBOR_METADATA_DEFINITE,
.allocated = size,
.end_ptr = 0}},
.data = (unsigned char *)data};
return item;
}
cbor_item_t *cbor_new_indefinite_array() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t));
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.refcount = 1,
.type = CBOR_TYPE_ARRAY,
.metadata = {.array_metadata = {.type = _CBOR_METADATA_INDEFINITE,
.allocated = 0,
.end_ptr = 0}},
.data = NULL /* Can be safely realloc-ed */
};
return item;
}

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_ARRAYS_H
#define LIBCBOR_ARRAYS_H
#include "cbor/cbor_export.h"
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Get the number of members
*
* @param item[borrow] An array
* @return The number of members
*/
CBOR_EXPORT size_t cbor_array_size(const cbor_item_t* item);
/** Get the size of the allocated storage
*
* @param item[borrow] An array
* @return The size of the allocated storage (number of items)
*/
CBOR_EXPORT size_t cbor_array_allocated(const cbor_item_t* item);
/** Get item by index
*
* @param item[borrow] An array
* @param index The index
* @return **incref** The item, or `NULL` in case of boundary violation
*/
CBOR_EXPORT cbor_item_t* cbor_array_get(const cbor_item_t* item, size_t index);
/** Set item by index
*
* Creating arrays with holes is not possible
*
* @param item[borrow] An array
* @param value[incref] The item to assign
* @param index The index, first item is 0.
* @return true on success, false on allocation failure.
*/
CBOR_EXPORT bool cbor_array_set(cbor_item_t* item, size_t index,
cbor_item_t* value);
/** Replace item at an index
*
* The item being replace will be #cbor_decref 'ed.
*
* @param item[borrow] An array
* @param value[incref] The item to assign
* @param index The index, first item is 0.
* @return true on success, false on allocation failure.
*/
CBOR_EXPORT bool cbor_array_replace(cbor_item_t* item, size_t index,
cbor_item_t* value);
/** Is the array definite?
*
* @param item[borrow] An array
* @return Is the array definite?
*/
CBOR_EXPORT bool cbor_array_is_definite(const cbor_item_t* item);
/** Is the array indefinite?
*
* @param item[borrow] An array
* @return Is the array indefinite?
*/
CBOR_EXPORT bool cbor_array_is_indefinite(const cbor_item_t* item);
/** Get the array contents
*
* The items may be reordered and modified as long as references remain
* consistent.
*
* @param item[borrow] An array
* @return #cbor_array_size items
*/
CBOR_EXPORT cbor_item_t** cbor_array_handle(const cbor_item_t* item);
/** Create new definite array
*
* @param size Number of slots to preallocate
* @return **new** array or `NULL` upon malloc failure
*/
CBOR_EXPORT cbor_item_t* cbor_new_definite_array(size_t size);
/** Create new indefinite array
*
* @return **new** array or `NULL` upon malloc failure
*/
CBOR_EXPORT cbor_item_t* cbor_new_indefinite_array();
/** Append to the end
*
* For indefinite items, storage may be realloacted. For definite items, only
* the preallocated capacity is available.
*
* @param array[borrow] An array
* @param pushee[incref] The item to push
* @return true on success, false on failure
*/
CBOR_EXPORT bool cbor_array_push(cbor_item_t* array, cbor_item_t* pushee);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_ARRAYS_H

View File

@ -0,0 +1,117 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "bytestrings.h"
#include <string.h>
#include "internal/memory_utils.h"
size_t cbor_bytestring_length(const cbor_item_t *item) {
assert(cbor_isa_bytestring(item));
return item->metadata.bytestring_metadata.length;
}
unsigned char *cbor_bytestring_handle(const cbor_item_t *item) {
assert(cbor_isa_bytestring(item));
return item->data;
}
bool cbor_bytestring_is_definite(const cbor_item_t *item) {
assert(cbor_isa_bytestring(item));
return item->metadata.bytestring_metadata.type == _CBOR_METADATA_DEFINITE;
}
bool cbor_bytestring_is_indefinite(const cbor_item_t *item) {
return !cbor_bytestring_is_definite(item);
}
cbor_item_t *cbor_new_definite_bytestring() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t));
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.refcount = 1,
.type = CBOR_TYPE_BYTESTRING,
.metadata = {.bytestring_metadata = {_CBOR_METADATA_DEFINITE, 0}}};
return item;
}
cbor_item_t *cbor_new_indefinite_bytestring() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t));
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.refcount = 1,
.type = CBOR_TYPE_BYTESTRING,
.metadata = {.bytestring_metadata = {.type = _CBOR_METADATA_INDEFINITE,
.length = 0}},
.data = _CBOR_MALLOC(sizeof(struct cbor_indefinite_string_data))};
_CBOR_DEPENDENT_NOTNULL(item, item->data);
*((struct cbor_indefinite_string_data *)item->data) =
(struct cbor_indefinite_string_data){
.chunk_count = 0,
.chunk_capacity = 0,
.chunks = NULL,
};
return item;
}
cbor_item_t *cbor_build_bytestring(cbor_data handle, size_t length) {
cbor_item_t *item = cbor_new_definite_bytestring();
_CBOR_NOTNULL(item);
void *content = _CBOR_MALLOC(length);
_CBOR_DEPENDENT_NOTNULL(item, content);
memcpy(content, handle, length);
cbor_bytestring_set_handle(item, content, length);
return item;
}
void cbor_bytestring_set_handle(cbor_item_t *item,
cbor_mutable_data CBOR_RESTRICT_POINTER data,
size_t length) {
assert(cbor_isa_bytestring(item));
assert(cbor_bytestring_is_definite(item));
item->data = data;
item->metadata.bytestring_metadata.length = length;
}
cbor_item_t **cbor_bytestring_chunks_handle(const cbor_item_t *item) {
assert(cbor_isa_bytestring(item));
assert(cbor_bytestring_is_indefinite(item));
return ((struct cbor_indefinite_string_data *)item->data)->chunks;
}
size_t cbor_bytestring_chunk_count(const cbor_item_t *item) {
assert(cbor_isa_bytestring(item));
assert(cbor_bytestring_is_indefinite(item));
return ((struct cbor_indefinite_string_data *)item->data)->chunk_count;
}
bool cbor_bytestring_add_chunk(cbor_item_t *item, cbor_item_t *chunk) {
assert(cbor_isa_bytestring(item));
assert(cbor_bytestring_is_indefinite(item));
struct cbor_indefinite_string_data *data =
(struct cbor_indefinite_string_data *)item->data;
if (data->chunk_count == data->chunk_capacity) {
// TODO: Add a test for this
if (!_cbor_safe_to_multiply(CBOR_BUFFER_GROWTH, data->chunk_capacity)) {
return false;
}
size_t new_chunk_capacity =
data->chunk_capacity == 0 ? 1
: CBOR_BUFFER_GROWTH * (data->chunk_capacity);
cbor_item_t **new_chunks_data = _cbor_realloc_multiple(
data->chunks, sizeof(cbor_item_t *), new_chunk_capacity);
if (new_chunks_data == NULL) {
return false;
}
data->chunk_capacity = new_chunk_capacity;
data->chunks = new_chunks_data;
}
data->chunks[data->chunk_count++] = cbor_incref(chunk);
return true;
}

View File

@ -0,0 +1,132 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_BYTESTRINGS_H
#define LIBCBOR_BYTESTRINGS_H
#include "cbor/cbor_export.h"
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* ============================================================================
* Byte string manipulation
* ============================================================================
*/
/** Returns the length of the binary data
*
* For definite byte strings only
*
* @param item[borrow] a definite bytestring
* @return length of the binary data. Zero if no chunk has been attached yet
*/
CBOR_EXPORT size_t cbor_bytestring_length(const cbor_item_t *item);
/** Is the byte string definite?
*
* @param item[borrow] a byte string
* @return Is the byte string definite?
*/
CBOR_EXPORT bool cbor_bytestring_is_definite(const cbor_item_t *item);
/** Is the byte string indefinite?
*
* @param item[borrow] a byte string
* @return Is the byte string indefinite?
*/
CBOR_EXPORT bool cbor_bytestring_is_indefinite(const cbor_item_t *item);
/** Get the handle to the binary data
*
* Definite items only. Modifying the data is allowed. In that case, the caller
* takes responsibility for the effect on items this item might be a part of
*
* @param item[borrow] A definite byte string
* @return The address of the binary data. `NULL` if no data have been assigned
* yet.
*/
CBOR_EXPORT cbor_mutable_data cbor_bytestring_handle(const cbor_item_t *item);
/** Set the handle to the binary data
*
* @param item[borrow] A definite byte string
* @param data The memory block. The caller gives up the ownership of the block.
* libcbor will deallocate it when appropriate using its free function
* @param length Length of the data block
*/
CBOR_EXPORT void cbor_bytestring_set_handle(
cbor_item_t *item, cbor_mutable_data CBOR_RESTRICT_POINTER data,
size_t length);
/** Get the handle to the array of chunks
*
* Manipulations with the memory block (e.g. sorting it) are allowed, but the
* validity and the number of chunks must be retained.
*
* @param item[borrow] A indefinite byte string
* @return array of #cbor_bytestring_chunk_count definite bytestrings
*/
CBOR_EXPORT cbor_item_t **cbor_bytestring_chunks_handle(
const cbor_item_t *item);
/** Get the number of chunks this string consist of
*
* @param item[borrow] A indefinite bytestring
* @return The chunk count. 0 for freshly created items.
*/
CBOR_EXPORT size_t cbor_bytestring_chunk_count(const cbor_item_t *item);
/** Appends a chunk to the bytestring
*
* Indefinite byte strings only.
*
* May realloc the chunk storage.
*
* @param item[borrow] An indefinite byte string
* @param item[incref] A definite byte string
* @return true on success, false on realloc failure. In that case, the refcount
* of `chunk` is not increased and the `item` is left intact.
*/
CBOR_EXPORT bool cbor_bytestring_add_chunk(cbor_item_t *item,
cbor_item_t *chunk);
/** Creates a new definite byte string
*
* The handle is initialized to `NULL` and length to 0
*
* @return **new** definite bytestring. `NULL` on malloc failure.
*/
CBOR_EXPORT cbor_item_t *cbor_new_definite_bytestring();
/** Creates a new indefinite byte string
*
* The chunks array is initialized to `NULL` and chunkcount to 0
*
* @return **new** indefinite bytestring. `NULL` on malloc failure.
*/
CBOR_EXPORT cbor_item_t *cbor_new_indefinite_bytestring();
/** Creates a new byte string and initializes it
*
* The `handle` will be copied to a newly allocated block
*
* @param handle Block of binary data
* @param length Length of `data`
* @return A **new** byte string with content `handle`. `NULL` on malloc
* failure.
*/
CBOR_EXPORT cbor_item_t *cbor_build_bytestring(cbor_data handle, size_t length);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_BYTESTRINGS_H

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "callbacks.h"
#define CBOR_DUMMY_CALLBACK \
{}
void cbor_null_uint8_callback(void *_ctx, uint8_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_uint16_callback(void *_ctx,
uint16_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_uint32_callback(void *_ctx,
uint32_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_uint64_callback(void *_ctx,
uint64_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_negint8_callback(void *_ctx,
uint8_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_negint16_callback(void *_ctx,
uint16_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_negint32_callback(void *_ctx,
uint32_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_negint64_callback(void *_ctx,
uint64_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_string_callback(void *_ctx, cbor_data _val,
size_t _val2) CBOR_DUMMY_CALLBACK
void cbor_null_string_start_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_byte_string_callback(void *_ctx, cbor_data _val,
size_t _val2) CBOR_DUMMY_CALLBACK
void cbor_null_byte_string_start_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_array_start_callback(void *_ctx,
size_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_indef_array_start_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_map_start_callback(void *_ctx,
size_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_indef_map_start_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_tag_callback(void *_ctx, uint64_t _val) CBOR_DUMMY_CALLBACK
void cbor_null_float2_callback(void *_ctx, float _val) CBOR_DUMMY_CALLBACK
void cbor_null_float4_callback(void *_ctx, float _val) CBOR_DUMMY_CALLBACK
void cbor_null_float8_callback(void *_ctx, double _val) CBOR_DUMMY_CALLBACK
void cbor_null_null_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_undefined_callback(void *_ctx) CBOR_DUMMY_CALLBACK
void cbor_null_boolean_callback(void *_ctx, bool _val) CBOR_DUMMY_CALLBACK
void cbor_null_indef_break_callback(void *_ctx) CBOR_DUMMY_CALLBACK
CBOR_EXPORT const struct cbor_callbacks cbor_empty_callbacks = {
/* Type 0 - Unsigned integers */
.uint8 = cbor_null_uint8_callback,
.uint16 = cbor_null_uint16_callback,
.uint32 = cbor_null_uint32_callback,
.uint64 = cbor_null_uint64_callback,
/* Type 1 - Negative integers */
.negint8 = cbor_null_negint8_callback,
.negint16 = cbor_null_negint16_callback,
.negint32 = cbor_null_negint32_callback,
.negint64 = cbor_null_negint64_callback,
/* Type 2 - Byte strings */
.byte_string_start = cbor_null_byte_string_start_callback,
.byte_string = cbor_null_byte_string_callback,
/* Type 3 - Strings */
.string_start = cbor_null_string_start_callback,
.string = cbor_null_string_callback,
/* Type 4 - Arrays */
.indef_array_start = cbor_null_indef_array_start_callback,
.array_start = cbor_null_array_start_callback,
/* Type 5 - Maps */
.indef_map_start = cbor_null_indef_map_start_callback,
.map_start = cbor_null_map_start_callback,
/* Type 6 - Tags */
.tag = cbor_null_tag_callback,
/* Type 7 - Floats & misc */
/* Type names cannot be member names */
.float2 = cbor_null_float2_callback,
/* 2B float is not supported in standard C */
.float4 = cbor_null_float4_callback,
.float8 = cbor_null_float8_callback,
.undefined = cbor_null_undefined_callback,
.null = cbor_null_null_callback,
.boolean = cbor_null_boolean_callback,
/* Shared indefinites */
.indef_break = cbor_null_indef_break_callback,
};

View File

@ -0,0 +1,187 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_CALLBACKS_H
#define LIBCBOR_CALLBACKS_H
#include "cbor/cbor_export.h"
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Callback prototype */
typedef void (*cbor_int8_callback)(void *, uint8_t);
/** Callback prototype */
typedef void (*cbor_int16_callback)(void *, uint16_t);
/** Callback prototype */
typedef void (*cbor_int32_callback)(void *, uint32_t);
/** Callback prototype */
typedef void (*cbor_int64_callback)(void *, uint64_t);
/** Callback prototype */
typedef void (*cbor_simple_callback)(void *);
/** Callback prototype */
typedef void (*cbor_string_callback)(void *, cbor_data, size_t);
/** Callback prototype */
typedef void (*cbor_collection_callback)(void *, size_t);
/** Callback prototype */
typedef void (*cbor_float_callback)(void *, float);
/** Callback prototype */
typedef void (*cbor_double_callback)(void *, double);
/** Callback prototype */
typedef void (*cbor_bool_callback)(void *, bool);
/** Callback bundle -- passed to the decoder */
struct cbor_callbacks {
/** Unsigned int */
cbor_int8_callback uint8;
/** Unsigned int */
cbor_int16_callback uint16;
/** Unsigned int */
cbor_int32_callback uint32;
/** Unsigned int */
cbor_int64_callback uint64;
/** Negative int */
cbor_int64_callback negint64;
/** Negative int */
cbor_int32_callback negint32;
/** Negative int */
cbor_int16_callback negint16;
/** Negative int */
cbor_int8_callback negint8;
/** Definite byte string */
cbor_simple_callback byte_string_start;
/** Indefinite byte string start */
cbor_string_callback byte_string;
/** Definite string */
cbor_string_callback string;
/** Indefinite string start */
cbor_simple_callback string_start;
/** Definite array */
cbor_simple_callback indef_array_start;
/** Indefinite array */
cbor_collection_callback array_start;
/** Definite map */
cbor_simple_callback indef_map_start;
/** Indefinite map */
cbor_collection_callback map_start;
/** Tags */
cbor_int64_callback tag;
/** Half float */
cbor_float_callback float2;
/** Single float */
cbor_float_callback float4;
/** Double float */
cbor_double_callback float8;
/** Undef */
cbor_simple_callback undefined;
/** Null */
cbor_simple_callback null;
/** Bool */
cbor_bool_callback boolean;
/** Indefinite item break */
cbor_simple_callback indef_break;
};
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_uint8_callback(void *, uint8_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_uint16_callback(void *, uint16_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_uint32_callback(void *, uint32_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_uint64_callback(void *, uint64_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_negint8_callback(void *, uint8_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_negint16_callback(void *, uint16_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_negint32_callback(void *, uint32_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_negint64_callback(void *, uint64_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_string_callback(void *, cbor_data, size_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_string_start_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_byte_string_callback(void *, cbor_data, size_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_byte_string_start_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_array_start_callback(void *, size_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_indef_array_start_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_map_start_callback(void *, size_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_indef_map_start_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_tag_callback(void *, uint64_t);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_float2_callback(void *, float);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_float4_callback(void *, float);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_float8_callback(void *, double);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_null_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_undefined_callback(void *);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_boolean_callback(void *, bool);
/** Dummy callback implementation - does nothing */
CBOR_EXPORT void cbor_null_indef_break_callback(void *);
/** Dummy callback bundle - does nothing */
CBOR_EXPORT extern const struct cbor_callbacks cbor_empty_callbacks;
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_CALLBACKS_H

View File

@ -0,0 +1,160 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "cbor/common.h"
#include "arrays.h"
#include "bytestrings.h"
#include "data.h"
#include "floats_ctrls.h"
#include "ints.h"
#include "maps.h"
#include "strings.h"
#include "tags.h"
bool cbor_isa_uint(const cbor_item_t *item) {
return item->type == CBOR_TYPE_UINT;
}
bool cbor_isa_negint(const cbor_item_t *item) {
return item->type == CBOR_TYPE_NEGINT;
}
bool cbor_isa_bytestring(const cbor_item_t *item) {
return item->type == CBOR_TYPE_BYTESTRING;
}
bool cbor_isa_string(const cbor_item_t *item) {
return item->type == CBOR_TYPE_STRING;
}
bool cbor_isa_array(const cbor_item_t *item) {
return item->type == CBOR_TYPE_ARRAY;
}
bool cbor_isa_map(const cbor_item_t *item) {
return item->type == CBOR_TYPE_MAP;
}
bool cbor_isa_tag(const cbor_item_t *item) {
return item->type == CBOR_TYPE_TAG;
}
bool cbor_isa_float_ctrl(const cbor_item_t *item) {
return item->type == CBOR_TYPE_FLOAT_CTRL;
}
cbor_type cbor_typeof(const cbor_item_t *item) { return item->type; }
bool cbor_is_int(const cbor_item_t *item) {
return cbor_isa_uint(item) || cbor_isa_negint(item);
}
bool cbor_is_bool(const cbor_item_t *item) {
return cbor_isa_float_ctrl(item) &&
(cbor_ctrl_value(item) == CBOR_CTRL_FALSE ||
cbor_ctrl_value(item) == CBOR_CTRL_TRUE);
}
bool cbor_is_null(const cbor_item_t *item) {
return cbor_isa_float_ctrl(item) && cbor_ctrl_value(item) == CBOR_CTRL_NULL;
}
bool cbor_is_undef(const cbor_item_t *item) {
return cbor_isa_float_ctrl(item) && cbor_ctrl_value(item) == CBOR_CTRL_UNDEF;
}
bool cbor_is_float(const cbor_item_t *item) {
return cbor_isa_float_ctrl(item) && !cbor_float_ctrl_is_ctrl(item);
}
cbor_item_t *cbor_incref(cbor_item_t *item) {
item->refcount++;
return item;
}
void cbor_decref(cbor_item_t **item_ref) {
cbor_item_t *item = *item_ref;
assert(item->refcount > 0);
if (--item->refcount == 0) {
switch (item->type) {
case CBOR_TYPE_UINT:
/* Fallthrough */
case CBOR_TYPE_NEGINT:
/* Combined allocation, freeing the item suffices */
{ break; }
case CBOR_TYPE_BYTESTRING: {
if (cbor_bytestring_is_definite(item)) {
_CBOR_FREE(item->data);
} else {
/* We need to decref all chunks */
cbor_item_t **handle = cbor_bytestring_chunks_handle(item);
for (size_t i = 0; i < cbor_bytestring_chunk_count(item); i++)
cbor_decref(&handle[i]);
_CBOR_FREE(
((struct cbor_indefinite_string_data *)item->data)->chunks);
_CBOR_FREE(item->data);
}
break;
}
case CBOR_TYPE_STRING: {
if (cbor_string_is_definite(item)) {
_CBOR_FREE(item->data);
} else {
/* We need to decref all chunks */
cbor_item_t **handle = cbor_string_chunks_handle(item);
for (size_t i = 0; i < cbor_string_chunk_count(item); i++)
cbor_decref(&handle[i]);
_CBOR_FREE(
((struct cbor_indefinite_string_data *)item->data)->chunks);
_CBOR_FREE(item->data);
}
break;
}
case CBOR_TYPE_ARRAY: {
/* Get all items and decref them */
cbor_item_t **handle = cbor_array_handle(item);
size_t size = cbor_array_size(item);
for (size_t i = 0; i < size; i++)
if (handle[i] != NULL) cbor_decref(&handle[i]);
_CBOR_FREE(item->data);
break;
}
case CBOR_TYPE_MAP: {
struct cbor_pair *handle = cbor_map_handle(item);
for (size_t i = 0; i < item->metadata.map_metadata.end_ptr;
i++, handle++) {
cbor_decref(&handle->key);
if (handle->value != NULL) cbor_decref(&handle->value);
}
_CBOR_FREE(item->data);
break;
};
case CBOR_TYPE_TAG: {
if (item->metadata.tag_metadata.tagged_item != NULL)
cbor_decref(&item->metadata.tag_metadata.tagged_item);
_CBOR_FREE(item->data);
break;
}
case CBOR_TYPE_FLOAT_CTRL: {
/* Floats have combined allocation */
break;
}
}
_CBOR_FREE(item);
// TODO
*item_ref = NULL;
}
}
void cbor_intermediate_decref(cbor_item_t *item) { cbor_decref(&item); }
size_t cbor_refcount(const cbor_item_t *item) { return item->refcount; }
cbor_item_t *cbor_move(cbor_item_t *item) {
item->refcount--;
return item;
}

View File

@ -0,0 +1,303 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_COMMON_H
#define LIBCBOR_COMMON_H
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include "cbor/cbor_export.h"
#include "cbor/configuration.h"
#include "data.h"
#ifdef __cplusplus
extern "C" {
/**
* C++ is not a subset of C99 -- 'restrict' qualifier is not a part of the
* language. This is a workaround to keep it in C headers -- compilers allow
* linking non-restrict signatures with restrict implementations.
*
* If you know a nicer way, please do let me know.
*/
#define CBOR_RESTRICT_POINTER
#else
// MSVC + C++ workaround
#define CBOR_RESTRICT_POINTER CBOR_RESTRICT_SPECIFIER
#endif
static const uint8_t cbor_major_version = CBOR_MAJOR_VERSION;
static const uint8_t cbor_minor_version = CBOR_MINOR_VERSION;
static const uint8_t cbor_patch_version = CBOR_PATCH_VERSION;
#define CBOR_VERSION \
TO_STR(CBOR_MAJOR_VERSION) \
"." TO_STR(CBOR_MINOR_VERSION) "." TO_STR(CBOR_PATCH_VERSION)
#define CBOR_HEX_VERSION \
((CBOR_MAJOR_VERSION << 16) | (CBOR_MINOR_VERSION << 8) | CBOR_PATCH_VERSION)
/* http://stackoverflow.com/questions/1644868/c-define-macro-for-debug-printing
*/
#ifdef DEBUG
#include <stdio.h>
#define debug_print(fmt, ...) \
do { \
if (DEBUG) \
fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, \
__VA_ARGS__); \
} while (0)
#else
#define debug_print(fmt, ...) \
do { \
} while (0)
#endif
#define TO_STR_(x) #x
#define TO_STR(x) TO_STR_(x) /* enables proper double expansion */
// Macro to short-circuit builder functions when memory allocation fails
#define _CBOR_NOTNULL(cbor_item) \
do { \
if (cbor_item == NULL) { \
return NULL; \
} \
} while (0)
// Macro to short-circuit builders when memory allocation of nested data fails
#define _CBOR_DEPENDENT_NOTNULL(cbor_item, pointer) \
do { \
if (pointer == NULL) { \
_CBOR_FREE(cbor_item); \
return NULL; \
} \
} while (0)
#if CBOR_CUSTOM_ALLOC
typedef void *(*_cbor_malloc_t)(size_t);
typedef void *(*_cbor_realloc_t)(void *, size_t);
typedef void (*_cbor_free_t)(void *);
CBOR_EXPORT extern _cbor_malloc_t _cbor_malloc;
CBOR_EXPORT extern _cbor_realloc_t _cbor_realloc;
CBOR_EXPORT extern _cbor_free_t _cbor_free;
/** Sets the memory management routines to use.
*
* Only available when `CBOR_CUSTOM_ALLOC` is truthy
*
* \rst
* .. warning:: This function modifies the global state and should therefore be
* used accordingly. Changing the memory handlers while allocated items exist
* will result in a ``free``/``malloc`` mismatch. This function is not thread
* safe with respect to both itself and all the other *libcbor* functions that
* work with the heap.
*
* .. note:: `realloc` implementation must correctly support `NULL` reallocation
* (see e.g. http://en.cppreference.com/w/c/memory/realloc)
* \endrst
*
* @param custom_malloc malloc implementation
* @param custom_realloc realloc implementation
* @param custom_free free implementation
*/
CBOR_EXPORT void cbor_set_allocs(_cbor_malloc_t custom_malloc,
_cbor_realloc_t custom_realloc,
_cbor_free_t custom_free);
#define _CBOR_MALLOC _cbor_malloc
#define _CBOR_REALLOC _cbor_realloc
#define _CBOR_FREE _cbor_free
#else
#define _CBOR_MALLOC malloc
#define _CBOR_REALLOC realloc
#define _CBOR_FREE free
#endif
/*
* ============================================================================
* Type manipulation
* ============================================================================
*/
/** Get the type of the item
*
* @param item[borrow]
* @return The type
*/
CBOR_EXPORT cbor_type cbor_typeof(
const cbor_item_t *item); /* Will be inlined iff link-time opt is enabled */
/* Standard item types as described by the RFC */
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item an #CBOR_TYPE_UINT?
*/
CBOR_EXPORT bool cbor_isa_uint(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_NEGINT?
*/
CBOR_EXPORT bool cbor_isa_negint(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_BYTESTRING?
*/
CBOR_EXPORT bool cbor_isa_bytestring(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_STRING?
*/
CBOR_EXPORT bool cbor_isa_string(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item an #CBOR_TYPE_ARRAY?
*/
CBOR_EXPORT bool cbor_isa_array(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_MAP?
*/
CBOR_EXPORT bool cbor_isa_map(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_TAG?
*/
CBOR_EXPORT bool cbor_isa_tag(const cbor_item_t *item);
/** Does the item have the appropriate major type?
* @param item[borrow] the item
* @return Is the item a #CBOR_TYPE_FLOAT_CTRL?
*/
CBOR_EXPORT bool cbor_isa_float_ctrl(const cbor_item_t *item);
/* Practical types with respect to their semantics (but not tag values) */
/** Is the item an integer, either positive or negative?
* @param item[borrow] the item
* @return Is the item an integer, either positive or negative?
*/
CBOR_EXPORT bool cbor_is_int(const cbor_item_t *item);
/** Is the item an a floating point number?
* @param item[borrow] the item
* @return Is the item a floating point number?
*/
CBOR_EXPORT bool cbor_is_float(const cbor_item_t *item);
/** Is the item an a boolean?
* @param item[borrow] the item
* @return Is the item a boolean?
*/
CBOR_EXPORT bool cbor_is_bool(const cbor_item_t *item);
/** Does this item represent `null`
*
* \rst
* .. warning:: This is in no way related to the value of the pointer. Passing a
* null pointer will most likely result in a crash.
* \endrst
*
* @param item[borrow] the item
* @return Is the item (CBOR logical) null?
*/
CBOR_EXPORT bool cbor_is_null(const cbor_item_t *item);
/** Does this item represent `undefined`
*
* \rst
* .. warning:: Care must be taken to distinguish nulls and undefined values in
* C.
* \endrst
*
* @param item[borrow] the item
* @return Is the item (CBOR logical) undefined?
*/
CBOR_EXPORT bool cbor_is_undef(const cbor_item_t *item);
/*
* ============================================================================
* Memory management
* ============================================================================
*/
/** Increases the reference count by one
*
* No dependent items are affected.
*
* @param item[incref] item the item
* @return the input reference
*/
CBOR_EXPORT cbor_item_t *cbor_incref(cbor_item_t *item);
/** Decreases the reference count by one, deallocating the item if needed
*
* In case the item is deallocated, the reference count of any dependent items
* is adjusted accordingly in a recursive manner.
*
* @param item[take] the item. Set to `NULL` if deallocated
*/
CBOR_EXPORT void cbor_decref(cbor_item_t **item);
/** Decreases the reference count by one, deallocating the item if needed
*
* Convenience wrapper for #cbor_decref when its set-to-null behavior is not
* needed
*
* @param item[take] the item
*/
CBOR_EXPORT void cbor_intermediate_decref(cbor_item_t *item);
/** Get the reference count
*
* \rst
* .. warning:: This does *not* account for transitive references.
* \endrst
*
* @param item[borrow] the item
* @return the reference count
*/
CBOR_EXPORT size_t cbor_refcount(const cbor_item_t *item);
/** Provides CPP-like move construct
*
* Decreases the reference count by one, but does not deallocate the item even
* if its refcount reaches zero. This is useful for passing intermediate values
* to functions that increase reference count. Should only be used with
* functions that `incref` their arguments.
*
* \rst
* .. warning:: If the item is moved without correctly increasing the reference
* count afterwards, the memory will be leaked.
* \endrst
*
* @param item[take] the item
* @return the item with reference count decreased by one
*/
CBOR_EXPORT cbor_item_t *cbor_move(cbor_item_t *item);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_COMMON_H

View File

@ -0,0 +1,16 @@
#ifndef LIBCBOR_CONFIGURATION_H
#define LIBCBOR_CONFIGURATION_H
#define CBOR_MAJOR_VERSION ${CBOR_VERSION_MAJOR}
#define CBOR_MINOR_VERSION ${CBOR_VERSION_MINOR}
#define CBOR_PATCH_VERSION ${CBOR_VERSION_PATCH}
#cmakedefine01 CBOR_CUSTOM_ALLOC
#define CBOR_BUFFER_GROWTH ${CBOR_BUFFER_GROWTH}
#define CBOR_MAX_STACK_SIZE ${CBOR_MAX_STACK_SIZE}
#cmakedefine01 CBOR_PRETTY_PRINTER
#define CBOR_RESTRICT_SPECIFIER ${CBOR_RESTRICT_SPECIFIER}
#define CBOR_INLINE_SPECIFIER ${CBOR_INLINE_SPECIFIER}
#endif //LIBCBOR_CONFIGURATION_H

View File

@ -0,0 +1,255 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_DATA_H
#define LIBCBOR_DATA_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef const unsigned char* cbor_data;
typedef unsigned char* cbor_mutable_data;
/** Specifies the Major type of ::cbor_item_t */
typedef enum cbor_type {
CBOR_TYPE_UINT /** 0 - positive integers */
,
CBOR_TYPE_NEGINT /** 1 - negative integers*/
,
CBOR_TYPE_BYTESTRING /** 2 - byte strings */
,
CBOR_TYPE_STRING /** 3 - strings */
,
CBOR_TYPE_ARRAY /** 4 - arrays */
,
CBOR_TYPE_MAP /** 5 - maps */
,
CBOR_TYPE_TAG /** 6 - tags */
,
CBOR_TYPE_FLOAT_CTRL /** 7 - decimals and special values (true, false, nil,
...) */
} cbor_type;
/** Possible decoding errors */
typedef enum {
CBOR_ERR_NONE,
CBOR_ERR_NOTENOUGHDATA,
CBOR_ERR_NODATA,
CBOR_ERR_MALFORMATED,
CBOR_ERR_MEMERROR /** Memory error - item allocation failed. Is it too big for
your allocator? */
,
CBOR_ERR_SYNTAXERROR /** Stack parsing algorithm failed */
} cbor_error_code;
/** Possible widths of #CBOR_TYPE_UINT items */
typedef enum {
CBOR_INT_8,
CBOR_INT_16,
CBOR_INT_32,
CBOR_INT_64
} cbor_int_width;
/** Possible widths of #CBOR_TYPE_FLOAT_CTRL items */
typedef enum {
CBOR_FLOAT_0 /** Internal use - ctrl and special values */
,
CBOR_FLOAT_16 /** Half float */
,
CBOR_FLOAT_32 /** Single float */
,
CBOR_FLOAT_64 /** Double */
} cbor_float_width;
/** Metadata for dynamically sized types */
typedef enum {
_CBOR_METADATA_DEFINITE,
_CBOR_METADATA_INDEFINITE
} _cbor_dst_metadata;
/** Semantic mapping for CTRL simple values */
typedef enum {
CBOR_CTRL_NONE = 0,
CBOR_CTRL_FALSE = 20,
CBOR_CTRL_TRUE = 21,
CBOR_CTRL_NULL = 22,
CBOR_CTRL_UNDEF = 23
} _cbor_ctrl;
/** Integers specific metadata */
struct _cbor_int_metadata {
cbor_int_width width;
};
/** Bytestrings specific metadata */
struct _cbor_bytestring_metadata {
size_t length;
_cbor_dst_metadata type;
};
/** Strings specific metadata */
struct _cbor_string_metadata {
size_t length;
size_t codepoint_count; /* Sum of chunks' codepoint_counts for indefinite
strings */
_cbor_dst_metadata type;
};
/** Arrays specific metadata */
struct _cbor_array_metadata {
size_t allocated;
size_t end_ptr;
_cbor_dst_metadata type;
};
/** Maps specific metadata */
struct _cbor_map_metadata {
size_t allocated;
size_t end_ptr;
_cbor_dst_metadata type;
};
/** Arrays specific metadata
*
* The pointer is included - cbor_item_metadata is
* 2 * sizeof(size_t) + sizeof(_cbor_string_type_metadata),
* lets use the space
*/
struct _cbor_tag_metadata {
struct cbor_item_t* tagged_item;
uint64_t value;
};
/** Floats specific metadata - includes CTRL values */
struct _cbor_float_ctrl_metadata {
cbor_float_width width;
uint8_t ctrl;
};
/** Raw memory casts helper */
union _cbor_float_helper {
float as_float;
uint32_t as_uint;
};
/** Raw memory casts helper */
union _cbor_double_helper {
double as_double;
uint64_t as_uint;
};
/** Union of metadata across all possible types - discriminated in #cbor_item_t
*/
union cbor_item_metadata {
struct _cbor_int_metadata int_metadata;
struct _cbor_bytestring_metadata bytestring_metadata;
struct _cbor_string_metadata string_metadata;
struct _cbor_array_metadata array_metadata;
struct _cbor_map_metadata map_metadata;
struct _cbor_tag_metadata tag_metadata;
struct _cbor_float_ctrl_metadata float_ctrl_metadata;
};
/** The item handle */
typedef struct cbor_item_t {
/** Discriminated by type */
union cbor_item_metadata metadata;
/** Reference count - initialize to 0 */
size_t refcount;
/** Major type discriminator */
cbor_type type;
/** Raw data block - interpretation depends on metadata */
unsigned char* data;
} cbor_item_t;
/** Defines cbor_item_t#data structure for indefinite strings and bytestrings
*
* Used to cast the raw representation for a sane manipulation
*/
struct cbor_indefinite_string_data {
size_t chunk_count;
size_t chunk_capacity;
cbor_item_t** chunks;
};
/** High-level decoding error */
struct cbor_error {
/** Aproximate position */
size_t position;
/** Description */
cbor_error_code code;
};
/** Simple pair of items for use in maps */
struct cbor_pair {
cbor_item_t *key, *value;
};
/** High-level decoding result */
struct cbor_load_result {
/** Error indicator */
struct cbor_error error;
/** Number of bytes read */
size_t read;
};
/** Streaming decoder result - status */
enum cbor_decoder_status {
/** Decoding finished successfully (a callback has been invoked)
*
* Note that this does *not* mean that the buffer has been fully decoded;
* there may still be unread bytes for which no callback has been involved.
*/
CBOR_DECODER_FINISHED,
/** Not enough data to invoke a callback */
CBOR_DECODER_NEDATA,
/** Bad data (reserved MTB, malformed value, etc.) */
CBOR_DECODER_ERROR
};
/** Streaming decoder result */
struct cbor_decoder_result {
/** Input bytes read/consumed
*
* If this is less than the size of input buffer, the client will likely
* resume parsing starting at the next byte (e.g. `buffer + result.read`).
*
* Set to 0 if the #status is not #CBOR_DECODER_FINISHED.
*/
size_t read;
/** The decoding status */
enum cbor_decoder_status status;
/** Number of bytes in the input buffer needed to resume parsing
*
* Set to 0 unless the result status is #CBOR_DECODER_NEDATA. If it is, then:
* - If at least one byte was passed, #required will be set to the minimum
* number of bytes needed to invoke a decoded callback on the current
* prefix.
*
* For example: Attempting to decode a 1B buffer containing `0x19` will
* set #required to 3 as `0x19` signals a 2B integer item, so we need at
* least 3B to continue (the `0x19` MTB byte and two bytes of data needed
* to invoke #cbor_callbacks.uint16).
*
* - If there was no data at all, #read will always be set to 1
*/
size_t required;
};
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_DATA_H

View File

@ -0,0 +1,192 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "encoding.h"
#include "internal/encoders.h"
size_t cbor_encode_uint8(uint8_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint8(value, buffer, buffer_size, 0x00);
}
size_t cbor_encode_uint16(uint16_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint16(value, buffer, buffer_size, 0x00);
}
size_t cbor_encode_uint32(uint32_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint32(value, buffer, buffer_size, 0x00);
}
size_t cbor_encode_uint64(uint64_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint64(value, buffer, buffer_size, 0x00);
}
size_t cbor_encode_uint(uint64_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint(value, buffer, buffer_size, 0x00);
}
size_t cbor_encode_negint8(uint8_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint8(value, buffer, buffer_size, 0x20);
}
size_t cbor_encode_negint16(uint16_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint16(value, buffer, buffer_size, 0x20);
}
size_t cbor_encode_negint32(uint32_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint32(value, buffer, buffer_size, 0x20);
}
size_t cbor_encode_negint64(uint64_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint64(value, buffer, buffer_size, 0x20);
}
size_t cbor_encode_negint(uint64_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint(value, buffer, buffer_size, 0x20);
}
size_t cbor_encode_bytestring_start(size_t length, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint((size_t)length, buffer, buffer_size, 0x40);
}
size_t _cbor_encode_byte(uint8_t value, unsigned char *buffer,
size_t buffer_size) {
if (buffer_size >= 1) {
buffer[0] = value;
return 1;
} else
return 0;
}
size_t cbor_encode_indef_bytestring_start(unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_byte(0x5F, buffer, buffer_size);
}
size_t cbor_encode_string_start(size_t length, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint((size_t)length, buffer, buffer_size, 0x60);
}
size_t cbor_encode_indef_string_start(unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_byte(0x7F, buffer, buffer_size);
}
size_t cbor_encode_array_start(size_t length, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint((size_t)length, buffer, buffer_size, 0x80);
}
size_t cbor_encode_indef_array_start(unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_byte(0x9F, buffer, buffer_size);
}
size_t cbor_encode_map_start(size_t length, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint((size_t)length, buffer, buffer_size, 0xA0);
}
size_t cbor_encode_indef_map_start(unsigned char *buffer, size_t buffer_size) {
return _cbor_encode_byte(0xBF, buffer, buffer_size);
}
size_t cbor_encode_tag(uint64_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint(value, buffer, buffer_size, 0xC0);
}
size_t cbor_encode_bool(bool value, unsigned char *buffer, size_t buffer_size) {
return value ? _cbor_encode_byte(0xF5, buffer, buffer_size)
: _cbor_encode_byte(0xF4, buffer, buffer_size);
}
size_t cbor_encode_null(unsigned char *buffer, size_t buffer_size) {
return _cbor_encode_byte(0xF6, buffer, buffer_size);
}
size_t cbor_encode_undef(unsigned char *buffer, size_t buffer_size) {
return _cbor_encode_byte(0xF7, buffer, buffer_size);
}
size_t cbor_encode_half(float value, unsigned char *buffer,
size_t buffer_size) {
/* Assuming value is normalized */
uint32_t val = ((union _cbor_float_helper){.as_float = value}).as_uint;
uint16_t res;
uint8_t exp = (uint8_t)((val & 0x7F800000u) >>
23u); /* 0b0111_1111_1000_0000_0000_0000_0000_0000 */
uint32_t mant =
val & 0x7FFFFFu; /* 0b0000_0000_0111_1111_1111_1111_1111_1111 */
if (exp == 0xFF) { /* Infinity or NaNs */
if (value != value) {
res = (uint16_t)0x007e00; /* Not IEEE semantics - required by CBOR
[s. 3.9] */
} else {
res = (uint16_t)((val & 0x80000000u) >> 16u | 0x7C00u |
(mant ? 1u : 0u) << 15u);
}
} else if (exp == 0x00) { /* Zeroes or subnorms */
res = (uint16_t)((val & 0x80000000u) >> 16u | mant >> 13u);
} else { /* Normal numbers */
int8_t logical_exp = (int8_t)(exp - 127);
assert(logical_exp == exp - 127);
// Now we know that 2^exp <= 0 logically
if (logical_exp < -24) {
/* No unambiguous representation exists, this float is not a half float
and is too small to be represented using a half, round off to zero.
Consistent with the reference implementation. */
res = 0;
} else if (logical_exp < -14) {
/* Offset the remaining decimal places by shifting the significand, the
value is lost. This is an implementation decision that works around the
absence of standard half-float in the language. */
res = (uint16_t)((val & 0x80000000u) >> 16u) | // Extract sign bit
(uint16_t)(1u << (24u + logical_exp));
} else {
res = (uint16_t)((val & 0x80000000u) >> 16u |
((((uint8_t)logical_exp) + 15u) << 10u) |
(uint16_t)(mant >> 13u));
}
}
return _cbor_encode_uint16(res, buffer, buffer_size, 0xE0);
}
size_t cbor_encode_single(float value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint32(
((union _cbor_float_helper){.as_float = value}).as_uint, buffer,
buffer_size, 0xE0);
}
size_t cbor_encode_double(double value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint64(
((union _cbor_double_helper){.as_double = value}).as_uint, buffer,
buffer_size, 0xE0);
}
size_t cbor_encode_break(unsigned char *buffer, size_t buffer_size) {
return _cbor_encode_byte(0xFF, buffer, buffer_size);
}
size_t cbor_encode_ctrl(uint8_t value, unsigned char *buffer,
size_t buffer_size) {
return _cbor_encode_uint8(value, buffer, buffer_size, 0xE0);
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_ENCODING_H
#define LIBCBOR_ENCODING_H
#include "cbor/cbor_export.h"
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* ============================================================================
* Primitives encoding
* ============================================================================
*/
CBOR_EXPORT size_t cbor_encode_uint8(uint8_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_uint16(uint16_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_uint32(uint32_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_uint64(uint64_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_uint(uint64_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_negint8(uint8_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_negint16(uint16_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_negint32(uint32_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_negint64(uint64_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_negint(uint64_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_bytestring_start(size_t, unsigned char *,
size_t);
CBOR_EXPORT size_t cbor_encode_indef_bytestring_start(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_string_start(size_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_indef_string_start(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_array_start(size_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_indef_array_start(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_map_start(size_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_indef_map_start(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_tag(uint64_t, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_bool(bool, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_null(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_undef(unsigned char *, size_t);
/** Encodes a half-precision float
*
* Since there is no native representation or semantics for half floats
* in the language, we use single-precision floats, as every value that
* can be expressed as a half-float can also be expressed as a float.
*
* This however means that not all floats passed to this function can be
* unambiguously encoded. The behavior is as follows:
* - Infinity, NaN are preserved
* - Zero is preserved
* - Denormalized numbers keep their sign bit and 10 most significant bit of
* the significand
* - All other numbers
* - If the logical value of the exponent is < -24, the output is zero
* - If the logical value of the exponent is between -23 and -14, the output
* is cut off to represent the 'magnitude' of the input, by which we
* mean (-1)^{signbit} x 1.0e{exponent}. The value in the significand is
* lost.
* - In all other cases, the sign bit, the exponent, and 10 most significant
* bits of the significand are kept
*
* @param value
* @param buffer Target buffer
* @param buffer_size Available space in the buffer
* @return number of bytes written
*/
CBOR_EXPORT size_t cbor_encode_half(float, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_single(float, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_double(double, unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_break(unsigned char *, size_t);
CBOR_EXPORT size_t cbor_encode_ctrl(uint8_t, unsigned char *, size_t);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_ENCODING_H

View File

@ -0,0 +1,189 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "floats_ctrls.h"
#include <math.h>
#include "assert.h"
cbor_float_width cbor_float_get_width(const cbor_item_t *item) {
assert(cbor_isa_float_ctrl(item));
return item->metadata.float_ctrl_metadata.width;
}
uint8_t cbor_ctrl_value(const cbor_item_t *item) {
assert(cbor_isa_float_ctrl(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_0);
return item->metadata.float_ctrl_metadata.ctrl;
}
bool cbor_float_ctrl_is_ctrl(const cbor_item_t *item) {
assert(cbor_isa_float_ctrl(item));
return cbor_float_get_width(item) == CBOR_FLOAT_0;
}
float cbor_float_get_float2(const cbor_item_t *item) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_16);
return *(float *)item->data;
}
float cbor_float_get_float4(const cbor_item_t *item) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_32);
return *(float *)item->data;
}
double cbor_float_get_float8(const cbor_item_t *item) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_64);
return *(double *)item->data;
}
double cbor_float_get_float(const cbor_item_t *item) {
assert(cbor_is_float(item));
switch (cbor_float_get_width(item)) {
case CBOR_FLOAT_0:
return NAN;
case CBOR_FLOAT_16:
return cbor_float_get_float2(item);
case CBOR_FLOAT_32:
return cbor_float_get_float4(item);
case CBOR_FLOAT_64:
return cbor_float_get_float8(item);
}
return NAN; /* Compiler complaints */
}
bool cbor_get_bool(const cbor_item_t *item) {
assert(cbor_is_bool(item));
return item->metadata.float_ctrl_metadata.ctrl == CBOR_CTRL_TRUE;
}
void cbor_set_float2(cbor_item_t *item, float value) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_16);
*((float *)item->data) = value;
}
void cbor_set_float4(cbor_item_t *item, float value) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_32);
*((float *)item->data) = value;
}
void cbor_set_float8(cbor_item_t *item, double value) {
assert(cbor_is_float(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_64);
*((double *)item->data) = value;
}
void cbor_set_ctrl(cbor_item_t *item, uint8_t value) {
assert(cbor_isa_float_ctrl(item));
assert(cbor_float_get_width(item) == CBOR_FLOAT_0);
item->metadata.float_ctrl_metadata.ctrl = value;
}
void cbor_set_bool(cbor_item_t *item, bool value) {
assert(cbor_is_bool(item));
item->metadata.float_ctrl_metadata.ctrl =
value ? CBOR_CTRL_TRUE : CBOR_CTRL_FALSE;
}
cbor_item_t *cbor_new_ctrl() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t));
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.type = CBOR_TYPE_FLOAT_CTRL,
.data = NULL,
.refcount = 1,
.metadata = {.float_ctrl_metadata = {.width = CBOR_FLOAT_0,
.ctrl = CBOR_CTRL_NONE}}};
return item;
}
cbor_item_t *cbor_new_float2() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t) + 4);
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.type = CBOR_TYPE_FLOAT_CTRL,
.data = (unsigned char *)item + sizeof(cbor_item_t),
.refcount = 1,
.metadata = {.float_ctrl_metadata = {.width = CBOR_FLOAT_16}}};
return item;
}
cbor_item_t *cbor_new_float4() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t) + 4);
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.type = CBOR_TYPE_FLOAT_CTRL,
.data = (unsigned char *)item + sizeof(cbor_item_t),
.refcount = 1,
.metadata = {.float_ctrl_metadata = {.width = CBOR_FLOAT_32}}};
return item;
}
cbor_item_t *cbor_new_float8() {
cbor_item_t *item = _CBOR_MALLOC(sizeof(cbor_item_t) + 8);
_CBOR_NOTNULL(item);
*item = (cbor_item_t){
.type = CBOR_TYPE_FLOAT_CTRL,
.data = (unsigned char *)item + sizeof(cbor_item_t),
.refcount = 1,
.metadata = {.float_ctrl_metadata = {.width = CBOR_FLOAT_64}}};
return item;
}
cbor_item_t *cbor_new_null() {
cbor_item_t *item = cbor_new_ctrl();
_CBOR_NOTNULL(item);
cbor_set_ctrl(item, CBOR_CTRL_NULL);
return item;
}
cbor_item_t *cbor_new_undef() {
cbor_item_t *item = cbor_new_ctrl();
_CBOR_NOTNULL(item);
cbor_set_ctrl(item, CBOR_CTRL_UNDEF);
return item;
}
cbor_item_t *cbor_build_bool(bool value) {
return cbor_build_ctrl(value ? CBOR_CTRL_TRUE : CBOR_CTRL_FALSE);
}
cbor_item_t *cbor_build_float2(float value) {
cbor_item_t *item = cbor_new_float2();
_CBOR_NOTNULL(item);
cbor_set_float2(item, value);
return item;
}
cbor_item_t *cbor_build_float4(float value) {
cbor_item_t *item = cbor_new_float4();
_CBOR_NOTNULL(item);
cbor_set_float4(item, value);
return item;
}
cbor_item_t *cbor_build_float8(double value) {
cbor_item_t *item = cbor_new_float8();
_CBOR_NOTNULL(item);
cbor_set_float8(item, value);
return item;
}
cbor_item_t *cbor_build_ctrl(uint8_t value) {
cbor_item_t *item = cbor_new_ctrl();
_CBOR_NOTNULL(item);
cbor_set_ctrl(item, value);
return item;
}

View File

@ -0,0 +1,212 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_FLOATS_CTRLS_H
#define LIBCBOR_FLOATS_CTRLS_H
#include "cbor/cbor_export.h"
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* ============================================================================
* Float manipulation
* ============================================================================
*/
/** Is this a ctrl value?
*
* @param item[borrow] A float or ctrl item
* @return Is this a ctrl value?
*/
CBOR_EXPORT bool cbor_float_ctrl_is_ctrl(const cbor_item_t *item);
/** Get the float width
*
* @param item[borrow] A float or ctrl item
* @return The width.
*/
CBOR_EXPORT cbor_float_width cbor_float_get_width(const cbor_item_t *item);
/** Get a half precision float
*
* The item must have the corresponding width
*
* @param[borrow] A half precision float
* @return half precision value
*/
CBOR_EXPORT float cbor_float_get_float2(const cbor_item_t *item);
/** Get a single precision float
*
* The item must have the corresponding width
*
* @param[borrow] A signle precision float
* @return single precision value
*/
CBOR_EXPORT float cbor_float_get_float4(const cbor_item_t *item);
/** Get a double precision float
*
* The item must have the corresponding width
*
* @param[borrow] A double precision float
* @return double precision value
*/
CBOR_EXPORT double cbor_float_get_float8(const cbor_item_t *item);
/** Get the float value represented as double
*
* Can be used regardless of the width.
*
* @param[borrow] Any float
* @return double precision value
*/
CBOR_EXPORT double cbor_float_get_float(const cbor_item_t *item);
/** Get value from a boolean ctrl item
*
* @param item[borrow] A ctrl item
* @return boolean value
*/
CBOR_EXPORT bool cbor_get_bool(const cbor_item_t *item);
/** Constructs a new ctrl item
*
* The width cannot be changed once the item is created
*
* @return **new** 1B ctrl or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_ctrl();
/** Constructs a new float item
*
* The width cannot be changed once the item is created
*
* @return **new** 2B float or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_float2();
/** Constructs a new float item
*
* The width cannot be changed once the item is created
*
* @return **new** 4B float or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_float4();
/** Constructs a new float item
*
* The width cannot be changed once the item is created
*
* @return **new** 8B float or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_float8();
/** Constructs new null ctrl item
*
* @return **new** null ctrl item or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_null();
/** Constructs new undef ctrl item
*
* @return **new** undef ctrl item or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_new_undef();
/** Constructs new boolean ctrl item
*
* @param value The value to use
* @return **new** boolen ctrl item or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_build_bool(bool value);
/** Assign a control value
*
* \rst
* .. warning:: It is possible to produce an invalid CBOR value by assigning a
* invalid value using this mechanism. Please consult the standard before use.
* \endrst
*
* @param item[borrow] A ctrl item
* @param value The simple value to assign. Please consult the standard for
* allowed values
*/
CBOR_EXPORT void cbor_set_ctrl(cbor_item_t *item, uint8_t value);
/** Assign a boolean value to a boolean ctrl item
*
* @param item[borrow] A ctrl item
* @param value The simple value to assign.
*/
CBOR_EXPORT void cbor_set_bool(cbor_item_t *item, bool value);
/** Assigns a float value
*
* @param item[borrow] A half precision float
* @param value The value to assign
*/
CBOR_EXPORT void cbor_set_float2(cbor_item_t *item, float value);
/** Assigns a float value
*
* @param item[borrow] A single precision float
* @param value The value to assign
*/
CBOR_EXPORT void cbor_set_float4(cbor_item_t *item, float value);
/** Assigns a float value
*
* @param item[borrow] A double precision float
* @param value The value to assign
*/
CBOR_EXPORT void cbor_set_float8(cbor_item_t *item, double value);
/** Reads the control value
*
* @param item[borrow] A ctrl item
* @return the simple value
*/
CBOR_EXPORT uint8_t cbor_ctrl_value(const cbor_item_t *item);
/** Constructs a new float
*
* @param value the value to use
* @return **new** float
*/
CBOR_EXPORT cbor_item_t *cbor_build_float2(float value);
/** Constructs a new float
*
* @param value the value to use
* @return **new** float or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_build_float4(float value);
/** Constructs a new float
*
* @param value the value to use
* @return **new** float or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_build_float8(double value);
/** Constructs a ctrl item
*
* @param value the value to use
* @return **new** ctrl item or `NULL` upon memory allocation failure
*/
CBOR_EXPORT cbor_item_t *cbor_build_ctrl(uint8_t value);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_FLOATS_CTRLS_H

View File

@ -0,0 +1,389 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "builder_callbacks.h"
#include <string.h>
#include "../arrays.h"
#include "../bytestrings.h"
#include "../floats_ctrls.h"
#include "../ints.h"
#include "../maps.h"
#include "../strings.h"
#include "../tags.h"
#include "unicode.h"
void _cbor_builder_append(cbor_item_t *item,
struct _cbor_decoder_context *ctx) {
if (ctx->stack->size == 0) {
/* Top level item */
ctx->root = item;
} else {
/* Part of a bigger structure */
switch (ctx->stack->top->item->type) {
case CBOR_TYPE_ARRAY: {
if (cbor_array_is_definite(ctx->stack->top->item)) {
/*
* We don't need an explicit check for whether the item still belongs
* into this array because if there are extra items, they will cause a
* syntax error when decoded.
*/
assert(ctx->stack->top->subitems > 0);
cbor_array_push(ctx->stack->top->item, item);
ctx->stack->top->subitems--;
if (ctx->stack->top->subitems == 0) {
cbor_item_t *item = ctx->stack->top->item;
_cbor_stack_pop(ctx->stack);
_cbor_builder_append(item, ctx);
}
cbor_decref(&item);
} else {
/* Indefinite array, don't bother with subitems */
cbor_array_push(ctx->stack->top->item, item);
cbor_decref(&item);
}
break;
}
case CBOR_TYPE_MAP: {
/* We use 0 and 1 subitems to distinguish between keys and values in
* indefinite items */
if (ctx->stack->top->subitems % 2) {
/* Odd record, this is a value */
_cbor_map_add_value(ctx->stack->top->item, cbor_move(item));
} else {
/* Even record, this is a key */
_cbor_map_add_key(ctx->stack->top->item, cbor_move(item));
}
if (cbor_map_is_definite(ctx->stack->top->item)) {
ctx->stack->top->subitems--;
if (ctx->stack->top->subitems == 0) {
cbor_item_t *item = ctx->stack->top->item;
_cbor_stack_pop(ctx->stack);
_cbor_builder_append(item, ctx);
}
} else {
ctx->stack->top->subitems ^=
1; /* Flip the indicator for indefinite items */
}
break;
}
case CBOR_TYPE_TAG: {
assert(ctx->stack->top->subitems == 1);
cbor_tag_set_item(ctx->stack->top->item, item);
cbor_decref(&item); /* Give up on our reference */
cbor_item_t *item = ctx->stack->top->item;
_cbor_stack_pop(ctx->stack);
_cbor_builder_append(item, ctx);
break;
}
default: {
cbor_decref(&item);
ctx->syntax_error = true;
}
}
}
}
#define CHECK_RES(ctx, res) \
do { \
if (res == NULL) { \
ctx->creation_failed = true; \
return; \
} \
} while (0)
#define PUSH_CTX_STACK(ctx, res, subitems) \
do { \
if (_cbor_stack_push(ctx->stack, res, subitems) == NULL) { \
cbor_decref(&res); \
ctx->creation_failed = true; \
} \
} while (0)
void cbor_builder_uint8_callback(void *context, uint8_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int8();
CHECK_RES(ctx, res);
cbor_mark_uint(res);
cbor_set_uint8(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_uint16_callback(void *context, uint16_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int16();
CHECK_RES(ctx, res);
cbor_mark_uint(res);
cbor_set_uint16(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_uint32_callback(void *context, uint32_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int32();
CHECK_RES(ctx, res);
cbor_mark_uint(res);
cbor_set_uint32(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_uint64_callback(void *context, uint64_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int64();
CHECK_RES(ctx, res);
cbor_mark_uint(res);
cbor_set_uint64(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_negint8_callback(void *context, uint8_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int8();
CHECK_RES(ctx, res);
cbor_mark_negint(res);
cbor_set_uint8(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_negint16_callback(void *context, uint16_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int16();
cbor_mark_negint(res);
cbor_set_uint16(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_negint32_callback(void *context, uint32_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int32();
CHECK_RES(ctx, res);
cbor_mark_negint(res);
cbor_set_uint32(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_negint64_callback(void *context, uint64_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_int64();
CHECK_RES(ctx, res);
cbor_mark_negint(res);
cbor_set_uint64(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_byte_string_callback(void *context, cbor_data data,
size_t length) {
struct _cbor_decoder_context *ctx = context;
unsigned char *new_handle = _CBOR_MALLOC(length);
if (new_handle == NULL) {
ctx->creation_failed = true;
return;
}
memcpy(new_handle, data, length);
cbor_item_t *res = cbor_new_definite_bytestring();
if (res == NULL) {
_CBOR_FREE(new_handle);
ctx->creation_failed = true;
return;
}
cbor_bytestring_set_handle(res, new_handle, length);
if (ctx->stack->size > 0 && cbor_isa_bytestring(ctx->stack->top->item)) {
if (cbor_bytestring_is_indefinite(ctx->stack->top->item)) {
cbor_bytestring_add_chunk(ctx->stack->top->item, cbor_move(res));
} else {
cbor_decref(&res);
ctx->syntax_error = true;
}
} else {
_cbor_builder_append(res, ctx);
}
}
void cbor_builder_byte_string_start_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_indefinite_bytestring();
CHECK_RES(ctx, res);
PUSH_CTX_STACK(ctx, res, 0);
}
void cbor_builder_string_callback(void *context, cbor_data data,
size_t length) {
struct _cbor_decoder_context *ctx = context;
struct _cbor_unicode_status unicode_status;
size_t codepoint_count =
_cbor_unicode_codepoint_count(data, length, &unicode_status);
if (unicode_status.status == _CBOR_UNICODE_BADCP) {
ctx->syntax_error = true;
return;
}
unsigned char *new_handle = _CBOR_MALLOC(length);
if (new_handle == NULL) {
ctx->creation_failed = true;
return;
}
memcpy(new_handle, data, length);
cbor_item_t *res = cbor_new_definite_string();
if (res == NULL) {
_CBOR_FREE(new_handle);
ctx->creation_failed = true;
return;
}
cbor_string_set_handle(res, new_handle, length);
res->metadata.string_metadata.codepoint_count = codepoint_count;
/* Careful here: order matters */
if (ctx->stack->size > 0 && cbor_isa_string(ctx->stack->top->item)) {
if (cbor_string_is_indefinite(ctx->stack->top->item)) {
cbor_string_add_chunk(ctx->stack->top->item, cbor_move(res));
} else {
cbor_decref(&res);
ctx->syntax_error = true;
}
} else {
_cbor_builder_append(res, ctx);
}
}
void cbor_builder_string_start_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_indefinite_string();
CHECK_RES(ctx, res);
PUSH_CTX_STACK(ctx, res, 0);
}
void cbor_builder_array_start_callback(void *context, size_t size) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_definite_array(size);
CHECK_RES(ctx, res);
if (size > 0) {
PUSH_CTX_STACK(ctx, res, size);
} else {
_cbor_builder_append(res, ctx);
}
}
void cbor_builder_indef_array_start_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_indefinite_array();
CHECK_RES(ctx, res);
PUSH_CTX_STACK(ctx, res, 0);
}
void cbor_builder_indef_map_start_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_indefinite_map();
CHECK_RES(ctx, res);
PUSH_CTX_STACK(ctx, res, 0);
}
void cbor_builder_map_start_callback(void *context, size_t size) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_definite_map(size);
CHECK_RES(ctx, res);
if (size > 0) {
PUSH_CTX_STACK(ctx, res, size * 2);
} else {
_cbor_builder_append(res, ctx);
}
}
/**
* Is the (partially constructed) item indefinite?
*/
bool _cbor_is_indefinite(cbor_item_t *item) {
switch (item->type) {
case CBOR_TYPE_BYTESTRING:
return item->metadata.bytestring_metadata.type ==
_CBOR_METADATA_INDEFINITE;
case CBOR_TYPE_STRING:
return item->metadata.string_metadata.type == _CBOR_METADATA_INDEFINITE;
case CBOR_TYPE_ARRAY:
return item->metadata.array_metadata.type == _CBOR_METADATA_INDEFINITE;
case CBOR_TYPE_MAP:
return item->metadata.map_metadata.type == _CBOR_METADATA_INDEFINITE;
default:
return false;
}
}
void cbor_builder_indef_break_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
/* There must be an item to break out of*/
if (ctx->stack->size > 0) {
cbor_item_t *item = ctx->stack->top->item;
if (_cbor_is_indefinite(
item) && /* Only indefinite items can be terminated by 0xFF */
/* Special case: we cannot append up if an indefinite map is incomplete
(we are expecting a value). */
(item->type != CBOR_TYPE_MAP || ctx->stack->top->subitems % 2 == 0)) {
_cbor_stack_pop(ctx->stack);
_cbor_builder_append(item, ctx);
return;
}
}
ctx->syntax_error = true;
}
void cbor_builder_float2_callback(void *context, float value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_float2();
cbor_set_float2(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_float4_callback(void *context, float value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_float4();
CHECK_RES(ctx, res);
cbor_set_float4(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_float8_callback(void *context, double value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_float8();
CHECK_RES(ctx, res);
cbor_set_float8(res, value);
_cbor_builder_append(res, ctx);
}
void cbor_builder_null_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_null();
CHECK_RES(ctx, res);
_cbor_builder_append(res, ctx);
}
void cbor_builder_undefined_callback(void *context) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_undef();
CHECK_RES(ctx, res);
_cbor_builder_append(res, ctx);
}
void cbor_builder_boolean_callback(void *context, bool value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_build_bool(value);
CHECK_RES(ctx, res);
_cbor_builder_append(res, ctx);
}
void cbor_builder_tag_callback(void *context, uint64_t value) {
struct _cbor_decoder_context *ctx = context;
cbor_item_t *res = cbor_new_tag(value);
CHECK_RES(ctx, res);
PUSH_CTX_STACK(ctx, res, 1);
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_BUILDER_CALLBACKS_H
#define LIBCBOR_BUILDER_CALLBACKS_H
#include "../callbacks.h"
#include "cbor/common.h"
#include "stack.h"
#ifdef __cplusplus
extern "C" {
#endif
/** High-level decoding context */
struct _cbor_decoder_context {
/** Callback creating the last item has failed */
bool creation_failed;
/** Stack expectation mismatch */
bool syntax_error;
cbor_item_t *root;
struct _cbor_stack *stack;
};
void cbor_builder_uint8_callback(void *, uint8_t);
void cbor_builder_uint16_callback(void *, uint16_t);
void cbor_builder_uint32_callback(void *, uint32_t);
void cbor_builder_uint64_callback(void *, uint64_t);
void cbor_builder_negint8_callback(void *, uint8_t);
void cbor_builder_negint16_callback(void *, uint16_t);
void cbor_builder_negint32_callback(void *, uint32_t);
void cbor_builder_negint64_callback(void *, uint64_t);
void cbor_builder_string_callback(void *, cbor_data, size_t);
void cbor_builder_string_start_callback(void *);
void cbor_builder_byte_string_callback(void *, cbor_data, size_t);
void cbor_builder_byte_string_start_callback(void *);
void cbor_builder_array_start_callback(void *, size_t);
void cbor_builder_indef_array_start_callback(void *);
void cbor_builder_map_start_callback(void *, size_t);
void cbor_builder_indef_map_start_callback(void *);
void cbor_builder_tag_callback(void *, uint64_t);
void cbor_builder_float2_callback(void *, float);
void cbor_builder_float4_callback(void *, float);
void cbor_builder_float8_callback(void *, double);
void cbor_builder_null_callback(void *);
void cbor_builder_undefined_callback(void *);
void cbor_builder_boolean_callback(void *, bool);
void cbor_builder_indef_break_callback(void *);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_BUILDER_CALLBACKS_H

View File

@ -0,0 +1,98 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "encoders.h"
#include <string.h>
size_t _cbor_encode_uint8(uint8_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset) {
if (value <= 23) {
if (buffer_size >= 1) {
buffer[0] = value + offset;
return 1;
}
} else {
if (buffer_size >= 2) {
buffer[0] = 0x18 + offset;
buffer[1] = value;
return 2;
}
}
return 0;
}
size_t _cbor_encode_uint16(uint16_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset) {
if (buffer_size >= 3) {
buffer[0] = 0x19 + offset;
#ifdef IS_BIG_ENDIAN
memcpy(buffer + 1, &value, 2);
#else
buffer[1] = value >> 8;
buffer[2] = value;
#endif
return 3;
} else
return 0;
}
size_t _cbor_encode_uint32(uint32_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset) {
if (buffer_size >= 5) {
buffer[0] = 0x1A + offset;
#ifdef IS_BIG_ENDIAN
memcpy(buffer + 1, &value, 4);
#else
buffer[1] = value >> 24;
buffer[2] = value >> 16;
buffer[3] = value >> 8;
buffer[4] = value;
#endif
return 5;
} else
return 0;
}
size_t _cbor_encode_uint64(uint64_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset) {
if (buffer_size >= 9) {
buffer[0] = 0x1B + offset;
#ifdef IS_BIG_ENDIAN
memcpy(buffer + 1, &value, 8);
#else
buffer[1] = value >> 56;
buffer[2] = value >> 48;
buffer[3] = value >> 40;
buffer[4] = value >> 32;
buffer[5] = value >> 24;
buffer[6] = value >> 16;
buffer[7] = value >> 8;
buffer[8] = value;
#endif
return 9;
} else
return 0;
}
size_t _cbor_encode_uint(uint64_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset) {
if (value <= UINT16_MAX)
if (value <= UINT8_MAX)
return _cbor_encode_uint8((uint8_t)value, buffer, buffer_size, offset);
else
return _cbor_encode_uint16((uint16_t)value, buffer, buffer_size, offset);
else if (value <= UINT32_MAX)
return _cbor_encode_uint32((uint32_t)value, buffer, buffer_size, offset);
else
return _cbor_encode_uint64((uint64_t)value, buffer, buffer_size, offset);
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_ENCODERS_H
#define LIBCBOR_ENCODERS_H
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
size_t _cbor_encode_uint8(uint8_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset);
size_t _cbor_encode_uint16(uint16_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset);
size_t _cbor_encode_uint32(uint32_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset);
size_t _cbor_encode_uint64(uint64_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset);
size_t _cbor_encode_uint(uint64_t value, unsigned char *buffer,
size_t buffer_size, uint8_t offset);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_ENCODERS_H

View File

@ -0,0 +1,80 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "loaders.h"
#include <math.h>
#include <string.h>
uint8_t _cbor_load_uint8(cbor_data source) { return (uint8_t)*source; }
uint16_t _cbor_load_uint16(const unsigned char *source) {
#ifdef IS_BIG_ENDIAN
uint16_t result;
memcpy(&result, source, 2);
return result;
#else
return ((uint16_t) * (source + 0) << 8) + (uint8_t) * (source + 1);
#endif
}
uint32_t _cbor_load_uint32(const unsigned char *source) {
#ifdef IS_BIG_ENDIAN
uint32_t result;
memcpy(&result, source, 4);
return result;
#else
return ((uint32_t) * (source + 0) << 0x18) +
((uint32_t) * (source + 1) << 0x10) +
((uint16_t) * (source + 2) << 0x08) + (uint8_t) * (source + 3);
#endif
}
uint64_t _cbor_load_uint64(const unsigned char *source) {
#ifdef IS_BIG_ENDIAN
uint64_t result;
memcpy(&result, source, 8);
return result;
#else
return ((uint64_t) * (source + 0) << 0x38) +
((uint64_t) * (source + 1) << 0x30) +
((uint64_t) * (source + 2) << 0x28) +
((uint64_t) * (source + 3) << 0x20) +
((uint32_t) * (source + 4) << 0x18) +
((uint32_t) * (source + 5) << 0x10) +
((uint16_t) * (source + 6) << 0x08) + (uint8_t) * (source + 7);
#endif
}
/* As per http://tools.ietf.org/html/rfc7049#appendix-D */
float _cbor_decode_half(unsigned char *halfp) {
int half = (halfp[0] << 8) + halfp[1];
int exp = (half >> 10) & 0x1f;
int mant = half & 0x3ff;
double val;
if (exp == 0)
val = ldexp(mant, -24);
else if (exp != 31)
val = ldexp(mant + 1024, exp - 25);
else
val = mant == 0 ? INFINITY : NAN;
return (float)(half & 0x8000 ? -val : val);
}
double _cbor_load_half(cbor_data source) {
/* Discard const */
return _cbor_decode_half((unsigned char *)source);
}
float _cbor_load_float(cbor_data source) {
union _cbor_float_helper helper = {.as_uint = _cbor_load_uint32(source)};
return helper.as_float;
}
double _cbor_load_double(cbor_data source) {
union _cbor_double_helper helper = {.as_uint = _cbor_load_uint64(source)};
return helper.as_double;
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_LOADERS_H
#define LIBCBOR_LOADERS_H
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Read the given uint from the given location, no questions asked */
uint8_t _cbor_load_uint8(const unsigned char *source);
uint16_t _cbor_load_uint16(const unsigned char *source);
uint32_t _cbor_load_uint32(const unsigned char *source);
uint64_t _cbor_load_uint64(const unsigned char *source);
double _cbor_load_half(cbor_data source);
float _cbor_load_float(cbor_data source);
double _cbor_load_double(cbor_data source);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_LOADERS_H

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "memory_utils.h"
#include "cbor/common.h"
// TODO: Consider builtins
// (https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html)
/** Highest on bit position */
size_t _cbor_highest_bit(size_t number) {
size_t bit = 0;
while (number != 0) {
bit++;
number >>= 1;
}
return bit;
}
bool _cbor_safe_to_multiply(size_t a, size_t b) {
return _cbor_highest_bit(a) + _cbor_highest_bit(b) <= sizeof(size_t) * 8;
}
void* _cbor_alloc_multiple(size_t item_size, size_t item_count) {
if (_cbor_safe_to_multiply(item_size, item_count)) {
return _CBOR_MALLOC(item_size * item_count);
} else {
return NULL;
}
}
void* _cbor_realloc_multiple(void* pointer, size_t item_size,
size_t item_count) {
if (_cbor_safe_to_multiply(item_size, item_count)) {
return _CBOR_REALLOC(pointer, item_size * item_count);
} else {
return NULL;
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_MEMORY_UTILS_H
#define LIBCBOR_MEMORY_UTILS_H
#include <stdbool.h>
#include <string.h>
/** Can a and b be multiplied without overflowing size_t? */
bool _cbor_safe_to_multiply(size_t a, size_t b);
/** Overflow-proof contiguous array allocation
*
* @param item_size
* @param item_count
* @return Region of item_size * item_count bytes, or NULL if the total size
* overflows size_t or the underlying allocator failed
*/
void* _cbor_alloc_multiple(size_t item_size, size_t item_count);
/** Overflow-proof contiguous array reallocation
*
* This implements the OpenBSD `reallocarray` functionality.
*
* @param pointer
* @param item_size
* @param item_count
* @return Realloc'd of item_size * item_count bytes, or NULL if the total size
* overflows size_t or the underlying allocator failed
*/
void* _cbor_realloc_multiple(void* pointer, size_t item_size,
size_t item_count);
#endif // LIBCBOR_MEMORY_UTILS_H

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#include "stack.h"
struct _cbor_stack _cbor_stack_init() {
return (struct _cbor_stack){.top = NULL, .size = 0};
}
void _cbor_stack_pop(struct _cbor_stack *stack) {
struct _cbor_stack_record *top = stack->top;
stack->top = stack->top->lower;
_CBOR_FREE(top);
stack->size--;
}
struct _cbor_stack_record *_cbor_stack_push(struct _cbor_stack *stack,
cbor_item_t *item,
size_t subitems) {
if (stack->size == CBOR_MAX_STACK_SIZE) return NULL;
struct _cbor_stack_record *new_top =
_CBOR_MALLOC(sizeof(struct _cbor_stack_record));
if (new_top == NULL) return NULL;
*new_top = (struct _cbor_stack_record){stack->top, item, subitems};
stack->top = new_top;
stack->size++;
return new_top;
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
*
* libcbor is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef LIBCBOR_STACK_H
#define LIBCBOR_STACK_H
#include "cbor/common.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Simple stack record for the parser */
struct _cbor_stack_record {
struct _cbor_stack_record *lower;
cbor_item_t *item;
size_t subitems;
};
/** Stack handle - contents and size */
struct _cbor_stack {
struct _cbor_stack_record *top;
size_t size;
};
struct _cbor_stack _cbor_stack_init();
void _cbor_stack_pop(struct _cbor_stack *);
struct _cbor_stack_record *_cbor_stack_push(struct _cbor_stack *, cbor_item_t *,
size_t);
#ifdef __cplusplus
}
#endif
#endif // LIBCBOR_STACK_H

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