diff --git a/CMakeLists.txt b/CMakeLists.txt index 3bd6791..24e55ef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,6 +11,7 @@ option(JSONSCHEMA_CONTINUOUS "Perform a continuous JSON Schema CLI release" ON) find_package(JSONToolkit REQUIRED) find_package(AlterSchema REQUIRED) +find_package(JSONBinPack REQUIRED) find_package(Hydra REQUIRED) add_subdirectory(src) diff --git a/DEPENDENCIES b/DEPENDENCIES index fdbbfe5..4c26a11 100644 --- a/DEPENDENCIES +++ b/DEPENDENCIES @@ -3,3 +3,4 @@ noa https://github.com/sourcemeta/noa 7e26abce7a4e31e86a16ef2851702a56773ca527 jsontoolkit https://github.com/sourcemeta/jsontoolkit 3ef19daf7ca042544239111c701a51232f3f5576 hydra https://github.com/sourcemeta/hydra 3c53d3fdef79e9ba603d48470a508cc45472a0dc alterschema https://github.com/sourcemeta/alterschema 744cf03a950b681a61f1f4cf6a7bb55bc52836c9 +jsonbinpack https://github.com/sourcemeta/jsonbinpack 43d53dd32c432333deb1aea147095ed8707b5f11 diff --git a/README.markdown b/README.markdown index 5ba8422..0d40c95 100644 --- a/README.markdown +++ b/README.markdown @@ -65,6 +65,7 @@ documentation: - [`jsonschema frame`](./docs/frame.markdown) (for debugging references) - [`jsonschema compile`](./docs/compile.markdown) (for internal debugging) - [`jsonschema identify`](./docs/identify.markdown) +- [`jsonschema canonicalize`](./docs/canonicalize.markdown) (for static analysis) Installation ------------ diff --git a/cmake/FindJSONBinPack.cmake b/cmake/FindJSONBinPack.cmake new file mode 100644 index 0000000..cc2b0f6 --- /dev/null +++ b/cmake/FindJSONBinPack.cmake @@ -0,0 +1,7 @@ +if(NOT JSONBinPack_FOUND) + set(JSONBINPACK_INSTALL OFF CACHE BOOL "disable installation") + set(JSONBINPACK_CLI OFF CACHE BOOL "disable the JSON BinPack CLI module") + set(JSONBINPACK_RUNTIME OFF CACHE BOOL "disable the JSON BinPack runtime module") + add_subdirectory("${PROJECT_SOURCE_DIR}/vendor/jsonbinpack") + set(JSONBinPack_FOUND ON) +endif() diff --git a/docs/canonicalize.markdown b/docs/canonicalize.markdown new file mode 100644 index 0000000..0adaa21 --- /dev/null +++ b/docs/canonicalize.markdown @@ -0,0 +1,83 @@ +Canonicalize +============ + +```sh +jsonschema canonicalize +``` + +JSON Schema is an extremely expressive schema language. As such, schema authors +can express the same constraints in a variety of ways, making the process of +statically analyzing schemas complex. This command attempts to tackle the +problem by transforming a given JSON Schema into a simpler (but more verbose) +normalized form referred to as _canonical_. + +> Refer to [Juan Cruz Viotti's dissertation on JSON +> BinPack's](https://www.jviotti.com/dissertation.pdf) for how JSON Schema +> canonicalization was originally defined. + +Examples +-------- + +For example, consider the following simple schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "foo": { "type": "string" } + } +} +``` + +The canonicalization process will result in something like this: + +``` +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "anyOf": [ + { + "enum": [ + null + ] + }, + { + "enum": [ + false, + true + ] + }, + { + "type": "object", + "minProperties": 0, + "properties": { + "foo": { + "type": "string", + "minLength": 0 + } + } + }, + { + "type": "array", + "minItems": 0 + }, + { + "type": "string", + "minLength": 0 + }, + { + "type": "number", + "multipleOf": 1 + }, + { + "type": "integer", + "multipleOf": 1 + } + ] +} +``` + +### Canonicalize a JSON Schema + +```sh +jsonschema canonicalize path/to/my/schema.json +``` diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d5df531..491a457 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -9,7 +9,8 @@ add_executable(jsonschema_cli command_lint.cc command_metaschema.cc command_validate.cc - command_identify.cc) + command_identify.cc + command_canonicalize.cc) noa_add_default_options(PRIVATE jsonschema_cli) set_target_properties(jsonschema_cli PROPERTIES OUTPUT_NAME jsonschema) @@ -20,6 +21,7 @@ target_link_libraries(jsonschema_cli PRIVATE sourcemeta::jsontoolkit::jsonschema target_link_libraries(jsonschema_cli PRIVATE sourcemeta::alterschema::engine) target_link_libraries(jsonschema_cli PRIVATE sourcemeta::alterschema::linter) target_link_libraries(jsonschema_cli PRIVATE sourcemeta::hydra::httpclient) +target_link_libraries(jsonschema_cli PRIVATE sourcemeta::jsonbinpack::compiler) configure_file(configure.h.in configure.h @ONLY) target_include_directories(jsonschema_cli PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") diff --git a/src/command.h b/src/command.h index 35eb3e4..f5641bc 100644 --- a/src/command.h +++ b/src/command.h @@ -14,6 +14,7 @@ auto lint(const std::span &arguments) -> int; auto validate(const std::span &arguments) -> int; auto metaschema(const std::span &arguments) -> int; auto identify(const std::span &arguments) -> int; +auto canonicalize(const std::span &arguments) -> int; } // namespace sourcemeta::jsonschema::cli #endif diff --git a/src/command_canonicalize.cc b/src/command_canonicalize.cc new file mode 100644 index 0000000..f9a61bf --- /dev/null +++ b/src/command_canonicalize.cc @@ -0,0 +1,30 @@ +#include +#include +#include + +#include // EXIT_SUCCESS +#include // std::cout, std::endl + +#include "command.h" +#include "utils.h" + +auto sourcemeta::jsonschema::cli::canonicalize( + const std::span &arguments) -> int { + const auto options{parse_options(arguments, {})}; + + if (options.at("").size() < 1) { + std::cerr + << "error: This command expects a path to a schema. For example:\n\n" + << " jsonschema canonicalize path/to/schema.json\n"; + return EXIT_FAILURE; + } + + auto schema{sourcemeta::jsontoolkit::from_file(options.at("").front())}; + sourcemeta::jsonbinpack::canonicalize( + schema, sourcemeta::jsontoolkit::default_schema_walker, + resolver(options, options.contains("h") || options.contains("http"))); + sourcemeta::jsontoolkit::prettify( + schema, std::cout, sourcemeta::jsontoolkit::schema_format_compare); + std::cout << std::endl; + return EXIT_SUCCESS; +} diff --git a/src/main.cc b/src/main.cc index 10b569c..928e6bf 100644 --- a/src/main.cc +++ b/src/main.cc @@ -69,6 +69,11 @@ Global Options: Print the URI of the given schema to standard output, optionally relative to a given base URI. + canonicalize + + Pre-process a JSON Schema into JSON BinPack's canonical form + for static analysis. + For more documentation, visit https://github.com/sourcemeta/jsonschema )EOF"}; @@ -92,6 +97,8 @@ auto jsonschema_main(const std::string &program, const std::string &command, return sourcemeta::jsonschema::cli::test(arguments); } else if (command == "identify") { return sourcemeta::jsonschema::cli::identify(arguments); + } else if (command == "canonicalize") { + return sourcemeta::jsonschema::cli::canonicalize(arguments); } else { std::cout << "JSON Schema CLI - v" << sourcemeta::jsonschema::cli::PROJECT_VERSION << "\n"; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 073547f..325a7be 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -166,6 +166,12 @@ add_jsonschema_test_unix(lint/pass_lint_fix) add_jsonschema_test_unix(lint/pass_lint_no_fix) add_jsonschema_test_unix(lint/fail_lint) +# Canonicalize +add_jsonschema_test_unix(canonicalize/pass_1) +add_jsonschema_test_unix(canonicalize/fail_no_schema) +add_jsonschema_test_unix(canonicalize/fail_schema_invalid_json) +add_jsonschema_test_unix(canonicalize/fail_unknown_metaschema) + # CI specific tests add_jsonschema_test_unix_ci(pass_bundle_http) add_jsonschema_test_unix_ci(fail_bundle_http_non_200) diff --git a/test/canonicalize/fail_no_schema.sh b/test/canonicalize/fail_no_schema.sh new file mode 100755 index 0000000..0298640 --- /dev/null +++ b/test/canonicalize/fail_no_schema.sh @@ -0,0 +1,19 @@ +#!/bin/sh + +set -o errexit +set -o nounset + +TMP="$(mktemp -d)" +clean() { rm -rf "$TMP"; } +trap clean EXIT + +"$1" canonicalize 2>"$TMP/stderr.txt" && CODE="$?" || CODE="$?" +test "$CODE" = "1" || exit 1 + +cat << 'EOF' > "$TMP/expected.txt" +error: This command expects a path to a schema. For example: + + jsonschema canonicalize path/to/schema.json +EOF + +diff "$TMP/stderr.txt" "$TMP/expected.txt" diff --git a/test/canonicalize/fail_schema_invalid_json.sh b/test/canonicalize/fail_schema_invalid_json.sh new file mode 100755 index 0000000..a76bcc4 --- /dev/null +++ b/test/canonicalize/fail_schema_invalid_json.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +set -o errexit +set -o nounset + +TMP="$(mktemp -d)" +clean() { rm -rf "$TMP"; } +trap clean EXIT + +cat << 'EOF' > "$TMP/schema.json" +{ + "type" string +} +EOF + +"$1" canonicalize "$TMP/schema.json" 2>"$TMP/stderr.txt" \ + && CODE="$?" || CODE="$?" +test "$CODE" = "1" || exit 1 + +cat << EOF > "$TMP/expected.txt" +error: Failed to parse the JSON document at line 2 and column 10 + $(realpath "$TMP")/schema.json +EOF + +diff "$TMP/stderr.txt" "$TMP/expected.txt" diff --git a/test/canonicalize/fail_unknown_metaschema.sh b/test/canonicalize/fail_unknown_metaschema.sh new file mode 100755 index 0000000..b642564 --- /dev/null +++ b/test/canonicalize/fail_unknown_metaschema.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +set -o errexit +set -o nounset + +TMP="$(mktemp -d)" +clean() { rm -rf "$TMP"; } +trap clean EXIT + +cat << 'EOF' > "$TMP/schema.json" +{ + "$schema": "https://example.com/unknown", + "$id": "https://example.com", + "$ref": "nested" +} +EOF + +"$1" canonicalize "$TMP/schema.json" 2>"$TMP/stderr.txt" && CODE="$?" || CODE="$?" +test "$CODE" = "1" || exit 1 + +cat << EOF > "$TMP/expected.txt" +error: Could not resolve the requested schema + at https://example.com/unknown +EOF + +diff "$TMP/stderr.txt" "$TMP/expected.txt" diff --git a/test/canonicalize/pass_1.sh b/test/canonicalize/pass_1.sh new file mode 100755 index 0000000..2e43396 --- /dev/null +++ b/test/canonicalize/pass_1.sh @@ -0,0 +1,68 @@ +#!/bin/sh + +set -o errexit +set -o nounset + +TMP="$(mktemp -d)" +clean() { rm -rf "$TMP"; } +trap clean EXIT + +cat << 'EOF' > "$TMP/schema.json" +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "foo": { "type": "string" } + } +} +EOF + +"$1" canonicalize "$TMP/schema.json" > "$TMP/result.json" + +cat "$TMP/result.json" + +cat << 'EOF' > "$TMP/expected.json" +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "anyOf": [ + { + "enum": [ + null + ] + }, + { + "enum": [ + false, + true + ] + }, + { + "type": "object", + "minProperties": 0, + "properties": { + "foo": { + "type": "string", + "minLength": 0 + } + } + }, + { + "type": "array", + "minItems": 0 + }, + { + "type": "string", + "minLength": 0 + }, + { + "type": "number", + "multipleOf": 1 + }, + { + "type": "integer", + "multipleOf": 1 + } + ] +} +EOF + +diff "$TMP/result.json" "$TMP/expected.json" diff --git a/vendor/jsonbinpack/CMakeLists.txt b/vendor/jsonbinpack/CMakeLists.txt new file mode 100644 index 0000000..389f082 --- /dev/null +++ b/vendor/jsonbinpack/CMakeLists.txt @@ -0,0 +1,113 @@ +cmake_minimum_required(VERSION 3.24) +project(jsonbinpack VERSION 0.0.1 LANGUAGES CXX + DESCRIPTION "\ +A space-efficient open-source binary JSON serialization \ +format based on JSON Schema with \ +both schema-driven and schema-less support." + HOMEPAGE_URL "https://jsonbinpack.sourcemeta.com") +list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake") +include(vendor/noa/cmake/noa.cmake) + +# Options +option(JSONBINPACK_CLI "Build the JSON BinPack CLI" ON) +option(JSONBINPACK_NUMERIC "Build the JSON BinPack numeric library" ON) +option(JSONBINPACK_RUNTIME "Build the JSON BinPack runtime" ON) +option(JSONBINPACK_COMPILER "Build the JSON BinPack compiler" ON) +option(JSONBINPACK_TESTS "Build the JSON BinPack tests" OFF) +option(JSONBINPACK_INSTALL "Install the JSON BinPack library" ON) +option(JSONBINPACK_WEBSITE "Build the JSON BinPack website" OFF) +option(JSONBINPACK_DOCS "Build the JSON BinPack documentation" OFF) +option(JSONBINPACK_ADDRESS_SANITIZER "Build JSON BinPack with an address sanitizer" OFF) +option(JSONBINPACK_UNDEFINED_SANITIZER "Build JSON BinPack with an undefined behavior sanitizer" OFF) + +if(JSONBINPACK_INSTALL) + include(GNUInstallDirs) + include(CMakePackageConfigHelpers) + configure_package_config_file( + config.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake" + INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config-version.cmake" + COMPATIBILITY SameMajorVersion) + install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config-version.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}-config.cmake" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}" + COMPONENT sourcemeta_jsonbinpack_dev) +endif() + +# Dependencies +find_package(JSONToolkit REQUIRED) +find_package(AlterSchema REQUIRED) + +# Numeric +if(JSONBINPACK_NUMERIC) + add_subdirectory(src/numeric) +endif() + +# Runtime +if(JSONBINPACK_RUNTIME) + add_subdirectory(src/runtime) +endif() + +# Compiler +if(JSONBINPACK_COMPILER) + add_subdirectory(src/compiler) +endif() + +# CLI +if(JSONBINPACK_CLI) + add_subdirectory(src/cli) +endif() + +if(JSONBINPACK_ADDRESS_SANITIZER) + noa_sanitizer(TYPE address) +elseif(JSONBINPACK_UNDEFINED_SANITIZER) + noa_sanitizer(TYPE undefined) +endif() + +if(JSONBINPACK_WEBSITE) + add_subdirectory(www) +endif() + +if(JSONBINPACK_DOCS) + noa_target_doxygen(CONFIG "${PROJECT_SOURCE_DIR}/doxygen/Doxyfile.in" + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/www/api") +endif() + +if(PROJECT_IS_TOP_LEVEL) + noa_target_clang_format(SOURCES + src/*.h src/*.cc + test/*.h test/*.cc) + noa_target_clang_tidy(SOURCES + src/*.h src/*.cc) +endif() + +# Testing +if(JSONBINPACK_TESTS) + find_package(GoogleTest REQUIRED) + enable_testing() + + if(JSONBINPACK_RUNTIME) + add_subdirectory(test/runtime) + endif() + + if(JSONBINPACK_COMPILER) + add_subdirectory(test/compiler) + endif() + + if(JSONBINPACK_CLI) + add_subdirectory(test/cli) + endif() + + add_subdirectory(test/e2e) + + if(PROJECT_IS_TOP_LEVEL) + # Otherwise we need the child project to link + # against the sanitizers too. + if(NOT JSONBINPACK_ADDRESS_SANITIZER AND NOT JSONBINPACK_UNDEFINED_SANITIZER) + add_subdirectory(test/packaging) + endif() + endif() +endif() diff --git a/vendor/jsonbinpack/LICENSE b/vendor/jsonbinpack/LICENSE new file mode 100644 index 0000000..6aef300 --- /dev/null +++ b/vendor/jsonbinpack/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + JSON BinPack - A binary JSON serialization format based on JSON Schema + Copyright (C) 2022 Juan Cruz Viotti + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/vendor/jsonbinpack/LICENSE-COMMERCIAL b/vendor/jsonbinpack/LICENSE-COMMERCIAL new file mode 100644 index 0000000..2b3c48a --- /dev/null +++ b/vendor/jsonbinpack/LICENSE-COMMERCIAL @@ -0,0 +1,2 @@ +Refer to https://www.sourcemeta.com/licensing/ for learning more about +obtaining a commercial license. diff --git a/vendor/jsonbinpack/cmake/FindAlterSchema.cmake b/vendor/jsonbinpack/cmake/FindAlterSchema.cmake new file mode 100644 index 0000000..dbb2787 --- /dev/null +++ b/vendor/jsonbinpack/cmake/FindAlterSchema.cmake @@ -0,0 +1,10 @@ +if(NOT Alterschema_FOUND) + if(JSONBINPACK_INSTALL) + set(ALTERSCHEMA_INSTALL ON CACHE BOOL "enable AlterSchema installation") + else() + set(ALTERSCHEMA_INSTALL OFF CACHE BOOL "disable AlterSchema installation") + endif() + + add_subdirectory("${PROJECT_SOURCE_DIR}/vendor/alterschema") + set(Alterschema_FOUND ON) +endif() diff --git a/vendor/jsonbinpack/cmake/FindGoogleTest.cmake b/vendor/jsonbinpack/cmake/FindGoogleTest.cmake new file mode 100644 index 0000000..99c2c02 --- /dev/null +++ b/vendor/jsonbinpack/cmake/FindGoogleTest.cmake @@ -0,0 +1,7 @@ +if(NOT GoogleTest_FOUND) + set(BUILD_GMOCK OFF CACHE BOOL "disable googlemock") + set(INSTALL_GTEST OFF CACHE BOOL "disable installation") + add_subdirectory("${PROJECT_SOURCE_DIR}/vendor/googletest") + include(GoogleTest) + set(GoogleTest_FOUND ON) +endif() diff --git a/vendor/jsonbinpack/cmake/FindJSONToolkit.cmake b/vendor/jsonbinpack/cmake/FindJSONToolkit.cmake new file mode 100644 index 0000000..f894a51 --- /dev/null +++ b/vendor/jsonbinpack/cmake/FindJSONToolkit.cmake @@ -0,0 +1,11 @@ +if(NOT JSONToolkit_FOUND) + if(JSONBINPACK_INSTALL) + set(JSONTOOLKIT_INSTALL ON CACHE BOOL "enable JSON Toolkit installation") + else() + set(JSONTOOLKIT_INSTALL OFF CACHE BOOL "disable JSON Toolkit installation") + endif() + + set(JSONTOOLKIT_JSONL OFF CACHE BOOL "disable JSONL support") + add_subdirectory("${PROJECT_SOURCE_DIR}/vendor/jsontoolkit") + set(JSONToolkit_FOUND ON) +endif() diff --git a/vendor/jsonbinpack/config.cmake.in b/vendor/jsonbinpack/config.cmake.in new file mode 100644 index 0000000..a20a44e --- /dev/null +++ b/vendor/jsonbinpack/config.cmake.in @@ -0,0 +1,30 @@ +@PACKAGE_INIT@ + +# Support both casing styles +list(APPEND JSONBINPACK_COMPONENTS ${JSONBinPack_FIND_COMPONENTS}) +list(APPEND JSONBINPACK_COMPONENTS ${jsonbinpack_FIND_COMPONENTS}) +if(NOT JSONBINPACK_COMPONENTS) + list(APPEND JSONBINPACK_COMPONENTS numeric) + list(APPEND JSONBINPACK_COMPONENTS runtime) + list(APPEND JSONBINPACK_COMPONENTS compiler) +endif() + +include(CMakeFindDependencyMacro) +find_dependency(JSONToolkit COMPONENTS uri json jsonpointer jsonschema) +find_dependency(AlterSchema COMPONENTS engine linter) + +foreach(component ${JSONBINPACK_COMPONENTS}) + if(component STREQUAL "numeric") + include("${CMAKE_CURRENT_LIST_DIR}/sourcemeta_jsonbinpack_numeric.cmake") + elseif(component STREQUAL "runtime") + include("${CMAKE_CURRENT_LIST_DIR}/sourcemeta_jsonbinpack_numeric.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/sourcemeta_jsonbinpack_runtime.cmake") + elseif(component STREQUAL "compiler") + include("${CMAKE_CURRENT_LIST_DIR}/sourcemeta_jsonbinpack_numeric.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/sourcemeta_jsonbinpack_compiler.cmake") + else() + message(FATAL_ERROR "Unknown JSON BinPack component: ${component}") + endif() +endforeach() + +check_required_components("@PROJECT_NAME@") diff --git a/vendor/jsonbinpack/src/cli/CMakeLists.txt b/vendor/jsonbinpack/src/cli/CMakeLists.txt new file mode 100644 index 0000000..994bf73 --- /dev/null +++ b/vendor/jsonbinpack/src/cli/CMakeLists.txt @@ -0,0 +1,24 @@ +configure_file(version.h.in version.h @ONLY) +add_executable(sourcemeta_jsonbinpack_cli main.cc commands.h + command_help.cc command_version.cc + command_canonicalize.cc command_compile.cc + command_encode.cc command_decode.cc + defaults.h version.h.in) + +noa_add_default_options(PRIVATE sourcemeta_jsonbinpack_cli) + +target_link_libraries(sourcemeta_jsonbinpack_cli PRIVATE sourcemeta::jsonbinpack::compiler) +target_link_libraries(sourcemeta_jsonbinpack_cli PRIVATE sourcemeta::jsonbinpack::runtime) +target_link_libraries(sourcemeta_jsonbinpack_cli PRIVATE sourcemeta::jsontoolkit::json) +target_link_libraries(sourcemeta_jsonbinpack_cli PRIVATE sourcemeta::jsontoolkit::jsonschema) + +# To find the generated version file +target_include_directories(sourcemeta_jsonbinpack_cli PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +# Set a friendly name for the binary +set_target_properties(sourcemeta_jsonbinpack_cli PROPERTIES + OUTPUT_NAME jsonbinpack + FOLDER "JSON BinPack/CLI") + +install(TARGETS sourcemeta_jsonbinpack_cli + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + COMPONENT sourcemeta_jsonbinpack) diff --git a/vendor/jsonbinpack/src/cli/command_canonicalize.cc b/vendor/jsonbinpack/src/cli/command_canonicalize.cc new file mode 100644 index 0000000..e5cbb4f --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_canonicalize.cc @@ -0,0 +1,33 @@ +#include "commands.h" +#include "defaults.h" + +#include +#include +#include + +#include // EXIT_SUCCESS +#include // std::filesystem +#include // std::cin, std::cout, std::endl; + +static auto canonicalize_from_json(sourcemeta::jsontoolkit::JSON &schema) + -> int { + sourcemeta::jsonbinpack::canonicalize( + schema, sourcemeta::jsontoolkit::default_schema_walker, + sourcemeta::jsontoolkit::official_resolver, + sourcemeta::jsonbinpack::DEFAULT_METASCHEMA); + sourcemeta::jsontoolkit::prettify(schema, std::cout); + std::cout << std::endl; + return EXIT_SUCCESS; +} + +auto sourcemeta::jsonbinpack::cli::canonicalize( + const std::filesystem::path &schema_path) -> int { + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return canonicalize_from_json(schema); +} + +auto sourcemeta::jsonbinpack::cli::canonicalize() -> int { + sourcemeta::jsontoolkit::JSON schema = + sourcemeta::jsontoolkit::parse(std::cin); + return canonicalize_from_json(schema); +} diff --git a/vendor/jsonbinpack/src/cli/command_compile.cc b/vendor/jsonbinpack/src/cli/command_compile.cc new file mode 100644 index 0000000..2ade3ce --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_compile.cc @@ -0,0 +1,32 @@ +#include "commands.h" +#include "defaults.h" + +#include +#include +#include + +#include // EXIT_SUCCESS +#include // std::filesystem +#include // std::cin, std::cout, std::endl + +static auto compile_from_json(sourcemeta::jsontoolkit::JSON &schema) -> int { + sourcemeta::jsonbinpack::compile( + schema, sourcemeta::jsontoolkit::default_schema_walker, + sourcemeta::jsontoolkit::official_resolver, + sourcemeta::jsonbinpack::DEFAULT_METASCHEMA); + sourcemeta::jsontoolkit::prettify(schema, std::cout); + std::cout << std::endl; + return EXIT_SUCCESS; +} + +auto sourcemeta::jsonbinpack::cli::compile( + const std::filesystem::path &schema_path) -> int { + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return compile_from_json(schema); +} + +auto sourcemeta::jsonbinpack::cli::compile() -> int { + sourcemeta::jsontoolkit::JSON schema = + sourcemeta::jsontoolkit::parse(std::cin); + return compile_from_json(schema); +} diff --git a/vendor/jsonbinpack/src/cli/command_decode.cc b/vendor/jsonbinpack/src/cli/command_decode.cc new file mode 100644 index 0000000..219d5e4 --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_decode.cc @@ -0,0 +1,46 @@ +#include "commands.h" +#include "defaults.h" + +#include +#include + +#include +#include + +#include // EXIT_SUCCESS +#include // std::filesystem +#include // std::ifstream +#include // std::ios_base, std::ios::binary +#include // std::cin, std::cout +#include // std::basic_istream + +template +static auto decode_from_stream(sourcemeta::jsontoolkit::JSON &schema, + std::basic_istream &stream) + -> int { + sourcemeta::jsonbinpack::compile( + schema, sourcemeta::jsontoolkit::default_schema_walker, + sourcemeta::jsontoolkit::official_resolver, + sourcemeta::jsonbinpack::DEFAULT_METASCHEMA); + const sourcemeta::jsonbinpack::Plan plan{ + sourcemeta::jsonbinpack::parse(schema)}; + sourcemeta::jsonbinpack::Decoder decoder{stream}; + const sourcemeta::jsontoolkit::JSON result = decoder.decode(plan); + sourcemeta::jsontoolkit::stringify(result, std::cout); + return EXIT_SUCCESS; +} + +auto sourcemeta::jsonbinpack::cli::decode( + const std::filesystem::path &schema_path, + const std::filesystem::path &data_path) -> int { + std::ifstream data_stream{data_path, std::ios::binary}; + data_stream.exceptions(std::ios_base::badbit); + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return decode_from_stream(schema, data_stream); +} + +auto sourcemeta::jsonbinpack::cli::decode( + const std::filesystem::path &schema_path) -> int { + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return decode_from_stream(schema, std::cin); +} diff --git a/vendor/jsonbinpack/src/cli/command_encode.cc b/vendor/jsonbinpack/src/cli/command_encode.cc new file mode 100644 index 0000000..b90222d --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_encode.cc @@ -0,0 +1,40 @@ +#include "commands.h" +#include "defaults.h" + +#include +#include + +#include +#include + +#include // EXIT_SUCCESS +#include // std::filesystem +#include // std::cin, std::cout + +static auto encode_from_json(sourcemeta::jsontoolkit::JSON &schema, + const sourcemeta::jsontoolkit::JSON &instance) + -> int { + sourcemeta::jsonbinpack::compile( + schema, sourcemeta::jsontoolkit::default_schema_walker, + sourcemeta::jsontoolkit::official_resolver, + sourcemeta::jsonbinpack::DEFAULT_METASCHEMA); + const sourcemeta::jsonbinpack::Plan plan{ + sourcemeta::jsonbinpack::parse(schema)}; + sourcemeta::jsonbinpack::Encoder encoder{std::cout}; + encoder.encode(instance, plan); + return EXIT_SUCCESS; +} + +auto sourcemeta::jsonbinpack::cli::encode( + const std::filesystem::path &schema_path, + const std::filesystem::path &instance_path) -> int { + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return encode_from_json(schema, + sourcemeta::jsontoolkit::from_file(instance_path)); +} + +auto sourcemeta::jsonbinpack::cli::encode( + const std::filesystem::path &schema_path) -> int { + auto schema = sourcemeta::jsontoolkit::from_file(schema_path); + return encode_from_json(schema, sourcemeta::jsontoolkit::parse(std::cin)); +} diff --git a/vendor/jsonbinpack/src/cli/command_help.cc b/vendor/jsonbinpack/src/cli/command_help.cc new file mode 100644 index 0000000..0983221 --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_help.cc @@ -0,0 +1,38 @@ +#include "commands.h" + +#include // EXIT_SUCCESS +#include // std::cerr + +static const char *USAGE_DETAILS = R"EOF( + version Print version information and quit. + + help Print this help information and quit. + + canonicalize [schema.json] Canonicalize a given JSON Schema definition + and print the result to stdout. If a path to + a schema is not provided, the schema will + be read from standard input. + + compile [schema.json] Compile a given JSON Schema definition + into an encoding schema and print the result to + stdout. If a path to a schema is not provided, + the schema will be read from standard input. + + encode [data.json] Encode a given JSON instance based on the given + encoding schema (or JSON Schema) and print the + results to stdout. If a path to the instance is + not provided, the instance will be read from + standard input. + + decode [data.bin] Decode a given bit-string based on the given + encoding schema (or JSON Schema) and print the + results to stdout. If a path to the bit-string + is not provided, it will be read from standard + input. +)EOF"; + +auto sourcemeta::jsonbinpack::cli::help(const std::string &program) -> int { + std::clog << "Usage: " << program << " [arguments...]\n"; + std::clog << USAGE_DETAILS; + return EXIT_SUCCESS; +} diff --git a/vendor/jsonbinpack/src/cli/command_version.cc b/vendor/jsonbinpack/src/cli/command_version.cc new file mode 100644 index 0000000..3990e6c --- /dev/null +++ b/vendor/jsonbinpack/src/cli/command_version.cc @@ -0,0 +1,10 @@ +#include "commands.h" +#include "version.h" + +#include // EXIT_SUCCESS +#include // std::cout + +auto sourcemeta::jsonbinpack::cli::version() -> int { + std::cout << sourcemeta::jsonbinpack::VERSION << "\n"; + return EXIT_SUCCESS; +} diff --git a/vendor/jsonbinpack/src/cli/commands.h b/vendor/jsonbinpack/src/cli/commands.h new file mode 100644 index 0000000..2b41a6d --- /dev/null +++ b/vendor/jsonbinpack/src/cli/commands.h @@ -0,0 +1,22 @@ +#ifndef SOURCEMETA_JSONBINPACK_CLI_COMMANDS_H_ +#define SOURCEMETA_JSONBINPACK_CLI_COMMANDS_H_ + +#include // std::filesystem +#include // std::string + +namespace sourcemeta::jsonbinpack::cli { +auto help(const std::string &program) -> int; +auto version() -> int; +auto canonicalize(const std::filesystem::path &schema_path) -> int; +auto canonicalize() -> int; +auto compile(const std::filesystem::path &schema_path) -> int; +auto compile() -> int; +auto encode(const std::filesystem::path &schema_path, + const std::filesystem::path &instance_path) -> int; +auto encode(const std::filesystem::path &schema_path) -> int; +auto decode(const std::filesystem::path &schema_path, + const std::filesystem::path &data_path) -> int; +auto decode(const std::filesystem::path &schema_path) -> int; +} // namespace sourcemeta::jsonbinpack::cli + +#endif diff --git a/vendor/jsonbinpack/src/cli/defaults.h b/vendor/jsonbinpack/src/cli/defaults.h new file mode 100644 index 0000000..76a906f --- /dev/null +++ b/vendor/jsonbinpack/src/cli/defaults.h @@ -0,0 +1,10 @@ +#ifndef SOURCEMETA_JSONBINPACK_CLI_DEFAULTS_H_ +#define SOURCEMETA_JSONBINPACK_CLI_DEFAULTS_H_ + +namespace sourcemeta::jsonbinpack { +// TODO: Rename to dialect +const char *const DEFAULT_METASCHEMA = + "https://json-schema.org/draft/2020-12/schema"; +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/cli/main.cc b/vendor/jsonbinpack/src/cli/main.cc new file mode 100644 index 0000000..7349cc8 --- /dev/null +++ b/vendor/jsonbinpack/src/cli/main.cc @@ -0,0 +1,94 @@ +#include "commands.h" + +#include // std::min +#include // EXIT_FAILURE +#include // std::exception +#include // std::cerr +#include // std::ostringstream +#include // std::runtime_error +#include // std::vector + +static auto assert_arguments(const std::string &command, + const std::vector &arguments, + const std::vector::size_type count) + -> void { + if (arguments.size() >= count) { + return; + } + + std::ostringstream error{}; + error << "Command '" << command << "' requires " << count + << " arguments, but you passed " << arguments.size() << "."; + throw std::runtime_error(error.str()); +} + +static auto cli_main(const std::string &program, const std::string &command, + const std::vector &arguments) -> int { + if (command.empty()) { + sourcemeta::jsonbinpack::cli::help(program); + return EXIT_FAILURE; + } + + if (command == "help") { + return sourcemeta::jsonbinpack::cli::help(program); + } + + if (command == "version") { + return sourcemeta::jsonbinpack::cli::version(); + } + + if (command == "canonicalize") { + if (arguments.empty()) { + return sourcemeta::jsonbinpack::cli::canonicalize(); + } + + assert_arguments(command, arguments, 1); + return sourcemeta::jsonbinpack::cli::canonicalize(arguments.at(0)); + } + + if (command == "compile") { + if (arguments.empty()) { + return sourcemeta::jsonbinpack::cli::compile(); + } + + assert_arguments(command, arguments, 1); + return sourcemeta::jsonbinpack::cli::compile(arguments.at(0)); + } + + if (command == "encode") { + if (arguments.size() == 1) { + return sourcemeta::jsonbinpack::cli::encode(arguments.at(0)); + } + + assert_arguments(command, arguments, 2); + return sourcemeta::jsonbinpack::cli::encode(arguments.at(0), + arguments.at(1)); + } + + if (command == "decode") { + if (arguments.size() == 1) { + return sourcemeta::jsonbinpack::cli::decode(arguments.at(0)); + } + + assert_arguments(command, arguments, 2); + return sourcemeta::jsonbinpack::cli::decode(arguments.at(0), + arguments.at(1)); + } + + std::cerr << "Unknown command: " << command << "\n"; + return EXIT_FAILURE; +} + +auto main(int argc, char *argv[]) -> int { + const std::string program{argv[0]}; + const std::string command{argc > 1 ? argv[1] : ""}; + const std::vector arguments{argv + std::min(2, argc), + argv + argc}; + + try { + return cli_main(program, command, arguments); + } catch (const std::exception &error) { + std::cerr << "Error: " << error.what() << "\n"; + return EXIT_FAILURE; + } +} diff --git a/vendor/jsonbinpack/src/cli/version.h.in b/vendor/jsonbinpack/src/cli/version.h.in new file mode 100644 index 0000000..3cc1e7b --- /dev/null +++ b/vendor/jsonbinpack/src/cli/version.h.in @@ -0,0 +1,10 @@ +#ifndef SOURCEMETA_JSONBINPACK_CLI_VERSION_H_ +#define SOURCEMETA_JSONBINPACK_CLI_VERSION_H_ + +namespace sourcemeta { + namespace jsonbinpack { + const char * const VERSION = "@CMAKE_PROJECT_VERSION@"; + } +} + +#endif diff --git a/vendor/jsonbinpack/src/compiler/CMakeLists.txt b/vendor/jsonbinpack/src/compiler/CMakeLists.txt new file mode 100644 index 0000000..86fa5df --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/CMakeLists.txt @@ -0,0 +1,34 @@ +noa_library(NAMESPACE sourcemeta PROJECT jsonbinpack NAME compiler + FOLDER "JSON BinPack/Compiler" + SOURCES + encoding.h compiler.cc + mapper/enum_8_bit.h + mapper/enum_8_bit_top_level.h + mapper/enum_arbitrary.h + mapper/enum_singleton.h + mapper/integer_bounded_8_bit.h + mapper/integer_bounded_greater_than_8_bit.h + mapper/integer_bounded_multiplier_8_bit.h + mapper/integer_bounded_multiplier_greater_than_8_bit.h + mapper/integer_lower_bound.h + mapper/integer_lower_bound_multiplier.h + mapper/integer_unbound.h + mapper/integer_unbound_multiplier.h + mapper/integer_upper_bound.h + mapper/integer_upper_bound_multiplier.h + mapper/number_arbitrary.h) + +if(JSONBINPACK_INSTALL) + noa_library_install(NAMESPACE sourcemeta PROJECT jsonbinpack NAME compiler) +endif() + +target_link_libraries(sourcemeta_jsonbinpack_compiler PRIVATE + sourcemeta::jsonbinpack::numeric) +target_link_libraries(sourcemeta_jsonbinpack_compiler PUBLIC + sourcemeta::jsontoolkit::json) +target_link_libraries(sourcemeta_jsonbinpack_compiler PUBLIC + sourcemeta::jsontoolkit::jsonschema) +target_link_libraries(sourcemeta_jsonbinpack_compiler PRIVATE + sourcemeta::alterschema::engine) +target_link_libraries(sourcemeta_jsonbinpack_compiler PRIVATE + sourcemeta::alterschema::linter) diff --git a/vendor/jsonbinpack/src/compiler/compiler.cc b/vendor/jsonbinpack/src/compiler/compiler.cc new file mode 100644 index 0000000..43e2ff9 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/compiler.cc @@ -0,0 +1,92 @@ +#include +#include + +#include +#include + +#include "encoding.h" + +namespace sourcemeta::jsonbinpack { + +auto canonicalize(sourcemeta::jsontoolkit::JSON &schema, + const sourcemeta::jsontoolkit::SchemaWalker &walker, + const sourcemeta::jsontoolkit::SchemaResolver &resolver, + const std::optional &default_dialect) -> void { + namespace alterschema = sourcemeta::alterschema; + alterschema::Bundle canonicalizer; + alterschema::add(canonicalizer, alterschema::LinterCategory::AntiPattern); + alterschema::add(canonicalizer, alterschema::LinterCategory::Simplify); + alterschema::add(canonicalizer, alterschema::LinterCategory::Desugar); + alterschema::add(canonicalizer, alterschema::LinterCategory::Implicit); + alterschema::add(canonicalizer, alterschema::LinterCategory::Superfluous); + canonicalizer.apply(schema, walker, make_resolver(resolver), + sourcemeta::jsontoolkit::empty_pointer, default_dialect); +} + +auto make_encoding(sourcemeta::alterschema::Transformer &document, + const std::string &encoding, + const sourcemeta::jsontoolkit::JSON &options) -> void { + document.replace(sourcemeta::jsontoolkit::JSON::make_object()); + document.assign("$schema", sourcemeta::jsontoolkit::JSON{ENCODING_V1}); + document.assign("binpackEncoding", sourcemeta::jsontoolkit::JSON{encoding}); + document.assign("binpackOptions", options); +} + +#include "mapper/enum_8_bit.h" +#include "mapper/enum_8_bit_top_level.h" +#include "mapper/enum_arbitrary.h" +#include "mapper/enum_singleton.h" +#include "mapper/integer_bounded_8_bit.h" +#include "mapper/integer_bounded_greater_than_8_bit.h" +#include "mapper/integer_bounded_multiplier_8_bit.h" +#include "mapper/integer_bounded_multiplier_greater_than_8_bit.h" +#include "mapper/integer_lower_bound.h" +#include "mapper/integer_lower_bound_multiplier.h" +#include "mapper/integer_unbound.h" +#include "mapper/integer_unbound_multiplier.h" +#include "mapper/integer_upper_bound.h" +#include "mapper/integer_upper_bound_multiplier.h" +#include "mapper/number_arbitrary.h" + +auto compile(sourcemeta::jsontoolkit::JSON &schema, + const sourcemeta::jsontoolkit::SchemaWalker &walker, + const sourcemeta::jsontoolkit::SchemaResolver &resolver, + const std::optional &default_dialect) -> void { + canonicalize(schema, walker, resolver, default_dialect); + + sourcemeta::alterschema::Bundle mapper; + + // Enums + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + + // Integers + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + mapper.add(); + + // Numbers + mapper.add(); + + mapper.apply(schema, walker, make_resolver(resolver), + sourcemeta::jsontoolkit::empty_pointer, default_dialect); + + // The "any" encoding is always the last resort + const auto dialect{sourcemeta::jsontoolkit::dialect(schema)}; + if (!dialect.has_value() || dialect.value() != ENCODING_V1) { + sourcemeta::alterschema::Transformer transformer{schema}; + make_encoding(transformer, "ANY_PACKED_TYPE_TAG_BYTE_PREFIX", + sourcemeta::jsontoolkit::JSON::make_object()); + } +} + +} // namespace sourcemeta::jsonbinpack diff --git a/vendor/jsonbinpack/src/compiler/encoding.h b/vendor/jsonbinpack/src/compiler/encoding.h new file mode 100644 index 0000000..be1f2b3 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/encoding.h @@ -0,0 +1,37 @@ +#ifndef SOURCEMETA_JSONBINPACK_COMPILER_ENCODING_H_ +#define SOURCEMETA_JSONBINPACK_COMPILER_ENCODING_H_ + +#include +#include + +#include // std::future + +namespace sourcemeta::jsonbinpack { + +constexpr auto ENCODING_V1{"tag:sourcemeta.com,2024:jsonbinpack/encoding/v1"}; + +inline auto +make_resolver(const sourcemeta::jsontoolkit::SchemaResolver &fallback) -> auto { + return [&fallback](std::string_view identifier) + -> std::future> { + std::promise> promise; + if (identifier == ENCODING_V1) { + promise.set_value(sourcemeta::jsontoolkit::parse(R"JSON({ + "$id": "tag:sourcemeta.com,2024:jsonbinpack/encoding/v1", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "tag:sourcemeta.com,2024:jsonbinpack/encoding/v1": true + } + })JSON")); + } else { + promise.set_value(fallback(identifier).get()); + } + + return promise.get_future(); + }; +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/compiler/include/sourcemeta/jsonbinpack/compiler.h b/vendor/jsonbinpack/src/compiler/include/sourcemeta/jsonbinpack/compiler.h new file mode 100644 index 0000000..5d1ca27 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/include/sourcemeta/jsonbinpack/compiler.h @@ -0,0 +1,89 @@ +#ifndef SOURCEMETA_JSONBINPACK_COMPILER_H_ +#define SOURCEMETA_JSONBINPACK_COMPILER_H_ + +#include "compiler_export.h" + +/// @defgroup compiler Compiler +/// @brief The built-time schema compiler of JSON BinPack +/// +/// This functionality is included as follows: +/// +/// ```cpp +/// #include +/// ``` + +#include +#include + +#include // std::optional +#include // std::string + +namespace sourcemeta::jsonbinpack { + +/// @ingroup compiler +/// +/// Compile a JSON Schema into an encoding schema. Keep in mind this function +/// mutates the input schema. For example: +/// +/// ```cpp +/// #include +/// #include +/// #include +/// +/// #include +/// +/// auto schema{sourcemeta::jsontoolkit::parse(R"JSON({ +/// "$schema": "https://json-schema.org/draft/2020-12/schema", +/// "type": "string" +/// })JSON")}; +/// +/// sourcemeta::jsonbinpack::compile( +/// schema, sourcemeta::jsontoolkit::default_schema_walker, +/// sourcemeta::jsontoolkit::official_resolver); +/// +/// sourcemeta::jsontoolkit::prettify(schema, std::cout); +/// std::cout << std::endl; +/// ``` +SOURCEMETA_JSONBINPACK_COMPILER_EXPORT +auto compile(sourcemeta::jsontoolkit::JSON &schema, + const sourcemeta::jsontoolkit::SchemaWalker &walker, + const sourcemeta::jsontoolkit::SchemaResolver &resolver, + const std::optional &default_dialect = std::nullopt) + -> void; + +/// @ingroup compiler +/// +/// Transform a JSON Schema into its canonical form to prepare it for +/// compilation. Keep in mind this function mutates the input schema. Also, the +/// `compile` function already performs canonicalization. This function is +/// exposed mainly for debugging and testing purposes. For example: +/// +/// ```cpp +/// #include +/// #include +/// #include +/// +/// #include +/// +/// auto schema{sourcemeta::jsontoolkit::parse(R"JSON({ +/// "$schema": "https://json-schema.org/draft/2020-12/schema", +/// "type": "string" +/// })JSON")}; +/// +/// sourcemeta::jsonbinpack::canonicalize( +/// schema, sourcemeta::jsontoolkit::default_schema_walker, +/// sourcemeta::jsontoolkit::official_resolver); +/// +/// sourcemeta::jsontoolkit::prettify(schema, std::cout); +/// std::cout << std::endl; +/// ``` +SOURCEMETA_JSONBINPACK_COMPILER_EXPORT +auto canonicalize( + sourcemeta::jsontoolkit::JSON &schema, + const sourcemeta::jsontoolkit::SchemaWalker &walker, + const sourcemeta::jsontoolkit::SchemaResolver &resolver, + const std::optional &default_dialect = std::nullopt) -> void; + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit.h b/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit.h new file mode 100644 index 0000000..476d893 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit.h @@ -0,0 +1,24 @@ +// TODO: Unit test this mapping once we have container encodings +class Enum8Bit final : public sourcemeta::alterschema::Rule { +public: + Enum8Bit() : sourcemeta::alterschema::Rule{"enum_8_bit", ""} {}; + + [[nodiscard]] auto condition( + const sourcemeta::jsontoolkit::JSON &schema, const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &pointer) const -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("enum") && schema.at("enum").is_array() && + !pointer.empty() && schema.at("enum").size() > 1 && + is_byte(schema.at("enum").size() - 1); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("choices", transformer.schema().at("enum")); + make_encoding(transformer, "BYTE_CHOICE_INDEX", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit_top_level.h b/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit_top_level.h new file mode 100644 index 0000000..4dc10d1 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/enum_8_bit_top_level.h @@ -0,0 +1,24 @@ +class Enum8BitTopLevel final : public sourcemeta::alterschema::Rule { +public: + Enum8BitTopLevel() + : sourcemeta::alterschema::Rule{"enum_8_bit_top_level", ""} {}; + + [[nodiscard]] auto condition( + const sourcemeta::jsontoolkit::JSON &schema, const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &pointer) const -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("enum") && schema.at("enum").is_array() && + pointer.empty() && schema.at("enum").size() > 1 && + is_byte(schema.at("enum").size() - 1); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("choices", transformer.schema().at("enum")); + make_encoding(transformer, "TOP_LEVEL_BYTE_CHOICE_INDEX", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/enum_arbitrary.h b/vendor/jsonbinpack/src/compiler/mapper/enum_arbitrary.h new file mode 100644 index 0000000..759ad52 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/enum_arbitrary.h @@ -0,0 +1,24 @@ +// TODO: Unit test this mapping once we have container encodings +class EnumArbitrary final : public sourcemeta::alterschema::Rule { +public: + EnumArbitrary() : sourcemeta::alterschema::Rule{"enum_arbitrary", ""} {}; + + [[nodiscard]] auto condition( + const sourcemeta::jsontoolkit::JSON &schema, const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &pointer) const -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("enum") && schema.at("enum").is_array() && + !pointer.empty() && schema.at("enum").size() > 1 && + !is_byte(schema.at("enum").size() - 1); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("choices", transformer.schema().at("enum")); + make_encoding(transformer, "LARGE_CHOICE_INDEX", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/enum_singleton.h b/vendor/jsonbinpack/src/compiler/mapper/enum_singleton.h new file mode 100644 index 0000000..3bce745 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/enum_singleton.h @@ -0,0 +1,23 @@ +class EnumSingleton final : public sourcemeta::alterschema::Rule { +public: + EnumSingleton() : sourcemeta::alterschema::Rule{"enum_singleton", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("enum") && schema.at("enum").is_array() && + schema.at("enum").size() == 1; + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("value", transformer.schema().at("enum").at(0)); + make_encoding(transformer, "CONST_NONE", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_8_bit.h b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_8_bit.h new file mode 100644 index 0000000..c045043 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_8_bit.h @@ -0,0 +1,32 @@ +class IntegerBounded8Bit final : public sourcemeta::alterschema::Rule { +public: + IntegerBounded8Bit() + : sourcemeta::alterschema::Rule{"integer_bounded_8_bit", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + schema.defines("minimum") && schema.defines("maximum") && + is_byte(schema.at("maximum").to_integer() - + schema.at("minimum").to_integer()) && + !schema.defines("multipleOf"); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto maximum = transformer.schema().at("maximum"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("maximum", std::move(maximum)); + options.assign("multiplier", sourcemeta::jsontoolkit::JSON{1}); + make_encoding(transformer, "BOUNDED_MULTIPLE_8BITS_ENUM_FIXED", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_greater_than_8_bit.h b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_greater_than_8_bit.h new file mode 100644 index 0000000..866dca1 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_greater_than_8_bit.h @@ -0,0 +1,32 @@ +class IntegerBoundedGreaterThan8Bit final + : public sourcemeta::alterschema::Rule { +public: + IntegerBoundedGreaterThan8Bit() + : sourcemeta::alterschema::Rule{"integer_bounded_greater_than_8_bit", + ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + schema.defines("minimum") && schema.defines("maximum") && + !is_byte(schema.at("maximum").to_integer() - + schema.at("minimum").to_integer()) && + !schema.defines("multipleOf"); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("multiplier", sourcemeta::jsontoolkit::JSON{1}); + make_encoding(transformer, "FLOOR_MULTIPLE_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_8_bit.h b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_8_bit.h new file mode 100644 index 0000000..fd43142 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_8_bit.h @@ -0,0 +1,41 @@ +class IntegerBoundedMultiplier8Bit final + : public sourcemeta::alterschema::Rule { +public: + IntegerBoundedMultiplier8Bit() + : sourcemeta::alterschema::Rule{"integer_bounded_multiplier_8_bit", ""} { + }; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + if (dialect != "https://json-schema.org/draft/2020-12/schema" || + !vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") || + !schema.defines("type") || schema.at("type").to_string() != "integer" || + !schema.defines("minimum") || !schema.at("minimum").is_integer() || + !schema.defines("maximum") || !schema.at("maximum").is_integer() || + !schema.defines("multipleOf") || + !schema.at("multipleOf").is_integer()) { + return false; + } + + return is_byte(count_multiples(schema.at("minimum").to_integer(), + schema.at("maximum").to_integer(), + schema.at("multipleOf").to_integer())); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto maximum = transformer.schema().at("maximum"); + auto multiplier = transformer.schema().at("multipleOf"); + + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("maximum", std::move(maximum)); + options.assign("multiplier", std::move(multiplier)); + make_encoding(transformer, "BOUNDED_MULTIPLE_8BITS_ENUM_FIXED", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_greater_than_8_bit.h b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_greater_than_8_bit.h new file mode 100644 index 0000000..b4220c3 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_bounded_multiplier_greater_than_8_bit.h @@ -0,0 +1,38 @@ +class IntegerBoundedMultiplierGreaterThan8Bit final + : public sourcemeta::alterschema::Rule { +public: + IntegerBoundedMultiplierGreaterThan8Bit() + : sourcemeta::alterschema::Rule{ + "integer_bounded_multiplier_greater_than_8_bit", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + if (dialect != "https://json-schema.org/draft/2020-12/schema" || + !vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") || + !schema.defines("type") || schema.at("type").to_string() != "integer" || + !schema.defines("minimum") || !schema.at("minimum").is_integer() || + !schema.defines("maximum") || !schema.at("maximum").is_integer() || + !schema.defines("multipleOf") || + !schema.at("multipleOf").is_integer()) { + return false; + } + + return !is_byte(count_multiples(schema.at("minimum").to_integer(), + schema.at("maximum").to_integer(), + schema.at("multipleOf").to_integer())); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto multiplier = transformer.schema().at("multipleOf"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("multiplier", std::move(multiplier)); + make_encoding(transformer, "FLOOR_MULTIPLE_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound.h b/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound.h new file mode 100644 index 0000000..8177f17 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound.h @@ -0,0 +1,28 @@ +class IntegerLowerBound final : public sourcemeta::alterschema::Rule { +public: + IntegerLowerBound() + : sourcemeta::alterschema::Rule{"integer_lower_bound", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + schema.defines("minimum") && !schema.defines("maximum") && + !schema.defines("multipleOf"); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("multiplier", sourcemeta::jsontoolkit::JSON{1}); + make_encoding(transformer, "FLOOR_MULTIPLE_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound_multiplier.h b/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound_multiplier.h new file mode 100644 index 0000000..9c866a8 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_lower_bound_multiplier.h @@ -0,0 +1,29 @@ +class IntegerLowerBoundMultiplier final : public sourcemeta::alterschema::Rule { +public: + IntegerLowerBoundMultiplier() + : sourcemeta::alterschema::Rule{"integer_lower_bound_multiplier", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + schema.defines("minimum") && !schema.defines("maximum") && + schema.defines("multipleOf") && schema.at("multipleOf").is_integer(); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto minimum = transformer.schema().at("minimum"); + auto multiplier = transformer.schema().at("multipleOf"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("minimum", std::move(minimum)); + options.assign("multiplier", std::move(multiplier)); + make_encoding(transformer, "FLOOR_MULTIPLE_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_unbound.h b/vendor/jsonbinpack/src/compiler/mapper/integer_unbound.h new file mode 100644 index 0000000..1662a39 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_unbound.h @@ -0,0 +1,25 @@ +class IntegerUnbound final : public sourcemeta::alterschema::Rule { +public: + IntegerUnbound() : sourcemeta::alterschema::Rule{"integer_unbound", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + !schema.defines("minimum") && !schema.defines("maximum") && + !schema.defines("multipleOf"); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("multiplier", sourcemeta::jsontoolkit::JSON{1}); + make_encoding(transformer, "ARBITRARY_MULTIPLE_ZIGZAG_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_unbound_multiplier.h b/vendor/jsonbinpack/src/compiler/mapper/integer_unbound_multiplier.h new file mode 100644 index 0000000..1d5bfd8 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_unbound_multiplier.h @@ -0,0 +1,27 @@ +class IntegerUnboundMultiplier final : public sourcemeta::alterschema::Rule { +public: + IntegerUnboundMultiplier() + : sourcemeta::alterschema::Rule{"integer_unbound_multiplier", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + !schema.defines("minimum") && !schema.defines("maximum") && + schema.defines("multipleOf") && schema.at("multipleOf").is_integer(); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto multiplier = transformer.schema().at("multipleOf"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("multiplier", std::move(multiplier)); + make_encoding(transformer, "ARBITRARY_MULTIPLE_ZIGZAG_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound.h b/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound.h new file mode 100644 index 0000000..9473b61 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound.h @@ -0,0 +1,28 @@ +class IntegerUpperBound final : public sourcemeta::alterschema::Rule { +public: + IntegerUpperBound() + : sourcemeta::alterschema::Rule{"integer_upper_bound", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + !schema.defines("minimum") && schema.defines("maximum") && + !schema.defines("multipleOf"); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto maximum = transformer.schema().at("maximum"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("maximum", std::move(maximum)); + options.assign("multiplier", sourcemeta::jsontoolkit::JSON{1}); + make_encoding(transformer, "ROOF_MULTIPLE_MIRROR_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound_multiplier.h b/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound_multiplier.h new file mode 100644 index 0000000..03e0ca8 --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/integer_upper_bound_multiplier.h @@ -0,0 +1,29 @@ +class IntegerUpperBoundMultiplier final : public sourcemeta::alterschema::Rule { +public: + IntegerUpperBoundMultiplier() + : sourcemeta::alterschema::Rule{"integer_upper_bound_multiplier", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && + schema.at("type").to_string() == "integer" && + !schema.defines("minimum") && schema.defines("maximum") && + schema.defines("multipleOf") && schema.at("multipleOf").is_integer(); + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + auto maximum = transformer.schema().at("maximum"); + auto multiplier = transformer.schema().at("multipleOf"); + auto options = sourcemeta::jsontoolkit::JSON::make_object(); + options.assign("maximum", std::move(maximum)); + options.assign("multiplier", std::move(multiplier)); + make_encoding(transformer, "ROOF_MULTIPLE_MIRROR_ENUM_VARINT", options); + } +}; diff --git a/vendor/jsonbinpack/src/compiler/mapper/number_arbitrary.h b/vendor/jsonbinpack/src/compiler/mapper/number_arbitrary.h new file mode 100644 index 0000000..fe72cbe --- /dev/null +++ b/vendor/jsonbinpack/src/compiler/mapper/number_arbitrary.h @@ -0,0 +1,21 @@ +class NumberArbitrary final : public sourcemeta::alterschema::Rule { +public: + NumberArbitrary() : sourcemeta::alterschema::Rule{"number_arbitrary", ""} {}; + + [[nodiscard]] auto condition(const sourcemeta::jsontoolkit::JSON &schema, + const std::string &dialect, + const std::set &vocabularies, + const sourcemeta::jsontoolkit::Pointer &) const + -> bool override { + return dialect == "https://json-schema.org/draft/2020-12/schema" && + vocabularies.contains( + "https://json-schema.org/draft/2020-12/vocab/validation") && + schema.defines("type") && schema.at("type").to_string() == "number"; + } + + auto transform(sourcemeta::alterschema::Transformer &transformer) const + -> void override { + make_encoding(transformer, "DOUBLE_VARINT_TUPLE", + sourcemeta::jsontoolkit::JSON::make_object()); + } +}; diff --git a/vendor/jsonbinpack/src/numeric/CMakeLists.txt b/vendor/jsonbinpack/src/numeric/CMakeLists.txt new file mode 100644 index 0000000..7e34924 --- /dev/null +++ b/vendor/jsonbinpack/src/numeric/CMakeLists.txt @@ -0,0 +1,6 @@ +noa_library(NAMESPACE sourcemeta PROJECT jsonbinpack NAME numeric + FOLDER "JSON BinPack/Numeric") + +if(JSONBINPACK_INSTALL) + noa_library_install(NAMESPACE sourcemeta PROJECT jsonbinpack NAME numeric) +endif() diff --git a/vendor/jsonbinpack/src/numeric/include/sourcemeta/jsonbinpack/numeric.h b/vendor/jsonbinpack/src/numeric/include/sourcemeta/jsonbinpack/numeric.h new file mode 100644 index 0000000..833c713 --- /dev/null +++ b/vendor/jsonbinpack/src/numeric/include/sourcemeta/jsonbinpack/numeric.h @@ -0,0 +1,35 @@ +#ifndef SOURCEMETA_JSONBINPACK_NUMERIC_H_ +#define SOURCEMETA_JSONBINPACK_NUMERIC_H_ + +#include // std::uint8_t, std::int64_t +#include // std::numeric_limits + +/// @defgroup numeric Numeric +/// @brief A comprehensive numeric library for JSON BinPack +/// +/// This functionality is included as follows: +/// +/// ```cpp +/// #include +/// ``` + +namespace sourcemeta::jsonbinpack { + +/// @ingroup numeric +template constexpr auto is_byte(const T value) noexcept -> bool { + return value <= std::numeric_limits::max(); +} + +/// @ingroup numeric +constexpr auto count_multiples(const std::int64_t minimum, + const std::int64_t maximum, + const std::int64_t multiplier) -> std::uint64_t { + assert(minimum <= maximum); + assert(multiplier > 0); + return static_cast((maximum / multiplier) - + ((minimum - 1) / multiplier)); +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/CMakeLists.txt b/vendor/jsonbinpack/src/runtime/CMakeLists.txt new file mode 100644 index 0000000..f45673a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/CMakeLists.txt @@ -0,0 +1,15 @@ +noa_library(NAMESPACE sourcemeta PROJECT jsonbinpack NAME runtime + FOLDER "JSON BinPack/Runtime" + PRIVATE_HEADERS + decoder.h decoder_basic.h + encoder.h encoder_basic.h encoder_context.h encoder_real.h + plan.h plan_wrap.h parser.h + zigzag.h varint.h numeric.h + SOURCES runtime_parser.cc runtime_parser_v1.h) + +if(JSONBINPACK_INSTALL) + noa_library_install(NAMESPACE sourcemeta PROJECT jsonbinpack NAME runtime) +endif() + +target_link_libraries(sourcemeta_jsonbinpack_runtime PUBLIC + sourcemeta::jsontoolkit::json) diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime.h new file mode 100644 index 0000000..8e64f51 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime.h @@ -0,0 +1,18 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_H_ + +/// @defgroup runtime Runtime +/// @brief The encoder/decoder parts of JSON BinPack +/// +/// This functionality is included as follows: +/// +/// ```cpp +/// #include +/// ``` + +#include +#include +#include +#include + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder.h new file mode 100644 index 0000000..8d01b6a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder.h @@ -0,0 +1,492 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_DECODER_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_DECODER_H_ + +#include +#include +#include +#include + +#include + +#include // assert +#include // std::pow +#include // std::uint8_t, std::uint16_t, std::uint32_t, std::int64_t, std::uint64_t +#include // std::abort +#include // std::setw, std::setfill +#include // std::basic_istream +#include // std::basic_ostringstream + +namespace sourcemeta::jsonbinpack { + +/// @ingroup runtime +template +class Decoder : private BasicDecoder { +public: + Decoder(std::basic_istream &input) + : BasicDecoder{input} {} + + auto decode(const Plan &encoding) -> sourcemeta::jsontoolkit::JSON { + switch (encoding.index()) { +#define HANDLE_DECODING(index, name) \ + case (index): \ + return this->name(std::get(encoding)); + HANDLE_DECODING(0, BOUNDED_MULTIPLE_8BITS_ENUM_FIXED) + HANDLE_DECODING(1, FLOOR_MULTIPLE_ENUM_VARINT) + HANDLE_DECODING(2, ROOF_MULTIPLE_MIRROR_ENUM_VARINT) + HANDLE_DECODING(3, ARBITRARY_MULTIPLE_ZIGZAG_VARINT) + HANDLE_DECODING(4, DOUBLE_VARINT_TUPLE) + HANDLE_DECODING(5, BYTE_CHOICE_INDEX) + HANDLE_DECODING(6, LARGE_CHOICE_INDEX) + HANDLE_DECODING(7, TOP_LEVEL_BYTE_CHOICE_INDEX) + HANDLE_DECODING(8, CONST_NONE) + HANDLE_DECODING(9, UTF8_STRING_NO_LENGTH) + HANDLE_DECODING(10, FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED) + HANDLE_DECODING(11, ROOF_VARINT_PREFIX_UTF8_STRING_SHARED) + HANDLE_DECODING(12, BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED) + HANDLE_DECODING(13, RFC3339_DATE_INTEGER_TRIPLET) + HANDLE_DECODING(14, PREFIX_VARINT_LENGTH_STRING_SHARED) + HANDLE_DECODING(15, FIXED_TYPED_ARRAY) + HANDLE_DECODING(16, BOUNDED_8BITS_TYPED_ARRAY) + HANDLE_DECODING(17, FLOOR_TYPED_ARRAY) + HANDLE_DECODING(18, ROOF_TYPED_ARRAY) + HANDLE_DECODING(19, FIXED_TYPED_ARBITRARY_OBJECT) + HANDLE_DECODING(20, VARINT_TYPED_ARBITRARY_OBJECT) + HANDLE_DECODING(21, ANY_PACKED_TYPE_TAG_BYTE_PREFIX) +#undef HANDLE_DECODING + } + + // We should never get here. If so, it is definitely a bug + assert(false); + std::abort(); + } + +// The methods that implement individual encodings as considered private +#ifndef DOXYGEN + + auto BOUNDED_MULTIPLE_8BITS_ENUM_FIXED( + const BOUNDED_MULTIPLE_8BITS_ENUM_FIXED &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.multiplier > 0); + const std::uint8_t byte{this->get_byte()}; + const std::int64_t closest_minimum{ + divide_ceil(options.minimum, options.multiplier)}; + if (closest_minimum >= 0) { + const std::uint64_t closest_minimum_multiple{ + static_cast(closest_minimum) * options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{static_cast( + (byte * options.multiplier) + closest_minimum_multiple)}; + } else { + const std::uint64_t closest_minimum_multiple{abs(closest_minimum) * + options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{static_cast( + (byte * options.multiplier) - closest_minimum_multiple)}; + } + } + + auto FLOOR_MULTIPLE_ENUM_VARINT(const FLOOR_MULTIPLE_ENUM_VARINT &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.multiplier > 0); + const std::int64_t closest_minimum{ + divide_ceil(options.minimum, options.multiplier)}; + if (closest_minimum >= 0) { + const std::uint64_t closest_minimum_multiple{ + static_cast(closest_minimum) * options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{ + static_cast((this->get_varint() * options.multiplier) + + closest_minimum_multiple)}; + } else { + const std::uint64_t closest_minimum_multiple{abs(closest_minimum) * + options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{ + static_cast((this->get_varint() * options.multiplier) - + closest_minimum_multiple)}; + } + } + + auto ROOF_MULTIPLE_MIRROR_ENUM_VARINT( + const ROOF_MULTIPLE_MIRROR_ENUM_VARINT &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.multiplier > 0); + const std::int64_t closest_maximum{ + divide_floor(options.maximum, options.multiplier)}; + if (closest_maximum >= 0) { + const std::uint64_t closest_maximum_multiple{ + static_cast(closest_maximum) * options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{static_cast( + -(static_cast(this->get_varint() * + options.multiplier)) + + static_cast(closest_maximum_multiple))}; + } else { + const std::uint64_t closest_maximum_multiple{abs(closest_maximum) * + options.multiplier}; + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{static_cast( + -(static_cast(this->get_varint() * + options.multiplier)) - + static_cast(closest_maximum_multiple))}; + } + } + + auto ARBITRARY_MULTIPLE_ZIGZAG_VARINT( + const ARBITRARY_MULTIPLE_ZIGZAG_VARINT &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.multiplier > 0); + // We trust the encoder that the data we are seeing + // corresponds to a valid 64-bit signed integer. + return sourcemeta::jsontoolkit::JSON{static_cast( + this->get_varint_zigzag() * + static_cast(options.multiplier))}; + } + + auto DOUBLE_VARINT_TUPLE(const DOUBLE_VARINT_TUPLE &) + -> sourcemeta::jsontoolkit::JSON { + const std::int64_t digits{this->get_varint_zigzag()}; + const std::uint64_t point{this->get_varint()}; + const double divisor{std::pow(10, static_cast(point))}; + return sourcemeta::jsontoolkit::JSON{static_cast(digits) / divisor}; + } + + auto BYTE_CHOICE_INDEX(const BYTE_CHOICE_INDEX &options) + -> sourcemeta::jsontoolkit::JSON { + assert(!options.choices.empty()); + assert(is_byte(options.choices.size())); + const std::uint8_t index{this->get_byte()}; + assert(options.choices.size() > index); + return options.choices[index]; + } + + auto LARGE_CHOICE_INDEX(const LARGE_CHOICE_INDEX &options) + -> sourcemeta::jsontoolkit::JSON { + assert(!options.choices.empty()); + const std::uint64_t index{this->get_varint()}; + assert(options.choices.size() > index); + return options.choices[index]; + } + + auto TOP_LEVEL_BYTE_CHOICE_INDEX(const TOP_LEVEL_BYTE_CHOICE_INDEX &options) + -> sourcemeta::jsontoolkit::JSON { + assert(!options.choices.empty()); + assert(is_byte(options.choices.size())); + if (!this->has_more_data()) { + return options.choices.front(); + } else { + const std::uint16_t index{ + static_cast(this->get_byte() + 1)}; + assert(options.choices.size() > index); + return options.choices[index]; + } + } + + auto CONST_NONE(const CONST_NONE &options) -> sourcemeta::jsontoolkit::JSON { + return options.value; + } + + auto UTF8_STRING_NO_LENGTH(const UTF8_STRING_NO_LENGTH &options) + -> sourcemeta::jsontoolkit::JSON { + return sourcemeta::jsontoolkit::JSON{this->get_string_utf8(options.size)}; + } + + auto FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED( + const FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t prefix{this->get_varint()}; + const bool is_shared{prefix == 0}; + const std::uint64_t length{(is_shared ? this->get_varint() : prefix) + + options.minimum - 1}; + assert(length >= options.minimum); + + if (is_shared) { + const std::uint64_t position{this->position()}; + const std::uint64_t current{this->rewind(this->get_varint(), position)}; + sourcemeta::jsontoolkit::JSON string{this->get_string_utf8(length)}; + this->seek(current); + return string; + } else { + return UTF8_STRING_NO_LENGTH({length}); + } + } + + auto ROOF_VARINT_PREFIX_UTF8_STRING_SHARED( + const ROOF_VARINT_PREFIX_UTF8_STRING_SHARED &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t prefix{this->get_varint()}; + const bool is_shared{prefix == 0}; + const std::uint64_t length{options.maximum - + (is_shared ? this->get_varint() : prefix) + 1}; + assert(length <= options.maximum); + + if (is_shared) { + const std::uint64_t position{this->position()}; + const std::uint64_t current{this->rewind(this->get_varint(), position)}; + sourcemeta::jsontoolkit::JSON string = UTF8_STRING_NO_LENGTH({length}); + this->seek(current); + return string; + } else { + return UTF8_STRING_NO_LENGTH({length}); + } + } + + auto BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED( + const BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.minimum <= options.maximum); + assert(is_byte(options.maximum - options.minimum)); + const std::uint8_t prefix{this->get_byte()}; + const bool is_shared{prefix == 0}; + const std::uint64_t length{(is_shared ? this->get_byte() : prefix) + + options.minimum - 1}; + assert(is_within(length, options.minimum, options.maximum)); + + if (is_shared) { + const std::uint64_t position{this->position()}; + const std::uint64_t current{this->rewind(this->get_varint(), position)}; + sourcemeta::jsontoolkit::JSON string = UTF8_STRING_NO_LENGTH({length}); + this->seek(current); + return string; + } else { + return UTF8_STRING_NO_LENGTH({length}); + } + } + + auto RFC3339_DATE_INTEGER_TRIPLET(const RFC3339_DATE_INTEGER_TRIPLET &) + -> sourcemeta::jsontoolkit::JSON { + const std::uint16_t year{this->get_word()}; + const std::uint8_t month{this->get_byte()}; + const std::uint8_t day{this->get_byte()}; + + assert(year <= 9999); + assert(month >= 1 && month <= 12); + assert(day >= 1 && day <= 31); + + std::basic_ostringstream output; + output << std::setfill('0'); + output << std::setw(4) << year; + output << "-"; + // Cast the bytes to a larger integer, otherwise + // they will be interpreted as characters. + output << std::setw(2) << static_cast(month); + output << "-"; + output << std::setw(2) << static_cast(day); + + return sourcemeta::jsontoolkit::JSON{output.str()}; + } + + auto PREFIX_VARINT_LENGTH_STRING_SHARED( + const PREFIX_VARINT_LENGTH_STRING_SHARED &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t prefix{this->get_varint()}; + if (prefix == 0) { + const std::uint64_t position{this->position()}; + const std::uint64_t current{this->rewind(this->get_varint(), position)}; + sourcemeta::jsontoolkit::JSON string = + PREFIX_VARINT_LENGTH_STRING_SHARED(options); + this->seek(current); + return string; + } else { + return sourcemeta::jsontoolkit::JSON{this->get_string_utf8(prefix - 1)}; + } + } + + // TODO: Implement STRING_BROTLI encoding + // TODO: Implement STRING_DICTIONARY_COMPRESSOR encoding + // TODO: Implement STRING_UNBOUNDED_SCOPED_PREFIX_LENGTH encoding + // TODO: Implement URL_PROTOCOL_HOST_REST encoding + + auto FIXED_TYPED_ARRAY(const FIXED_TYPED_ARRAY &options) + -> sourcemeta::jsontoolkit::JSON { + const auto prefix_encodings{options.prefix_encodings.size()}; + sourcemeta::jsontoolkit::JSON result = + sourcemeta::jsontoolkit::JSON::make_array(); + for (std::size_t index = 0; index < options.size; index++) { + const Plan &encoding{prefix_encodings > index + ? options.prefix_encodings[index].value + : options.encoding->value}; + result.push_back(this->decode(encoding)); + } + + assert(result.size() == options.size); + return result; + }; + + auto BOUNDED_8BITS_TYPED_ARRAY(const BOUNDED_8BITS_TYPED_ARRAY &options) + -> sourcemeta::jsontoolkit::JSON { + assert(options.maximum >= options.minimum); + assert(is_byte(options.maximum - options.minimum)); + const std::uint8_t byte{this->get_byte()}; + const std::uint64_t size{byte + options.minimum}; + assert(is_within(size, options.minimum, options.maximum)); + return this->FIXED_TYPED_ARRAY({size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + }; + + auto FLOOR_TYPED_ARRAY(const FLOOR_TYPED_ARRAY &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t value{this->get_varint()}; + const std::uint64_t size{value + options.minimum}; + assert(size >= value); + assert(size >= options.minimum); + return this->FIXED_TYPED_ARRAY({size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + }; + + auto ROOF_TYPED_ARRAY(const ROOF_TYPED_ARRAY &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t value{this->get_varint()}; + const std::uint64_t size{options.maximum - value}; + assert(size <= options.maximum); + return this->FIXED_TYPED_ARRAY({size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + }; + + auto FIXED_TYPED_ARBITRARY_OBJECT(const FIXED_TYPED_ARBITRARY_OBJECT &options) + -> sourcemeta::jsontoolkit::JSON { + sourcemeta::jsontoolkit::JSON document = + sourcemeta::jsontoolkit::JSON::make_object(); + for (std::size_t index = 0; index < options.size; index++) { + const sourcemeta::jsontoolkit::JSON key = + this->decode(options.key_encoding->value); + assert(key.is_string()); + document.assign(key.to_string(), this->decode(options.encoding->value)); + } + + assert(document.size() == options.size); + return document; + }; + + auto + VARINT_TYPED_ARBITRARY_OBJECT(const VARINT_TYPED_ARBITRARY_OBJECT &options) + -> sourcemeta::jsontoolkit::JSON { + const std::uint64_t size{this->get_varint()}; + sourcemeta::jsontoolkit::JSON document = + sourcemeta::jsontoolkit::JSON::make_object(); + for (std::size_t index = 0; index < size; index++) { + const sourcemeta::jsontoolkit::JSON key = + this->decode(options.key_encoding->value); + assert(key.is_string()); + document.assign(key.to_string(), this->decode(options.encoding->value)); + } + + assert(document.size() == size); + return document; + }; + + auto ANY_PACKED_TYPE_TAG_BYTE_PREFIX(const ANY_PACKED_TYPE_TAG_BYTE_PREFIX &) + -> sourcemeta::jsontoolkit::JSON { + using namespace internal::ANY_PACKED_TYPE_TAG_BYTE_PREFIX; + const std::uint8_t byte{this->get_byte()}; + const std::uint8_t type{ + static_cast(byte & (0xff >> subtype_size))}; + const std::uint8_t subtype{static_cast(byte >> type_size)}; + + if (type == TYPE_OTHER) { + switch (subtype) { + case SUBTYPE_NULL: + return sourcemeta::jsontoolkit::JSON{nullptr}; + case SUBTYPE_FALSE: + return sourcemeta::jsontoolkit::JSON{false}; + case SUBTYPE_TRUE: + return sourcemeta::jsontoolkit::JSON{true}; + case SUBTYPE_NUMBER: + return this->DOUBLE_VARINT_TUPLE({}); + case SUBTYPE_POSITIVE_INTEGER: + return sourcemeta::jsontoolkit::JSON{ + static_cast(this->get_varint())}; + case SUBTYPE_NEGATIVE_INTEGER: + return sourcemeta::jsontoolkit::JSON{ + -static_cast(this->get_varint()) - 1}; + case SUBTYPE_LONG_STRING_BASE_EXPONENT_7: + return sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(this->get_varint() + 128)}; + case SUBTYPE_LONG_STRING_BASE_EXPONENT_8: + return sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(this->get_varint() + 256)}; + case SUBTYPE_LONG_STRING_BASE_EXPONENT_9: + return sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(this->get_varint() + 512)}; + case SUBTYPE_LONG_STRING_BASE_EXPONENT_10: + return sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(this->get_varint() + 1024)}; + } + + // We should never get here. If so, it is definitely a bug + assert(false); + std::abort(); + } else { + switch (type) { + case TYPE_POSITIVE_INTEGER_BYTE: + return sourcemeta::jsontoolkit::JSON{subtype > 0 ? subtype - 1 + : this->get_byte()}; + case TYPE_NEGATIVE_INTEGER_BYTE: + return sourcemeta::jsontoolkit::JSON{ + subtype > 0 ? static_cast(-subtype) + : static_cast(-this->get_byte() - 1)}; + case TYPE_SHARED_STRING: { + const auto length = subtype == 0 + ? this->get_varint() - 1 + uint_max<5> * 2 + : subtype - 1; + const std::uint64_t position{this->position()}; + const std::uint64_t current{ + this->rewind(this->get_varint(), position)}; + sourcemeta::jsontoolkit::JSON string{this->get_string_utf8(length)}; + this->seek(current); + return string; + }; + case TYPE_STRING: + return subtype == 0 ? this->FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED( + {uint_max<5> * 2}) + : sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(subtype - 1)}; + case TYPE_LONG_STRING: + return sourcemeta::jsontoolkit::JSON{ + this->get_string_utf8(subtype + uint_max<5>)}; + case TYPE_ARRAY: + return subtype == 0 + ? this->FIXED_TYPED_ARRAY( + {this->get_varint() + uint_max<5>, + wrap(sourcemeta::jsonbinpack:: + ANY_PACKED_TYPE_TAG_BYTE_PREFIX{}), + {}}) + : this->FIXED_TYPED_ARRAY( + {static_cast(subtype - 1), + wrap(sourcemeta::jsonbinpack:: + ANY_PACKED_TYPE_TAG_BYTE_PREFIX{}), + {}}); + case TYPE_OBJECT: + return subtype == 0 + ? this->FIXED_TYPED_ARBITRARY_OBJECT( + {this->get_varint() + uint_max<5>, + wrap(sourcemeta::jsonbinpack:: + PREFIX_VARINT_LENGTH_STRING_SHARED{}), + wrap(sourcemeta::jsonbinpack:: + ANY_PACKED_TYPE_TAG_BYTE_PREFIX{})}) + : this->FIXED_TYPED_ARBITRARY_OBJECT( + {static_cast(subtype - 1), + wrap(sourcemeta::jsonbinpack:: + PREFIX_VARINT_LENGTH_STRING_SHARED{}), + wrap(sourcemeta::jsonbinpack:: + ANY_PACKED_TYPE_TAG_BYTE_PREFIX{})}); + } + + // We should never get here. If so, it is definitely a bug + assert(false); + std::abort(); + } + } + +#endif +}; + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder_basic.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder_basic.h new file mode 100644 index 0000000..3b7af0a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_decoder_basic.h @@ -0,0 +1,99 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_DECODER_BASIC_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_DECODER_BASIC_H_ +#ifndef DOXYGEN + +#include +#include + +#include // assert +#include // std::ceil +#include // std::uint8_t, std::int64_t, std::uint64_t +#include // std::ios_base +#include // std::basic_istream + +namespace sourcemeta::jsonbinpack { + +template class BasicDecoder { +public: + BasicDecoder(std::basic_istream &input) : stream{input} { + this->stream.exceptions(std::ios_base::badbit | std::ios_base::failbit | + std::ios_base::eofbit); + } + + // Prevent copying, as this class is tied to a stream resource + BasicDecoder(const BasicDecoder &) = delete; + auto operator=(const BasicDecoder &) -> BasicDecoder & = delete; + + inline auto position() const noexcept -> std::uint64_t { + return static_cast(this->stream.tellg()); + } + + inline auto seek(const std::uint64_t offset) -> void { + this->stream.seekg(static_cast(offset)); + } + + // Seek backwards given a relative offset + inline auto rewind(const std::uint64_t relative_offset, + const std::uint64_t position) -> std::uint64_t { + assert(position >= relative_offset); + const std::uint64_t offset{position - relative_offset}; + assert(offset < position); + const std::uint64_t current{this->position()}; + this->seek(offset); + return current; + } + + inline auto get_byte() -> std::uint8_t { + return static_cast(this->stream.get()); + } + + // A "word" corresponds to two bytes + // See https://stackoverflow.com/questions/28066462/how-many-bits-is-a-word + inline auto get_word() -> std::uint16_t { + std::uint16_t word; + this->stream.read(reinterpret_cast(&word), sizeof word); + return word; + } + + inline auto get_varint() -> std::uint64_t { + return varint_decode(this->stream); + } + + inline auto get_varint_zigzag() -> std::int64_t { + const std::uint64_t value = varint_decode(this->stream); + return zigzag_decode(value); + } + + inline auto has_more_data() const noexcept -> bool { + // A way to check if the stream is empty without using `.peek()`, + // which throws given we set exceptions on the EOF bit. + // However, `in_avail()` works on characters and will return zero + // if all that's remaining is 0x00 (null), so we need to handle + // that case separately. + return this->stream.rdbuf()->in_avail() > 0 || + this->stream.rdbuf()->sgetc() == '\0'; + } + + inline auto get_string_utf8(const std::uint64_t length) + -> std::basic_string { + std::basic_string result; + result.reserve(length); + std::uint64_t counter = 0; + while (counter < length) { + result += static_cast(this->get_byte()); + counter += 1; + } + + assert(counter == length); + assert(result.size() == length); + return result; + } + +private: + std::basic_istream &stream; +}; + +} // namespace sourcemeta::jsonbinpack + +#endif +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder.h new file mode 100644 index 0000000..bee9ca0 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder.h @@ -0,0 +1,549 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_H_ + +#include +#include +#include +#include +#include + +#include + +#include // std::uint8_t, std::uint16_t, std::int64_t, std::uint64_t +#include // std::abort +#include // std::basic_ostream +#include // std::basic_string, std::stoul +#include // std::move + +namespace sourcemeta::jsonbinpack { + +/// @ingroup runtime +template +class Encoder : private BasicEncoder { +public: + Encoder(std::basic_ostream &output) + : BasicEncoder{output} {} + + auto encode(const sourcemeta::jsontoolkit::JSON &document, + const Plan &encoding) -> void { + switch (encoding.index()) { +#define HANDLE_ENCODING(index, name) \ + case (index): \ + return this->name(document, \ + std::get(encoding)); + HANDLE_ENCODING(0, BOUNDED_MULTIPLE_8BITS_ENUM_FIXED) + HANDLE_ENCODING(1, FLOOR_MULTIPLE_ENUM_VARINT) + HANDLE_ENCODING(2, ROOF_MULTIPLE_MIRROR_ENUM_VARINT) + HANDLE_ENCODING(3, ARBITRARY_MULTIPLE_ZIGZAG_VARINT) + HANDLE_ENCODING(4, DOUBLE_VARINT_TUPLE) + HANDLE_ENCODING(5, BYTE_CHOICE_INDEX) + HANDLE_ENCODING(6, LARGE_CHOICE_INDEX) + HANDLE_ENCODING(7, TOP_LEVEL_BYTE_CHOICE_INDEX) + HANDLE_ENCODING(8, CONST_NONE) + HANDLE_ENCODING(9, UTF8_STRING_NO_LENGTH) + HANDLE_ENCODING(10, FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED) + HANDLE_ENCODING(11, ROOF_VARINT_PREFIX_UTF8_STRING_SHARED) + HANDLE_ENCODING(12, BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED) + HANDLE_ENCODING(13, RFC3339_DATE_INTEGER_TRIPLET) + HANDLE_ENCODING(14, PREFIX_VARINT_LENGTH_STRING_SHARED) + HANDLE_ENCODING(15, FIXED_TYPED_ARRAY) + HANDLE_ENCODING(16, BOUNDED_8BITS_TYPED_ARRAY) + HANDLE_ENCODING(17, FLOOR_TYPED_ARRAY) + HANDLE_ENCODING(18, ROOF_TYPED_ARRAY) + HANDLE_ENCODING(19, FIXED_TYPED_ARBITRARY_OBJECT) + HANDLE_ENCODING(20, VARINT_TYPED_ARBITRARY_OBJECT) + HANDLE_ENCODING(21, ANY_PACKED_TYPE_TAG_BYTE_PREFIX) +#undef HANDLE_ENCODING + } + + // We should never get here. If so, it is definitely a bug + assert(false); + std::abort(); + } + +// The methods that implement individual encodings as considered private +#ifndef DOXYGEN + + auto BOUNDED_MULTIPLE_8BITS_ENUM_FIXED( + const sourcemeta::jsontoolkit::JSON &document, + const BOUNDED_MULTIPLE_8BITS_ENUM_FIXED &options) -> void { + assert(document.is_integer()); + const std::int64_t value{document.to_integer()}; + assert(is_within(value, options.minimum, options.maximum)); + assert(options.multiplier > 0); + assert(abs(value) % options.multiplier == 0); + const std::int64_t enum_minimum{ + divide_ceil(options.minimum, options.multiplier)}; +#ifndef NDEBUG + const std::int64_t enum_maximum{ + divide_floor(options.maximum, options.multiplier)}; +#endif + assert(is_byte(enum_maximum - enum_minimum)); + this->put_byte(static_cast( + (value / static_cast(options.multiplier)) - + enum_minimum)); + } + + auto FLOOR_MULTIPLE_ENUM_VARINT(const sourcemeta::jsontoolkit::JSON &document, + const FLOOR_MULTIPLE_ENUM_VARINT &options) + -> void { + assert(document.is_integer()); + const std::int64_t value{document.to_integer()}; + assert(options.minimum <= value); + assert(options.multiplier > 0); + assert(abs(value) % options.multiplier == 0); + if (options.multiplier == 1) { + return this->put_varint( + static_cast(value - options.minimum)); + } + + return this->put_varint( + (static_cast(value) / options.multiplier) - + static_cast(divide_ceil( + options.minimum, static_cast(options.multiplier)))); + } + + auto ROOF_MULTIPLE_MIRROR_ENUM_VARINT( + const sourcemeta::jsontoolkit::JSON &document, + const ROOF_MULTIPLE_MIRROR_ENUM_VARINT &options) -> void { + assert(document.is_integer()); + const std::int64_t value{document.to_integer()}; + assert(value <= options.maximum); + assert(options.multiplier > 0); + assert(abs(value) % options.multiplier == 0); + if (options.multiplier == 1) { + return this->put_varint( + static_cast(options.maximum - value)); + } + + return this->put_varint( + static_cast( + divide_floor(options.maximum, options.multiplier)) - + (static_cast(value) / options.multiplier)); + } + + auto ARBITRARY_MULTIPLE_ZIGZAG_VARINT( + const sourcemeta::jsontoolkit::JSON &document, + const ARBITRARY_MULTIPLE_ZIGZAG_VARINT &options) -> void { + assert(document.is_integer()); + const std::int64_t value{document.to_integer()}; + assert(options.multiplier > 0); + assert(abs(value) % options.multiplier == 0); + this->put_varint_zigzag(value / + static_cast(options.multiplier)); + } + + auto DOUBLE_VARINT_TUPLE(const sourcemeta::jsontoolkit::JSON &document, + const DOUBLE_VARINT_TUPLE &) -> void { + assert(document.is_real()); + const auto value{document.to_real()}; + std::uint64_t point_position; + const std::int64_t integral{ + real_digits(value, &point_position)}; + this->put_varint_zigzag(integral); + this->put_varint(point_position); + } + + auto BYTE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &document, + const BYTE_CHOICE_INDEX &options) -> void { + assert(!options.choices.empty()); + assert(is_byte(options.choices.size())); + const auto iterator{std::find_if( + std::cbegin(options.choices), std::cend(options.choices), + [&document](const auto &choice) { return choice == document; })}; + assert(iterator != std::cend(options.choices)); + const auto cursor{std::distance(std::cbegin(options.choices), iterator)}; + assert(is_within(cursor, 0, + static_cast(options.choices.size()))); + this->put_byte(static_cast(cursor)); + } + + auto LARGE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &document, + const LARGE_CHOICE_INDEX &options) -> void { + assert(options.choices.size() > 0); + const auto iterator{std::find_if( + std::cbegin(options.choices), std::cend(options.choices), + [&document](const auto &choice) { return choice == document; })}; + assert(iterator != std::cend(options.choices)); + const auto cursor{std::distance(std::cbegin(options.choices), iterator)}; + assert(is_within(cursor, static_cast(0), + options.choices.size() - 1)); + this->put_varint(static_cast(cursor)); + } + + auto + TOP_LEVEL_BYTE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &document, + const TOP_LEVEL_BYTE_CHOICE_INDEX &options) + -> void { + assert(options.choices.size() > 0); + assert(is_byte(options.choices.size())); + const auto iterator{std::find_if( + std::cbegin(options.choices), std::cend(options.choices), + [&document](auto const &choice) { return choice == document; })}; + assert(iterator != std::cend(options.choices)); + const auto cursor{std::distance(std::cbegin(options.choices), iterator)}; + assert(is_within(cursor, 0, + static_cast(options.choices.size()) - 1)); + // This encoding encodes the first option of the enum as "no data" + if (cursor > 0) { + this->put_byte(static_cast(cursor - 1)); + } + } + + auto CONST_NONE( +#ifndef NDEBUG + const sourcemeta::jsontoolkit::JSON &document, const CONST_NONE &options) +#else + const sourcemeta::jsontoolkit::JSON &, const CONST_NONE &) +#endif + -> void { + assert(document == options.value); + } + + auto UTF8_STRING_NO_LENGTH(const sourcemeta::jsontoolkit::JSON &document, + const UTF8_STRING_NO_LENGTH &options) -> void { + assert(document.is_string()); + const std::basic_string value{document.to_string()}; + this->put_string_utf8(value, options.size); + } + + auto FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &document, + const FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED &options) -> void { + assert(document.is_string()); + const std::basic_string value{document.to_string()}; + const auto size{value.size()}; + assert(document.size() == size); + const bool is_shared{this->context().has(value, ContextType::Standalone)}; + + // (1) Write 0x00 if shared, else do nothing + if (is_shared) { + this->put_byte(0); + } + + // (2) Write length of the string + 1 (so it will never be zero) + this->put_varint(size - options.minimum + 1); + + // (3) Write relative offset if shared, else write plain string + if (is_shared) { + this->put_varint(this->position() - + this->context().offset(value, ContextType::Standalone)); + } else { + this->context().record(value, this->position(), ContextType::Standalone); + this->put_string_utf8(value, size); + } + } + + auto ROOF_VARINT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &document, + const ROOF_VARINT_PREFIX_UTF8_STRING_SHARED &options) -> void { + assert(document.is_string()); + const std::basic_string value{document.to_string()}; + const auto size{value.size()}; + assert(document.size() == size); + assert(size <= options.maximum); + const bool is_shared{this->context().has(value, ContextType::Standalone)}; + + // (1) Write 0x00 if shared, else do nothing + if (is_shared) { + this->put_byte(0); + } + + // (2) Write length of the string + 1 (so it will never be zero) + this->put_varint(options.maximum - size + 1); + + // (3) Write relative offset if shared, else write plain string + if (is_shared) { + this->put_varint(this->position() - + this->context().offset(value, ContextType::Standalone)); + } else { + this->context().record(value, this->position(), ContextType::Standalone); + this->put_string_utf8(value, size); + } + } + + auto BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &document, + const BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED &options) -> void { + assert(document.is_string()); + const std::basic_string value{document.to_string()}; + const auto size{value.size()}; + assert(document.size() == size); + assert(options.minimum <= options.maximum); + assert(is_byte(options.maximum - options.minimum + 1)); + assert(is_within(size, options.minimum, options.maximum)); + const bool is_shared{this->context().has(value, ContextType::Standalone)}; + + // (1) Write 0x00 if shared, else do nothing + if (is_shared) { + this->put_byte(0); + } + + // (2) Write length of the string + 1 (so it will never be zero) + this->put_byte(static_cast(size - options.minimum + 1)); + + // (3) Write relative offset if shared, else write plain string + if (is_shared) { + this->put_varint(this->position() - + this->context().offset(value, ContextType::Standalone)); + } else { + this->context().record(value, this->position(), ContextType::Standalone); + this->put_string_utf8(value, size); + } + } + + auto + RFC3339_DATE_INTEGER_TRIPLET(const sourcemeta::jsontoolkit::JSON &document, + const RFC3339_DATE_INTEGER_TRIPLET &) -> void { + assert(document.is_string()); + const auto &value{document.to_string()}; + assert(value.size() == 10); + assert(document.size() == value.size()); + + // As according to RFC3339: Internet Protocols MUST + // generate four digit years in dates. + const std::uint16_t year{ + static_cast(std::stoul(value.substr(0, 4)))}; + const std::uint8_t month{ + static_cast(std::stoul(value.substr(5, 2)))}; + const std::uint8_t day{ + static_cast(std::stoul(value.substr(8, 2)))}; + assert(month >= 1 && month <= 12); + assert(day >= 1 && day <= 31); + + this->put_bytes(year); + this->put_byte(month); + this->put_byte(day); + } + + auto PREFIX_VARINT_LENGTH_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &document, + const PREFIX_VARINT_LENGTH_STRING_SHARED &) -> void { + assert(document.is_string()); + const std::basic_string value{document.to_string()}; + + if (this->context().has(value, ContextType::PrefixLengthVarintPlusOne)) { + const auto new_offset{this->position()}; + this->put_byte(0); + this->put_varint(this->position() - + this->context().offset( + value, ContextType::PrefixLengthVarintPlusOne)); + // Bump the context cache for locality purposes + this->context().record(value, new_offset, + ContextType::PrefixLengthVarintPlusOne); + } else { + const auto size{value.size()}; + assert(document.size() == size); + this->context().record(value, this->position(), + ContextType::PrefixLengthVarintPlusOne); + this->put_varint(size + 1); + // Also record a standalone variant of it + this->context().record(value, this->position(), ContextType::Standalone); + this->put_string_utf8(value, size); + } + } + + // TODO: Implement STRING_BROTLI encoding + // TODO: Implement STRING_DICTIONARY_COMPRESSOR encoding + // TODO: Implement STRING_UNBOUNDED_SCOPED_PREFIX_LENGTH encoding + // TODO: Implement URL_PROTOCOL_HOST_REST encoding + + auto FIXED_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &document, + const FIXED_TYPED_ARRAY &options) -> void { + assert(document.is_array()); + assert(document.size() == options.size); + const auto prefix_encodings{options.prefix_encodings.size()}; + assert(prefix_encodings <= document.size()); + for (std::size_t index = 0; index < options.size; index++) { + const Plan &encoding{prefix_encodings > index + ? options.prefix_encodings[index].value + : options.encoding->value}; + this->encode(document.at(index), encoding); + } + } + + auto BOUNDED_8BITS_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &document, + const BOUNDED_8BITS_TYPED_ARRAY &options) + -> void { + assert(options.maximum >= options.minimum); + const auto size{document.size()}; + assert(is_within(size, options.minimum, options.maximum)); + assert(is_byte(options.maximum - options.minimum)); + this->put_byte(static_cast(size - options.minimum)); + this->FIXED_TYPED_ARRAY(document, {size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + } + + auto FLOOR_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &document, + const FLOOR_TYPED_ARRAY &options) -> void { + const auto size{document.size()}; + assert(size >= options.minimum); + this->put_varint(size - options.minimum); + this->FIXED_TYPED_ARRAY(document, {size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + } + + auto ROOF_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &document, + const ROOF_TYPED_ARRAY &options) -> void { + const auto size{document.size()}; + assert(size <= options.maximum); + this->put_varint(options.maximum - size); + this->FIXED_TYPED_ARRAY(document, {size, std::move(options.encoding), + std::move(options.prefix_encodings)}); + } + + auto + FIXED_TYPED_ARBITRARY_OBJECT(const sourcemeta::jsontoolkit::JSON &document, + const FIXED_TYPED_ARBITRARY_OBJECT &options) + -> void { + assert(document.is_object()); + assert(document.size() == options.size); + + for (const auto &[key, value] : document.as_object()) { + this->encode(sourcemeta::jsontoolkit::JSON{key}, + options.key_encoding->value); + this->encode(value, options.encoding->value); + } + } + + auto + VARINT_TYPED_ARBITRARY_OBJECT(const sourcemeta::jsontoolkit::JSON &document, + const VARINT_TYPED_ARBITRARY_OBJECT &options) + -> void { + assert(document.is_object()); + const auto size{document.size()}; + this->put_varint(size); + + for (const auto &[key, value] : document.as_object()) { + this->encode(sourcemeta::jsontoolkit::JSON{key}, + options.key_encoding->value); + this->encode(value, options.encoding->value); + } + } + + auto + ANY_PACKED_TYPE_TAG_BYTE_PREFIX(const sourcemeta::jsontoolkit::JSON &document, + const ANY_PACKED_TYPE_TAG_BYTE_PREFIX &) + -> void { + using namespace internal::ANY_PACKED_TYPE_TAG_BYTE_PREFIX; + if (document.is_null()) { + this->put_byte(TYPE_OTHER | (SUBTYPE_NULL << type_size)); + } else if (document.is_boolean()) { + const std::uint8_t subtype{document.to_boolean() ? SUBTYPE_TRUE + : SUBTYPE_FALSE}; + this->put_byte(TYPE_OTHER | + static_cast(subtype << type_size)); + } else if (document.is_real()) { + this->put_byte(TYPE_OTHER | SUBTYPE_NUMBER << type_size); + this->DOUBLE_VARINT_TUPLE(document, {}); + } else if (document.is_integer()) { + const std::int64_t value{document.to_integer()}; + const bool is_positive{value >= 0}; + const std::uint64_t absolute{ + is_positive ? static_cast(value) : abs(value) - 1}; + if (is_byte(absolute)) { + const std::uint8_t type{is_positive ? TYPE_POSITIVE_INTEGER_BYTE + : TYPE_NEGATIVE_INTEGER_BYTE}; + const std::uint8_t absolute_byte{static_cast(absolute)}; + if (absolute < uint_max<5>) { + this->put_byte(type | static_cast((absolute_byte + 1) + << type_size)); + } else { + this->put_byte(type); + this->put_byte(absolute_byte); + } + } else { + const std::uint8_t subtype{is_positive ? SUBTYPE_POSITIVE_INTEGER + : SUBTYPE_NEGATIVE_INTEGER}; + this->put_byte(TYPE_OTHER | + static_cast(subtype << type_size)); + this->put_varint(absolute); + } + } else if (document.is_string()) { + const std::basic_string value{document.to_string()}; + const auto size{document.byte_size()}; + const bool is_shared{this->context().has(value, ContextType::Standalone)}; + if (size < uint_max<5>) { + const std::uint8_t type{is_shared ? TYPE_SHARED_STRING : TYPE_STRING}; + this->put_byte( + static_cast(type | ((size + 1) << type_size))); + if (is_shared) { + this->put_varint( + this->position() - + this->context().offset(value, ContextType::Standalone)); + } else { + this->context().record(value, this->position(), + ContextType::Standalone); + this->put_string_utf8(value, size); + } + } else if (size >= uint_max<5> && size < uint_max<5> * 2 && !is_shared) { + this->put_byte(static_cast( + TYPE_LONG_STRING | ((size - uint_max<5>) << type_size))); + this->put_string_utf8(value, size); + } else if (size >= 2 << (SUBTYPE_LONG_STRING_BASE_EXPONENT_7 - 1) && + !is_shared) { + const std::uint8_t exponent{closest_smallest_exponent( + size, 2, SUBTYPE_LONG_STRING_BASE_EXPONENT_7, + SUBTYPE_LONG_STRING_BASE_EXPONENT_10)}; + this->put_byte( + static_cast(TYPE_OTHER | (exponent << type_size))); + this->put_varint(size - + static_cast(2 << (exponent - 1))); + this->put_string_utf8(value, size); + } else { + // Exploit the fact that a shared string always starts + // with an impossible length marker (0) to avoid having + // to encode an additional tag + if (!is_shared) { + this->put_byte(TYPE_STRING); + } + + // If we got this far, the string is at least a certain length + return FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED(document, + {uint_max<5> * 2}); + } + } else if (document.is_array()) { + const auto size{document.size()}; + if (size >= uint_max<5>) { + this->put_byte(TYPE_ARRAY); + this->put_varint(size - uint_max<5>); + } else { + this->put_byte( + static_cast(TYPE_ARRAY | ((size + 1) << type_size))); + } + + Plan encoding{sourcemeta::jsonbinpack::ANY_PACKED_TYPE_TAG_BYTE_PREFIX{}}; + this->FIXED_TYPED_ARRAY(document, {size, wrap(std::move(encoding)), {}}); + } else if (document.is_object()) { + const auto size{document.size()}; + if (size >= uint_max<5>) { + this->put_byte(TYPE_OBJECT); + this->put_varint(size - uint_max<5>); + } else { + this->put_byte( + static_cast(TYPE_OBJECT | ((size + 1) << type_size))); + } + + Plan key_encoding{ + sourcemeta::jsonbinpack::PREFIX_VARINT_LENGTH_STRING_SHARED{}}; + Plan value_encoding{ + sourcemeta::jsonbinpack::ANY_PACKED_TYPE_TAG_BYTE_PREFIX{}}; + this->FIXED_TYPED_ARBITRARY_OBJECT(document, + {size, wrap(std::move(key_encoding)), + wrap(std::move(value_encoding))}); + } else { + // We should never get here. + assert(false); + std::abort(); + } + } + +#endif + +private: + using ContextType = typename Context::Type; +}; + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_basic.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_basic.h new file mode 100644 index 0000000..3261b6f --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_basic.h @@ -0,0 +1,70 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_BASIC_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_BASIC_H_ +#ifndef DOXYGEN + +#include +#include +#include + +#include // std::find_if +#include // assert +#include // std::int8_t, std::uint8_t, std::int64_t +#include // std::ios_base +#include // std::cbegin, std::cend, std::distance +#include // std::basic_ostream +#include // std::basic_string + +namespace sourcemeta::jsonbinpack { + +template class BasicEncoder { +public: + BasicEncoder(std::basic_ostream &output) : stream{output} { + this->stream.exceptions(std::ios_base::badbit | std::ios_base::failbit | + std::ios_base::eofbit); + } + + // Prevent copying, as this class is tied to a stream resource + BasicEncoder(const BasicEncoder &) = delete; + auto operator=(const BasicEncoder &) -> BasicEncoder & = delete; + + inline auto position() const noexcept -> std::uint64_t { + return static_cast(this->stream.tellp()); + } + + inline auto put_byte(const std::uint8_t byte) -> void { + this->stream.put(static_cast(byte)); + } + + inline auto put_bytes(const std::uint16_t bytes) -> void { + this->stream.write(reinterpret_cast(&bytes), sizeof bytes); + } + + inline auto put_varint(const std::uint64_t value) -> void { + varint_encode(this->stream, value); + } + + inline auto put_varint_zigzag(const std::int64_t value) -> void { + varint_encode(this->stream, zigzag_encode(value)); + } + + inline auto put_string_utf8(const std::basic_string &string, + const std::uint64_t length) -> void { + assert(string.size() == length); + // Do a manual for-loop based on the provided length instead of a range + // loop based on the string value to avoid accidental overflows + for (std::uint64_t index = 0; index < length; index++) { + this->put_byte(static_cast(string[index])); + } + } + + inline auto context() -> Context & { return this->context_; } + +private: + std::basic_ostream &stream; + Context context_; +}; + +} // namespace sourcemeta::jsonbinpack + +#endif +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_context.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_context.h new file mode 100644 index 0000000..c908a7a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_context.h @@ -0,0 +1,104 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_CONTEXT_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_CONTEXT_H_ +#ifndef DOXYGEN + +#include // assert +#include // std::cbegin, std::cend +#include // std::map +#include // std::logic_error +#include // std::basic_string +#include // std::pair, std::make_pair + +// Encoding a shared string has some overhead, such as the +// shared string marker + the offset, so its not worth +// doing for strings that are too small. +static constexpr auto MINIMUM_STRING_LENGTH{3}; + +// We don't want to allow the context to grow +// forever, otherwise an attacker could force the +// program to exhaust memory given an input +// document that contains a high number of large strings. +static constexpr auto MAXIMUM_BYTE_SIZE{20971520}; + +namespace sourcemeta::jsonbinpack { + +template class Context { +public: + enum class Type { Standalone, PrefixLengthVarintPlusOne }; + + auto record(const std::basic_string &value, const std::uint64_t offset, + const Type type) -> void { + const auto value_size{value.size()}; + if (value_size < MINIMUM_STRING_LENGTH) { + return; + // The value is too big for the context to start with + } else if (value_size >= MAXIMUM_BYTE_SIZE) { + return; + } + + // Remove the oldest entries to make space if needed + while (!this->strings.empty() && + this->byte_size + value_size >= MAXIMUM_BYTE_SIZE) { + this->remove_oldest(); + } + + // If the string already exists, we want to + // bump the offset for locality purposes. + if (this->has(value, type)) { + const auto key{std::make_pair(value, type)}; + const auto previous_offset{this->strings[key]}; + if (offset > previous_offset) { + this->strings[key] = offset; + this->offsets.erase(previous_offset); + this->offsets.insert({offset, std::make_pair(value, type)}); + } + } else { + const auto result{ + this->offsets.insert({offset, std::make_pair(value, type)})}; + // Prevent recording two strings to the same offset + assert(result.second); + if (result.second) { + this->strings.insert({std::make_pair(value, type), offset}); + this->byte_size += value_size; + } + } + } + + auto remove_oldest() -> void { + assert(!this->strings.empty()); + // std::map are by definition ordered by key, + // so the begin iterator points to the entry + // with the lowest offset, a.k.a. the oldest. + const auto iterator{std::cbegin(this->offsets)}; + this->strings.erase( + std::make_pair(iterator->second.first, iterator->second.second)); + this->byte_size -= iterator->second.first.size(); + this->offsets.erase(iterator); + } + + auto has(const std::basic_string &value, const Type type) const + -> bool { + return this->strings.contains(std::make_pair(value, type)); + } + + auto offset(const std::basic_string &value, const Type type) const + -> std::uint64_t { + // This method assumes the value indeed exists for performance reasons + assert(this->has(value, type)); + return this->strings.at(std::make_pair(value, type)); + } + +private: + std::map, Type>, std::uint64_t> strings; + // A mirror of the above map to be able to sort by offset. + // While this means we need 2x the amount of memory to keep track + // of strings, it allows us to efficiently put an upper bound + // on the amount of memory being consumed by this class. + std::map, Type>> offsets; + std::uint64_t byte_size = 0; +}; + +} // namespace sourcemeta::jsonbinpack + +#endif +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_real.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_real.h new file mode 100644 index 0000000..37788a5 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_encoder_real.h @@ -0,0 +1,54 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_REAL_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODER_REAL_H_ + +#include // assert +#include // std::modf, std::floor, std::isfinite +#include // std::floating_point, std::integral + +// TODO: Move to src/numeric + +namespace sourcemeta::jsonbinpack { + +// IEEE764 floating-point encoding is not precise. Some real numbers +// cannot be represented directly and thus approximations must be +// used. Here, we abuse those imprecision characteristics for +// space-efficiency by performing rounding on a very, very low +// threshold. +template +constexpr auto correct_ieee764(const Real value) -> Real { + assert(std::isfinite(value)); + const Real IEEE764_CORRECTION_THRESHOLD{0.000000001}; + const Real base{std::floor(value)}; + const Real next{base + 1}; + if (next - value <= IEEE764_CORRECTION_THRESHOLD) { + return next; + } else if (value - base <= IEEE764_CORRECTION_THRESHOLD) { + return base; + } else { + return value; + } +} + +template +constexpr auto real_digits(Real value, std::uint64_t *point_position) + -> Integer { + assert(std::isfinite(value)); + Real integral; + std::uint64_t shifts{0}; + + Real result = std::modf(value, &integral); + while (result != 0.0) { + value *= 10; + shifts += 1; + result = std::modf(correct_ieee764(value), &integral); + } + + // This is the point position from right to left + *point_position = shifts; + + return static_cast(std::floor(integral)); +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_numeric.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_numeric.h new file mode 100644 index 0000000..0adcbcf --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_numeric.h @@ -0,0 +1,114 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_NUMERIC_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_NUMERIC_H_ + +#include // assert +#include // std::abs +#include // std::uint8_t, std::int64_t, std::uint64_t +#include // std::numeric_limits + +// TODO: Move to src/numeric + +namespace sourcemeta::jsonbinpack { + +template constexpr auto uint_max = (2 << (T - 1)) - 1; + +template constexpr auto is_byte(const T value) noexcept -> bool { + return value <= std::numeric_limits::max(); +} + +template +constexpr auto is_within(const T value, const std::int64_t lower, + const std::int64_t higher) noexcept -> bool { + return value >= lower && value <= higher; +} + +template +constexpr auto is_within(const T value, const std::uint64_t lower, + const std::uint64_t higher) noexcept -> bool { + if (value >= 0) { + return static_cast(value) >= lower && + static_cast(value) <= higher; + } else { + return false; + } +} + +constexpr auto abs(const std::int64_t value) noexcept -> std::uint64_t { + if (value < 0) { + return static_cast(value * -1); + } else { + return static_cast(value); + } +} + +constexpr auto divide_ceil(const std::int64_t dividend, + const std::uint64_t divisor) noexcept + -> std::int64_t { + // Division by zero is invalid + assert(divisor > 0); + + // Avoid std::ceil as it involves casting to IEEE 764 imprecise types + if (divisor == 1) { + return dividend; + } else if (dividend >= 0) { + // This branch guards against overflows + if (static_cast(dividend) + divisor < divisor) { + return static_cast( + (static_cast(dividend) / divisor) + 1 - (1 / divisor)); + } else { + return static_cast( + (static_cast(dividend) + divisor - 1) / divisor); + } + } else { + // `dividend` is negative, so `abs(dividend)` is ensured to be positive + // Then, `divisor` is ensured to be at least 2, which means the + // division result fits in a signed integer. + return -(static_cast( + static_cast(std::abs(dividend)) / divisor)); + } +} + +constexpr auto divide_floor(const std::int64_t dividend, + const std::uint64_t divisor) noexcept + -> std::int64_t { + // Division by zero is invalid + assert(divisor > 0); + + // Avoid std::floor as it involves casting to IEEE 764 imprecise types + if (divisor == 1) { + return dividend; + } else if (dividend >= 0) { + return static_cast(static_cast(dividend) / + divisor); + } else { + const std::uint64_t absolute_dividend{ + static_cast(std::abs(dividend))}; + return -( + static_cast(1 + ((absolute_dividend - 1) / divisor))); + } +} + +constexpr auto closest_smallest_exponent(const std::uint64_t value, + const std::uint8_t base, + const std::uint8_t exponent_start, + const std::uint8_t exponent_end) + -> std::uint8_t { + assert(exponent_start <= exponent_end); + std::uint64_t result{base}; + for (std::uint8_t exponent = 1; exponent < exponent_end; exponent++) { + // Avoid std::pow, which officially only returns `double` + const std::uint64_t next{result * base}; + if (next > value && exponent >= exponent_start) { + return exponent; + } else { + result = next; + } + } + + assert(result <= value); + return exponent_end; +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_parser.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_parser.h new file mode 100644 index 0000000..d8a0d82 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_parser.h @@ -0,0 +1,18 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_PARSER_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_PARSER_H_ + +#include "runtime_export.h" + +#include +#include + +namespace sourcemeta::jsonbinpack { + +// TODO: Give this a better name +/// @ingroup runtime +SOURCEMETA_JSONBINPACK_RUNTIME_EXPORT +auto parse(const sourcemeta::jsontoolkit::JSON &input) -> Plan; + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan.h new file mode 100644 index 0000000..ef4e34a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan.h @@ -0,0 +1,1040 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODING_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODING_H_ + +#include +#include + +#include // std::int64_t, std::uint64_t +#include // std::shared_ptr +#include // std::variant +#include // std::vector + +namespace sourcemeta::jsonbinpack { + +// We cannot directly create an Plan variant type whose values potentially +// include other Plan instances. As a workaround, we have a helper +// encoding wrapper that we can use as an incomplete type +struct __internal_encoding_wrapper; +// Use these alias types. Never use the internal wrapper type directly +using SinglePlan = std::shared_ptr<__internal_encoding_wrapper>; +using MultiplePlans = std::vector<__internal_encoding_wrapper>; + +/// @ingroup runtime +/// @defgroup plan_integer Integer Encodings +/// @{ + +// clang-format off +/// @brief The encoding consists of the integer value divided by the +/// `multiplier`, minus the ceil of `minimum` divided by the `multiplier`, +/// encoded as an 8-bit fixed-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |--------------|--------|-----------------------------| +/// | `minimum` | `int` | The inclusive minimum value | +/// | `maximum` | `int` | The inclusive maximum value | +/// | `multiplier` | `uint` | The multiplier value | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |------------------------------|---------------------------------------------------------------------| +/// | `value >= minimum` | The input value must be greater than or equal to the minimum | +/// | `value <= maximum` | The input value must be less than or equal to the maximum | +/// | `value % multiplier == 0` | The input value must be divisible by the multiplier | +/// | `floor(maximum / multiplier) - ceil(minimum / multiplier) < 2 ** 8` | The divided range must be representable in 8 bits | +/// +/// ### Examples +/// +/// Given the input value 15, where the minimum is 1, the maximum is 19, and the +/// multiplier is 5, the encoding results in the 8-bit unsigned integer 2: +/// +/// ``` +/// +------+ +/// | 0x02 | +/// +------+ +/// ``` +// clang-format on +struct BOUNDED_MULTIPLE_8BITS_ENUM_FIXED { + /// The inclusive minimum value + const std::int64_t minimum; + /// The inclusive maximum value + const std::int64_t maximum; + /// The multiplier value + const std::uint64_t multiplier; +}; + +// clang-format off +/// @brief The encoding consists of the integer value divided by the +/// `multiplier`, minus the ceil of `minimum` divided by the `multiplier`, +/// encoded as a Base-128 64-bit Little Endian variable-length unsigned +/// integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |--------------|--------|-----------------------------| +/// | `minimum` | `int` | The inclusive minimum value | +/// | `multiplier` | `uint` | The multiplier value | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |---------------------------|--------------------------------------------------------------| +/// | `value >= minimum` | The input value must be greater than or equal to the minimum | +/// | `value % multiplier == 0` | The input value must be divisible by the multiplier | +/// +/// ### Examples +/// +/// Given the input value 1000, where the minimum is -2 and the multiplier is 4, +/// the encoding results in the Base-128 64-bit Little Endian variable-length +/// unsigned integer 250: +/// +/// ``` +/// +------+------+ +/// | 0xfa | 0x01 | +/// +------+------+ +/// ``` +// clang-format on +struct FLOOR_MULTIPLE_ENUM_VARINT { + /// The inclusive minimum value + const std::int64_t minimum; + /// The multiplier value + const std::uint64_t multiplier; +}; + +// clang-format off +/// @brief The encoding consists of the floor of `maximum` divided by the +/// `multiplier`, minus the integer value divided by the `multiplier`, encoded +/// as a Base-128 64-bit Little Endian variable-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |--------------|--------|-----------------------------| +/// | `maximum` | `int` | The inclusive maximum value | +/// | `multiplier` | `uint` | The multiplier value | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |---------------------------|-----------------------------------------------------------| +/// | `value <= maximum` | The input value must be less than or equal to the maximum | +/// | `value % multiplier == 0` | The input value must be divisible by the multiplier | +/// +/// ### Examples +/// +/// Given the input value 5, where the maximum is 16 and the multiplier is 5, the +/// encoding results in the Base-128 64-bit Little Endian variable-length unsigned +/// integer 2: +/// +/// ``` +/// +------+ +/// | 0x02 | +/// +------+ +/// ``` +// clang-format on +struct ROOF_MULTIPLE_MIRROR_ENUM_VARINT { + /// The inclusive maximum value + const std::int64_t maximum; + /// The multiplier value + const std::uint64_t multiplier; +}; + +// clang-format off +/// @brief The encoding consists of the the integer value divided by the +/// `multiplier` encoded as a ZigZag-encoded Base-128 64-bit Little Endian +/// variable-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |--------------|--------|----------------------| +/// | `multiplier` | `uint` | The multiplier value | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |---------------------------|-----------------------------------------------------| +/// | `value % multiplier == 0` | The input value must be divisible by the multiplier | +/// +/// ### Examples +/// +/// Given the input value 10, where the multiplier is 5, the encoding results in +/// the Base-128 64-bit Little Endian variable-length unsigned integer 4: +/// +/// ``` +/// +------+ +/// | 0x04 | +/// +------+ +/// ``` +// clang-format on +struct ARBITRARY_MULTIPLE_ZIGZAG_VARINT { + /// The multiplier value + const std::uint64_t multiplier; +}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_number Number Encodings +/// @{ + +// clang-format off +/// @brief The encoding consists of a sequence of two integers: The signed +/// integer that results from concatenating the integral part and the decimal +/// part of the number, if any, as a ZigZag-encoded Base-128 64-bit Little +/// Endian variable-length unsigned integer; and the position of the decimal +/// mark from the last digit of the number encoded as a Base-128 64-bit Little +/// Endian variable-length unsigned integer. +/// +/// ### Options +/// +/// None +/// +/// ### Conditions +/// +/// None +/// +/// ### Examples +/// +/// Given the input value 3.14, the encoding results in the variable-length integer +/// 628 (the ZigZag encoding of 314) followed by the variable-length unsigned +/// integer 2 (the number of decimal digits in the number). +/// +/// ``` +/// +------+------+------+ +/// | 0xf4 | 0x04 | 0x02 | +/// +------+------+------+ +/// ``` +/// +/// Real numbers that represent integers are encoded with a decimal mark of zero. +/// Given the input value -5.0, the encoding results in the variable-length integer +/// 9 (the ZigZag encoding of -5) followed by the variable-length unsigned integer +/// 0. +/// +/// ``` +/// +------+------+ +/// | 0x09 | 0x00 | +/// +------+------+ +/// ``` +// clang-format on +struct DOUBLE_VARINT_TUPLE {}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_enum Enumeration Encodings +/// @{ + +// clang-format off +/// @brief The encoding consists of an index to the enumeration choices encoded +/// as an 8-bit fixed-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-----------|---------|--------------------------| +/// | `choices` | `any[]` | The set of choice values | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |--------------------------|--------------------------------------------------------| +/// | `len(choices) > 0` | The choices array must not be empty | +/// | `len(choices) < 2 ** 8` | The number of choices must be representable in 8 bits | +/// | `value in choices` | The input value must be included in the set of choices | +/// +/// ### Examples +/// +/// Given an enumeration `[ "foo", "bar", "baz" ]` and an input value `"bar"`, the +/// encoding results in the unsigned 8 bit integer 1: +/// +/// ``` +/// +------+ +/// | 0x01 | +/// +------+ +/// ``` +/// +/// Given an enumeration `[ "foo", "bar", "baz" ]` and an input value `"foo"`, the +/// encoding results in the unsigned 8 bit integer 0: +/// +/// ``` +/// +------+ +/// | 0x00 | +/// +------+ +/// ``` +// clang-format on +struct BYTE_CHOICE_INDEX { + /// The set of choice values + const std::vector choices; +}; + +// clang-format off +/// @brief The encoding consists of an index to the enumeration choices encoded +/// as a Base-128 64-bit Little Endian variable-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-----------|---------|--------------------------| +/// | `choices` | `any[]` | The set of choice values | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |--------------------------|--------------------------------------------------------| +/// | `len(choices) > 0` | The choices array must not be empty | +/// | `value in choices` | The input value must be included in the set of choices | +/// +/// ### Examples +/// +/// Given an enumeration with 1000 members and an input value that equals the 300th +/// enumeration value, the encoding results in the Base-128 64-bit Little Endian +/// variable-length unsigned integer 300: +/// +/// ``` +/// +------+------+ +/// | 0xac | 0x02 | +/// +------+------+ +/// ``` +// clang-format on +struct LARGE_CHOICE_INDEX { + /// The set of choice values + const std::vector choices; +}; + +// clang-format off +/// @brief If the input value corresponds to the index 0 to the enumeration +/// choices, the encoding stores no data. Otherwise, the encoding consists of +/// an index to the enumeration choices minus 1 encoded as an 8-bit +/// fixed-length unsigned integer. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-----------|---------|--------------------------| +/// | `choices` | `any[]` | The set of choice values | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |--------------------------|--------------------------------------------------------| +/// | `len(choices) > 0` | The choices array must not be empty | +/// | `len(choices) < 2 ** 8` | The number of choices must be representable in 8 bits | +/// | `value in choices` | The input value must be included in the set of choices | +/// +/// ### Examples +/// +/// Given an enumeration `[ "foo", "bar", "baz" ]` and an input value `"bar"`, the +/// encoding results in the unsigned 8 bit integer 0: +/// +/// ``` +/// +------+ +/// | 0x00 | +/// +------+ +/// ``` +/// +/// Given an enumeration `[ "foo", "bar", "baz" ]` and an input value `"foo"`, the +/// value is not encoded. +// clang-format on +struct TOP_LEVEL_BYTE_CHOICE_INDEX { + /// The set of choice values + const std::vector choices; +}; + +// clang-format off +/// @brief The constant input value is not encoded. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |---------|-------|--------------------| +/// | `value` | `any` | The constant value | +/// +/// ### Conditions +/// +/// None +/// +/// ### Examples +/// +/// The input value that matches the `value` option is not encoded. +// clang-format on +struct CONST_NONE { + /// The constant value + const sourcemeta::jsontoolkit::JSON value; +}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_string String Encodings +/// @{ + +// clang-format off +/// @brief The encoding consist in the UTF-8 encoding of the input string. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |--------|--------|------------------------------| +/// | `size` | `uint` | The string UTF-8 byte-length | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |----------------------|-----------------------------------------------------------| +/// | `len(value) == size` | The input string must have the declared UTF-8 byte-length | +/// +/// ### Examples +/// +/// Given the input value "foo bar" with a corresponding size of 7, the encoding +/// results in: +/// +/// ``` +/// +------+------+------+------+------+------+------+ +/// | 0x66 | 0x6f | 0x6f | 0x20 | 0x62 | 0x61 | 0x72 | +/// +------+------+------+------+------+------+------+ +/// f o o b a r +/// ``` +// clang-format on +struct UTF8_STRING_NO_LENGTH { + /// The string UTF-8 byte-length + const std::uint64_t size; +}; + +// clang-format off +/// @brief The encoding consists of the byte-length of the string minus +/// `minimum` plus 1 as a Base-128 64-bit Little Endian variable-length +/// unsigned integer followed by the UTF-8 encoding of the input value. +/// +/// Optionally, if the input string has already been encoded to the buffer +/// using UTF-8, the encoding may consist of the byte constant `0x00` followed +/// by the byte-length of the string minus `minimum` plus 1 as a Base-128 +/// 64-bit Little Endian variable-length unsigned integer, followed by the +/// current offset minus the offset to the start of the UTF-8 string value in +/// the buffer encoded as a Base-128 64-bit Little Endian variable-length +/// unsigned integer. +/// +/// #### Options +/// +/// | Option | Type | Description | +/// |-----------|--------|------------------------------------------------| +/// | `minimum` | `uint` | The inclusive minimum string UTF-8 byte-length | +/// +/// #### Conditions +/// +/// | Condition | Description | +/// |-------------------------|----------------------------------------------------------------------| +/// | `len(value) >= minimum` | The input string byte-length is equal to or greater than the minimum | +/// +/// #### Examples +/// +/// Given the input string `foo` with a minimum 3 where the string has not been +/// previously encoded, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x01 | 0x66 | 0x6f | 0x6f | +/// +------+------+------+------+ +/// f o o +/// ``` +/// +/// Given the encoding of `foo` with a minimum of 0 followed by the encoding of +/// `foo` with a minimum of 3, the encoding may result in: +/// +/// ``` +/// 0 1 2 3 4 5 6 +/// ^ ^ ^ ^ ^ ^ ^ +/// +------+------+------+------+------+------+------+ +/// | 0x04 | 0x66 | 0x6f | 0x6f | 0x00 | 0x01 | 0x05 | +/// +------+------+------+------+------+------+------+ +/// f o o 6 - 1 +/// ``` +// clang-format on +struct FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED { + /// The inclusive minimum string UTF-8 byte-length + const std::uint64_t minimum; +}; + +// clang-format off +/// @brief The encoding consists of `maximum` minus the byte-length of the +/// string plus 1 as a Base-128 64-bit Little Endian variable-length unsigned +/// integer followed by the UTF-8 encoding of the input value. +/// +/// Optionally, if the input string has already been encoded to the buffer +/// using UTF-8, the encoding may consist of the byte constant `0x00` followed +/// by `maximum` minus the byte-length of the string plus 1 as a Base-128 +/// 64-bit Little Endian variable-length unsigned integer, followed by the +/// current offset minus the offset to the start of the UTF-8 string value in +/// the buffer encoded as a Base-128 64-bit Little Endian variable-length +/// unsigned integer. +/// +/// #### Options +/// +/// | Option | Type | Description | +/// |-----------|--------|------------------------------------------------| +/// | `maximum` | `uint` | The inclusive maximum string UTF-8 byte-length | +/// +/// #### Conditions +/// +/// | Condition | Description | +/// |-------------------------|-------------------------------------------------------------------| +/// | `len(value) <= maximum` | The input string byte-length is equal to or less than the maximum | +/// +/// #### Examples +/// +/// Given the input string `foo` with a maximum 4 where the string has not been +/// previously encoded, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x02 | 0x66 | 0x6f | 0x6f | +/// +------+------+------+------+ +/// f o o +/// ``` +/// +/// Given the encoding of `foo` with a maximum of 3 followed by the encoding of +/// `foo` with a maximum of 5, the encoding may result in: +/// +/// ``` +/// 0 1 2 3 4 5 6 +/// ^ ^ ^ ^ ^ ^ ^ +/// +------+------+------+------+------+------+------+ +/// | 0x01 | 0x66 | 0x6f | 0x6f | 0x00 | 0x03 | 0x05 | +/// +------+------+------+------+------+------+------+ +/// f o o 6 - 1 +/// ``` +// clang-format on +struct ROOF_VARINT_PREFIX_UTF8_STRING_SHARED { + /// The inclusive maximum string UTF-8 byte-length + const std::uint64_t maximum; +}; + +// clang-format off +/// @brief The encoding consists of the byte-length of the string minus +/// `minimum` plus 1 as an 8-bit fixed-length unsigned integer followed by the +/// UTF-8 encoding of the input value. +/// +/// Optionally, if the input string has already been encoded to the buffer +/// using UTF-8, the encoding may consist of the byte constant `0x00` followed +/// by the byte-length of the string minus `minimum` plus 1 as an 8-bit +/// fixed-length unsigned integer, followed by the current offset minus the +/// offset to the start of the UTF-8 string value in the buffer encoded as a +/// Base-128 64-bit Little Endian variable-length unsigned integer. +/// +/// The byte-length of the string is encoded even if `maximum` equals `minimum` +/// in order to disambiguate between shared and non-shared fixed strings. +/// +/// #### Options +/// +/// | Option | Type | Description | +/// |-----------|--------|------------------------------------------------| +/// | `minimum` | `uint` | The inclusive minimum string UTF-8 byte-length | +/// | `maximum` | `uint` | The inclusive maximum string UTF-8 byte-length | +/// +/// #### Conditions +/// +/// | Condition | Description | +/// |----------------------------------|----------------------------------------------------------------------| +/// | `len(value) >= minimum` | The input string byte-length is equal to or greater than the minimum | +/// | `len(value) <= maximum` | The input string byte-length is equal to or less than the maximum | +/// | `maximum - minimum < 2 ** 8 - 1` | The range minus 1 must be representable in 8 bits | +/// +/// #### Examples +/// +/// Given the input string `foo` with a minimum 3 and a maximum 5 where the string +/// has not been previously encoded, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x01 | 0x66 | 0x6f | 0x6f | +/// +------+------+------+------+ +/// f o o +/// ``` +/// +/// Given the encoding of `foo` with a minimum of 0 and a maximum of 6 followed by +/// the encoding of `foo` with a minimum of 3 and a maximum of 100, the encoding +/// may result in: +/// +/// ``` +/// 0 1 2 3 4 5 6 +/// ^ ^ ^ ^ ^ ^ ^ +/// +------+------+------+------+------+------+------+ +/// | 0x04 | 0x66 | 0x6f | 0x6f | 0x00 | 0x01 | 0x05 | +/// +------+------+------+------+------+------+------+ +/// f o o 6 - 1 +/// ``` +// clang-format on +struct BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED { + /// The inclusive minimum string UTF-8 byte-length + const std::uint64_t minimum; + /// The inclusive maximum string UTF-8 byte-length + const std::uint64_t maximum; +}; + +// clang-format off +/// @brief The encoding consists of an implementation of +/// [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339) date expressions +/// as the sequence of 3 integers: the year as a 16-bit fixed-length Little +/// Endian unsigned integer, the month as an 8-bit fixed-length unsigned +/// integer, and the day as an 8-bit fixed-length unsigned integer. +/// +/// #### Options +/// +/// None +/// +/// #### Conditions +/// +/// | Condition | Description | +/// |----------------------|-------------------------------------------------------------| +/// | `len(value) == 10` | The input string consists of 10 characters | +/// | `value[0:4] >= 0` | The year is greater than or equal to 0 | +/// | `value[0:4] <= 9999` | The year is less than or equal to 9999 as stated by RFC3339 | +/// | `value[4] == "-"` | The year and the month are divided by a hyphen | +/// | `value[5:7] >= 1` | The month is greater than or equal to 1 | +/// | `value[5:7] <= 12` | The month is less than or equal to 12 | +/// | `value[7] == "-"` | The month and the day are divided by a hyphen | +/// | `value[8:10] >= 1` | The day is greater than or equal to 1 | +/// | `value[8:10] <= 31` | The day is less than or equal to 31 | +/// +/// #### Examples +/// +/// Given the input string `2014-10-01`, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0xde | 0x07 | 0x0a | 0x01 | +/// +------+------+------+------+ +/// year ... month day +/// ``` +// clang-format on +struct RFC3339_DATE_INTEGER_TRIPLET {}; + +// clang-format off +/// @brief The encoding consists of the byte-length of the string plus 1 as a +/// Base-128 64-bit Little Endian variable-length unsigned integer followed by +/// the UTF-8 encoding of the input value. +/// +/// Optionally, if the input string has already been encoded to the buffer +/// using this encoding the encoding may consist of the byte constant `0x00` +/// followed by the current offset minus the offset to the start of the string +/// as a Base-128 64-bit Little Endian variable-length unsigned integer. It is +/// permissible to point to another instance of the string that is a pointer +/// itself. +/// +/// ### Options +/// +/// None +/// +/// ### Conditions +/// +/// None +/// +/// ### Examples +/// +/// Given the input string `foo` where the string has not been previously encoded, +/// the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x04 | 0x66 | 0x6f | 0x6f | +/// +------+------+------+------+ +/// f o o +/// ``` +/// +/// Given the encoding of `foo` repeated 3 times, the encoding may result in: +/// +/// ``` +/// 0 1 2 3 4 5 6 7 +/// ^ ^ ^ ^ ^ ^ ^ ^ +/// +------+------+------+------+------+------+------+------+ +/// | 0x04 | 0x66 | 0x6f | 0x6f | 0x00 | 0x05 | 0x00 | 0x03 | +/// +------+------+------+------+------+------+------+------+ +/// f o o 5 - 0 7 - 4 +/// ``` +// clang-format on +struct PREFIX_VARINT_LENGTH_STRING_SHARED {}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_array Array Encodings +/// @{ + +// clang-format off +/// @brief The encoding consists of the elements of the fixed array encoded in +/// order. The encoding of the element at index `i` is either +/// `prefix_encodings[i]` if set, or `encoding`. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-------------------|--------------|----------------------| +/// | `size` | `uint` | The array length | +/// | `prefixEncodings` | `encoding[]` | Positional encodings | +/// | `encoding` | `encoding` | Element encoding | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |--------------------------------|-----------------------------------------------------------------------| +/// | `len(prefixEncodings) <= size` | The number of prefix encodings must be less than or equal to the size | +/// | `len(value) == size` | The input array must have the declared size | +/// +/// ### Examples +/// +/// Given the array `[ 1, 2, true ]` where the `prefixEncodings` corresponds to +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED (minimum 0, maximum 10, multiplier 1) and +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED (minimum 0, maximum 10, multiplier 1) and +/// `encoding` corresponds to BYTE_CHOICE_INDEX with choices `[ false, true ]`, +/// the encoding results in: +/// +/// ``` +/// +------+------+------+ +/// | 0x00 | 0x01 | 0x01 | +/// +------+------+------+ +/// 1 2 true +/// ``` +// clang-format on +struct FIXED_TYPED_ARRAY { + /// The array length + const std::uint64_t size; + /// Element encoding + const SinglePlan encoding; + /// Positional encodings + const MultiplePlans prefix_encodings; +}; + +// clang-format off +/// @brief The encoding consists of the length of the array minus `minimum` +/// encoded as an 8-bit fixed-length unsigned integer followed by the elements +/// of the array encoded in order. The encoding of the element at index `i` is +/// either `prefix_encodings[i]` if set, or `encoding`. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-------------------|--------------|---------------------------------| +/// | `minimum` | `uint` | The minimum length of the array | +/// | `maximum` | `uint` | The maximum length of the array | +/// | `prefixEncodings` | `encoding[]` | Positional encodings | +/// | `encoding` | `encoding` | Element encoding | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |----------------------------------------|---------------------------------------------------------------------------------------| +/// | `len(value) >= minimum` | The length of the array must be greater than or equal to the minimum | +/// | `len(value) <= maximum` | The length of the array must be less than or equal to the maximum | +/// | `len(prefixEncodings) <= maximum` | The number of prefix encodings must be less than or equal to the maximum array length | +/// | `len(maximum) - len(minimum) < 2 ** 8` | The array length must be representable in 8 bits | +/// +/// ### Examples +/// +/// Given the array `[ true, false, 5 ]` where the minimum is 1 and the maximum is +/// 3, the `prefixEncodings` corresponds to BYTE_CHOICE_INDEX with +/// choices `[ false, true ]` and BYTE_CHOICE_INDEX with choices `[ +/// false, true ]` and `encoding` corresponds to +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED with minimum 0 and maximum +/// 255, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x02 | 0x01 | 0x00 | 0x05 | +/// +------+------+------+------+ +/// size true false 5 +/// ``` +// clang-format on +struct BOUNDED_8BITS_TYPED_ARRAY { + /// The minimum length of the array + const std::uint64_t minimum; + /// The maximum length of the array + const std::uint64_t maximum; + /// Element encoding + const SinglePlan encoding; + /// Positional encodings + const MultiplePlans prefix_encodings; +}; + +// clang-format off +/// @brief The encoding consists of the length of the array minus `minimum` +/// encoded as a Base-128 64-bit Little Endian variable-length unsigned integer +/// followed by the elements of the array encoded in order. The encoding of the +/// element at index `i` is either `prefix_encodings[i]` if set, or `encoding`. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-------------------|--------------|---------------------------------| +/// | `minimum` | `uint` | The minimum length of the array | +/// | `prefixEncodings` | `encoding[]` | Positional encodings | +/// | `encoding` | `encoding` | Element encoding | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |-------------------------|----------------------------------------------------------------------| +/// | `len(value) >= minimum` | The length of the array must be greater than or equal to the minimum | +/// +/// ### Examples +/// +/// TODO: Give an example of an array with more than 8-bit of elements +/// +/// Given the array `[ true, false, 5 ]` where the minimum is 1, the +/// `prefixEncodings` corresponds to BYTE_CHOICE_INDEX with choices `[ +/// false, true ]` and BYTE_CHOICE_INDEX with choices `[ false, true ]` +/// and `encoding` corresponds to BOUNDED_MULTIPLE_8BITS_ENUM_FIXED +/// with minimum 0 and maximum 255, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x02 | 0x01 | 0x00 | 0x05 | +/// +------+------+------+------+ +/// size true false 5 +/// ``` +// clang-format on +struct FLOOR_TYPED_ARRAY { + /// The minimum length of the array + const std::uint64_t minimum; + /// Element encoding + const SinglePlan encoding; + /// Positional encodings + const MultiplePlans prefix_encodings; +}; + +// clang-format off +/// @brief The encoding consists of `maximum` minus the length of the array +/// encoded as a Base-128 64-bit Little Endian variable-length unsigned integer +/// followed by the elements of the array encoded in order. The encoding of the +/// element at index `i` is either `prefix_encodings[i]` if set, or `encoding`. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |-------------------|--------------|---------------------------------| +/// | `maximum` | `uint` | The maximum length of the array | +/// | `prefixEncodings` | `encoding[]` | Positional encodings | +/// | `encoding` | `encoding` | Element encoding | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |-----------------------------------|---------------------------------------------------------------------------------------| +/// | `len(prefixEncodings) <= maximum` | The number of prefix encodings must be less than or equal to the maximum array length | +/// +/// ### Examples +/// +/// Given the array `[ true, false, 5 ]` where the maximum is 3, the +/// `prefixEncodings` options corresponds to BYTE_CHOICE_INDEX with +/// choices `[ false, true ]` and BYTE_CHOICE_INDEX with choices `[ +/// false, true ]` and `encoding` corresponds to +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED with minimum 0 and maximum +/// 255, the encoding results in: +/// +/// ``` +/// +------+------+------+------+ +/// | 0x00 | 0x01 | 0x00 | 0x05 | +/// +------+------+------+------+ +/// size true false 5 +/// ``` +// clang-format on +struct ROOF_TYPED_ARRAY { + /// The maximum length of the array + const std::uint64_t maximum; + /// Element encoding + const SinglePlan encoding; + /// Positional encodings + const MultiplePlans prefix_encodings; +}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_object Object Encodings +/// @{ + +// clang-format off +/// @brief The encoding consists of each pair encoded as the key followed by +/// the value according to `key_encoding` and `encoding`. The order in which +/// pairs are encoded is undefined. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |---------------|------------|-----------------| +/// | `size` | `uint` | The object size | +/// | `keyEncoding` | `encoding` | Key encoding | +/// | `encoding` | `encoding` | Value encoding | +/// +/// ### Conditions +/// +/// | Condition | Description | +/// |----------------------|-----------------------------------------------------------| +/// | `len(value) == size` | The input object must have the declared amount of entries | +/// +/// ### Examples +/// +/// Given the array `{ "foo": 1, "bar": 2 }` where `keyEncoding` corresponds to +/// UTF8_STRING_NO_LENGTH (size 3) and `encoding` corresponds to +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED (minimum 0, maximum 10, +/// multiplier 1), the encoding results in: +/// +/// ``` +/// +------+------+------+------+------+------+------+------+ +/// | 0x66 | 0x6f | 0x6f | 0x01 | 0x62 | 0x61 | 0x72 | 0x02 | +/// +------+------+------+------+------+------+------+------+ +/// f o o 1 b a r 2 +/// ``` +/// +/// Or: +/// +/// ``` +/// +------+------+------+------+------+------+------+------+ +/// | 0x62 | 0x61 | 0x72 | 0x02 | 0x66 | 0x6f | 0x6f | 0x01 | +/// +------+------+------+------+------+------+------+------+ +/// b a r 2 f o o 1 +/// ``` +// clang-format on +struct FIXED_TYPED_ARBITRARY_OBJECT { + /// The object size + const std::uint64_t size; + /// Key encoding + const SinglePlan key_encoding; + /// Value encoding + const SinglePlan encoding; +}; + +// clang-format off +/// @brief The encoding consists of the number of key-value pairs in the input +/// object as a Base-128 64-bit Little Endian variable-length unsigned integer +/// followed by each pair encoded as the key followed by the value according to +/// `key_encoding` and `encoding`. The order in which pairs are encoded is +/// undefined. +/// +/// ### Options +/// +/// | Option | Type | Description | +/// |---------------|------------|----------------| +/// | `keyEncoding` | `encoding` | Key encoding | +/// | `encoding` | `encoding` | Value encoding | +/// +/// ### Examples +/// +/// Given the array `{ "foo": 1, "bar": 2 }` where `keyEncoding` corresponds to +/// UTF8_STRING_NO_LENGTH (size 3) and `encoding` corresponds to +/// BOUNDED_MULTIPLE_8BITS_ENUM_FIXED (minimum 0, maximum 10, +/// multiplier 1), the encoding results in: +/// +/// ``` +/// +------+------+------+------+------+------+------+------+------+ +/// | 0x02 | 0x66 | 0x6f | 0x6f | 0x01 | 0x62 | 0x61 | 0x72 | 0x02 | +/// +------+------+------+------+------+------+------+------+------+ +/// 2 f o o 1 b a r 2 +/// ``` +/// +/// Or: +/// +/// ``` +/// +------+------+------+------+------+------+------+------+------+ +/// | 0x02 | 0x62 | 0x61 | 0x72 | 0x02 | 0x66 | 0x6f | 0x6f | 0x01 | +/// +------+------+------+------+------+------+------+------+------+ +/// 2 b a r 2 f o o 1 +/// ``` +// clang-format on +struct VARINT_TYPED_ARBITRARY_OBJECT { + /// Key encoding + const SinglePlan key_encoding; + /// Value encoding + const SinglePlan encoding; +}; + +/// @} + +/// @ingroup runtime +/// @defgroup plan_any Any Encodings +/// @{ + +// TODO: Write brief description +struct ANY_PACKED_TYPE_TAG_BYTE_PREFIX {}; +#ifndef DOXYGEN +namespace internal::ANY_PACKED_TYPE_TAG_BYTE_PREFIX { +constexpr auto type_size = 3; +constexpr std::uint8_t TYPE_SHARED_STRING = 0b00000000; +constexpr std::uint8_t TYPE_STRING = 0b00000001; +constexpr std::uint8_t TYPE_LONG_STRING = 0b00000010; +constexpr std::uint8_t TYPE_OBJECT = 0b00000011; +constexpr std::uint8_t TYPE_ARRAY = 0b00000100; +constexpr std::uint8_t TYPE_POSITIVE_INTEGER_BYTE = 0b00000101; +constexpr std::uint8_t TYPE_NEGATIVE_INTEGER_BYTE = 0b00000110; +constexpr std::uint8_t TYPE_OTHER = 0b00000111; +static_assert(TYPE_SHARED_STRING <= uint_max); +static_assert(TYPE_STRING <= uint_max); +static_assert(TYPE_LONG_STRING <= uint_max); +static_assert(TYPE_OBJECT <= uint_max); +static_assert(TYPE_ARRAY <= uint_max); +static_assert(TYPE_POSITIVE_INTEGER_BYTE <= uint_max); +static_assert(TYPE_NEGATIVE_INTEGER_BYTE <= uint_max); +static_assert(TYPE_OTHER <= uint_max); + +constexpr auto subtype_size = 5; +constexpr std::uint8_t SUBTYPE_FALSE = 0b00000000; +constexpr std::uint8_t SUBTYPE_TRUE = 0b00000001; +constexpr std::uint8_t SUBTYPE_NULL = 0b00000010; +constexpr std::uint8_t SUBTYPE_POSITIVE_INTEGER = 0b00000011; +constexpr std::uint8_t SUBTYPE_NEGATIVE_INTEGER = 0b00000100; +constexpr std::uint8_t SUBTYPE_NUMBER = 0b00000101; +constexpr std::uint8_t SUBTYPE_LONG_STRING_BASE_EXPONENT_7 = 0b00000111; +constexpr std::uint8_t SUBTYPE_LONG_STRING_BASE_EXPONENT_8 = 0b00001000; +constexpr std::uint8_t SUBTYPE_LONG_STRING_BASE_EXPONENT_9 = 0b00001001; +constexpr std::uint8_t SUBTYPE_LONG_STRING_BASE_EXPONENT_10 = 0b00001010; + +static_assert(SUBTYPE_FALSE <= uint_max); +static_assert(SUBTYPE_TRUE <= uint_max); +static_assert(SUBTYPE_NULL <= uint_max); +static_assert(SUBTYPE_POSITIVE_INTEGER <= uint_max); +static_assert(SUBTYPE_NEGATIVE_INTEGER <= uint_max); +static_assert(SUBTYPE_NUMBER <= uint_max); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_7 <= uint_max); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_8 <= uint_max); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_9 <= uint_max); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_10 <= uint_max); + +// Note that the binary values actually match the declared exponents +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_7 == 7); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_8 == 8); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_9 == 9); +static_assert(SUBTYPE_LONG_STRING_BASE_EXPONENT_10 == 10); +} // namespace internal::ANY_PACKED_TYPE_TAG_BYTE_PREFIX +#endif + +/// @} +// clang-format on + +/// @ingroup runtime +/// Represents an encoding plan +using Plan = std::variant< + BOUNDED_MULTIPLE_8BITS_ENUM_FIXED, FLOOR_MULTIPLE_ENUM_VARINT, + ROOF_MULTIPLE_MIRROR_ENUM_VARINT, ARBITRARY_MULTIPLE_ZIGZAG_VARINT, + DOUBLE_VARINT_TUPLE, BYTE_CHOICE_INDEX, LARGE_CHOICE_INDEX, + TOP_LEVEL_BYTE_CHOICE_INDEX, CONST_NONE, UTF8_STRING_NO_LENGTH, + FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED, + ROOF_VARINT_PREFIX_UTF8_STRING_SHARED, + BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED, RFC3339_DATE_INTEGER_TRIPLET, + PREFIX_VARINT_LENGTH_STRING_SHARED, FIXED_TYPED_ARRAY, + BOUNDED_8BITS_TYPED_ARRAY, FLOOR_TYPED_ARRAY, ROOF_TYPED_ARRAY, + FIXED_TYPED_ARBITRARY_OBJECT, VARINT_TYPED_ARBITRARY_OBJECT, + ANY_PACKED_TYPE_TAG_BYTE_PREFIX>; + +// Helper definitions that rely on the Plan data type +#ifndef DOXYGEN +// Ignore this definition on the documentation +struct __internal_encoding_wrapper { + const Plan value; +}; +#endif + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan_wrap.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan_wrap.h new file mode 100644 index 0000000..6d3d149 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_plan_wrap.h @@ -0,0 +1,53 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ENCODING_WRAP_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ENCODING_WRAP_H_ + +#include + +#include // std::transform +#include // std::initializer_list +#include // std::back_inserter, std::forward_iterator +#include // std::make_shared +#include // std::move, std::forward +#include // std::vector + +namespace { + +// Adapter to make smart pointers using struct aggregate initialization +// From https://stackoverflow.com/a/35300172/1641422 +template struct aggregate_adapter : public T { + template + aggregate_adapter(Args &&...args) : T{std::forward(args)...} {} +}; + +} // namespace + +namespace sourcemeta::jsonbinpack { + +// We define all wrap helper functions inline in this header file, +// as we want to avoid including their definitions in if the user +// doesn't import this header. + +inline auto wrap(Plan &&encoding) -> SinglePlan { + return std::make_shared>( + std::move(encoding)); +} + +// clang-format off +template +requires std::forward_iterator +// clang-format on +inline auto wrap(Iterator begin, Iterator end) -> MultiplePlans { + MultiplePlans result; + std::transform(begin, end, std::back_inserter(result), [](Plan encoding) { + return __internal_encoding_wrapper{std::move(encoding)}; + }); + return result; +} + +inline auto wrap(std::initializer_list encodings) -> MultiplePlans { + return wrap(encodings.begin(), encodings.end()); +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_varint.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_varint.h new file mode 100644 index 0000000..9017a7a --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_varint.h @@ -0,0 +1,60 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_VARINT_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_VARINT_H_ + +#include // assert +#include // std::uint8_t, std::uint64_t +#include // std::basic_istream +#include // std::basic_ostream + +namespace sourcemeta::jsonbinpack { + +// This encoder does not handle negative integers. Use ZigZag first instead. +template +auto varint_encode(std::basic_ostream &stream, + const std::uint64_t value) + -> std::basic_ostream & { + constexpr std::uint8_t LEAST_SIGNIFICANT_BITS{0b01111111}; + constexpr std::uint8_t MOST_SIGNIFICANT_BIT{0b10000000}; + constexpr std::uint8_t SHIFT{7}; + std::uint64_t accumulator = value; + + while (accumulator > LEAST_SIGNIFICANT_BITS) { + stream.put(static_cast((accumulator & LEAST_SIGNIFICANT_BITS) | + MOST_SIGNIFICANT_BIT)); + accumulator >>= SHIFT; + } + + stream.put(static_cast(accumulator)); + return stream; +} + +template +auto varint_decode(std::basic_istream &stream) -> std::uint64_t { + constexpr std::uint8_t LEAST_SIGNIFICANT_BITS{0b01111111}; + constexpr std::uint8_t MOST_SIGNIFICANT_BIT{0b10000000}; + constexpr std::uint8_t SHIFT{7}; + std::uint64_t result{0}; + std::size_t cursor{0}; + while (true) { + const std::uint8_t byte{static_cast(stream.get())}; + assert(!stream.eof()); + const std::uint64_t value{ + static_cast(byte & LEAST_SIGNIFICANT_BITS)}; +#ifndef NDEBUG + const std::uint64_t current = result; +#endif + result += static_cast(value << SHIFT * cursor); + // Try to catch potential overflows from the above addition + assert(result >= current); + cursor += 1; + if ((byte & MOST_SIGNIFICANT_BIT) == 0) { + break; + } + } + + return result; +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_zigzag.h b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_zigzag.h new file mode 100644 index 0000000..27052f2 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/include/sourcemeta/jsonbinpack/runtime_zigzag.h @@ -0,0 +1,31 @@ +#ifndef SOURCEMETA_JSONBINPACK_RUNTIME_ZIGZAG_H_ +#define SOURCEMETA_JSONBINPACK_RUNTIME_ZIGZAG_H_ + +#include // std::abs +#include // std::uint64_t, std::int64_t + +// TODO: Move to src/numeric + +namespace sourcemeta::jsonbinpack { + +constexpr auto zigzag_encode(const std::int64_t value) noexcept + -> std::uint64_t { + if (value >= 0) { + return static_cast(value * 2); + } + + return (static_cast(std::abs(value)) * 2) - 1; +} + +constexpr auto zigzag_decode(const std::uint64_t value) noexcept + -> std::int64_t { + if (value % 2 == 0) { + return static_cast(value / 2); + } + + return -(static_cast((value + 1) / 2)); +} + +} // namespace sourcemeta::jsonbinpack + +#endif diff --git a/vendor/jsonbinpack/src/runtime/runtime_parser.cc b/vendor/jsonbinpack/src/runtime/runtime_parser.cc new file mode 100644 index 0000000..ff3b657 --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/runtime_parser.cc @@ -0,0 +1,56 @@ +#include + +#include "runtime_parser_v1.h" + +#include // assert +#include // std::ostringstream +#include // std::runtime_error + +namespace sourcemeta::jsonbinpack { + +auto parse(const sourcemeta::jsontoolkit::JSON &input) -> Plan { + assert(input.defines("binpackEncoding")); + assert(input.defines("binpackOptions")); + const auto encoding{input.at("binpackEncoding").to_string()}; + const auto &options{input.at("binpackOptions")}; + +#define PARSE_ENCODING(version, name) \ + if (encoding == #name) \ + return version::name(options); + + // Integers + PARSE_ENCODING(v1, BOUNDED_MULTIPLE_8BITS_ENUM_FIXED) + PARSE_ENCODING(v1, FLOOR_MULTIPLE_ENUM_VARINT) + PARSE_ENCODING(v1, ROOF_MULTIPLE_MIRROR_ENUM_VARINT) + PARSE_ENCODING(v1, ARBITRARY_MULTIPLE_ZIGZAG_VARINT) + // Numbers + PARSE_ENCODING(v1, DOUBLE_VARINT_TUPLE) + // Enumerations + PARSE_ENCODING(v1, BYTE_CHOICE_INDEX) + PARSE_ENCODING(v1, LARGE_CHOICE_INDEX) + PARSE_ENCODING(v1, TOP_LEVEL_BYTE_CHOICE_INDEX) + PARSE_ENCODING(v1, CONST_NONE) + // Strings + PARSE_ENCODING(v1, UTF8_STRING_NO_LENGTH) + PARSE_ENCODING(v1, FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED) + PARSE_ENCODING(v1, ROOF_VARINT_PREFIX_UTF8_STRING_SHARED) + PARSE_ENCODING(v1, BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED) + PARSE_ENCODING(v1, RFC3339_DATE_INTEGER_TRIPLET) + PARSE_ENCODING(v1, PREFIX_VARINT_LENGTH_STRING_SHARED) + // Arrays + PARSE_ENCODING(v1, FIXED_TYPED_ARRAY) + PARSE_ENCODING(v1, BOUNDED_8BITS_TYPED_ARRAY) + PARSE_ENCODING(v1, FLOOR_TYPED_ARRAY) + PARSE_ENCODING(v1, ROOF_TYPED_ARRAY) + // Any + PARSE_ENCODING(v1, ANY_PACKED_TYPE_TAG_BYTE_PREFIX) + +#undef PARSE_ENCODING + + // TODO: Have a custom error for this + std::ostringstream error; + error << "Unrecognized encoding: " << encoding; + throw std::runtime_error(error.str()); +} + +} // namespace sourcemeta::jsonbinpack diff --git a/vendor/jsonbinpack/src/runtime/runtime_parser_v1.h b/vendor/jsonbinpack/src/runtime/runtime_parser_v1.h new file mode 100644 index 0000000..2cef4ae --- /dev/null +++ b/vendor/jsonbinpack/src/runtime/runtime_parser_v1.h @@ -0,0 +1,281 @@ +#ifndef SOURCEMETA_JSONBINPACK_PARSER_V1_H_ +#define SOURCEMETA_JSONBINPACK_PARSER_V1_H_ + +#include +#include +#include + +#include // std::transform +#include // assert +#include // std::uint64_t +#include // std::back_inserter +#include // std::move +#include // std::vector + +namespace sourcemeta::jsonbinpack::v1 { + +// Integers + +auto BOUNDED_MULTIPLE_8BITS_ENUM_FIXED( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("minimum")); + assert(options.defines("maximum")); + assert(options.defines("multiplier")); + const auto &minimum{options.at("minimum")}; + const auto &maximum{options.at("maximum")}; + const auto &multiplier{options.at("multiplier")}; + assert(minimum.is_integer()); + assert(maximum.is_integer()); + assert(multiplier.is_integer()); + assert(multiplier.is_positive()); + return sourcemeta::jsonbinpack::BOUNDED_MULTIPLE_8BITS_ENUM_FIXED{ + minimum.to_integer(), maximum.to_integer(), + static_cast(multiplier.to_integer())}; +} + +auto FLOOR_MULTIPLE_ENUM_VARINT(const sourcemeta::jsontoolkit::JSON &options) + -> Plan { + assert(options.defines("minimum")); + assert(options.defines("multiplier")); + const auto &minimum{options.at("minimum")}; + const auto &multiplier{options.at("multiplier")}; + assert(minimum.is_integer()); + assert(multiplier.is_integer()); + assert(multiplier.is_positive()); + return sourcemeta::jsonbinpack::FLOOR_MULTIPLE_ENUM_VARINT{ + minimum.to_integer(), + static_cast(multiplier.to_integer())}; +} + +auto ROOF_MULTIPLE_MIRROR_ENUM_VARINT( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("maximum")); + assert(options.defines("multiplier")); + const auto &maximum{options.at("maximum")}; + const auto &multiplier{options.at("multiplier")}; + assert(maximum.is_integer()); + assert(multiplier.is_integer()); + assert(multiplier.is_positive()); + return sourcemeta::jsonbinpack::ROOF_MULTIPLE_MIRROR_ENUM_VARINT{ + maximum.to_integer(), + static_cast(multiplier.to_integer())}; +} + +auto ARBITRARY_MULTIPLE_ZIGZAG_VARINT( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("multiplier")); + const auto &multiplier{options.at("multiplier")}; + assert(multiplier.is_integer()); + assert(multiplier.is_positive()); + return sourcemeta::jsonbinpack::ARBITRARY_MULTIPLE_ZIGZAG_VARINT{ + static_cast(multiplier.to_integer())}; +} + +// Numbers + +auto DOUBLE_VARINT_TUPLE(const sourcemeta::jsontoolkit::JSON &) -> Plan { + return sourcemeta::jsonbinpack::DOUBLE_VARINT_TUPLE{}; +} + +// Enumerations + +auto BYTE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("choices")); + const auto &choices{options.at("choices")}; + assert(choices.is_array()); + const auto &array{choices.as_array()}; + std::vector elements{array.cbegin(), + array.cend()}; + return sourcemeta::jsonbinpack::BYTE_CHOICE_INDEX({std::move(elements)}); +} + +auto LARGE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("choices")); + const auto &choices{options.at("choices")}; + assert(choices.is_array()); + const auto &array{choices.as_array()}; + std::vector elements{array.cbegin(), + array.cend()}; + return sourcemeta::jsonbinpack::LARGE_CHOICE_INDEX({std::move(elements)}); +} + +auto TOP_LEVEL_BYTE_CHOICE_INDEX(const sourcemeta::jsontoolkit::JSON &options) + -> Plan { + assert(options.defines("choices")); + const auto &choices{options.at("choices")}; + assert(choices.is_array()); + const auto &array{choices.as_array()}; + std::vector elements{array.cbegin(), + array.cend()}; + return sourcemeta::jsonbinpack::TOP_LEVEL_BYTE_CHOICE_INDEX( + {std::move(elements)}); +} + +auto CONST_NONE(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("value")); + return sourcemeta::jsonbinpack::CONST_NONE({options.at("value")}); +} + +// Strings + +auto UTF8_STRING_NO_LENGTH(const sourcemeta::jsontoolkit::JSON &options) + -> Plan { + assert(options.defines("size")); + const auto &size{options.at("size")}; + assert(size.is_integer()); + assert(size.is_positive()); + return sourcemeta::jsonbinpack::UTF8_STRING_NO_LENGTH{ + static_cast(size.to_integer())}; +} + +auto FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("minimum")); + const auto &minimum{options.at("minimum")}; + assert(minimum.is_integer()); + assert(minimum.is_positive()); + return sourcemeta::jsonbinpack::FLOOR_VARINT_PREFIX_UTF8_STRING_SHARED{ + static_cast(minimum.to_integer())}; +} + +auto ROOF_VARINT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("maximum")); + const auto &maximum{options.at("maximum")}; + assert(maximum.is_integer()); + assert(maximum.is_positive()); + return sourcemeta::jsonbinpack::ROOF_VARINT_PREFIX_UTF8_STRING_SHARED{ + static_cast(maximum.to_integer())}; +} + +auto BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED( + const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("minimum")); + assert(options.defines("maximum")); + const auto &minimum{options.at("minimum")}; + const auto &maximum{options.at("maximum")}; + assert(minimum.is_integer()); + assert(maximum.is_integer()); + assert(minimum.is_positive()); + assert(maximum.is_positive()); + return sourcemeta::jsonbinpack::BOUNDED_8BIT_PREFIX_UTF8_STRING_SHARED{ + static_cast(minimum.to_integer()), + static_cast(maximum.to_integer())}; +} + +auto RFC3339_DATE_INTEGER_TRIPLET(const sourcemeta::jsontoolkit::JSON &) + -> Plan { + return sourcemeta::jsonbinpack::RFC3339_DATE_INTEGER_TRIPLET{}; +} + +auto PREFIX_VARINT_LENGTH_STRING_SHARED(const sourcemeta::jsontoolkit::JSON &) + -> Plan { + return sourcemeta::jsonbinpack::PREFIX_VARINT_LENGTH_STRING_SHARED{}; +} + +// Arrays + +auto FIXED_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("size")); + assert(options.defines("encoding")); + assert(options.defines("prefixEncodings")); + const auto &size{options.at("size")}; + const auto &array_encoding{options.at("encoding")}; + const auto &prefix_encodings{options.at("prefixEncodings")}; + assert(size.is_integer()); + assert(size.is_positive()); + assert(array_encoding.is_object()); + assert(prefix_encodings.is_array()); + std::vector encodings; + std::transform(prefix_encodings.as_array().cbegin(), + prefix_encodings.as_array().cend(), + std::back_inserter(encodings), + [](const auto &element) { return parse(element); }); + assert(encodings.size() == prefix_encodings.size()); + return sourcemeta::jsonbinpack::FIXED_TYPED_ARRAY{ + static_cast(size.to_integer()), + wrap(parse(array_encoding)), wrap(encodings.begin(), encodings.end())}; +} + +auto BOUNDED_8BITS_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &options) + -> Plan { + assert(options.defines("minimum")); + assert(options.defines("maximum")); + assert(options.defines("encoding")); + assert(options.defines("prefixEncodings")); + const auto &minimum{options.at("minimum")}; + const auto &maximum{options.at("maximum")}; + const auto &array_encoding{options.at("encoding")}; + const auto &prefix_encodings{options.at("prefixEncodings")}; + assert(minimum.is_integer()); + assert(maximum.is_integer()); + assert(minimum.is_positive()); + assert(maximum.is_positive()); + assert(array_encoding.is_object()); + assert(prefix_encodings.is_array()); + std::vector encodings; + std::transform(prefix_encodings.as_array().cbegin(), + prefix_encodings.as_array().cend(), + std::back_inserter(encodings), + [](const auto &element) { return parse(element); }); + assert(encodings.size() == prefix_encodings.size()); + return sourcemeta::jsonbinpack::BOUNDED_8BITS_TYPED_ARRAY{ + static_cast(minimum.to_integer()), + static_cast(maximum.to_integer()), + wrap(parse(array_encoding)), wrap(encodings.begin(), encodings.end())}; +} + +auto FLOOR_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("minimum")); + assert(options.defines("encoding")); + assert(options.defines("prefixEncodings")); + const auto &minimum{options.at("minimum")}; + const auto &array_encoding{options.at("encoding")}; + const auto &prefix_encodings{options.at("prefixEncodings")}; + assert(minimum.is_integer()); + assert(minimum.is_positive()); + assert(array_encoding.is_object()); + assert(prefix_encodings.is_array()); + std::vector encodings; + std::transform(prefix_encodings.as_array().cbegin(), + prefix_encodings.as_array().cend(), + std::back_inserter(encodings), + [](const auto &element) { return parse(element); }); + assert(encodings.size() == prefix_encodings.size()); + return sourcemeta::jsonbinpack::FLOOR_TYPED_ARRAY{ + static_cast(minimum.to_integer()), + wrap(parse(array_encoding)), wrap(encodings.begin(), encodings.end())}; +} + +auto ROOF_TYPED_ARRAY(const sourcemeta::jsontoolkit::JSON &options) -> Plan { + assert(options.defines("maximum")); + assert(options.defines("encoding")); + assert(options.defines("prefixEncodings")); + const auto &maximum{options.at("maximum")}; + const auto &array_encoding{options.at("encoding")}; + const auto &prefix_encodings{options.at("prefixEncodings")}; + assert(maximum.is_integer()); + assert(maximum.is_positive()); + assert(array_encoding.is_object()); + assert(prefix_encodings.is_array()); + std::vector encodings; + std::transform(prefix_encodings.as_array().cbegin(), + prefix_encodings.as_array().cend(), + std::back_inserter(encodings), + [](const auto &element) { return parse(element); }); + assert(encodings.size() == prefix_encodings.size()); + return sourcemeta::jsonbinpack::ROOF_TYPED_ARRAY{ + static_cast(maximum.to_integer()), + wrap(parse(array_encoding)), wrap(encodings.begin(), encodings.end())}; +} + +// Any + +auto ANY_PACKED_TYPE_TAG_BYTE_PREFIX(const sourcemeta::jsontoolkit::JSON &) + -> Plan { + return sourcemeta::jsonbinpack::ANY_PACKED_TYPE_TAG_BYTE_PREFIX{}; +} + +} // namespace sourcemeta::jsonbinpack::v1 + +#endif diff --git a/vendor/jsonbinpack/vendor/noa/LICENSE b/vendor/jsonbinpack/vendor/noa/LICENSE new file mode 100644 index 0000000..efbd81c --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Noa - A set of re-usable and opinionated utilities for Sourcemeta projects + Copyright (C) 2022 Juan Cruz Viotti + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa.cmake new file mode 100644 index 0000000..d55ca54 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa.cmake @@ -0,0 +1,13 @@ +set(NOA_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}/noa") +include("${NOA_DIRECTORY}/shim.cmake") +include("${NOA_DIRECTORY}/variables.cmake") +include("${NOA_DIRECTORY}/defaults.cmake") +include("${NOA_DIRECTORY}/compiler/sanitizer.cmake") +include("${NOA_DIRECTORY}/compiler/options.cmake") +include("${NOA_DIRECTORY}/library.cmake") +include("${NOA_DIRECTORY}/options/enum.cmake") +include("${NOA_DIRECTORY}/commands/copy-file.cmake") +include("${NOA_DIRECTORY}/targets/clang-format.cmake") +include("${NOA_DIRECTORY}/targets/clang-tidy.cmake") +include("${NOA_DIRECTORY}/targets/shellcheck.cmake") +include("${NOA_DIRECTORY}/targets/doxygen.cmake") diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/commands/copy-file.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/commands/copy-file.cmake new file mode 100644 index 0000000..bed4cb8 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/commands/copy-file.cmake @@ -0,0 +1,17 @@ +function(noa_command_copy_file) + cmake_parse_arguments(NOA_COMMAND_COPY_FILE "" "FROM;TO" "" ${ARGN}) + + if(NOT NOA_COMMAND_COPY_FILE_FROM) + message(FATAL_ERROR "You must pass the file to copy using the FROM option") + endif() + if(NOT NOA_COMMAND_COPY_FILE_TO) + message(FATAL_ERROR "You must pass the destination to copy to using the TO option") + endif() + + add_custom_command( + OUTPUT "${NOA_COMMAND_COPY_FILE_TO}" + COMMAND "${CMAKE_COMMAND}" -E copy "${NOA_COMMAND_COPY_FILE_FROM}" "${NOA_COMMAND_COPY_FILE_TO}" + MAIN_DEPENDENCY "${NOA_COMMAND_COPY_FILE_FROM}" + DEPENDS "${NOA_COMMAND_COPY_FILE_FROM}" + COMMENT "Copying ${NOA_COMMAND_COPY_FILE_FROM} ot ${NOA_COMMAND_COPY_FILE_TO}") +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/options.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/options.cmake new file mode 100644 index 0000000..c859781 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/options.cmake @@ -0,0 +1,73 @@ +function(noa_add_default_options visibility target) + if(NOA_COMPILER_MSVC) + # See https://learn.microsoft.com/en-us/cpp/build/reference/compiler-options-listed-by-category + target_compile_options("${target}" ${visibility} + /options:strict + /permissive- + /W4 + /WL + /MP + /sdl) + else() + target_compile_options("${target}" ${visibility} + -Wall + -Wextra + -Wpedantic + -Wshadow + -Wdouble-promotion + -Wconversion + -Wunused-parameter + -Wtrigraphs + -Wunreachable-code + -Wmissing-braces + -Wparentheses + -Wswitch + -Wunused-function + -Wunused-label + -Wunused-parameter + -Wunused-variable + -Wunused-value + -Wempty-body + -Wuninitialized + -Wshadow + -Wconversion + -Wenum-conversion + -Wfloat-conversion + -Wimplicit-fallthrough + -Wsign-compare + -Wsign-conversion + -Wunknown-pragmas + -Wnon-virtual-dtor + -Woverloaded-virtual + -Winvalid-offsetof + + # Assume that signed arithmetic overflow of addition, subtraction and + # multiplication wraps around using twos-complement representation + # See https://users.cs.utah.edu/~regehr/papers/overflow12.pdf + # See https://www.postgresql.org/message-id/1689.1134422394@sss.pgh.pa.us + -fwrapv) + endif() + + if(NOA_COMPILER_LLVM) + target_compile_options("${target}" ${visibility} + -Wbool-conversion + -Wint-conversion + -Wpointer-sign + -Wconditional-uninitialized + -Wconstant-conversion + -Wnon-literal-null-conversion + -Wshorten-64-to-32 + -Wdeprecated-implementations + -Winfinite-recursion + -Wnewline-eof + -Wfour-char-constants + -Wselector + -Wundeclared-selector + -Wdocumentation + -Wmove + -Wc++11-extensions + -Wcomma + -Wno-exit-time-destructors + -Wrange-loop-analysis) + endif() +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/sanitizer.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/sanitizer.cmake new file mode 100644 index 0000000..37ff6f9 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/compiler/sanitizer.cmake @@ -0,0 +1,40 @@ +function(noa_sanitizer) + cmake_parse_arguments(NOA_SANITIZER "" "TYPE" "" ${ARGN}) + + if(NOT NOA_SANITIZER_TYPE) + message(FATAL_ERROR "You must pass the intended sanitizer") + endif() + + if(NOA_COMPILER_LLVM AND "${NOA_SANITIZER_TYPE}" STREQUAL "address") + # See https://clang.llvm.org/docs/AddressSanitizer.html + message(STATUS "Enabling sanitizer: Clang AddressSanitizer") + add_compile_options(-fsanitize=address -fsanitize-address-use-after-scope) + add_link_options(-fsanitize=address) + # Get nicer stack traces with the Address sanitizer + add_compile_options(-fno-omit-frame-pointer -fno-optimize-sibling-calls) + add_compile_options(-O1) + elseif(NOA_COMPILER_LLVM AND "${NOA_SANITIZER_TYPE}" STREQUAL "memory") + if(APPLE) + message(FATAL_ERROR "Clang MemorySanitizer is not available on Apple platforms") + endif() + + # See https://clang.llvm.org/docs/MemorySanitizer.html + message(STATUS "Enabling sanitizer: Clang MemorySanitizer") + add_compile_options(-fsanitize=memory -fno-sanitize-memory-use-after-dtor) + add_link_options(-fsanitize=memory) + # Get nicer stack traces with the Memory sanitizer + add_compile_options(-fno-omit-frame-pointer -fno-optimize-sibling-calls) + add_compile_options(-O1) + elseif(NOA_COMPILER_LLVM AND "${NOA_SANITIZER_TYPE}" STREQUAL "undefined") + # See https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html + message(STATUS "Enabling sanitizer: Clang UndefinedBehaviorSanitizer") + add_compile_options(-fsanitize=undefined,nullability,integer,implicit-conversion,local-bounds + -fno-sanitize=unsigned-integer-overflow) + add_link_options(-fsanitize=undefined,nullability,integer,implicit-conversion,local-bounds + -fno-sanitize=unsigned-integer-overflow) + # Exit after an error, otherwise this sanitizer only prints warnings + add_compile_options(-fno-sanitize-recover=all) + else() + message(FATAL_ERROR "Unrecognized compiler and/or sanitizer combination") + endif() +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/defaults.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/defaults.cmake new file mode 100644 index 0000000..0709ee2 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/defaults.cmake @@ -0,0 +1,94 @@ +# Standards (sane modern defaults) +if("CXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_CXX_STANDARD 20) +endif() +if("C" IN_LIST NOA_LANGUAGES) + set(CMAKE_C_STANDARD 11) +endif() +if("OBJCXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_OBJCXX_STANDARD "${CMAKE_CXX_STANDARD}") +endif() + +# Hide symbols from shared libraries by default +# In certain compilers, like GCC and Clang, +# symbols are visible by default. +set(CMAKE_VISIBILITY_INLINES_HIDDEN YES) +if("CXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) +endif() +if("C" IN_LIST NOA_LANGUAGES) + set(CMAKE_C_VISIBILITY_PRESET hidden) +endif() +if("OBJCXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_OBJCXX_VISIBILITY_PRESET hidden) +endif() + +# By default, stay within ISO C++ +if("CXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() +if("C" IN_LIST NOA_LANGUAGES) + set(CMAKE_C_STANDARD_REQUIRED ON) + set(CMAKE_C_EXTENSIONS OFF) +endif() +if("OBJCXX" IN_LIST NOA_LANGUAGES) + set(CMAKE_OBJCXX_STANDARD_REQUIRED ON) + set(CMAKE_OBJCXX_EXTENSIONS OFF) +endif() + +# Export compile commands by default. +# It is very useful for IDE integration, linting, etc +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# Prevent DT_RPATH/DT_RUNPATH problem +# This problem is not present on Apple platforms. +# See https://www.youtube.com/watch?v=m0DwB4OvDXk +if(NOT APPLE) + set(CMAKE_INSTALL_RPATH $ORIGIN) +endif() + +# Delay GoogleTest discovery until before running the tests +# See https://discourse.cmake.org/t/default-value-for-new-discovery-mode-option-for-gtest-discover-tests/1422 +set(CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE PRE_TEST) + +# Always use folders in IDE +# See https://cmake.org/cmake/help/latest/prop_gbl/USE_FOLDERS.html +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + +# On Windows, during build, put executables and libraries in the same directory. +# Otherwise, if there is any shared library being generated, the binaries +# linking to it will not be able to find it and i.e. unit tests will fail. +# Note that GoogleTest does this already to a non-configurable top-level +# `bin` directory, so adopting that convention here. +# See https://stackoverflow.com/q/39807664 +# See https://github.com/google/googletest/blob/e47544ad31cb3ceecd04cc13e8fe556f8df9fe0b/googletest/cmake/internal_utils.cmake#L173-L174 +if(WIN32) + # For EXE files + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" CACHE STRING "") + # For DLL files + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" CACHE STRING "") +endif() + +# Enable IPO/LTO to help the compiler optimize across modules. +# Only do so in release, given these optimizations can significantly +# increase build times. +# See: https://cmake.org/cmake/help/latest/module/CheckIPOSupported.html +if(CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT BUILD_SHARED_LIBS) + include(CheckIPOSupported) + check_ipo_supported(RESULT ipo_supported OUTPUT ipo_supported_error) + if(ipo_supported) + # TODO: Make IPO/LTO work on Linux + LLVM + if(APPLE OR NOT NOA_COMPILER_LLVM) + message(STATUS "Enabling IPO") + cmake_policy(SET CMP0069 NEW) + set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON) + else() + message(WARNING "Avoiding IPO on this configuration") + endif() + else() + message(WARNING "IPO not supported: ${ipo_supported_error}") + endif() + unset(ipo_supported) + unset(ipo_supported_error) +endif() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/library.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/library.cmake new file mode 100644 index 0000000..56e152b --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/library.cmake @@ -0,0 +1,134 @@ +function(noa_library) + cmake_parse_arguments(NOA_LIBRARY "" + "NAMESPACE;PROJECT;NAME;FOLDER" "PRIVATE_HEADERS;SOURCES" ${ARGN}) + + if(NOT NOA_LIBRARY_PROJECT) + message(FATAL_ERROR "You must pass the project name using the PROJECT option") + endif() + if(NOT NOA_LIBRARY_NAME) + message(FATAL_ERROR "You must pass the library name using the NAME option") + endif() + if(NOT NOA_LIBRARY_FOLDER) + message(FATAL_ERROR "You must pass the folder name using the FOLDER option") + endif() + + if(NOA_LIBRARY_NAMESPACE) + set(INCLUDE_PREFIX "include/${NOA_LIBRARY_NAMESPACE}/${NOA_LIBRARY_PROJECT}") + else() + set(INCLUDE_PREFIX "include/${NOA_LIBRARY_PROJECT}") + endif() + + set(PUBLIC_HEADER "${INCLUDE_PREFIX}/${NOA_LIBRARY_NAME}.h") + + if(NOA_LIBRARY_SOURCES) + set(ABSOLUTE_PRIVATE_HEADERS "${CMAKE_CURRENT_BINARY_DIR}/${NOA_LIBRARY_NAME}_export.h") + foreach(private_header IN LISTS NOA_LIBRARY_PRIVATE_HEADERS) + list(APPEND ABSOLUTE_PRIVATE_HEADERS "${INCLUDE_PREFIX}/${NOA_LIBRARY_NAME}_${private_header}") + endforeach() + else() + set(ABSOLUTE_PRIVATE_HEADERS) + endif() + + if(NOA_LIBRARY_NAMESPACE) + set(TARGET_NAME "${NOA_LIBRARY_NAMESPACE}_${NOA_LIBRARY_PROJECT}_${NOA_LIBRARY_NAME}") + set(ALIAS_NAME "${NOA_LIBRARY_NAMESPACE}::${NOA_LIBRARY_PROJECT}::${NOA_LIBRARY_NAME}") + else() + set(TARGET_NAME "${NOA_LIBRARY_PROJECT}_${NOA_LIBRARY_NAME}") + set(ALIAS_NAME "${NOA_LIBRARY_PROJECT}::${NOA_LIBRARY_NAME}") + endif() + + if(NOA_LIBRARY_SOURCES) + add_library(${TARGET_NAME} + ${PUBLIC_HEADER} ${ABSOLUTE_PRIVATE_HEADERS} ${NOA_LIBRARY_SOURCES}) + noa_add_default_options(PRIVATE ${TARGET_NAME}) + else() + add_library(${TARGET_NAME} INTERFACE + ${PUBLIC_HEADER} ${ABSOLUTE_PRIVATE_HEADERS}) + noa_add_default_options(INTERFACE ${TARGET_NAME}) + endif() + + add_library(${ALIAS_NAME} ALIAS ${TARGET_NAME}) + + if(NOA_LIBRARY_SOURCES) + target_include_directories(${TARGET_NAME} PUBLIC + "$" + "$") + else() + target_include_directories(${TARGET_NAME} INTERFACE + "$" + "$") + endif() + + if(NOA_LIBRARY_SOURCES) + set_target_properties(${TARGET_NAME} + PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + PUBLIC_HEADER "${PUBLIC_HEADER}" + PRIVATE_HEADER "${ABSOLUTE_PRIVATE_HEADERS}" + EXPORT_NAME "${NOA_LIBRARY_PROJECT}::${NOA_LIBRARY_NAME}" + FOLDER "${NOA_LIBRARY_FOLDER}") + else() + set_target_properties(${TARGET_NAME} + PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + PUBLIC_HEADER "${PUBLIC_HEADER}" + PRIVATE_HEADER "${ABSOLUTE_PRIVATE_HEADERS}" + FOLDER "${NOA_LIBRARY_FOLDER}") + endif() + + if(NOA_LIBRARY_SOURCES) + include(GenerateExportHeader) + generate_export_header(${TARGET_NAME} + EXPORT_FILE_NAME ${NOA_LIBRARY_NAME}_export.h) + set_target_properties(${TARGET_NAME} + PROPERTIES + SOVERSION "${PROJECT_VERSION_MAJOR}" + VERSION "${PROJECT_VERSION}") + + # To find the generated files + target_include_directories(${TARGET_NAME} + PUBLIC "$") + endif() +endfunction() + +function(noa_library_install) + cmake_parse_arguments(NOA_LIBRARY "" "NAMESPACE;PROJECT;NAME" "" ${ARGN}) + + if(NOT NOA_LIBRARY_PROJECT) + message(FATAL_ERROR "You must pass the project name using the PROJECT option") + endif() + if(NOT NOA_LIBRARY_NAME) + message(FATAL_ERROR "You must pass the library name using the NAME option") + endif() + + if(NOA_LIBRARY_NAMESPACE) + set(COMPONENT_NAME "${NOA_LIBRARY_NAMESPACE}_${NOA_LIBRARY_PROJECT}") + set(TARGET_NAME "${NOA_LIBRARY_NAMESPACE}_${NOA_LIBRARY_PROJECT}_${NOA_LIBRARY_NAME}") + set(INCLUDE_PATH "${CMAKE_INSTALL_INCLUDEDIR}/${NOA_LIBRARY_NAMESPACE}/${NOA_LIBRARY_PROJECT}") + set(NAMESPACE_PREFIX "${NOA_LIBRARY_NAMESPACE}::") + else() + set(COMPONENT_NAME "${NOA_LIBRARY_PROJECT}") + set(TARGET_NAME "${NOA_LIBRARY_PROJECT}_${NOA_LIBRARY_NAME}") + set(INCLUDE_PATH "${CMAKE_INSTALL_INCLUDEDIR}/${NOA_LIBRARY_PROJECT}") + set(NAMESPACE_PREFIX "") + endif() + + include(GNUInstallDirs) + install(TARGETS ${TARGET_NAME} + EXPORT ${TARGET_NAME} + PUBLIC_HEADER DESTINATION "${INCLUDE_PATH}" + COMPONENT ${COMPONENT_NAME}_dev + PRIVATE_HEADER DESTINATION "${INCLUDE_PATH}" + COMPONENT ${COMPONENT_NAME}_dev + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + COMPONENT ${COMPONENT_NAME} + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + COMPONENT ${COMPONENT_NAME} + NAMELINK_COMPONENT ${COMPONENT_NAME}_dev + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + COMPONENT ${COMPONENT_NAME}_dev) + install(EXPORT ${TARGET_NAME} + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${NOA_LIBRARY_PROJECT}" + NAMESPACE ${NAMESPACE_PREFIX} + COMPONENT ${COMPONENT_NAME}_dev) +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/options/enum.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/options/enum.cmake new file mode 100644 index 0000000..b75eb2a --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/options/enum.cmake @@ -0,0 +1,32 @@ +function(noa_option_enum) + cmake_parse_arguments(NOA_OPTION_ENUM "" "NAME;DEFAULT;DESCRIPTION" "CHOICES" ${ARGN}) + + if(NOT NOA_OPTION_ENUM_NAME) + message(FATAL_ERROR "You must pass the option name as NAME") + endif() + if(NOT NOA_OPTION_ENUM_DEFAULT) + message(FATAL_ERROR "You must pass the option default value as DEFAULT") + endif() + if(NOT "${NOA_OPTION_ENUM_DEFAULT}" IN_LIST NOA_OPTION_ENUM_CHOICES) + message(FATAL_ERROR "Default value of ${NOA_OPTION_ENUM_NAME} must be one of these: ${NOA_OPTION_ENUM_CHOICES}") + endif() + if(NOT NOA_OPTION_ENUM_DESCRIPTION) + message(FATAL_ERROR "You must pass the option description as DESCRIPTION") + endif() + if(NOT NOA_OPTION_ENUM_CHOICES) + message(FATAL_ERROR "You must pass the option enum choices as CHOICES") + endif() + + # Declare the option + set("${NOA_OPTION_ENUM_NAME}" "${NOA_OPTION_ENUM_DEFAULT}" + CACHE STRING "${NOA_OPTION_ENUM_DESCRIPTION}") + + # Display a nice set of options in `cmake-gui` + set_property(CACHE "${NOA_OPTION_ENUM_NAME}" + PROPERTY STRINGS ${NOA_OPTION_ENUM_CHOICES}) + + # Perform validation + if(NOT "${${NOA_OPTION_ENUM_NAME}}" IN_LIST NOA_OPTION_ENUM_CHOICES) + message(FATAL_ERROR "Value of ${NOA_OPTION_ENUM_NAME} must be one of these: ${NOA_OPTION_ENUM_CHOICES}") + endif() +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/shim.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/shim.cmake new file mode 100644 index 0000000..e2b6325 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/shim.cmake @@ -0,0 +1,5 @@ +# The PROJECT_IS_TOP_LEVEL handy variable is only +# available on CMake >=3.21. +if(NOT DEFINED PROJECT_IS_TOP_LEVEL AND "${CMAKE_PROJECT_NAME}" STREQUAL "${PROJECT_NAME}") + set(PROJECT_IS_TOP_LEVEL YES) +endif() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.cmake new file mode 100644 index 0000000..c12b1c5 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.cmake @@ -0,0 +1,48 @@ +set(NOA_TARGET_CLANG_FORMAT_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}") + +function(noa_target_clang_format) + cmake_parse_arguments(NOA_TARGET_CLANG_FORMAT "REQUIRED" "" "SOURCES" ${ARGN}) + + if(NOA_TARGET_CLANG_FORMAT_REQUIRED) + find_program(CLANG_FORMAT_BIN NAMES clang-format REQUIRED) + else() + find_program(CLANG_FORMAT_BIN NAMES clang-format) + endif() + + # This covers the empty list too + if(NOT NOA_TARGET_CLANG_FORMAT_SOURCES) + message(FATAL_ERROR "You must pass file globs to format in the SOURCES option") + endif() + file(GLOB_RECURSE NOA_TARGET_CLANG_FORMAT_FILES + ${NOA_TARGET_CLANG_FORMAT_SOURCES}) + + set(CLANG_FORMAT_CONFIG "${NOA_TARGET_CLANG_FORMAT_DIRECTORY}/clang-format.config") + if(CLANG_FORMAT_BIN) + add_custom_target(clang_format + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CLANG_FORMAT_BIN}" "--style=file:${CLANG_FORMAT_CONFIG}" + -i ${NOA_TARGET_CLANG_FORMAT_FILES} + COMMENT "Formatting sources using ClangFormat") + add_custom_target(clang_format_test + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CLANG_FORMAT_BIN}" "--style=file:${CLANG_FORMAT_CONFIG}" + --dry-run -Werror + -i ${NOA_TARGET_CLANG_FORMAT_FILES} + COMMENT "Checking for ClangFormat compliance") + else() + add_custom_target(clang_format + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CMAKE_COMMAND}" -E echo "Could not locate ClangFormat" + COMMAND "${CMAKE_COMMAND}" -E false) + add_custom_target(clang_format_test + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CMAKE_COMMAND}" -E echo "Could not locate ClangFormat" + COMMAND "${CMAKE_COMMAND}" -E false) + endif() + + set_target_properties(clang_format clang_format_test PROPERTIES FOLDER "Formatting") +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.config b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.config new file mode 100644 index 0000000..d9c695c --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-format.config @@ -0,0 +1,3 @@ +--- +BasedOnStyle: LLVM +IndentCaseLabels: true diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.cmake new file mode 100644 index 0000000..6dbb43b --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.cmake @@ -0,0 +1,58 @@ +set(NOA_TARGET_CLANG_TIDY_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}") + +function(noa_target_clang_tidy) + cmake_parse_arguments(NOA_TARGET_CLANG_TIDY "REQUIRED" "" "SOURCES" ${ARGN}) + + set(CLANG_TIDY_FIND_PATHS "") + + # Locate ClangTidy on default Homebrew installations, + # given that the LLVM formula won't symlink `clang-tidy` + # to any available path by default. + if(APPLE) + if(IS_DIRECTORY "/opt/homebrew/Cellar/llvm") + set(HOMEBREW_LLVM "/opt/homebrew/Cellar/llvm") + elseif(IS_DIRECTORY "/usr/local/Cellar/llvm") + set(HOMEBREW_LLVM "/opt/local/Cellar/llvm") + endif() + if(HOMEBREW_LLVM) + file(GLOB llvm_version_paths LIST_DIRECTORIES true "${HOMEBREW_LLVM}/*") + foreach(llvm_version_path ${llvm_version_paths}) + list(APPEND CLANG_TIDY_FIND_PATHS "${llvm_version_path}/bin") + endforeach() + endif() + endif() + + if(NOA_TARGET_CLANG_TIDY_REQUIRED) + find_program(CLANG_TIDY_BIN NAMES clang-tidy REQUIRED + PATHS ${CLANG_TIDY_FIND_PATHS}) + else() + find_program(CLANG_TIDY_BIN NAMES clang-tidy + PATHS ${CLANG_TIDY_FIND_PATHS}) + endif() + + # This covers the empty list too + if(NOT NOA_TARGET_CLANG_TIDY_SOURCES) + message(FATAL_ERROR "You must pass file globs to analyze in the SOURCES option") + endif() + file(GLOB_RECURSE NOA_TARGET_CLANG_TIDY_FILES + ${NOA_TARGET_CLANG_TIDY_SOURCES}) + + set(CLANG_TIDY_CONFIG "${NOA_TARGET_CLANG_TIDY_DIRECTORY}/clang-tidy.config") + if(CLANG_TIDY_BIN) + add_custom_target(clang_tidy + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CLANG_TIDY_BIN}" -p "${PROJECT_BINARY_DIR}" + --config-file "${CLANG_TIDY_CONFIG}" + ${NOA_TARGET_CLANG_TIDY_FILES} + COMMENT "Analyzing sources using ClangTidy") + else() + add_custom_target(clang_tidy + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CMAKE_COMMAND}" -E echo "Could not locate ClangTidy" + COMMAND "${CMAKE_COMMAND}" -E false) + endif() + + set_target_properties(clang_tidy PROPERTIES FOLDER "Linting") +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.config b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.config new file mode 100644 index 0000000..1ea469b --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/clang-tidy.config @@ -0,0 +1,7 @@ +--- +# See https://clang.llvm.org/extra/clang-tidy/index.html +# First disable all default checks (with -*) +Checks: '-*,bugprone-*,clang-analyzer-*,clang-diagnostic-*,modernize-*,concurrency-*,cppcoreguidelines-*,performance-*,portability-*,objc-*,misc-*,-misc-no-recursion,-bugprone-easily-swappable-parameters' +WarningsAsErrors: '*' +HeaderFilterRegex: '' +FormatStyle: none diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/doxygen.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/doxygen.cmake new file mode 100644 index 0000000..1a3bfc2 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/doxygen.cmake @@ -0,0 +1,26 @@ +function(noa_target_doxygen) + cmake_parse_arguments(NOA_TARGET_DOXYGEN "" "CONFIG;OUTPUT" "" ${ARGN}) + + if(NOT NOA_TARGET_DOXYGEN_CONFIG) + message(FATAL_ERROR "You must pass an input config file using the CONFIG option") + endif() + if(NOT NOA_TARGET_DOXYGEN_OUTPUT) + message(FATAL_ERROR "You must pass an output directory using the OUTPUT option") + endif() + + find_package(Doxygen) + if(DOXYGEN_FOUND) + set(DOXYGEN_IN "${NOA_TARGET_DOXYGEN_CONFIG}") + set(DOXYGEN_OUT "${CMAKE_CURRENT_BINARY_DIR}/Doxyfile") + configure_file("${DOXYGEN_IN}" "${DOXYGEN_OUT}" @ONLY) + add_custom_target(doxygen + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CMAKE_COMMAND}" -E make_directory "${NOA_TARGET_DOXYGEN_OUTPUT}" + COMMAND "${DOXYGEN_EXECUTABLE}" "${DOXYGEN_OUT}") + else() + add_custom_target(doxygen VERBATIM + COMMAND "${CMAKE_COMMAND}" -E echo "Could not locate Doxygen" + COMMAND "${CMAKE_COMMAND}" -E false) + endif() +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/shellcheck.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/shellcheck.cmake new file mode 100644 index 0000000..03f0a10 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/targets/shellcheck.cmake @@ -0,0 +1,34 @@ +set(NOA_TARGET_SHELLCHECK_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}") + +function(noa_target_shellcheck) + cmake_parse_arguments(NOA_TARGET_SHELLCHECK "REQUIRED" "" "SOURCES" ${ARGN}) + + if(NOA_TARGET_SHELLCHECK_REQUIRED) + find_program(SHELLCHECK_BIN NAMES shellcheck REQUIRED) + else() + find_program(SHELLCHECK_BIN NAMES shellcheck) + endif() + + # This covers the empty list too + if(NOT NOA_TARGET_SHELLCHECK_SOURCES) + message(FATAL_ERROR "You must pass file globs to lint in the SOURCES option") + endif() + file(GLOB_RECURSE NOA_TARGET_SHELLCHECK_FILES + ${NOA_TARGET_SHELLCHECK_SOURCES}) + + if(SHELLCHECK_BIN) + add_custom_target(shellcheck + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${SHELLCHECK_BIN}" ${NOA_TARGET_SHELLCHECK_FILES} + COMMENT "Analyzing sources using ShellCheck") + else() + add_custom_target(shellcheck + WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" + VERBATIM + COMMAND "${CMAKE_COMMAND}" -E echo "Could not locate ShellCheck" + COMMAND "${CMAKE_COMMAND}" -E false) + endif() + + set_target_properties(shellcheck PROPERTIES FOLDER "Linting") +endfunction() diff --git a/vendor/jsonbinpack/vendor/noa/cmake/noa/variables.cmake b/vendor/jsonbinpack/vendor/noa/cmake/noa/variables.cmake new file mode 100644 index 0000000..d294898 --- /dev/null +++ b/vendor/jsonbinpack/vendor/noa/cmake/noa/variables.cmake @@ -0,0 +1,12 @@ +# Get the list of languages defined in the project +get_property(NOA_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES) + +# Compiler detection (C++) +# TODO: Detect compilers on programming languages other than C++ +if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") + set(NOA_COMPILER_LLVM ON) +elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(NOA_COMPILER_GCC ON) +elseif(MSVC) + set(NOA_COMPILER_MSVC ON) +endif()