From 8d0dc4518602e50b0a4adf3ea10172d3c7fa3104 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:42:49 -0300 Subject: [PATCH 001/157] codecs: the library's skeleton, its configuration, its errors and the test rules codecs-run and codecs-compile --- AGENTS.md | 28 ++++ build.jam | 25 ++++ doc/Jamfile | 10 ++ doc/changelog.adoc | 20 +++ doc/codecs.adoc | 33 +++++ example/.clang-tidy | 24 ++++ example/Jamfile | 14 ++ include/webcpp/codecs.hpp | 19 +++ include/webcpp/codecs/config.hpp | 51 +++++++ include/webcpp/codecs/detail/core/error.hpp | 146 ++++++++++++++++++++ meta/include-boundaries.json | 58 ++++++++ meta/libraries.json | 10 ++ meta/lint.json | 3 + test/.clang-tidy | 26 ++++ test/Jamfile | 43 ++++++ test/config_test.cpp | 44 ++++++ test/error_test.cpp | 78 +++++++++++ 17 files changed, 632 insertions(+) create mode 100644 AGENTS.md create mode 100644 build.jam create mode 100644 doc/Jamfile create mode 100644 doc/changelog.adoc create mode 100644 doc/codecs.adoc create mode 100644 example/.clang-tidy create mode 100644 example/Jamfile create mode 100644 include/webcpp/codecs.hpp create mode 100644 include/webcpp/codecs/config.hpp create mode 100644 include/webcpp/codecs/detail/core/error.hpp create mode 100644 meta/include-boundaries.json create mode 100644 meta/libraries.json create mode 100644 meta/lint.json create mode 100644 test/.clang-tidy create mode 100644 test/Jamfile create mode 100644 test/config_test.cpp create mode 100644 test/error_test.cpp diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..09c21e7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,28 @@ +# Working on codecs + +webcpp's rules apply here: read the superproject's +[CODING-GUIDELINES.md](../../CODING-GUIDELINES.md) +() and its +[AGENTS.md](../../AGENTS.md) +() first. This file holds only what is +specific to codecs. + +## What codecs is + +- **webcpp's own library** (`"port-of": null`): one contract for converting bytes and typed + values to text and back, and any data through one-shot and stream transformers, with seven + formats (hex, base32, base58, base64, bech32, percent-encoding and RFC 7468's armor). +- **Header-only**, built on secure (`/webcpp/secure//secure`) and config. percent alone + depends on Boost.URL, through the target `/webcpp/codecs//percent`. + +## Cautions + +- A test is declared through `codecs-run` (or `codecs-compile`) in `test/Jamfile`, which builds it + with exceptions and without. +- A test that defines a seam includes the seam's header first, before any header of codecs. +- The core (`codecs.hpp` and `detail/core/`) includes no format and no Boost.URL: + `meta/include-boundaries.json` checks it, and checks that no header names another webcpp + library but config and secure. +- Constant-time code uses secure's building blocks alone: codecs keeps no guard, wipe, secret + type or constant-time primitive of its own. +- `detail` is not API: another library's header never includes it. diff --git a/build.jam b/build.jam new file mode 100644 index 0000000..54b4559 --- /dev/null +++ b/build.jam @@ -0,0 +1,25 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# codecs: one contract for converting bytes and values to text and back, and +# any data through streams; a program names /webcpp/codecs//codecs, and +# /webcpp/codecs//percent for percent-encoding: +# +# exe app : app.cpp /webcpp/codecs//codecs ; + +import webcpp-target ; + +project /webcpp/codecs ; + +# tag::codecs[] +alias codecs : : : : include /boost//headers /webcpp/config//config + /webcpp/secure//secure ; +# end::codecs[] +# percent.hpp adapts Boost.URL's percent-encoding: a program that includes it +# names this target, which links Boost.URL built from Boost's sources. +# tag::percent[] +alias percent : : : : codecs /webcpp//boost_url ; +# end::percent[] diff --git a/doc/Jamfile b/doc/Jamfile new file mode 100644 index 0000000..79e00bb --- /dev/null +++ b/doc/Jamfile @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.doc codecs : codecs.adoc ; +webcpp.reference codecs ; diff --git a/doc/changelog.adoc b/doc/changelog.adoc new file mode 100644 index 0000000..84238ca --- /dev/null +++ b/doc/changelog.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[appendix] +[#codecs-changelog] +== Changelog + +What changed in codecs in each version of webcpp, newest first, one line +per change. "Unreleased" is what the next version brings. The release notes +of every version are on webcpp's index page. + +[#codecs-changelog-unreleased] +=== Unreleased + +// tag::unreleased[] +* Added webcpp::codecs' skeleton, its configuration and its errors. +// end::unreleased[] diff --git a/doc/codecs.adoc b/doc/codecs.adoc new file mode 100644 index 0000000..4365671 --- /dev/null +++ b/doc/codecs.adoc @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + += codecs: bytes and values to text and back, and streams of any data, for {cpp} +:toc: left +:toclevels: 2 +:idprefix: +:sectanchors: +:example-caption!: +:attribute-missing: warn + +codecs is the conversion library of +https://github.com/webcpporg/webcpp[webcpp], for a {cpp}20 program on every +target webcpp has: one contract for converting bytes and typed values to text +and back, and any data through one-shot and stream transformers, with hex, +base32, base58, base64, bech32, percent-encoding and RFC 7468's armor. It is +built on webcpp::secure, so that the conversions of secrets keep their timing +and their memory clean. + +[#reference] +== Reference + +Every name codecs declares, in the namespace `webcpp::codecs`, from the Doc +Comments of its headers: each class, function, type and enumerator with its +declaration, what it does, what it asks of its caller and how it fails. The +other sections teach the library; this one is where a name is looked up. + +include::{reference}[leveloffset=+1] + +include::changelog.adoc[] diff --git a/example/.clang-tidy b/example/.clang-tidy new file mode 100644 index 0000000..bb3c779 --- /dev/null +++ b/example/.clang-tidy @@ -0,0 +1,24 @@ +# The examples inherit the superproject's configuration and switch off one +# check and one option. +# +# bugprone-exception-escape.CheckMain treats every example's main as a +# function that should not throw. An example is a short program that lets +# what the standard library may throw, a std::bad_alloc or a +# std::length_error from a container that grows, end the process uncaught, +# the way Boost's own examples do; that is main's ordinary role, not a +# defect. The check stays on for everything else: a noexcept function, a +# destructor, a move or a swap. +# +# bugprone-forward-declaration-namespace reports a tag declared and never +# referenced when another namespace declares one of the same name. Libraries +# that name their tags alike on purpose, each declared and never defined, make +# an example that includes several of them report the tag it does not name, in +# either library's header. The check stays on for the library's headers (the +# aggregate) and its tests. +--- +InheritParentConfig: true +Checks: > + -bugprone-forward-declaration-namespace +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/example/Jamfile b/example/Jamfile new file mode 100644 index 0000000..65ab5ed --- /dev/null +++ b/example/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# The guide's programs: each section's example, built and run on every target, +# its output compared with the .expected beside it. None yet. diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp new file mode 100644 index 0000000..e141364 --- /dev/null +++ b/include/webcpp/codecs.hpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The core of webcpp::codecs: one contract for converting bytes and typed + values to text and back, and any data through streams. It includes no format: + a format's header is included by the program that uses it, so that a format + named without its header is an error at the name. +*/ +#ifndef WEBCPP_CODECS_HPP +#define WEBCPP_CODECS_HPP + +#include +#include + +#endif // WEBCPP_CODECS_HPP diff --git a/include/webcpp/codecs/config.hpp b/include/webcpp/codecs/config.hpp new file mode 100644 index 0000000..f8d06ce --- /dev/null +++ b/include/webcpp/codecs/config.hpp @@ -0,0 +1,51 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The configuration of codecs, which each of its headers includes first: whether + codecs is built without exceptions. +*/ +#ifndef WEBCPP_CODECS_CONFIG_HPP +#define WEBCPP_CODECS_CONFIG_HPP + +#include + +// MrDocs parses codecs as a build with exceptions does, where the macro is not +// defined: this definition, undone at once, is the one the reference lists. +#ifdef __MRDOCS__ +/** + Defined when codecs is built without exceptions: when webcpp has none (the + compiler has none, or the developer defined `WEBCPP_NO_EXCEPTIONS` for every + webcpp library), or when the developer defines it alone, to disable codecs' + in a build that has them. + + codecs reports every failure as an error code, so the macro changes nothing + in what a function returns. It is provided so that a program can set it for + every webcpp library alike. +*/ +#define WEBCPP_CODECS_NO_EXCEPTIONS +#undef WEBCPP_CODECS_NO_EXCEPTIONS +#endif + +#if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_CODECS_NO_EXCEPTIONS) +#define WEBCPP_CODECS_NO_EXCEPTIONS +#endif + +/** + One contract for converting bytes and typed values to text and back, and any + data through streams. +*/ +namespace webcpp::codecs { + +/** + The formats: each one is declared by its own header, and none by the core, so + that a format named without its header is a name the namespace lacks. +*/ +namespace formats {} // namespace formats + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_CONFIG_HPP diff --git a/include/webcpp/codecs/detail/core/error.hpp b/include/webcpp/codecs/detail/core/error.hpp new file mode 100644 index 0000000..799842c --- /dev/null +++ b/include/webcpp/codecs/detail/core/error.hpp @@ -0,0 +1,146 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The errors of webcpp::codecs, in the category `webcpp.codecs`. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_ERROR_HPP +#define WEBCPP_CODECS_DETAIL_CORE_ERROR_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The result of an operation of webcpp::codecs: a value or an error code. + + @tparam T The type of the value. +*/ +template +using result = boost::system::result; + +/** + Why a conversion of webcpp::codecs failed. + + The values are fixed and never reused. +*/ +enum class error : int { + /** A character is outside the format's alphabet. */ + invalid_character = 1, + /** The length is one no encoding of the format has. */ + invalid_length = 2, + /** The padding is missing, misplaced or not zero. */ + invalid_padding = 3, + /** The checksum does not match. */ + checksum_mismatch = 4, + /** The prefix or label is not the format's. */ + invalid_prefix = 5, + /** The text mixes upper and lower case. */ + mixed_case = 6, + /** The output is shorter than the result. */ + output_too_small = 7, + /** The input is longer than the format or the buffer allows. */ + input_too_long = 8, +}; + +namespace detail { + +/** The message of a value of @ref error, or the unknown message for a value it does not define. */ +inline const char* message_of(int error_value) noexcept { + switch (static_cast(error_value)) { + case error::invalid_character: return "a character is outside the format's alphabet"; + case error::invalid_length: return "the length is one no encoding of the format has"; + case error::invalid_padding: return "the padding is missing, misplaced or not zero"; + case error::checksum_mismatch: return "the checksum does not match"; + case error::invalid_prefix: return "the prefix or label is not the format's"; + case error::mixed_case: return "the text mixes upper and lower case"; + case error::output_too_small: return "the output is shorter than the result"; + case error::input_too_long: + return "the input is longer than the format or the buffer allows"; + } + return "unknown webcpp.codecs error"; +} + +/** + A constant category with a fixed identity, so it holds no mutable state. + + @note The identity is the ASCII of "codecs" followed by two zero bytes. +*/ +class category final : public boost::system::error_category { +public: + /** Constructs the category with its fixed identity. */ + constexpr category() noexcept : boost::system::error_category(0x636f646563730000ULL) {} + + /** The category's name, "webcpp.codecs". */ + const char* name() const noexcept override { return "webcpp.codecs"; } + + /** The message of the error `error_value`, as @ref message_of spells it. */ + std::string message(int error_value) const override { return message_of(error_value); } + + /** + Copies the message of the error `error_value` into `text_buffer`, cut to fit `byte_count` bytes + with its terminating zero, and returns the whole message, a static text. + */ + const char* message(int error_value, char* text_buffer, + std::size_t byte_count) const noexcept override { + const char* message_text = message_of(error_value); + if (text_buffer != nullptr && byte_count != 0) { + const std::string_view message_spelling(message_text); + const std::size_t size_limit = byte_count - 1; + const std::size_t copied_count = + message_spelling.size() < size_limit ? message_spelling.size() : size_limit; + std::memcpy(text_buffer, message_spelling.data(), copied_count); + text_buffer[copied_count] = '\0'; + } + return message_text; + } +}; + +/** The one category of codecs' errors, which @ref webcpp::codecs::category returns. */ +inline constexpr category the_category{}; + +} // namespace detail + +/** + The category of every @ref error. + + Its `name()` is "webcpp.codecs", and its `message(value)` the message of the error, or + "unknown webcpp.codecs error" for a value @ref error does not define. + + @return The category, a constant with a fixed identity. +*/ +[[nodiscard]] inline const boost::system::error_category& category() noexcept { + return detail::the_category; +} + +/** + Makes the `error_code` of an @ref error, as its implicit conversion does. + + @param error_value The error. + @return `error_value` as an `error_code` of the category @ref category. +*/ +[[nodiscard]] inline boost::system::error_code make_error_code(error error_value) noexcept { + return {static_cast(error_value), category()}; +} + +} // namespace webcpp::codecs + +namespace boost::system { +template <> +struct is_error_code_enum : std::true_type {}; +} // namespace boost::system + +#endif // WEBCPP_CODECS_DETAIL_CORE_ERROR_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json new file mode 100644 index 0000000..53b2b5b --- /dev/null +++ b/meta/include-boundaries.json @@ -0,0 +1,58 @@ +{ + "boundaries": [ + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/detail/core/*.hpp" + ], + "must-not-include": [ + "webcpp/codecs/hex", + "webcpp/codecs/base32", + "webcpp/codecs/base58", + "webcpp/codecs/base64", + "webcpp/codecs/bech32", + "webcpp/codecs/percent", + "webcpp/codecs/armor", + "webcpp/codecs/detail/formats", + "boost/url" + ], + "why": "the core registers no format and needs no Boost.URL" + }, + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/*.hpp", + "include/webcpp/codecs/detail/core/*.hpp" + ], + "must-not-include": [ + "boost/url" + ], + "why": "only percent depends on Boost.URL" + }, + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/*.hpp", + "include/webcpp/codecs/detail/core/*.hpp" + ], + "must-not-include": [ + "webcpp/asio", + "webcpp/beast", + "webcpp/cobalt", + "webcpp/crypto", + "webcpp/document", + "webcpp/hash", + "webcpp/idna", + "webcpp/lexical", + "webcpp/pratt", + "webcpp/trystero", + "webcpp/wasi", + "webcpp/webrtc", + "webcpp/xactor", + "webcpp/xstate", + "webcpp/test" + ], + "why": "codecs depends on config and secure alone" + } + ] +} diff --git a/meta/libraries.json b/meta/libraries.json new file mode 100644 index 0000000..61e7d16 --- /dev/null +++ b/meta/libraries.json @@ -0,0 +1,10 @@ +{ + "key": "codecs", + "name": "codecs", + "authors": ["R"], + "description": "One contract for converting bytes and typed values to text and back, and any data through one-shot and stream transformers, with hex, base32, base58, base64, bech32, percent-encoding and RFC 7468's armor.", + "category": ["String", "Cryptography"], + "maintainers": ["R "], + "cxxstd": "20", + "port-of": null +} diff --git a/meta/lint.json b/meta/lint.json new file mode 100644 index 0000000..df56400 --- /dev/null +++ b/meta/lint.json @@ -0,0 +1,3 @@ +{ + "nodiscard-results": "a dropped result is a refused text or a short buffer that would pass as a conversion" +} diff --git a/test/.clang-tidy b/test/.clang-tidy new file mode 100644 index 0000000..6cca041 --- /dev/null +++ b/test/.clang-tidy @@ -0,0 +1,26 @@ +# The tests inherit the superproject's configuration and switch off one check +# and one option. +# +# bugprone-unchecked-optional-access reports an optional that a test reads +# where its value must be there. Either the test has asserted it first, with +# `if (!BOOST_TEST(x.has_value())) { return; }`, and BOOST_TEST is a call +# returning whether its condition held, which the checker does not look into; +# or the test calls value(), whose failure on an empty optional ends the +# program, with std::bad_optional_access or, built without exceptions, an +# abort, and so fails the test. The library's headers are still analysed with +# it, through the aggregate translation unit tools/lint/compile_commands.py +# writes. +# +# bugprone-exception-escape.CheckMain treats every test's main as a function +# that should not throw. A test's main lets what a failing case throws, a +# boost::system::system_error from value() on a failed result or a +# std::bad_alloc, end the process uncaught, which fails the test as it should; +# example/.clang-tidy says the same of the examples. The check stays on for +# everything else: a noexcept function, a destructor, a move or a swap. +--- +InheritParentConfig: true +Checks: > + -bugprone-unchecked-optional-access +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/test/Jamfile b/test/Jamfile new file mode 100644 index 0000000..5a51eac --- /dev/null +++ b/test/Jamfile @@ -0,0 +1,43 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# Every program that runs, runs with exceptions on and off, and every check +# that compiles, compiles both ways: the second has the suffix _no_exceptions +# and is built with exception-handling=off. +rule codecs-run ( name : sources + : requirements * : targets * ) +{ + webcpp.run $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.run $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} +rule codecs-compile ( name : sources + : requirements * : targets * ) +{ + webcpp.compile $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.compile $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} + +webcpp.headers-alone codecs : ../include : + codecs.hpp codecs/config.hpp codecs/detail/core/*.hpp ; + +# config.hpp defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when webcpp has no +# exceptions, keeps it when a developer defines it, and defines it when +# WEBCPP_NO_EXCEPTIONS is; it declares webcpp::codecs::formats. +webcpp.compile config : config_test.cpp ; +webcpp.compile config_no_exceptions : config_test.cpp : off ; +webcpp.compile config_all_off : config_test.cpp + : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_CODECS_ALL_OFF ; +webcpp.compile config_developer_defined : config_test.cpp + : WEBCPP_CODECS_NO_EXCEPTIONS WEBCPP_TEST_CODECS_DEVELOPER_DEFINED ; + +# The errors: eight fixed values, the category webcpp.codecs, their messages. +codecs-run error : error_test.cpp ; diff --git a/test/config_test.cpp b/test/config_test.cpp new file mode 100644 index 0000000..7aea5bc --- /dev/null +++ b/test/config_test.cpp @@ -0,0 +1,44 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when +// webcpp has no exceptions, and keeps the developer's own definition in a build +// that has them. test/Jamfile builds this file as the build asks; without +// exceptions; with WEBCPP_NO_EXCEPTIONS defined as a developer defines it for +// every webcpp library, which WEBCPP_TEST_CODECS_ALL_OFF tells this file; and +// with the macro itself defined on the command line, which +// WEBCPP_TEST_CODECS_DEVELOPER_DEFINED tells this file. + +#include + +// webcpp's configuration, which config.hpp includes, has said whether webcpp +// has exceptions and which target the program is for. +#ifndef WEBCPP_CONFIG_HPP +#error "config.hpp does not include " +#endif + +#ifndef WEBCPP_VERSION +#error "webcpp's configuration does not define WEBCPP_VERSION" +#endif + +#ifdef WEBCPP_TEST_CODECS_ALL_OFF +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS +#error "WEBCPP_NO_EXCEPTIONS does not define WEBCPP_CODECS_NO_EXCEPTIONS" +#endif +#elif defined(WEBCPP_TEST_CODECS_DEVELOPER_DEFINED) +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS +#error "config.hpp drops WEBCPP_CODECS_NO_EXCEPTIONS, which the developer defined" +#endif +#elif defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_CODECS_NO_EXCEPTIONS) +#error "WEBCPP_CODECS_NO_EXCEPTIONS is not defined exactly when webcpp has no exceptions" +#endif + +// The namespace of the formats is declared by the configuration alone. +namespace probe = webcpp::codecs::formats; + +int main() { + return 0; +} diff --git a/test/error_test.cpp b/test/error_test.cpp new file mode 100644 index 0000000..0a37c86 --- /dev/null +++ b/test/error_test.cpp @@ -0,0 +1,78 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The errors of webcpp::codecs: eight fixed values, one category, eight +// distinct messages and the unknown text for a value that is none of them. + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void check(bool condition, char const* what) { + if (!condition) { + std::cerr << "FAILED: " << what << '\n'; + ++failures; + } +} + +} // namespace + +int main() { + namespace codecs = webcpp::codecs; + constexpr std::array all{ + codecs::error::invalid_character, codecs::error::invalid_length, + codecs::error::invalid_padding, codecs::error::checksum_mismatch, + codecs::error::invalid_prefix, codecs::error::mixed_case, + codecs::error::output_too_small, codecs::error::input_too_long}; + std::set messages; + int expected = 1; + for (codecs::error const value : all) { + auto const code = make_error_code(value); + check(code.value() == static_cast(value), "the code's value is the enumerator's"); + check(static_cast(value) == expected, "the values are 1 to 8 in order"); + ++expected; + check(code.category() == codecs::category(), "the code is of the codecs category"); + check(!code.message().empty(), "every message is not empty"); + messages.insert(code.message()); + } + check(messages.size() == 8, "the eight messages are distinct"); + check(codecs::category().name() == std::string_view{"webcpp.codecs"}, + "the category is named webcpp.codecs"); + check(codecs::category().message(9) == "unknown webcpp.codecs error", + "a value that is no error has the unknown text"); + check(codecs::category().message(0) == "unknown webcpp.codecs error", + "zero is no error either"); + check(boost::system::error_code{codecs::error::mixed_case} == codecs::error::mixed_case, + "an error converts to an equal error code"); + check(&codecs::category() == &codecs::category(), "the category is one object"); + // The exact texts the contract fixes. + check(make_error_code(codecs::error::invalid_character).message() == + "a character is outside the format's alphabet", + "invalid_character's message"); + check(make_error_code(codecs::error::input_too_long).message() == + "the input is longer than the format or the buffer allows", + "input_too_long's message"); + // A message cut to a small buffer is still terminated. + char small[4]; + auto const whole = codecs::category().message(4, small, sizeof small); + check(std::string_view{small} == "the" && + std::string_view{whole} == "the checksum does not match", + "a message is cut to the buffer"); + codecs::result const fine = 3; + check(fine.has_value() && *fine == 3, "result carries a value"); + return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} From 48623400bef7913139b3c796a80e78ea37b9bf44 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:09:12 -0300 Subject: [PATCH 002/157] codecs: skeleton lint fix --- include/webcpp/codecs/config.hpp | 6 ++---- test/config_test.cpp | 3 ++- test/error_test.cpp | 33 ++++++++++++++++---------------- 3 files changed, 20 insertions(+), 22 deletions(-) diff --git a/include/webcpp/codecs/config.hpp b/include/webcpp/codecs/config.hpp index f8d06ce..1d3a145 100644 --- a/include/webcpp/codecs/config.hpp +++ b/include/webcpp/codecs/config.hpp @@ -38,14 +38,12 @@ One contract for converting bytes and typed values to text and back, and any data through streams. */ -namespace webcpp::codecs { +namespace webcpp::codecs {} // namespace webcpp::codecs /** The formats: each one is declared by its own header, and none by the core, so that a format named without its header is a name the namespace lacks. */ -namespace formats {} // namespace formats - -} // namespace webcpp::codecs +namespace webcpp::codecs::formats {} // namespace webcpp::codecs::formats #endif // WEBCPP_CODECS_CONFIG_HPP diff --git a/test/config_test.cpp b/test/config_test.cpp index 7aea5bc..e566330 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -37,7 +37,8 @@ #endif // The namespace of the formats is declared by the configuration alone. -namespace probe = webcpp::codecs::formats; +namespace probe = + webcpp::codecs::formats; // NOLINT(misc-unused-alias-decls): the name is the check int main() { return 0; diff --git a/test/error_test.cpp b/test/error_test.cpp index 0a37c86..2202650 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -18,26 +18,23 @@ #include #include -namespace { - -int failures = 0; - -void check(bool condition, char const* what) { - if (!condition) { - std::cerr << "FAILED: " << what << '\n'; - ++failures; - } -} - -} // namespace +namespace {} // namespace int main() { + int failures = 0; + auto const check = [&failures](bool condition, char const* what) { + if (!condition) { + std::cerr << "FAILED: " << what << '\n'; + ++failures; + } + }; namespace codecs = webcpp::codecs; constexpr std::array all{ codecs::error::invalid_character, codecs::error::invalid_length, codecs::error::invalid_padding, codecs::error::checksum_mismatch, codecs::error::invalid_prefix, codecs::error::mixed_case, - codecs::error::output_too_small, codecs::error::input_too_long}; + codecs::error::output_too_small, codecs::error::input_too_long, + }; std::set messages; int expected = 1; for (codecs::error const value : all) { @@ -58,7 +55,9 @@ int main() { "zero is no error either"); check(boost::system::error_code{codecs::error::mixed_case} == codecs::error::mixed_case, "an error converts to an equal error code"); - check(&codecs::category() == &codecs::category(), "the category is one object"); + auto const& first = codecs::category(); + auto const& second = codecs::category(); + check(&first == &second, "the category is one object"); // The exact texts the contract fixes. check(make_error_code(codecs::error::invalid_character).message() == "a character is outside the format's alphabet", @@ -67,9 +66,9 @@ int main() { "the input is longer than the format or the buffer allows", "input_too_long's message"); // A message cut to a small buffer is still terminated. - char small[4]; - auto const whole = codecs::category().message(4, small, sizeof small); - check(std::string_view{small} == "the" && + std::array small{}; + auto const* const whole = codecs::category().message(4, small.data(), small.size()); + check(std::string_view{small.data()} == "the" && std::string_view{whole} == "the checksum does not match", "a message is cut to the buffer"); codecs::result const fine = 3; From 06944577bacb405de33d72274669ebab5f0e15d3 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:21:19 -0300 Subject: [PATCH 003/157] codecs: skeleton lint fix, the namespace probe's suppression --- test/config_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/config_test.cpp b/test/config_test.cpp index e566330..00c57b6 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -37,8 +37,8 @@ #endif // The namespace of the formats is declared by the configuration alone. -namespace probe = - webcpp::codecs::formats; // NOLINT(misc-unused-alias-decls): the name is the check +// NOLINTNEXTLINE(misc-unused-alias-decls): the name is the check. +namespace probe = webcpp::codecs::formats; int main() { return 0; From 43a84b4fd7ac02c5582cd3879744891478582be7 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 07:50:50 -0300 Subject: [PATCH 004/157] codecs: the error test without its empty namespace, the config test's builds as a list --- test/config_test.cpp | 12 +++++++----- test/error_test.cpp | 2 -- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/test/config_test.cpp b/test/config_test.cpp index 00c57b6..0823155 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -6,11 +6,13 @@ // defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when // webcpp has no exceptions, and keeps the developer's own definition in a build -// that has them. test/Jamfile builds this file as the build asks; without -// exceptions; with WEBCPP_NO_EXCEPTIONS defined as a developer defines it for -// every webcpp library, which WEBCPP_TEST_CODECS_ALL_OFF tells this file; and -// with the macro itself defined on the command line, which -// WEBCPP_TEST_CODECS_DEVELOPER_DEFINED tells this file. +// that has them. test/Jamfile builds this file four ways: +// - as the build asks; +// - without exceptions; +// - with WEBCPP_NO_EXCEPTIONS defined, as a developer defines it for every +// webcpp library, which WEBCPP_TEST_CODECS_ALL_OFF tells this file; +// - with the macro itself defined on the command line, which +// WEBCPP_TEST_CODECS_DEVELOPER_DEFINED tells this file. #include diff --git a/test/error_test.cpp b/test/error_test.cpp index 2202650..cca431b 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -18,8 +18,6 @@ #include #include -namespace {} // namespace - int main() { int failures = 0; auto const check = [&failures](bool condition, char const* what) { From 790eab6e91e9bdc6bfba0017d4c7b327d832f590 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 08:00:44 -0300 Subject: [PATCH 005/157] codecs: the format contract, its concepts and refusal, the sizes and the buffer forms, over a format of the tests' own --- include/webcpp/codecs.hpp | 2 + .../webcpp/codecs/detail/core/contract.hpp | 346 ++++++++++++++++++ include/webcpp/codecs/detail/core/sizes.hpp | 211 +++++++++++ test/Jamfile | 12 + test/allocation_test.cpp | 188 ++++++++++ test/contract_test.cpp | 142 +++++++ test/messages/Jamfile | 15 + test/messages/forgotten_header/Jamfile | 16 + .../forgotten_header/forgotten_header.cpp | 24 ++ test/messages/refused_size/Jamfile | 16 + test/messages/refused_size/refused_size.cpp | 23 ++ test/noexcept_test.cpp | 36 ++ test/sizes_test.cpp | 211 +++++++++++ test/support/counting.hpp | 316 ++++++++++++++++ test/support/letters.hpp | 122 ++++++ 15 files changed, 1680 insertions(+) create mode 100644 include/webcpp/codecs/detail/core/contract.hpp create mode 100644 include/webcpp/codecs/detail/core/sizes.hpp create mode 100644 test/allocation_test.cpp create mode 100644 test/contract_test.cpp create mode 100644 test/messages/Jamfile create mode 100644 test/messages/forgotten_header/Jamfile create mode 100644 test/messages/forgotten_header/forgotten_header.cpp create mode 100644 test/messages/refused_size/Jamfile create mode 100644 test/messages/refused_size/refused_size.cpp create mode 100644 test/noexcept_test.cpp create mode 100644 test/sizes_test.cpp create mode 100644 test/support/counting.hpp create mode 100644 test/support/letters.hpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index e141364..b22fa71 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -14,6 +14,8 @@ #define WEBCPP_CODECS_HPP #include +#include #include +#include #endif // WEBCPP_CODECS_HPP diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp new file mode 100644 index 0000000..e6c1adf --- /dev/null +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -0,0 +1,346 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The format contract of webcpp::codecs: the two specialization points `codec` and `value_codec`, + the concepts that say which pairs convert, the inputs the core reads, and the refusal of a pair + that does not convert. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_CONTRACT_HPP +#define WEBCPP_CODECS_DETAIL_CORE_CONTRACT_HPP + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The conversion of a format between bytes and text: declared by the core, never defined, and + specialized by each format's header for its format's type. + + A specialization has six functions and one constant, every function `noexcept`, and every + public operation of codecs is written over them alone: + + @code + template <> struct codec { + // Whether encode and decode run in a time that does not depend on the data. + static constexpr bool constant_time = true; + // A bound on the text of input_size bytes, over every option of the format, + // SIZE_MAX when it does not fit in std::size_t. + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept; + // A bound on the bytes of text_size characters, SIZE_MAX when it does not fit. + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept; + // The exact size of the text the format writes for input. + static constexpr std::size_t encoded_size(formats::hex_t const& format, + std::span input) noexcept; + // The exact size of the bytes text decodes to, the whole text checked. + static result decoded_size(formats::hex_t const& format, + std::string_view text) noexcept; + static result encode(formats::hex_t const& format, + std::span input, + std::span output) noexcept; + static result decode(formats::hex_t const& format, std::string_view text, + std::span output) noexcept; + }; + @endcode + + The bounds saturate at `SIZE_MAX`, which means "does not fit": an input whose bound saturates is + refused with @ref error::input_too_long before it is read. When a data error is found, the one + with the lowest value of @ref error is reported. + + @tparam Format The format's type. +*/ +template +struct codec; + +/** + The conversion of a format between a typed value and its encoding: declared by the core, never + defined, and specialized by the library that owns the format or the type, in the header that + defines the pair. + + A specialization states the kind of its encoding and has the functions of the directions it + converts, encoding only, decoding only, or both: + + @code + template <> struct value_codec { + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + static constexpr bool secret = true; // optional; false when absent + static constexpr std::size_t max_encoded_size = 138; // optional; a fixed result when present + static std::size_t encoded_size(Format const& format, Value const& value) noexcept; + static result encode(Format const& format, Value const& value, + std::span output) noexcept; + static result decode(Format const& format, + std::span input) noexcept; + }; + @endcode + + A value codec whose `output` is @ref output_kind::text writes a `std::span` and reads a + `std::string_view`. The errors it returns, of any category, reach the caller unchanged. + + @tparam Format The format's type. + @tparam Value The value's type. +*/ +template +struct value_codec; + +/** What a value codec's encoding is made of. */ +enum class output_kind : unsigned char { + /** Bytes: the encoding is written to a `std::span`. */ + bytes = 1, + /** Text: the encoding is written to a `std::span`. */ + text = 2, +}; + +/** + A format: a copyable type with a constant `name` that converts to `std::string_view`, passed by + value as the first argument of every operation. + + @tparam F The type to check. +*/ +template +concept format = std::copyable && requires { + { F::name } -> std::convertible_to; +}; + +namespace detail { + +/** An element type of one byte: `std::uint8_t`, `unsigned char`, `char` or `std::byte`. */ +template +concept byte_element = + std::same_as, std::uint8_t> || + std::same_as, unsigned char> || std::same_as, char> || + std::same_as, std::byte>; + +/** A contiguous sized range of byte elements. */ +template +concept byte_range = + std::ranges::contiguous_range && std::ranges::sized_range && + byte_element>; + +/** A type of a constant `size()` that converts to a span of that many bytes: `secure::secret`. */ +template +concept static_byte_view = requires { typename std::integral_constant; } && + std::convertible_to>; + +/** + A byte input: a contiguous sized range of `std::uint8_t`, `unsigned char`, `char` or `std::byte` + (a string literal is read as a `std::string_view`, B5), or a type with a static constexpr `size()` + that converts to `std::span` (`secure::secret`). +*/ +template +concept byte_input = byte_range> || static_byte_view>; + +/** A text input: anything a `std::string_view` is made from. */ +template +concept text_input = std::convertible_to; + +/** The size of an input known at compile time, else `std::dynamic_extent`. */ +template +struct static_input_size : std::integral_constant {}; + +/** A `std::array` of bytes: its size. */ +template + requires byte_element +struct static_input_size> : std::integral_constant {}; + +/** An array of bytes other than `char`: its size; a `char` array is read as a text (B5). */ +template + requires(byte_element && !std::same_as, char>) +struct static_input_size : std::integral_constant {}; + +/** A span of bytes of a static extent: its extent. */ +template + requires(byte_element && N != std::dynamic_extent) +struct static_input_size> : std::integral_constant {}; + +/** A type of a constant size that converts to a span of that many bytes: its size. */ +template +struct static_input_size : std::integral_constant {}; + +} // namespace detail + +/** + The size of an input of type `T` when it is known at compile time, else `std::dynamic_extent`. + + It is known for a `std::array` and a `std::span` of a static extent of byte elements, an array of + `std::uint8_t`, `unsigned char` or `std::byte`, and a type with a static constexpr `size()` that + converts to `std::span`, as `secure::secret` does. An array of + `char`, a string literal, is read as a `std::string_view` and its size is not static (B5). + + @tparam T The input's type; a reference and `const` are ignored. +*/ +template +inline constexpr std::size_t static_input_size_v = + detail::static_input_size>::value; + +namespace detail { + +/** Whether `codec` is specialized. */ +template +concept has_codec = requires { sizeof(codec); }; + +/** Whether `T` is a byte result the core builds: a string, a vector or an array of bytes. */ +template +struct byte_result_type : std::false_type {}; + +/** A string of `char`, whatever its traits and allocator. */ +template +struct byte_result_type> : std::true_type {}; + +/** A vector of `std::uint8_t`, whatever its allocator. */ +template +struct byte_result_type> : std::true_type {}; + +/** An array of `N` bytes, which a decode fills exactly. */ +template +struct byte_result_type> : std::true_type {}; + +/** A byte result the core builds from a decode (D5); later parts add their own types. */ +template +concept byte_result = byte_result_type>::value; + +/** The span a value codec of `Format` and `Value` encodes into, by its `output`. */ +template +using value_output_span = + std::conditional_t::output == output_kind::bytes, + std::span, std::span>; + +/** The input a value codec of `Format` and `Value` decodes from, by its `output`. */ +template +using value_input_view = + std::conditional_t::output == output_kind::bytes, + std::span, std::string_view>; + +/** Whether `value_codec` is specialized with `output`, `encoded_size` and `encode`. */ +template +concept value_encodable = + requires { sizeof(value_codec>); } && + requires(F const& format_value, std::remove_cvref_t const& held_value, + value_output_span> output_span) { + { + value_codec>::encoded_size(format_value, held_value) + } -> std::same_as; + { + value_codec>::encode(format_value, held_value, output_span) + } -> std::same_as>; + }; + +/** Whether `value_codec` is specialized with `output` and `decode`. */ +template +concept value_decodable = requires { + sizeof(value_codec>); +} && requires(F const& format_value, value_input_view> input_view) { + { + value_codec>::decode(format_value, input_view) + } -> std::same_as>>; +}; + +} // namespace detail + +/** + Whether a value of type `V` encodes in the format `F`: `V` is a byte input and `codec` is + specialized, or `value_codec` is specialized with `encode` and `encoded_size`. + + A byte input is a contiguous sized range of `std::uint8_t`, `unsigned char`, `char` or + `std::byte`, or a type with a static constexpr `size()` that converts to + `std::span`, as `secure::secret`. + + @tparam V The value's type. + @tparam F The format's type. +*/ +template +concept encodable = + format && ((detail::byte_input && detail::has_codec) || detail::value_encodable); + +/** + Whether a value of type `V` decodes from the format `F`: `V` is a byte result the core builds + (`std::string`, `std::vector`, `std::array`) and `codec` is + specialized, or `value_codec` is specialized with `decode`. + + @tparam V The value's type. + @tparam F The format's type. +*/ +template +concept decodable = format && ((detail::byte_result && detail::has_codec) || + detail::value_decodable); + +namespace detail { + +/** + The requirement of a refusal: false for every pair, so that a refusal's static assertion, which + names it, prints the value's type and the format's type (ruling R2). +*/ +template +inline constexpr bool converts = false; + +/** + Stops the build: the format `Format` does not convert the type `Value` in the direction of the + operation that calls this, which has found that the pair is not `encodable` or not `decodable`. +*/ +template +constexpr void refuse() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::converts, + "webcpp::codecs: this format does not convert this type; include the format's " + "header, or specialize webcpp::codecs::value_codec for the format and the type"); +} + +/** + The characters of a text input; an array of `char` is read up to its first zero and never past + its end, as a string literal is read as a `std::string_view` (B5). +*/ +template +[[nodiscard]] constexpr std::string_view text_view(Text const& text) noexcept { + if constexpr (std::is_array_v) { + auto const characters_end = std::ranges::find(text, '\0'); + return {std::ranges::data(text), static_cast(std::ranges::distance( + std::ranges::begin(text), characters_end))}; + } else { + return text; + } +} + +/** + The bytes of a byte input; a text input among them (a `std::string`, a string literal) is read as + its `std::string_view`. +*/ +template +[[nodiscard]] constexpr std::span input_bytes(Input const& input) noexcept { + if constexpr (text_input) { + std::string_view const characters = text_view(input); + // A char is read through an unsigned char, which may alias any object. + return {reinterpret_cast(characters.data()), characters.size()}; + } else if constexpr (static_byte_view) { + return std::span{input}; + } else if constexpr (std::same_as>, + std::uint8_t>) { + return {std::ranges::data(input), std::ranges::size(input)}; + } else { + // A std::byte or a char is read through an unsigned char, which may alias any object. + return {reinterpret_cast(std::ranges::data(input)), + std::ranges::size(input)}; + } +} + +} // namespace detail + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_CONTRACT_HPP diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp new file mode 100644 index 0000000..fdee58f --- /dev/null +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -0,0 +1,211 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The sizes of webcpp::codecs, the exact size of an encoding and the bound of a decoding, and the + buffer forms, which convert into the caller's buffer. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_SIZES_HPP +#define WEBCPP_CODECS_DETAIL_CORE_SIZES_HPP + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** The sum of two sizes, or `SIZE_MAX` when it does not fit in `std::size_t`. */ +constexpr std::size_t saturating_add(std::size_t first_size, std::size_t second_size) noexcept { + constexpr std::size_t size_maximum = std::numeric_limits::max(); + return first_size > size_maximum - second_size ? size_maximum : first_size + second_size; +} + +/** The product of two sizes, or `SIZE_MAX` when it does not fit in `std::size_t`. */ +constexpr std::size_t saturating_multiply(std::size_t first_size, + std::size_t second_size) noexcept { + constexpr std::size_t size_maximum = std::numeric_limits::max(); + if (first_size != 0 && second_size > size_maximum / first_size) { + return size_maximum; + } + return first_size * second_size; +} + +/** + @ref error::input_too_long when the encoding of `input_size` bytes does not fit, its bound + saturated at `SIZE_MAX`; no error otherwise. Every form checks it before it reads the input. +*/ +template + requires has_codec +[[nodiscard]] constexpr std::optional input_size_fault(F const& /*format*/, + std::size_t input_size) noexcept { + if (codec::max_encoded_size(input_size) == std::numeric_limits::max()) { + return error::input_too_long; + } + return std::nullopt; +} + +/** + @ref error::input_too_long when the bytes of `text_size` characters do not fit, their bound + saturated at `SIZE_MAX`; no error otherwise. Every form checks it before it reads the text. +*/ +template + requires has_codec +[[nodiscard]] constexpr std::optional text_size_fault(F const& /*format*/, + std::size_t text_size) noexcept { + if (codec::max_decoded_size(text_size) == std::numeric_limits::max()) { + return error::input_too_long; + } + return std::nullopt; +} + +} // namespace detail + +/** + The exact size of what `encode` writes for `input` in `format`: characters, or bytes for a value + codec of bytes. + + It is a constant expression where the format and the input are, and the input's bytes are + `std::uint8_t` or `unsigned char` (or the input is a value of a value codec whose `encoded_size` + is `constexpr`). A value codec of `F` and `Input` is used when it encodes, else `codec`. + + A pair that is not @ref encodable stops the build with a message that the format does not + convert this type. + + @tparam F The format's type. + @tparam Input The input's type: a byte input, or a value of a value codec. + @param format The format. + @param input The bytes, or the value, to encode. + @return The size, `SIZE_MAX` when it does not fit in `std::size_t`. +*/ +template +[[nodiscard]] constexpr std::size_t encoded_size(F const& format, Input const& input) noexcept { + if constexpr (detail::value_encodable) { + return value_codec::encoded_size(format, input); + } else if constexpr (detail::byte_input && detail::has_codec) { + return codec::encoded_size(format, detail::input_bytes(input)); + } else { + detail::refuse(); + return 0; + } +} + +/** + A bound on the bytes `decode` writes for `text` in `format`, from the text's size alone. + + It is a constant expression where the format and the text are. A format with no `codec` + specialization stops the build with a message that the format does not convert bytes. + + @tparam F The format's type. + @tparam Text The text's type: anything a `std::string_view` is made from. + @param format The format. + @param text The text; a string literal is read up to its terminating zero. + @return The bound, `SIZE_MAX` when it does not fit in `std::size_t`. +*/ +template +[[nodiscard]] constexpr std::size_t max_decoded_size([[maybe_unused]] F const& format, + Text const& text) noexcept { + if constexpr (detail::has_codec) { + return codec::max_decoded_size(detail::text_view(text).size()); + } else { + detail::refuse, F>(); + return 0; + } +} + +/** + Encodes `input` in `format` into the caller's buffer, allocating nothing. + + The checks come first, and on every error nothing is written: an input whose encoding does not + fit in `std::size_t` is @ref error::input_too_long, before it is read; an `output` shorter than + the exact size is @ref error::output_too_small. The text is then written at the start of + `output`, whose other characters are unchanged. + + A format with no `codec` specialization stops the build with a message that the format does not + convert this type. + + @tparam F The format's type. + @tparam Input The input's type: a contiguous sized range of `std::uint8_t`, `unsigned char`, + `char` or `std::byte` (a string literal is read without its terminating zero), or a type of a + constant `size()` that converts to a span of that many bytes, as `secure::secret`. + @param format The format. + @param input The bytes to encode. + @param output The buffer the text is written to. + @return The number of characters written, or the error. +*/ +template +[[nodiscard]] result encode(F const& format, Input const& input, + std::span output) noexcept { + if constexpr (detail::has_codec) { + std::span const input_view = detail::input_bytes(input); + if (auto const size_fault = detail::input_size_fault(format, input_view.size())) { + return *size_fault; + } + std::size_t const text_size = codec::encoded_size(format, input_view); + if (output.size() < text_size) { + return error::output_too_small; + } + return codec::encode(format, input_view, output.first(text_size)); + } else { + detail::refuse(); + return std::size_t{0}; + } +} + +/** + Decodes `text` in `format` into the caller's buffer, allocating nothing. + + The checks come first, and on every error nothing is written: a text whose bytes do not fit in + `std::size_t` is @ref error::input_too_long, before it is read; then the whole text is checked, + and its data error with the lowest value of @ref error is returned; then an `output` shorter + than the exact size is @ref error::output_too_small. The bytes are then written at the start of + `output`, whose other bytes are unchanged. Where the format's page says so, `output` may be the + text's own storage. + + A format with no `codec` specialization stops the build with a message that the format does not + convert bytes. + + @tparam F The format's type. + @tparam Text The text's type: anything a `std::string_view` is made from. + @param format The format. + @param text The text to decode; a string literal is read up to its terminating zero. + @param output The buffer the bytes are written to. + @return The number of bytes written, or the error. +*/ +template +[[nodiscard]] result decode(F const& format, Text const& text, + std::span output) noexcept { + if constexpr (detail::has_codec) { + std::string_view const text_characters = detail::text_view(text); + if (auto const size_fault = detail::text_size_fault(format, text_characters.size())) { + return *size_fault; + } + result const byte_count = codec::decoded_size(format, text_characters); + if (!byte_count) { + return byte_count; + } + if (output.size() < *byte_count) { + return error::output_too_small; + } + return codec::decode(format, text_characters, output.first(*byte_count)); + } else { + detail::refuse, F>(); + return std::size_t{0}; + } +} + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_SIZES_HPP diff --git a/test/Jamfile b/test/Jamfile index 5a51eac..7dcb800 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -41,3 +41,15 @@ webcpp.compile config_developer_defined : config_test.cpp # The errors: eight fixed values, the category webcpp.codecs, their messages. codecs-run error : error_test.cpp ; + +# The concepts: formats, byte and text inputs, static sizes, the pairs that convert. +codecs-run contract : contract_test.cpp ; +# The sizes and the buffer forms: B23's order, nothing written on an error, bounds. +codecs-run sizes : sizes_test.cpp ; +# The forms that allocate nothing leave a counting operator new where it was. +codecs-run allocation : allocation_test.cpp ; +# Every form that allocates nothing is noexcept, and every form that allocates is not. +codecs-compile noexcept : noexcept_test.cpp ; + +# The refusals and a forgotten format header stop the build with their messages. +build-project messages ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp new file mode 100644 index 0000000..c0e17e9 --- /dev/null +++ b/test/allocation_test.cpp @@ -0,0 +1,188 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The forms of codecs that allocate nothing leave the count where it was: every call is made +// under support/counting.hpp's replacement of every form of operator new (and the C library's +// allocator where a program can count it). A control first calls each form of operator new once +// and checks that each is counted, so a zero is not a replacement that never ran. Later tasks +// add their rows. + +#include "support/counting.hpp" + +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace counting = webcpp::codecs::test; +namespace test = webcpp::codecs::test; + +constexpr std::size_t big = 64; +constexpr std::align_val_t aligned{big}; + +/** Runs `body` and checks that it moved neither counter. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const new_before = counting::counted_new.load(); + std::size_t const c_before = counting::counted_c.load(); + body(); + std::size_t const new_after = counting::counted_new.load(); + std::size_t const c_after = counting::counted_c.load(); + if (new_after != new_before || c_after != c_before) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(new_after - new_before, 0U); + BOOST_TEST_EQ(c_after - c_before, 0U); +} + +/** Runs `body`, one allocation of operator new's form, and checks that the counter saw it. */ +template +void expect_counted(char const* form, Body body) { + std::size_t const before = counting::counted_new.load(); + body(); + std::size_t const counted = counting::counted_new.load() - before; + if (counted != 1) { + std::printf("not counted once: %s\n", form); + } + BOOST_TEST_EQ(counted, 1U); +} + +/** Every form of operator new moves the counter: the control of the zeros below. */ +void control_counts_every_form() { + expect_counted("new", [] { + void* volatile block = ::operator new(24); + ::operator delete(block); + }); + expect_counted("new[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block); + }); + expect_counted("sized delete", [] { + void* volatile block = ::operator new(24); + ::operator delete(block, std::size_t{24}); + }); + expect_counted("sized delete[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block, std::size_t{24}); + }); + expect_counted("nothrow new", [] { + void* volatile block = ::operator new(24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, std::nothrow); + }); + expect_counted("nothrow new[]", [] { + void* volatile block = ::operator new[](24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, std::nothrow); + }); + expect_counted("aligned new", [] { + void* volatile block = ::operator new(24, aligned); + ::operator delete(block, aligned); + }); + expect_counted("aligned new[]", [] { + void* volatile block = ::operator new[](24, aligned); + ::operator delete[](block, aligned); + }); + expect_counted("aligned nothrow new", [] { + void* volatile block = ::operator new(24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, aligned, std::nothrow); + }); + expect_counted("aligned nothrow new[]", [] { + void* volatile block = ::operator new[](24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, aligned, std::nothrow); + }); + // The standard allocator's storage, which every container takes: not a container's own, since + // MSVC's debug library (_ITERATOR_DEBUG_LEVEL 1 or 2) also allocates a proxy per container. + expect_counted("std::allocator's storage", [] { + std::allocator allocator; + std::uint8_t* volatile block = allocator.allocate(16); + BOOST_TEST(block != nullptr); + allocator.deallocate(block, 16); + }); + expect_counted("new int[]", [] { + int const* volatile block = new int[4]; + delete[] block; + }); +} + +/** The sizes and the buffer forms (Task 2): each call of sizes_test, on every path. */ +void check_buffer_forms() { + std::array const input{0x01, 0xff}; + std::array const wide_input{}; + std::vector const heap_input(3); // built before the window + std::array output{}; + std::array decoded{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + expect_no_allocation("encoded_size", [&] { + sink = codecs::encoded_size(test::letters, input); + sink = codecs::encoded_size(test::letters, heap_input); + }); + expect_no_allocation("max_decoded_size", [&] { + sink = codecs::max_decoded_size(test::letters, std::string_view{"abpp"}); + sink = codecs::max_decoded_size(test::letters, "abpp"); + }); + expect_no_allocation("encode into a buffer", [&] { + verdict = codecs::encode(test::letters, input, output).has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("decode into a buffer", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abpp"}, decoded).has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("encode into a short buffer", [&] { + verdict = codecs::encode(test::letters, wide_input, std::span{output}.first(63)) + .has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("decode into a short buffer", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abab"}, + std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("decode of a refused text", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abq"}, decoded).has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("empty inputs", [&] { + verdict = codecs::encode(test::letters, std::span{}, std::span{}) + .has_value() && + codecs::decode(test::letters, std::string_view{}, std::span{}) + .has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("input_size_fault", [&] { + verdict = codecs::detail::input_size_fault(test::letters, SIZE_MAX).has_value(); + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +} // namespace + +int main() { + std::printf("c_allocations_counted=%d\n", counting::c_allocations_counted ? 1 : 0); + control_counts_every_form(); + check_buffer_forms(); + return boost::report_errors(); +} diff --git a/test/contract_test.cpp b/test/contract_test.cpp new file mode 100644 index 0000000..f408db1 --- /dev/null +++ b/test/contract_test.cpp @@ -0,0 +1,142 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The format contract's concepts: what a format is, which inputs are bytes and which texts, the +// sizes known at compile time (D7, B5), and which pairs encode and decode (D5); then the bytes +// and the text the core reads from each kind of input. + +#include "support/letters.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +// A format: copyable, with a name that converts to std::string_view. +static_assert(codecs::format); +static_assert(!codecs::format); + +/** A type with a name but no copy: not a format. */ +struct not_copyable_t { + static constexpr std::string_view name = "not_copyable"; + not_copyable_t() = default; + not_copyable_t(not_copyable_t const&) = delete; + not_copyable_t& operator=(not_copyable_t const&) = delete; + not_copyable_t(not_copyable_t&&) = delete; + not_copyable_t& operator=(not_copyable_t&&) = delete; + ~not_copyable_t() = default; +}; + +// It has a name: only the copy is missing. +static_assert(std::convertible_to); +static_assert(!codecs::format); + +/** A format no header specializes `codec` for. */ +struct unregistered_t { + static constexpr std::string_view name = "unregistered"; +}; + +static_assert(codecs::format); + +// The sizes known at compile time: a static extent, an array of bytes, secure's secret. +static_assert(codecs::static_input_size_v> == 32); +static_assert(codecs::static_input_size_v == 32); +static_assert(codecs::static_input_size_v> == 32); +static_assert(codecs::static_input_size_v> == 32); +static_assert(codecs::static_input_size_v const&> == 5); +// Run-time sizes, and a string literal, read as a std::string_view (B5). +static_assert(codecs::static_input_size_v> == std::dynamic_extent); +static_assert(codecs::static_input_size_v == std::dynamic_extent); +static_assert(codecs::static_input_size_v == std::dynamic_extent); +static_assert(codecs::static_input_size_v> == std::dynamic_extent); + +// Byte inputs and text inputs (D7). +static_assert(codecs::detail::byte_input>); +static_assert(codecs::detail::byte_input>); +static_assert(codecs::detail::byte_input); +static_assert(codecs::detail::byte_input); +static_assert(codecs::detail::byte_input>); +static_assert(!codecs::detail::byte_input); +static_assert(!codecs::detail::byte_input>); +static_assert(codecs::detail::text_input); +static_assert(codecs::detail::text_input); +static_assert(codecs::detail::text_input); +static_assert(!codecs::detail::text_input>); + +// The pairs that encode and decode (D5). +static_assert(codecs::encodable, test::letters_t>); +static_assert(codecs::encodable, test::letters_t>); +static_assert(codecs::encodable, test::letters_t>); +static_assert(!codecs::encodable); +static_assert(!codecs::encodable, unregistered_t>); +static_assert(!codecs::encodable, int>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable); +static_assert(codecs::decodable, test::letters_t>); +static_assert(!codecs::decodable); +static_assert(!codecs::decodable, test::letters_t>); +static_assert(!codecs::decodable, unregistered_t>); +static_assert(codecs::detail::has_codec); +static_assert(!codecs::detail::has_codec); + +/** Whether a span views the bytes `expected`. */ +bool views(std::span viewed, std::string_view expected) { + return std::string_view{reinterpret_cast(viewed.data()), viewed.size()} == + expected; +} + +/** The bytes the core reads from each kind of byte input. */ +void input_bytes_of_each_input() { + std::array const array_input{'x', 'y', 'z'}; + BOOST_TEST(views(codecs::detail::input_bytes(array_input), "xyz")); + std::array const byte_input{std::byte{'o'}, std::byte{'k'}}; + BOOST_TEST(views(codecs::detail::input_bytes(byte_input), "ok")); + std::vector const vector_input{'a', 'b'}; + BOOST_TEST(views(codecs::detail::input_bytes(vector_input), "ab")); + std::string const string_input{"a\0b", 3}; + BOOST_TEST(views(codecs::detail::input_bytes(string_input), std::string_view{"a\0b", 3})); + // A string literal is read as a std::string_view: its terminating zero is not a byte (B5). + BOOST_TEST_EQ(codecs::detail::input_bytes("abc").size(), 3U); + BOOST_TEST(views(codecs::detail::input_bytes("abc"), "abc")); + // An array of char that holds no zero is read whole, never past its end. + // NOLINTNEXTLINE(modernize-avoid-c-arrays): the kind of input under test + char const unterminated[] = {'w', 'x', 'y', 'z'}; + BOOST_TEST(views(codecs::detail::input_bytes(unterminated), "wxyz")); + webcpp::secure::secret<2> held; + held.writable()[0] = 's'; + held.writable()[1] = 'k'; + BOOST_TEST(views(codecs::detail::input_bytes(held), "sk")); +} + +/** The text the core reads from each kind of text input. */ +void text_view_of_each_input() { + BOOST_TEST_EQ(codecs::detail::text_view("abcd"), "abcd"); + BOOST_TEST_EQ(codecs::detail::text_view(std::string{"ab"}), "ab"); + BOOST_TEST_EQ(codecs::detail::text_view(std::string_view{"a\0b", 3}).size(), 3U); +} + +} // namespace + +int main() { + input_bytes_of_each_input(); + text_view_of_each_input(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile new file mode 100644 index 0000000..310793e --- /dev/null +++ b/test/messages/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Each message test in a directory of its own (secure's form): a directory's +# Jamfile gives its case the requirements that raise the message, and nothing +# else. Each case is a clang message test on native, wasip2 and wasip3, and a +# compile-fail test of the same source, _refused, where the message test +# is not built (gcc and MSVC natively, and Emscripten), so that every compiler +# sees the build stop. + +build-project forgotten_header ; +build-project refused_size ; diff --git a/test/messages/forgotten_header/Jamfile b/test/messages/forgotten_header/Jamfile new file mode 100644 index 0000000..ab3eddf --- /dev/null +++ b/test/messages/forgotten_header/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the undeclared name is the compile's only error, so a regression that +# puts another error before or after it fails the test. +webcpp.compile-diagnostic forgotten_header : forgotten_header.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail forgotten_header_refused : forgotten_header.cpp + : clang:no : native emscripten ; diff --git a/test/messages/forgotten_header/forgotten_header.cpp b/test/messages/forgotten_header/forgotten_header.cpp new file mode 100644 index 0000000..4113e91 --- /dev/null +++ b/test/messages/forgotten_header/forgotten_header.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a format without including its header stops at the name: the core +// declares the namespace of the formats and no format in it. + +#include + +#include +#include + +int main() { + namespace codecs = webcpp::codecs; + // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the + // whole text stays on one line. + // clang-format off + // expected-error@+2 {{no member named 'base64' in namespace 'webcpp::codecs::formats'}} + // clang-format on + static_cast(codecs::encode(codecs::formats::base64, std::vector{})); + return 0; +} diff --git a/test/messages/refused_size/Jamfile b/test/messages/refused_size/Jamfile new file mode 100644 index 0000000..84f67df --- /dev/null +++ b/test/messages/refused_size/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_size : refused_size.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_size_refused : refused_size.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_size/refused_size.cpp b/test/messages/refused_size/refused_size.cpp new file mode 100644 index 0000000..d4462aa --- /dev/null +++ b/test/messages/refused_size/refused_size.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that asks the size of a type the format does not convert stops in the core's +// refusal, whose requirement names the type and the format's type (ruling R2). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + return static_cast(codecs::encoded_size(codecs::test::letters, 42)); +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp new file mode 100644 index 0000000..c55b574 --- /dev/null +++ b/test/noexcept_test.cpp @@ -0,0 +1,36 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Which forms are noexcept: every function that allocates nothing is, and a function that +// allocates is not, so that an allocator's exception propagates (owner decision 24). Later tasks +// add their rows, both ways. + +#include "support/letters.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +// The sizes and the buffer forms (Task 2). +static_assert(noexcept(codecs::encode(test::letters, std::span{}, + std::span{}))); +static_assert(noexcept(codecs::encode(test::letters, std::vector{}, + std::span{}))); +static_assert(noexcept(codecs::decode(test::letters, std::string_view{}, + std::span{}))); +static_assert(noexcept(codecs::encoded_size(test::letters, std::array{}))); +static_assert(noexcept(codecs::max_decoded_size(test::letters, std::string_view{}))); + +} // namespace diff --git a/test/sizes_test.cpp b/test/sizes_test.cpp new file mode 100644 index 0000000..6ea9b86 --- /dev/null +++ b/test/sizes_test.cpp @@ -0,0 +1,211 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The sizes and the buffer forms over letters: the exact size and the bound in constant +// expressions (D6); a buffer form writes what fits and nothing on an error, in B23's order +// (input_too_long, the data's errors with the lowest value first, then output_too_small); +// empty inputs (Review Focus 3); bounds saturate at SIZE_MAX and an input whose bound saturates +// is refused (Review Focus 2). + +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +constexpr std::size_t size_maximum = SIZE_MAX; + +// The exact size and the bound, in constant expressions. +static_assert(codecs::encoded_size(test::letters, std::array{}) == 6); +static_assert(codecs::max_decoded_size(test::letters, std::string_view{"abcd"}) == 2); +static_assert(codecs::max_decoded_size(test::letters, "abcde") == 2); +static_assert(codecs::encoded_size(test::letters, std::array{}) == 0); + +// Saturating arithmetic. +static_assert(codecs::detail::saturating_multiply(size_maximum / 2, 3) == size_maximum); +static_assert(codecs::detail::saturating_multiply(size_maximum / 2, 2) == size_maximum - 1); +static_assert(codecs::detail::saturating_multiply(0, size_maximum) == 0); +static_assert(codecs::detail::saturating_multiply(size_maximum, 0) == 0); +static_assert(codecs::detail::saturating_multiply(size_maximum, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(size_maximum, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(size_maximum - 1, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(3, 4) == 7); + +// A bound that saturates means "does not fit", and the input is refused before it is read. +static_assert(codecs::codec::max_encoded_size(size_maximum / 2 + 1) == + size_maximum); +static_assert(codecs::detail::input_size_fault(test::letters, size_maximum / 2 + 1) == + codecs::error::input_too_long); +static_assert(!codecs::detail::input_size_fault(test::letters, size_maximum / 4).has_value()); +static_assert(!codecs::detail::input_size_fault(test::letters, 0).has_value()); +// letters' decoded bound never saturates: no text is too long to decode. +static_assert(!codecs::detail::text_size_fault(test::letters, size_maximum).has_value()); + +/** Bytes as a std::string_view, to compare. */ +std::string_view as_text(std::span viewed) { + return {reinterpret_cast(viewed.data()), viewed.size()}; +} + +/** Two bytes encode to four letters and decode back. */ +void round_trip() { + std::array const input{0x01, 0xff}; + std::array output{}; + output.fill('#'); + auto const written = codecs::encode(test::letters, input, output); + if (!BOOST_TEST(written.has_value())) { + return; + } + BOOST_TEST_EQ(*written, 4U); + BOOST_TEST_EQ((std::string_view{output.data(), output.size()}), "abpp####"); + std::array decoded{}; + decoded.fill(0x23); + auto const read = codecs::decode(test::letters, std::string_view{output.data(), *written}, + std::span{decoded}); + if (!BOOST_TEST(read.has_value())) { + return; + } + BOOST_TEST_EQ(*read, 2U); + BOOST_TEST_EQ(decoded[0], 0x01U); + BOOST_TEST_EQ(decoded[1], 0xffU); + BOOST_TEST_EQ(decoded[2], 0x23U); + // An exact output is enough. + std::array exact{}; + auto const exactly = codecs::encode(test::letters, input, exact); + BOOST_TEST(exactly.has_value() && *exactly == 4U); + BOOST_TEST_EQ((std::string_view{exact.data(), exact.size()}), "abpp"); +} + +/** Every kind of byte input encodes, a string literal as its characters without the zero (B5). */ +void each_byte_input() { + std::array output{}; + auto const from_literal = codecs::encode(test::letters, "A", output); + BOOST_TEST(from_literal.has_value() && *from_literal == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "eb"); + std::vector const heap_input{0x10}; + auto const from_vector = codecs::encode(test::letters, heap_input, output); + BOOST_TEST(from_vector.has_value() && *from_vector == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "ba"); + std::array const raw_input{std::byte{0x2f}}; + auto const from_bytes = codecs::encode(test::letters, raw_input, output); + BOOST_TEST(from_bytes.has_value() && *from_bytes == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "cp"); + std::string const text_input{"ab"}; + std::array decoded{}; + auto const from_string = codecs::decode(test::letters, text_input, decoded); + BOOST_TEST(from_string.has_value() && *from_string == 1U); + BOOST_TEST_EQ(decoded[0], 0x01U); +} + +/** 32 bytes need 64 letters: 63 are refused, and the buffer is unchanged. */ +void short_output() { + std::array input{}; + input.fill(0x5a); + std::array output{}; + output.fill('#'); + auto const written = codecs::encode(test::letters, input, output); + BOOST_TEST(!written.has_value()); + BOOST_TEST(written.error() == codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(output, [](char held) { return held == '#'; })); + // A decode into too few bytes, after the text was found valid. + std::array decoded{0x23}; + auto const read = codecs::decode(test::letters, std::string_view{"abab"}, decoded); + BOOST_TEST(!read.has_value()); + BOOST_TEST(read.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(decoded[0], 0x23U); +} + +/** A text with several faults reports the lowest value, and nothing is written. */ +void refused_text() { + std::array decoded{}; + decoded.fill(0x23); + // Both an odd length and a character past 'p': invalid_character, the lower value. + auto const both = codecs::decode(test::letters, std::string_view{"abq"}, decoded); + BOOST_TEST(!both.has_value()); + BOOST_TEST(both.error() == codecs::error::invalid_character); + // An odd length alone. + auto const odd = codecs::decode(test::letters, std::string_view{"abc"}, decoded); + BOOST_TEST(!odd.has_value()); + BOOST_TEST(odd.error() == codecs::error::invalid_length); + // A data error wins over a short output. + std::array no_room{}; + auto const bad_and_short = codecs::decode(test::letters, std::string_view{"zz"}, no_room); + BOOST_TEST(!bad_and_short.has_value()); + BOOST_TEST(bad_and_short.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(as_text(decoded), "####"); + // Each byte value as a character, with char signed: only 'a' to 'p' decode. + for (unsigned value = 0; value < 256; ++value) { + std::array const pair{static_cast(value), 'a'}; + auto const verdict = + codecs::decode(test::letters, std::string_view{pair.data(), pair.size()}, decoded); + bool const in_alphabet = value >= 'a' && value <= 'p'; + BOOST_TEST_EQ(verdict.has_value(), in_alphabet); + if (!in_alphabet) { + BOOST_TEST(verdict.error() == codecs::error::invalid_character); + } + } + BOOST_TEST_EQ(as_text(std::span{decoded}.subspan(2)), "##"); +} + +/** Empty inputs give 0 and write nothing (Review Focus 3). */ +void empty_input() { + std::array output{'#', '#'}; + auto const written = + codecs::encode(test::letters, std::span{}, std::span{output}); + BOOST_TEST(written.has_value() && *written == 0U); + BOOST_TEST_EQ((std::string_view{output.data(), output.size()}), "##"); + auto const into_nothing = + codecs::encode(test::letters, std::span{}, std::span{}); + BOOST_TEST(into_nothing.has_value() && *into_nothing == 0U); + std::array decoded{0x23}; + auto const read = codecs::decode(test::letters, std::string_view{}, decoded); + BOOST_TEST(read.has_value() && *read == 0U); + BOOST_TEST_EQ(decoded[0], 0x23U); + auto const from_empty_literal = codecs::decode(test::letters, "", std::span{}); + BOOST_TEST(from_empty_literal.has_value() && *from_empty_literal == 0U); + BOOST_TEST_EQ(codecs::encoded_size(test::letters, std::vector{}), 0U); + BOOST_TEST_EQ(codecs::max_decoded_size(test::letters, std::string{}), 0U); +} + +/** A text decoded into its own storage (Review Focus 4). */ +void in_place() { + std::array buffer{'a', 'b', 'p', 'p', 'h', 'h'}; + auto const read = + codecs::decode(test::letters, std::string_view{buffer.data(), buffer.size()}, + std::span{reinterpret_cast(buffer.data()), 3}); + if (!BOOST_TEST(read.has_value())) { + return; + } + BOOST_TEST_EQ(*read, 3U); + BOOST_TEST_EQ(static_cast(buffer[0]), 0x01U); + BOOST_TEST_EQ(static_cast(buffer[1]), 0xffU); + BOOST_TEST_EQ(static_cast(buffer[2]), 0x77U); +} + +} // namespace + +int main() { + round_trip(); + each_byte_input(); + short_output(); + refused_text(); + empty_input(); + in_place(); + return boost::report_errors(); +} diff --git a/test/support/counting.hpp b/test/support/counting.hpp new file mode 100644 index 0000000..6dfa2be --- /dev/null +++ b/test/support/counting.hpp @@ -0,0 +1,316 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Copied from webcpp::secure's test/support/counting.hpp at 951401a, with its namespace +// webcpp::secure::test renamed webcpp::codecs::test and its include guard renamed; nothing else +// differs, and the references below (spec section 8.5, N1) are secure's. codecs keeps its own +// test support, as secure does, until webcpp::core holds it (the design's O5). +// +// Counts every allocation of the program that includes this header once (spec section 8.5): +// every form of the global operator new (plain, array, aligned, nothrow, aligned nothrow), and +// the C library's malloc, calloc, realloc, aligned_alloc and posix_memalign, where a program +// can see them: glibc's replaced and forwarded to its __libc_* functions, Emscripten's replaced +// and forwarded to its emscripten_builtin_* (its dlmalloc defines them weak), macOS's through +// malloc_logger, the hook libsystem_malloc calls on every allocation. The glibc functions +// memalign, valloc, pvalloc and reallocarray are not replaced and so not counted. WASI's +// wasi-libc defines malloc and its __libc_malloc in one object (dlmalloc.c.obj, measured with +// nm), so a program cannot replace one and keep the other, and MSVC's C runtime has no hook: +// there the C library's allocations are not counted, and c_allocations_counted says so, which +// the tests print. +// A block of operator new is counted twice where the C library is counted (once by new, once +// by the malloc it calls): every test compares a count before and after a window, so this +// changes no verdict. The replaced throwing operator new does not run the new_handler loop: a +// failed allocation throws std::bad_alloc (or aborts without exceptions) at once. +// Nothing here reads a thread_local: on macOS the first read of one on a thread allocates +// through dyld (_tlv_get_addr), inside malloc_logger, which recursed until the stack ended +// (N1: measured with a malloc_logger that read a thread_local, which crashed before main). +// On macOS the hook is installed at static initialisation, relies on the private malloc_logger +// symbol of libsystem_malloc, and overwrites any hook already there (MallocStackLogging's, a +// sanitizer's). + +#ifndef WEBCPP_TEST_CODECS_SUPPORT_COUNTING_HPP +#define WEBCPP_TEST_CODECS_SUPPORT_COUNTING_HPP + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef __APPLE__ +#include +#elif defined(__EMSCRIPTEN__) +#include +#endif + +namespace webcpp::codecs::test { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the replaced new's count +inline std::atomic counted_new{0}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the C library's count +inline std::atomic counted_c{0}; +static_assert(std::atomic::is_always_lock_free, + "the counters are called from inside the allocator and must not allocate or lock"); + +/** Every allocation counted so far: operator new's and the C library's. */ +inline std::size_t allocations() { + return counted_new.load() + counted_c.load(); +} + +/** Whether this target counts the C library's allocations too. */ +inline constexpr bool c_allocations_counted = +#if defined(__GLIBC__) || defined(__EMSCRIPTEN__) || defined(__APPLE__) + true; +#else + false; +#endif + +inline void count_c() noexcept { + ++counted_c; +} + +/** + * Allocates for an operator new form: plain forms use malloc, aligned forms the aligned + * allocator of the platform (on Windows always _aligned_malloc, so that _aligned_free matches). + */ +inline void* new_block(std::size_t size, std::size_t alignment, bool aligned) { + ++counted_new; + std::size_t const bytes = size == 0 ? 1 : size; + if (!aligned) { + return std::malloc(bytes); + } +#ifdef _WIN32 + return _aligned_malloc(bytes, alignment); +#else + alignment = std::max(alignment, sizeof(void*)); // posix_memalign's and macOS's minimum + std::size_t const padded = bytes + alignment - 1; + if (padded < bytes) { + return nullptr; // the rounding overflows: a failure, never a small block + } + return std::aligned_alloc(alignment, padded / alignment * alignment); +#endif +} + +} // namespace webcpp::codecs::test + +[[noreturn]] inline void webcpp_test_out_of_memory() { +#ifdef __cpp_exceptions + throw std::bad_alloc(); // the replaced operator's contract +#else + std::abort(); +#endif +} + +// The replaceable global allocation functions cannot be inline: they are defined here, in the +// one translation unit of a program that includes this header, under the standard's names. None is +// ever inlined: GCC 15 at -O3, seeing the malloc or the free inside one, pairs it with the other's +// call (a std::allocator's operator new, an exception's) and warns of a mismatch +// (-Wmismatched-new-delete), though both replaced forms use the C library. +// NOLINTBEGIN(misc-definitions-in-headers,readability-inconsistent-declaration-parameter-name) +BOOST_NOINLINE void* operator new(std::size_t size) { + if (void* const p = webcpp::codecs::test::new_block(size, alignof(std::max_align_t), false)) { + return p; + } + webcpp_test_out_of_memory(); +} + +BOOST_NOINLINE void* operator new[](std::size_t size) { + return operator new(size); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment) { + if (void* const p = + webcpp::codecs::test::new_block(size, static_cast(alignment), true)) { + return p; + } + webcpp_test_out_of_memory(); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment) { + return operator new(size, alignment); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::nothrow_t const& /*unused*/) noexcept { + return webcpp::codecs::test::new_block(size, alignof(std::max_align_t), false); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::nothrow_t const& /*unused*/) noexcept { + return webcpp::codecs::test::new_block(size, alignof(std::max_align_t), false); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { + return webcpp::codecs::test::new_block(size, static_cast(alignment), true); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { + return webcpp::codecs::test::new_block(size, static_cast(alignment), true); +} + +BOOST_NOINLINE void operator delete(void* p) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} +#ifdef _WIN32 +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + _aligned_free(p); +} +#else +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} +#endif +// NOLINTEND(misc-definitions-in-headers,readability-inconsistent-declaration-parameter-name) + +#if defined(__GLIBC__) || defined(__EMSCRIPTEN__) +#ifdef __GLIBC__ +extern "C" { +void* __libc_malloc(std::size_t); +void* __libc_calloc(std::size_t, std::size_t); +void* __libc_realloc(void*, std::size_t); +void* __libc_memalign(std::size_t, std::size_t); +void __libc_free(void*); +} +#define WEBCPP_TEST_C(name) __libc_##name +// glibc declares these with __THROW, noexcept in C++11 and later: a replacement must match. +#define WEBCPP_TEST_C_NOEXCEPT noexcept +#else +#define WEBCPP_TEST_C(name) emscripten_builtin_##name +// Emscripten's musl declares them without an exception specification. +#define WEBCPP_TEST_C_NOEXCEPT +#endif +// The C library's allocation functions, replaced for this program alone; cert-dcl58-cpp takes +// a replacement of what declares for a change to namespace std. +// misc-definitions-in-headers: a replacement is a definition, and each test program includes +// this header in one translation unit. +// NOLINTBEGIN(misc-definitions-in-headers) +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +extern "C" { +void* malloc(std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::codecs::test::count_c(); + return WEBCPP_TEST_C(malloc)(size); +} + +void* calloc(std::size_t count, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::codecs::test::count_c(); + return WEBCPP_TEST_C(calloc)(count, size); +} + +void* realloc(void* p, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::codecs::test::count_c(); + return WEBCPP_TEST_C(realloc)(p, size); +} + +void* aligned_alloc(std::size_t alignment, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::codecs::test::count_c(); + return WEBCPP_TEST_C(memalign)(alignment, size); +} + +int posix_memalign(void** p, std::size_t alignment, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::codecs::test::count_c(); + *p = WEBCPP_TEST_C(memalign)(alignment, size); + return *p == nullptr ? 12 /* ENOMEM */ : 0; +} + +void free(void* p) WEBCPP_TEST_C_NOEXCEPT { + WEBCPP_TEST_C(free)(p); +} +} +// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +// NOLINTEND(misc-definitions-in-headers) +#elif defined(__APPLE__) +// libsystem_malloc's hook, called on every allocation and release of the process. +using webcpp_test_malloc_logger = void(std::uint32_t, std::uintptr_t, std::uintptr_t, + std::uintptr_t, std::uintptr_t, std::uint32_t); +extern "C" webcpp_test_malloc_logger* malloc_logger; + +inline void webcpp_test_count_c_allocation(std::uint32_t type, std::uintptr_t /*unused*/, + std::uintptr_t /*unused*/, std::uintptr_t /*unused*/, + std::uintptr_t /*unused*/, std::uint32_t /*unused*/) { + constexpr std::uint32_t allocate = 2; // MALLOC_LOG_TYPE_ALLOCATE + if ((type & allocate) != 0) { + webcpp::codecs::test::count_c(); + } +} + +namespace webcpp::codecs::test { +/** Installs the hook at static initialisation, before main, as this inline variable is defined. */ +inline bool const logger_installed = (malloc_logger = &webcpp_test_count_c_allocation, true); +} // namespace webcpp::codecs::test +#endif + +#endif diff --git a/test/support/letters.hpp b/test/support/letters.hpp new file mode 100644 index 0000000..92253bf --- /dev/null +++ b/test/support/letters.hpp @@ -0,0 +1,122 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// letters, a format of the tests' own: every byte is written as two letters `a` to `p`, its high +// half then its low half, so that the contract is proven before any real format exists. Its codec +// is the six functions of D3 and nothing else; it is not constant time. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The type of the format letters. */ +struct letters_t { + /** The format's name. */ + static constexpr std::string_view name = "letters"; +}; + +/** The format letters: byte `b` as `'a' + (b >> 4)` then `'a' + (b & 15)`. */ +inline constexpr letters_t letters{}; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The codec of letters. */ +template <> +struct codec { + /** letters branches on its data. */ + static constexpr bool constant_time = false; + + /** Two letters a byte, saturated at `SIZE_MAX`. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return detail::saturating_multiply(input_size, 2); + } + + /** One byte every two letters. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return text_size / 2; + } + + /** Two letters a byte. */ + static constexpr std::size_t encoded_size(test::letters_t const& /*format*/, + std::span input_bytes) noexcept { + return max_encoded_size(input_bytes.size()); + } + + /** + The bytes of a text: `invalid_character` for a character outside `a` to `p`, else + `invalid_length` for an odd length (the lowest value wins, B23). + */ + static result decoded_size(test::letters_t const& /*format*/, + std::string_view text_characters) noexcept { + for (char const text_character : text_characters) { + // Read as an unsigned byte first: a signed char from 0x80 up is negative. + auto const character_value = static_cast(text_character); + if (character_value < static_cast('a') || + character_value > static_cast('p')) { + return error::invalid_character; + } + } + if (text_characters.size() % 2 != 0) { + return error::invalid_length; + } + return text_characters.size() / 2; + } + + /** Writes two letters a byte into `output_characters`, which must hold them. */ + static result encode(test::letters_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { + std::size_t const written_size = encoded_size(format_value, input_bytes); + if (output_characters.size() < written_size) { + return error::output_too_small; + } + std::size_t character_index = 0; + for (std::uint8_t const input_byte : input_bytes) { + output_characters[character_index] = static_cast('a' + (input_byte >> 4U)); + output_characters[character_index + 1] = static_cast('a' + (input_byte & 15U)); + character_index += 2; + } + return written_size; + } + + /** + Writes the bytes of a valid text into `output_bytes`, which must hold them; refuses the text + as `decoded_size` does, writing nothing. The output may be the text's own storage: byte `i` + is written after letters `2i` and `2i + 1` are read. + */ + static result decode(test::letters_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { + result const decoded_count = decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count; + } + if (output_bytes.size() < *decoded_count) { + return error::output_too_small; + } + for (std::size_t byte_index = 0; byte_index < *decoded_count; ++byte_index) { + auto const high_half = static_cast(text_characters[2 * byte_index] - 'a'); + auto const low_half = + static_cast(text_characters[(2 * byte_index) + 1] - 'a'); + output_bytes[byte_index] = static_cast((high_half << 4U) | low_half); + } + return *decoded_count; + } +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP From 7191614a2c85edde1ae56c24b03617fcb6b0e8a4 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 08:22:23 -0300 Subject: [PATCH 006/157] codecs: the format contract lint fix --- include/webcpp/codecs/detail/core/contract.hpp | 11 +++++++---- include/webcpp/codecs/detail/core/sizes.hpp | 6 ++++-- test/Jamfile | 6 +++--- test/contract_test.cpp | 3 +++ test/sizes_test.cpp | 4 ++-- test/support/letters.hpp | 8 +++++--- 6 files changed, 24 insertions(+), 14 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index e6c1adf..e7be6ae 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -163,6 +163,7 @@ struct static_input_size> : std::integral_constant requires(byte_element && !std::same_as, char>) +// NOLINTNEXTLINE(modernize-avoid-c-arrays): an array of bytes is one of the inputs (D7) struct static_input_size : std::integral_constant {}; /** A span of bytes of a static extent: its extent. */ @@ -310,8 +311,9 @@ template [[nodiscard]] constexpr std::string_view text_view(Text const& text) noexcept { if constexpr (std::is_array_v) { auto const characters_end = std::ranges::find(text, '\0'); - return {std::ranges::data(text), static_cast(std::ranges::distance( - std::ranges::begin(text), characters_end))}; + auto const character_count = static_cast( + std::ranges::distance(std::ranges::begin(text), characters_end)); + return {std::ranges::data(text), character_count}; } else { return text; } @@ -334,8 +336,9 @@ template return {std::ranges::data(input), std::ranges::size(input)}; } else { // A std::byte or a char is read through an unsigned char, which may alias any object. - return {reinterpret_cast(std::ranges::data(input)), - std::ranges::size(input)}; + auto const* const first_byte = + reinterpret_cast(std::ranges::data(input)); + return {first_byte, std::ranges::size(input)}; } } diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index fdee58f..d0ba71d 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -196,10 +196,12 @@ template if (!byte_count) { return byte_count; } - if (output.size() < *byte_count) { + // Read unchecked: the error was returned above. + std::size_t const bytes_size = byte_count.unsafe_value(); + if (output.size() < bytes_size) { return error::output_too_small; } - return codec::decode(format, text_characters, output.first(*byte_count)); + return codec::decode(format, text_characters, output.first(bytes_size)); } else { detail::refuse, F>(); return std::size_t{0}; diff --git a/test/Jamfile b/test/Jamfile index 7dcb800..a2756a5 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -42,13 +42,13 @@ webcpp.compile config_developer_defined : config_test.cpp # The errors: eight fixed values, the category webcpp.codecs, their messages. codecs-run error : error_test.cpp ; -# The concepts: formats, byte and text inputs, static sizes, the pairs that convert. +# The concepts: formats, inputs, static sizes, the pairs that convert. codecs-run contract : contract_test.cpp ; -# The sizes and the buffer forms: B23's order, nothing written on an error, bounds. +# The sizes and the buffer forms: B23's order, nothing written on an error. codecs-run sizes : sizes_test.cpp ; # The forms that allocate nothing leave a counting operator new where it was. codecs-run allocation : allocation_test.cpp ; -# Every form that allocates nothing is noexcept, and every form that allocates is not. +# Every form that allocates nothing is noexcept, and one that allocates is not. codecs-compile noexcept : noexcept_test.cpp ; # The refusals and a forgotten format header stop the build with their messages. diff --git a/test/contract_test.cpp b/test/contract_test.cpp index f408db1..2b36c8d 100644 --- a/test/contract_test.cpp +++ b/test/contract_test.cpp @@ -58,6 +58,7 @@ static_assert(codecs::format); // The sizes known at compile time: a static extent, an array of bytes, secure's secret. static_assert(codecs::static_input_size_v> == 32); +// NOLINTNEXTLINE(modernize-avoid-c-arrays): the kind of input under test static_assert(codecs::static_input_size_v == 32); static_assert(codecs::static_input_size_v> == 32); static_assert(codecs::static_input_size_v> == 32); @@ -71,6 +72,7 @@ static_assert(codecs::static_input_size_v> == std: // Byte inputs and text inputs (D7). static_assert(codecs::detail::byte_input>); static_assert(codecs::detail::byte_input>); +// NOLINTNEXTLINE(modernize-avoid-c-arrays): the kind of input under test static_assert(codecs::detail::byte_input); static_assert(codecs::detail::byte_input); static_assert(codecs::detail::byte_input>); @@ -78,6 +80,7 @@ static_assert(!codecs::detail::byte_input); static_assert(!codecs::detail::byte_input>); static_assert(codecs::detail::text_input); static_assert(codecs::detail::text_input); +// NOLINTNEXTLINE(modernize-avoid-c-arrays): the kind of input under test static_assert(codecs::detail::text_input); static_assert(!codecs::detail::text_input>); diff --git a/test/sizes_test.cpp b/test/sizes_test.cpp index 6ea9b86..4054d0b 100644 --- a/test/sizes_test.cpp +++ b/test/sizes_test.cpp @@ -49,9 +49,9 @@ static_assert(codecs::detail::saturating_add(size_maximum - 1, 1) == size_maximu static_assert(codecs::detail::saturating_add(3, 4) == 7); // A bound that saturates means "does not fit", and the input is refused before it is read. -static_assert(codecs::codec::max_encoded_size(size_maximum / 2 + 1) == +static_assert(codecs::codec::max_encoded_size((size_maximum / 2) + 1) == size_maximum); -static_assert(codecs::detail::input_size_fault(test::letters, size_maximum / 2 + 1) == +static_assert(codecs::detail::input_size_fault(test::letters, (size_maximum / 2) + 1) == codecs::error::input_too_long); static_assert(!codecs::detail::input_size_fault(test::letters, size_maximum / 4).has_value()); static_assert(!codecs::detail::input_size_fault(test::letters, 0).has_value()); diff --git a/test/support/letters.hpp b/test/support/letters.hpp index 92253bf..a3df9a9 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -104,16 +104,18 @@ struct codec { if (!decoded_count) { return decoded_count; } - if (output_bytes.size() < *decoded_count) { + // Read unchecked: the error was returned above. + std::size_t const byte_count = decoded_count.unsafe_value(); + if (output_bytes.size() < byte_count) { return error::output_too_small; } - for (std::size_t byte_index = 0; byte_index < *decoded_count; ++byte_index) { + for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) { auto const high_half = static_cast(text_characters[2 * byte_index] - 'a'); auto const low_half = static_cast(text_characters[(2 * byte_index) + 1] - 'a'); output_bytes[byte_index] = static_cast((high_half << 4U) | low_half); } - return *decoded_count; + return byte_count; } }; From b33bb523cffdee4eb511d9ce734ae5f909971c9e Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 08:51:09 -0300 Subject: [PATCH 007/157] codecs: the format contract's review fixes: text inputs of any char range, two-word names, the saturation refusal tested, a stable refusal type --- .../webcpp/codecs/detail/core/contract.hpp | 63 +++++++---- include/webcpp/codecs/detail/core/sizes.hpp | 102 +++++++++--------- test/allocation_test.cpp | 26 +++-- test/contract_test.cpp | 13 +++ test/messages/Jamfile | 1 + test/messages/refused_decode/Jamfile | 16 +++ .../refused_decode/refused_decode.cpp | 33 ++++++ test/sizes_test.cpp | 44 ++++++++ test/support/saturating.hpp | 94 ++++++++++++++++ 9 files changed, 316 insertions(+), 76 deletions(-) create mode 100644 test/messages/refused_decode/Jamfile create mode 100644 test/messages/refused_decode/refused_decode.cpp create mode 100644 test/support/saturating.hpp diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index e7be6ae..77bda02 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -83,11 +83,13 @@ struct codec; static constexpr codecs::output_kind output = codecs::output_kind::bytes; static constexpr bool secret = true; // optional; false when absent static constexpr std::size_t max_encoded_size = 138; // optional; a fixed result when present - static std::size_t encoded_size(Format const& format, Value const& value) noexcept; - static result encode(Format const& format, Value const& value, + static std::size_t encoded_size(crypto::formats::pkcs8_t const& format, + crypto::curves::p256::keypair const& value) noexcept; + static result encode(crypto::formats::pkcs8_t const& format, + crypto::curves::p256::keypair const& value, std::span output) noexcept; - static result decode(Format const& format, - std::span input) noexcept; + static result decode( + crypto::formats::pkcs8_t const& format, std::span input) noexcept; }; @endcode @@ -147,9 +149,19 @@ concept static_byte_view = requires { typename std::integral_constant concept byte_input = byte_range> || static_byte_view>; -/** A text input: anything a `std::string_view` is made from. */ +/** A contiguous sized range of `char`. */ template -concept text_input = std::convertible_to; +concept char_range = + std::ranges::contiguous_range && std::ranges::sized_range && + std::same_as>, char>; + +/** + A text input: anything a `std::string_view` is made from, a contiguous sized range of `char` + included (D7). +*/ +template +concept text_input = + std::convertible_to || char_range>; /** The size of an input known at compile time, else `std::dynamic_extent`. */ template @@ -291,6 +303,12 @@ namespace detail { template inline constexpr bool converts = false; +/** + The bytes a decode writes, as a refusal names them: a type that prints alike on every target, + where a span would print its extent and a vector its allocator. +*/ +struct decoded_bytes {}; + /** Stops the build: the format `Format` does not convert the type `Value` in the direction of the operation that calls this, which has found that the pair is not `encodable` or not `decodable`. @@ -305,17 +323,20 @@ constexpr void refuse() noexcept { /** The characters of a text input; an array of `char` is read up to its first zero and never past - its end, as a string literal is read as a `std::string_view` (B5). + its end, as a string literal is read as a `std::string_view` (B5), and another range of `char` + whole. */ template -[[nodiscard]] constexpr std::string_view text_view(Text const& text) noexcept { +[[nodiscard]] constexpr std::string_view text_view(Text const& text_value) noexcept { if constexpr (std::is_array_v) { - auto const characters_end = std::ranges::find(text, '\0'); + auto const characters_end = std::ranges::find(text_value, '\0'); auto const character_count = static_cast( - std::ranges::distance(std::ranges::begin(text), characters_end)); - return {std::ranges::data(text), character_count}; + std::ranges::distance(std::ranges::begin(text_value), characters_end)); + return {std::ranges::data(text_value), character_count}; + } else if constexpr (std::convertible_to) { + return text_value; } else { - return text; + return {std::ranges::data(text_value), std::ranges::size(text_value)}; } } @@ -324,21 +345,23 @@ template its `std::string_view`. */ template -[[nodiscard]] constexpr std::span input_bytes(Input const& input) noexcept { +[[nodiscard]] constexpr std::span input_bytes( + Input const& input_value) noexcept { if constexpr (text_input) { - std::string_view const characters = text_view(input); + std::string_view const input_characters = text_view(input_value); // A char is read through an unsigned char, which may alias any object. - return {reinterpret_cast(characters.data()), characters.size()}; + return {reinterpret_cast(input_characters.data()), + input_characters.size()}; } else if constexpr (static_byte_view) { - return std::span{input}; + return std::span{input_value}; } else if constexpr (std::same_as>, std::uint8_t>) { - return {std::ranges::data(input), std::ranges::size(input)}; + return {std::ranges::data(input_value), std::ranges::size(input_value)}; } else { - // A std::byte or a char is read through an unsigned char, which may alias any object. + // A std::byte is read through an unsigned char, which may alias any object. auto const* const first_byte = - reinterpret_cast(std::ranges::data(input)); - return {first_byte, std::ranges::size(input)}; + reinterpret_cast(std::ranges::data(input_value)); + return {first_byte, std::ranges::size(input_value)}; } } diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index d0ba71d..edecf28 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -74,8 +74,8 @@ template } // namespace detail /** - The exact size of what `encode` writes for `input` in `format`: characters, or bytes for a value - codec of bytes. + The exact size of what `encode` writes for `input_value` in `format_value`: characters, or bytes + for a value codec of bytes. It is a constant expression where the format and the input are, and the input's bytes are `std::uint8_t` or `unsigned char` (or the input is a value of a value codec whose `encoded_size` @@ -86,16 +86,17 @@ template @tparam F The format's type. @tparam Input The input's type: a byte input, or a value of a value codec. - @param format The format. - @param input The bytes, or the value, to encode. + @param format_value The format. + @param input_value The bytes, or the value, to encode. @return The size, `SIZE_MAX` when it does not fit in `std::size_t`. */ template -[[nodiscard]] constexpr std::size_t encoded_size(F const& format, Input const& input) noexcept { +[[nodiscard]] constexpr std::size_t encoded_size(F const& format_value, + Input const& input_value) noexcept { if constexpr (detail::value_encodable) { - return value_codec::encoded_size(format, input); + return value_codec::encoded_size(format_value, input_value); } else if constexpr (detail::byte_input && detail::has_codec) { - return codec::encoded_size(format, detail::input_bytes(input)); + return codec::encoded_size(format_value, detail::input_bytes(input_value)); } else { detail::refuse(); return 0; @@ -103,35 +104,38 @@ template } /** - A bound on the bytes `decode` writes for `text` in `format`, from the text's size alone. + A bound on the bytes `decode` writes for `text_value` in `format_value`, from the text's size + alone. It is a constant expression where the format and the text are. A format with no `codec` - specialization stops the build with a message that the format does not convert bytes. + specialization stops the build with a message that the format does not convert bytes (named + `webcpp::codecs::detail::decoded_bytes`). @tparam F The format's type. - @tparam Text The text's type: anything a `std::string_view` is made from. - @param format The format. - @param text The text; a string literal is read up to its terminating zero. + @tparam Text The text's type: anything a `std::string_view` is made from, or a contiguous + sized range of `char`. + @param format_value The format. + @param text_value The text; a string literal is read up to its terminating zero. @return The bound, `SIZE_MAX` when it does not fit in `std::size_t`. */ template -[[nodiscard]] constexpr std::size_t max_decoded_size([[maybe_unused]] F const& format, - Text const& text) noexcept { +[[nodiscard]] constexpr std::size_t max_decoded_size([[maybe_unused]] F const& format_value, + Text const& text_value) noexcept { if constexpr (detail::has_codec) { - return codec::max_decoded_size(detail::text_view(text).size()); + return codec::max_decoded_size(detail::text_view(text_value).size()); } else { - detail::refuse, F>(); + detail::refuse(); return 0; } } /** - Encodes `input` in `format` into the caller's buffer, allocating nothing. + Encodes `input_value` in `format_value` into the caller's buffer, allocating nothing. The checks come first, and on every error nothing is written: an input whose encoding does not - fit in `std::size_t` is @ref error::input_too_long, before it is read; an `output` shorter than - the exact size is @ref error::output_too_small. The text is then written at the start of - `output`, whose other characters are unchanged. + fit in `std::size_t` is @ref error::input_too_long, before it is read; an `output_buffer` shorter + than the exact size is @ref error::output_too_small. The text is then written at the start of + `output_buffer`, whose other characters are unchanged. A format with no `codec` specialization stops the build with a message that the format does not convert this type. @@ -140,24 +144,24 @@ template @tparam Input The input's type: a contiguous sized range of `std::uint8_t`, `unsigned char`, `char` or `std::byte` (a string literal is read without its terminating zero), or a type of a constant `size()` that converts to a span of that many bytes, as `secure::secret`. - @param format The format. - @param input The bytes to encode. - @param output The buffer the text is written to. + @param format_value The format. + @param input_value The bytes to encode. + @param output_buffer The buffer the text is written to. @return The number of characters written, or the error. */ template -[[nodiscard]] result encode(F const& format, Input const& input, - std::span output) noexcept { +[[nodiscard]] result encode(F const& format_value, Input const& input_value, + std::span output_buffer) noexcept { if constexpr (detail::has_codec) { - std::span const input_view = detail::input_bytes(input); - if (auto const size_fault = detail::input_size_fault(format, input_view.size())) { + std::span const input_view = detail::input_bytes(input_value); + if (auto const size_fault = detail::input_size_fault(format_value, input_view.size())) { return *size_fault; } - std::size_t const text_size = codec::encoded_size(format, input_view); - if (output.size() < text_size) { + std::size_t const text_size = codec::encoded_size(format_value, input_view); + if (output_buffer.size() < text_size) { return error::output_too_small; } - return codec::encode(format, input_view, output.first(text_size)); + return codec::encode(format_value, input_view, output_buffer.first(text_size)); } else { detail::refuse(); return std::size_t{0}; @@ -165,45 +169,47 @@ template } /** - Decodes `text` in `format` into the caller's buffer, allocating nothing. + Decodes `text_value` in `format_value` into the caller's buffer, allocating nothing. The checks come first, and on every error nothing is written: a text whose bytes do not fit in `std::size_t` is @ref error::input_too_long, before it is read; then the whole text is checked, - and its data error with the lowest value of @ref error is returned; then an `output` shorter - than the exact size is @ref error::output_too_small. The bytes are then written at the start of - `output`, whose other bytes are unchanged. Where the format's page says so, `output` may be the - text's own storage. + and its data error with the lowest value of @ref error is returned; then an `output_buffer` + shorter than the exact size is @ref error::output_too_small. The bytes are then written at the + start of `output_buffer`, whose other bytes are unchanged. Where the format's page says so, + `output_buffer` may be the text's own storage. A format with no `codec` specialization stops the build with a message that the format does not - convert bytes. + convert bytes (named `webcpp::codecs::detail::decoded_bytes`). @tparam F The format's type. - @tparam Text The text's type: anything a `std::string_view` is made from. - @param format The format. - @param text The text to decode; a string literal is read up to its terminating zero. - @param output The buffer the bytes are written to. + @tparam Text The text's type: anything a `std::string_view` is made from, or a contiguous + sized range of `char`. + @param format_value The format. + @param text_value The text to decode; a string literal is read up to its terminating zero. + @param output_buffer The buffer the bytes are written to. @return The number of bytes written, or the error. */ template -[[nodiscard]] result decode(F const& format, Text const& text, - std::span output) noexcept { +[[nodiscard]] result decode(F const& format_value, Text const& text_value, + std::span output_buffer) noexcept { if constexpr (detail::has_codec) { - std::string_view const text_characters = detail::text_view(text); - if (auto const size_fault = detail::text_size_fault(format, text_characters.size())) { + std::string_view const text_characters = detail::text_view(text_value); + if (auto const size_fault = detail::text_size_fault(format_value, text_characters.size())) { return *size_fault; } - result const byte_count = codec::decoded_size(format, text_characters); + result const byte_count = + codec::decoded_size(format_value, text_characters); if (!byte_count) { return byte_count; } // Read unchecked: the error was returned above. std::size_t const bytes_size = byte_count.unsafe_value(); - if (output.size() < bytes_size) { + if (output_buffer.size() < bytes_size) { return error::output_too_small; } - return codec::decode(format, text_characters, output.first(bytes_size)); + return codec::decode(format_value, text_characters, output_buffer.first(bytes_size)); } else { - detail::refuse, F>(); + detail::refuse(); return std::size_t{0}; } } diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index c0e17e9..b4fb11c 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -13,6 +13,7 @@ #include "support/counting.hpp" #include "support/letters.hpp" +#include "support/saturating.hpp" #include @@ -31,7 +32,6 @@ namespace { namespace codecs = webcpp::codecs; -namespace counting = webcpp::codecs::test; namespace test = webcpp::codecs::test; constexpr std::size_t big = 64; @@ -40,11 +40,11 @@ constexpr std::align_val_t aligned{big}; /** Runs `body` and checks that it moved neither counter. */ template void expect_no_allocation(char const* what, Body body) { - std::size_t const new_before = counting::counted_new.load(); - std::size_t const c_before = counting::counted_c.load(); + std::size_t const new_before = test::counted_new.load(); + std::size_t const c_before = test::counted_c.load(); body(); - std::size_t const new_after = counting::counted_new.load(); - std::size_t const c_after = counting::counted_c.load(); + std::size_t const new_after = test::counted_new.load(); + std::size_t const c_after = test::counted_c.load(); if (new_after != new_before || c_after != c_before) { std::printf("allocated: %s\n", what); } @@ -55,9 +55,9 @@ void expect_no_allocation(char const* what, Body body) { /** Runs `body`, one allocation of operator new's form, and checks that the counter saw it. */ template void expect_counted(char const* form, Body body) { - std::size_t const before = counting::counted_new.load(); + std::size_t const before = test::counted_new.load(); body(); - std::size_t const counted = counting::counted_new.load() - before; + std::size_t const counted = test::counted_new.load() - before; if (counted != 1) { std::printf("not counted once: %s\n", form); } @@ -171,6 +171,16 @@ void check_buffer_forms() { .has_value(); }); BOOST_TEST(verdict); + std::array const long_input{}; + std::array long_text{}; + long_text.fill('a'); + expect_no_allocation("an input whose bound saturates", [&] { + sink = codecs::encoded_size(test::saturating, long_input); + sink = codecs::max_decoded_size(test::saturating, long_text); + verdict = codecs::encode(test::saturating, long_input, output).has_value() || + codecs::decode(test::saturating, long_text, decoded).has_value(); + }); + BOOST_TEST(!verdict); expect_no_allocation("input_size_fault", [&] { verdict = codecs::detail::input_size_fault(test::letters, SIZE_MAX).has_value(); }); @@ -181,7 +191,7 @@ void check_buffer_forms() { } // namespace int main() { - std::printf("c_allocations_counted=%d\n", counting::c_allocations_counted ? 1 : 0); + std::printf("c_allocations_counted=%d\n", test::c_allocations_counted ? 1 : 0); control_counts_every_form(); check_buffer_forms(); return boost::report_errors(); diff --git a/test/contract_test.cpp b/test/contract_test.cpp index 2b36c8d..8a1e64a 100644 --- a/test/contract_test.cpp +++ b/test/contract_test.cpp @@ -83,6 +83,13 @@ static_assert(codecs::detail::text_input); // NOLINTNEXTLINE(modernize-avoid-c-arrays): the kind of input under test static_assert(codecs::detail::text_input); static_assert(!codecs::detail::text_input>); +// A contiguous sized range of char is a text too (D7). +static_assert(codecs::detail::text_input>); +static_assert(codecs::detail::text_input>); +static_assert(codecs::detail::text_input>); +static_assert(codecs::detail::text_input const&>); +static_assert(!codecs::detail::text_input>); +static_assert(!codecs::detail::text_input>); // The pairs that encode and decode (D5). static_assert(codecs::encodable, test::letters_t>); @@ -134,6 +141,12 @@ void text_view_of_each_input() { BOOST_TEST_EQ(codecs::detail::text_view("abcd"), "abcd"); BOOST_TEST_EQ(codecs::detail::text_view(std::string{"ab"}), "ab"); BOOST_TEST_EQ(codecs::detail::text_view(std::string_view{"a\0b", 3}).size(), 3U); + // A range of char that is no array is read whole, a zero included. + std::vector const heap_text{'a', '\0', 'b'}; + BOOST_TEST_EQ(codecs::detail::text_view(heap_text), (std::string_view{"a\0b", 3})); + std::array const array_text{'c', 'd'}; + BOOST_TEST_EQ(codecs::detail::text_view(array_text), "cd"); + BOOST_TEST_EQ(codecs::detail::text_view(std::span{array_text}), "cd"); } } // namespace diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 310793e..8803d9e 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -13,3 +13,4 @@ build-project forgotten_header ; build-project refused_size ; +build-project refused_decode ; diff --git a/test/messages/refused_decode/Jamfile b/test/messages/refused_decode/Jamfile new file mode 100644 index 0000000..b7e8e1c --- /dev/null +++ b/test/messages/refused_decode/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_decode : refused_decode.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_decode_refused : refused_decode.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_decode/refused_decode.cpp b/test/messages/refused_decode/refused_decode.cpp new file mode 100644 index 0000000..c390af4 --- /dev/null +++ b/test/messages/refused_decode/refused_decode.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that decodes into a buffer with a format no header gave a codec stops in the core's +// refusal, whose requirement names the bytes as webcpp::codecs::detail::decoded_bytes, a type +// every target prints alike, and the format's type (ruling R2). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include + +#include +#include +#include + +/** A format no header specializes `codec` for. */ +struct unregistered_t { + static constexpr std::string_view name = "unregistered"; +}; + +int main() { + namespace codecs = webcpp::codecs; + auto const decoded = + codecs::decode(unregistered_t{}, std::string_view{"ab"}, std::span{}); + return decoded.has_value() ? 0 : 1; +} diff --git a/test/sizes_test.cpp b/test/sizes_test.cpp index 4054d0b..fe1ae46 100644 --- a/test/sizes_test.cpp +++ b/test/sizes_test.cpp @@ -11,6 +11,7 @@ // is refused (Review Focus 2). #include "support/letters.hpp" +#include "support/saturating.hpp" #include @@ -111,6 +112,12 @@ void each_byte_input() { auto const from_string = codecs::decode(test::letters, text_input, decoded); BOOST_TEST(from_string.has_value() && *from_string == 1U); BOOST_TEST_EQ(decoded[0], 0x01U); + // A range of char is a text, read whole, with no std::string_view around it. + std::array const array_text{'p', 'a'}; + auto const from_array = codecs::decode(test::letters, array_text, decoded); + BOOST_TEST(from_array.has_value() && *from_array == 1U); + BOOST_TEST_EQ(decoded[0], 0xf0U); + BOOST_TEST_EQ(codecs::max_decoded_size(test::letters, array_text), 1U); } /** 32 bytes need 64 letters: 63 are refused, and the buffer is unchanged. */ @@ -183,6 +190,42 @@ void empty_input() { BOOST_TEST_EQ(codecs::max_decoded_size(test::letters, std::string{}), 0U); } +/** + An input whose bound saturates is input_too_long in every form, before the codec runs, and the + output is untouched (Review Focus 2); one byte or character less reaches the codec, the control. +*/ +void saturated_bounds() { + constexpr std::size_t most_bytes = test::saturating_t::most_bytes; + constexpr std::size_t most_characters = test::saturating_t::most_characters; + std::array const long_input{}; + std::array output{}; + output.fill('#'); + BOOST_TEST_EQ(codecs::encoded_size(test::saturating, long_input), size_maximum); + auto const encoded = codecs::encode(test::saturating, long_input, output); + BOOST_TEST(!encoded.has_value()); + BOOST_TEST(encoded.error() == codecs::error::input_too_long); + BOOST_TEST(std::ranges::all_of(output, [](char held) { return held == '#'; })); + std::array const fitting_input{}; + auto const reached = codecs::encode(test::saturating, fitting_input, output); + BOOST_TEST(!reached.has_value()); + BOOST_TEST(reached.error() == codecs::error::checksum_mismatch); + BOOST_TEST_EQ(output[0], '!'); + + std::array long_text{}; + long_text.fill('a'); + std::array decoded{}; + decoded.fill(0x23); + BOOST_TEST_EQ(codecs::max_decoded_size(test::saturating, long_text), size_maximum); + auto const read = codecs::decode(test::saturating, long_text, decoded); + BOOST_TEST(!read.has_value()); + BOOST_TEST(read.error() == codecs::error::input_too_long); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t held) { return held == 0x23U; })); + auto const text_reached = codecs::decode( + test::saturating, std::string_view{long_text.data(), most_characters}, decoded); + BOOST_TEST(!text_reached.has_value()); + BOOST_TEST(text_reached.error() == codecs::error::checksum_mismatch); +} + /** A text decoded into its own storage (Review Focus 4). */ void in_place() { std::array buffer{'a', 'b', 'p', 'p', 'h', 'h'}; @@ -206,6 +249,7 @@ int main() { short_output(); refused_text(); empty_input(); + saturated_bounds(); in_place(); return boost::report_errors(); } diff --git a/test/support/saturating.hpp b/test/support/saturating.hpp new file mode 100644 index 0000000..498b036 --- /dev/null +++ b/test/support/saturating.hpp @@ -0,0 +1,94 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// saturating, a format of the tests' own whose bounds saturate at SIZE_MAX past a few bytes or +// characters, so that a test reaches the refusal of an input too long to fit (Review Focus 2) +// with a small input. Past the core's size checks every function of its codec reports +// checksum_mismatch and the encode and decode write `!`, so that a form that reaches them is +// seen: a refused input leaves the output as it was and reports input_too_long. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_SATURATING_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_SATURATING_HPP + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The type of the format saturating. */ +struct saturating_t { + /** The format's name. */ + static constexpr std::string_view name = "saturating"; + /** The most bytes whose encoding fits: past it, the encoded bound saturates. */ + static constexpr std::size_t most_bytes = 4; + /** The most characters whose decoding fits: past it, the decoded bound saturates. */ + static constexpr std::size_t most_characters = 8; +}; + +/** The format saturating. */ +inline constexpr saturating_t saturating{}; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The codec of saturating: bounds that saturate early, and functions that must not run. */ +template <> +struct codec { + /** Not used by the core's size checks. */ + static constexpr bool constant_time = false; + + /** Two characters a byte up to `most_bytes` bytes, else `SIZE_MAX`. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return input_size > test::saturating_t::most_bytes ? std::numeric_limits::max() + : 2 * input_size; + } + + /** One byte every two characters up to `most_characters` characters, else `SIZE_MAX`. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return text_size > test::saturating_t::most_characters + ? std::numeric_limits::max() + : text_size / 2; + } + + /** The bound itself, saturated as it is. */ + static constexpr std::size_t encoded_size(test::saturating_t const& /*format*/, + std::span input_bytes) noexcept { + return max_encoded_size(input_bytes.size()); + } + + /** Must not run for a refused text: reports checksum_mismatch. */ + static result decoded_size(test::saturating_t const& /*format*/, + std::string_view /*text*/) noexcept { + return error::checksum_mismatch; + } + + /** Must not run for a refused input: writes `!` and reports checksum_mismatch. */ + static result encode(test::saturating_t const& /*format*/, + std::span /*input*/, + std::span output_characters) noexcept { + std::ranges::fill(output_characters, '!'); + return error::checksum_mismatch; + } + + /** Must not run for a refused text: writes `!` and reports checksum_mismatch. */ + static result decode(test::saturating_t const& /*format*/, + std::string_view /*text*/, + std::span output_bytes) noexcept { + std::ranges::fill(output_bytes, static_cast('!')); + return error::checksum_mismatch; + } +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_TEST_SUPPORT_SATURATING_HPP From a1b7a832a4455650ba25909cff8f3cb006622ff3 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 09:09:52 -0300 Subject: [PATCH 008/157] codecs: the contract's doc examples with two-word parameter names --- .../webcpp/codecs/detail/core/contract.hpp | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 77bda02..cd586ca 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -48,16 +48,17 @@ namespace webcpp::codecs { // A bound on the bytes of text_size characters, SIZE_MAX when it does not fit. static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept; // The exact size of the text the format writes for input. - static constexpr std::size_t encoded_size(formats::hex_t const& format, - std::span input) noexcept; + static constexpr std::size_t encoded_size(formats::hex_t const& format_value, + std::span input_bytes) noexcept; // The exact size of the bytes text decodes to, the whole text checked. - static result decoded_size(formats::hex_t const& format, - std::string_view text) noexcept; - static result encode(formats::hex_t const& format, - std::span input, - std::span output) noexcept; - static result decode(formats::hex_t const& format, std::string_view text, - std::span output) noexcept; + static result decoded_size(formats::hex_t const& format_value, + std::string_view text_value) noexcept; + static result encode(formats::hex_t const& format_value, + std::span input_bytes, + std::span output_buffer) noexcept; + static result decode(formats::hex_t const& format_value, + std::string_view text_value, + std::span output_buffer) noexcept; }; @endcode @@ -83,13 +84,14 @@ struct codec; static constexpr codecs::output_kind output = codecs::output_kind::bytes; static constexpr bool secret = true; // optional; false when absent static constexpr std::size_t max_encoded_size = 138; // optional; a fixed result when present - static std::size_t encoded_size(crypto::formats::pkcs8_t const& format, - crypto::curves::p256::keypair const& value) noexcept; - static result encode(crypto::formats::pkcs8_t const& format, - crypto::curves::p256::keypair const& value, - std::span output) noexcept; + static std::size_t encoded_size(crypto::formats::pkcs8_t const& format_value, + crypto::curves::p256::keypair const& held_value) noexcept; + static result encode(crypto::formats::pkcs8_t const& format_value, + crypto::curves::p256::keypair const& held_value, + std::span output_buffer) noexcept; static result decode( - crypto::formats::pkcs8_t const& format, std::span input) noexcept; + crypto::formats::pkcs8_t const& format_value, + std::span input_bytes) noexcept; }; @endcode From cb0c0101422ff82880ac6fc8cb184f84009ea48e Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 09:14:33 -0300 Subject: [PATCH 009/157] codecs: text and bytes, the default results, and the typed decode into fixed byte types and value codecs --- include/webcpp/codecs.hpp | 2 + .../webcpp/codecs/detail/core/contract.hpp | 67 +++- .../webcpp/codecs/detail/core/operations.hpp | 379 ++++++++++++++++++ include/webcpp/codecs/detail/core/results.hpp | 175 ++++++++ include/webcpp/codecs/detail/core/sizes.hpp | 4 +- test/Jamfile | 8 + test/allocation_test.cpp | 96 +++++ test/default_result_test.cpp | 182 +++++++++ test/messages/Jamfile | 3 + test/messages/refused_encode/Jamfile | 16 + .../refused_encode/refused_encode.cpp | 24 ++ test/messages/refused_encode_only/Jamfile | 16 + .../refused_encode_only.cpp | 62 +++ test/messages/refused_pair/Jamfile | 16 + test/messages/refused_pair/refused_pair.cpp | 29 ++ test/noexcept_test.cpp | 23 ++ test/results_test.cpp | 174 ++++++++ test/support/be16.hpp | 83 ++++ test/typed_decode_test.cpp | 177 ++++++++ test/value_codec_test.cpp | 224 +++++++++++ 20 files changed, 1754 insertions(+), 6 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/operations.hpp create mode 100644 include/webcpp/codecs/detail/core/results.hpp create mode 100644 test/default_result_test.cpp create mode 100644 test/messages/refused_encode/Jamfile create mode 100644 test/messages/refused_encode/refused_encode.cpp create mode 100644 test/messages/refused_encode_only/Jamfile create mode 100644 test/messages/refused_encode_only/refused_encode_only.cpp create mode 100644 test/messages/refused_pair/Jamfile create mode 100644 test/messages/refused_pair/refused_pair.cpp create mode 100644 test/results_test.cpp create mode 100644 test/support/be16.hpp create mode 100644 test/typed_decode_test.cpp create mode 100644 test/value_codec_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index b22fa71..70feb87 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -16,6 +16,8 @@ #include #include #include +#include +#include #include #endif // WEBCPP_CODECS_HPP diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index cd586ca..fce32df 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -104,6 +104,24 @@ struct codec; template struct value_codec; +/** The fixed text result: `N` characters in place and a size (defined in results.hpp). */ +template +class text; + +/** The fixed bytes result: `N` bytes in place and a size (defined in results.hpp). */ +template +class bytes; + +/** + Lets a library's fixed type be the target of a typed decode: a specialization has + `static constexpr std::size_t size` and `static std::span writable(T&) + noexcept`, and the decode fills exactly `size` bytes. Declared by the core, never defined. + + @tparam T The library's fixed type. +*/ +template +struct fixed_byte_storage; + /** What a value codec's encoding is made of. */ enum class output_kind : unsigned char { /** Bytes: the encoding is written to a `std::span`. */ @@ -138,6 +156,18 @@ concept byte_range = std::ranges::contiguous_range && std::ranges::sized_range && byte_element>; +/** Whether `T` is `text` or `bytes`, the fixed results, which are inputs too. */ +template +struct fixed_result_type : std::false_type {}; + +/** A `text`. */ +template +struct fixed_result_type> : std::true_type {}; + +/** A `bytes`. */ +template +struct fixed_result_type> : std::true_type {}; + /** A type of a constant `size()` that converts to a span of that many bytes: `secure::secret`. */ template concept static_byte_view = requires { typename std::integral_constant; } && @@ -145,11 +175,14 @@ concept static_byte_view = requires { typename std::integral_constant` (`secure::secret`). + (a string literal is read as a `std::string_view`, B5), a type with a static constexpr `size()` + that converts to `std::span` (`secure::secret`), or a fixed result + (`text`, `bytes`), which is read through its `view()`. */ template -concept byte_input = byte_range> || static_byte_view>; +concept byte_input = + byte_range> || static_byte_view> || + fixed_result_type>::value; /** A contiguous sized range of `char`. */ template @@ -189,14 +222,23 @@ struct static_input_size> : std::integral_constant struct static_input_size : std::integral_constant {}; +/** A `text`: its capacity. */ +template +struct static_input_size> : std::integral_constant {}; + +/** A `bytes`: its capacity. */ +template +struct static_input_size> : std::integral_constant {}; + } // namespace detail /** The size of an input of type `T` when it is known at compile time, else `std::dynamic_extent`. It is known for a `std::array` and a `std::span` of a static extent of byte elements, an array of - `std::uint8_t`, `unsigned char` or `std::byte`, and a type with a static constexpr `size()` that - converts to `std::span`, as `secure::secret` does. An array of + `std::uint8_t`, `unsigned char` or `std::byte`, `text` and `bytes` (their capacity), and a + type with a static constexpr `size()` that converts to `std::span`, + as `secure::secret` does. An array of `char`, a string literal, is read as a `std::string_view` and its size is not static (B5). @tparam T The input's type; a reference and `const` are ignored. @@ -227,6 +269,19 @@ struct byte_result_type> : std::true_type { template struct byte_result_type> : std::true_type {}; +/** A `bytes`: a decode fills up to `N` bytes. */ +template +struct byte_result_type> : std::true_type {}; + +/** Whether `fixed_byte_storage` is specialized. */ +template +concept fixed_target = requires { sizeof(fixed_byte_storage); }; + +/** A library's fixed type, a decode fills exactly its size. */ +template + requires fixed_target +struct byte_result_type : std::true_type {}; + /** A byte result the core builds from a decode (D5); later parts add their own types. */ template concept byte_result = byte_result_type>::value; @@ -356,6 +411,8 @@ template input_characters.size()}; } else if constexpr (static_byte_view) { return std::span{input_value}; + } else if constexpr (fixed_result_type::value) { + return input_value.view(); } else if constexpr (std::same_as>, std::uint8_t>) { return {std::ranges::data(input_value), std::ranges::size(input_value)}; diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp new file mode 100644 index 0000000..324f7c3 --- /dev/null +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -0,0 +1,379 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The operations of webcpp::codecs that return their result: `encode` and `decode` with the default + result, the typed `decode` into the type the caller names, and the buffer forms of `encode` for a + value codec. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP +#define WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** Whether `T` is `text` or `bytes`: a result that holds its elements in place. */ +template +inline constexpr bool is_fixed_result = fixed_result_type::value; + +/** Whether `Codec`, a value codec, states `max_encoded_size`: its result is a fixed one. */ +template +concept has_encoded_bound = requires { + { Codec::max_encoded_size } -> std::convertible_to; +}; + +/** + The type `encode` returns, without a token, for `Input` in `F` (D9): `text` or `bytes` + when the size is known at compile time, `std::string` or `std::vector` otherwise. + A pair that is not `encodable` gets `std::string`, which its refusal never returns. +*/ +template +constexpr auto default_encode_type() noexcept { + if constexpr (value_encodable) { + using value_type = value_codec>; + constexpr bool writes_bytes = value_type::output == output_kind::bytes; + if constexpr (has_encoded_bound) { + constexpr std::size_t bound = value_type::max_encoded_size; + if constexpr (writes_bytes) { + return std::type_identity>{}; + } else { + return std::type_identity>{}; + } + } else if constexpr (writes_bytes) { + return std::type_identity>{}; + } else { + return std::type_identity{}; + } + } else if constexpr (byte_input && has_codec && + static_input_size_v != std::dynamic_extent) { + return std::type_identity::max_encoded_size(static_input_size_v)>>{}; + } else { + return std::type_identity{}; + } +} + +/** The type `encode` returns for `Input` in `F`, without a token. */ +template +using default_encode_result = typename decltype(default_encode_type())::type; + +/** + The type `decode` returns, without a token, for the text `Text` in `F` (D9): `bytes` when the + text's size is known at compile time, `std::vector` otherwise. +*/ +template +constexpr auto default_decode_type() noexcept { + if constexpr (has_codec && static_input_size_v != std::dynamic_extent) { + return std::type_identity::max_decoded_size(static_input_size_v)>>{}; + } else { + return std::type_identity>{}; + } +} + +/** The type `decode` returns for the text `Text` in `F`, without a token. */ +template +using default_decode_result = typename decltype(default_decode_type())::type; + +/** Whether `T` is a `std::array` of `std::uint8_t`. */ +template +inline constexpr bool is_byte_array = false; + +/** An array of `N` bytes. */ +template +inline constexpr bool is_byte_array> = true; + +/** Whether a decode of text into `Target`, a byte result, allocates nothing and cannot throw. */ +template +inline constexpr bool decode_is_fixed = + is_fixed_result || fixed_target || is_byte_array; + +/** Whether a typed decode into `Value` allocates nothing and cannot throw. */ +template +inline constexpr bool typed_decode_is_fixed = + value_decodable || (has_codec && decode_is_fixed); + +/** + Encodes into a `Result`, which `encode` picked for the pair (D9): the exact size is asked, the + `Result` made to hold it, and the format's own `encode` writes into it. + + @tparam Result `text`, `bytes`, `std::string` or `std::vector`. +*/ +template +[[nodiscard]] result encode_as(F const& format_value, + Input const& input_value) noexcept(is_fixed_result) { + std::size_t output_size = 0; + [[maybe_unused]] std::span input_view; + if constexpr (value_encodable) { + output_size = value_codec::encoded_size(format_value, input_value); + } else { + input_view = input_bytes(input_value); + if (auto const size_fault = input_size_fault(format_value, input_view.size())) { + return *size_fault; + } + output_size = codec::encoded_size(format_value, input_view); + } + Result output_value{}; + auto output_span = [&] { + if constexpr (is_fixed_result) { + return fixed_access::writable(output_value).first(output_size); + } else { + output_value.resize(output_size); + return std::span{output_value}; + } + }; + if constexpr (is_fixed_result) { + if (output_size > Result::capacity()) { + return error::output_too_small; + } + } + result written_size = std::size_t{0}; + if constexpr (value_encodable) { + written_size = value_codec::encode(format_value, input_value, output_span()); + } else { + written_size = codec::encode(format_value, input_view, output_span()); + } + if (!written_size) { + return written_size.error(); + } + if constexpr (is_fixed_result) { + fixed_access::resize(output_value, written_size.unsafe_value()); + } + return output_value; +} + +/** + Decodes the text into a `Target` that holds the bytes: the exact size is asked, the `Target` + made to hold it (or refused as too small, or of the wrong length), and the format's own `decode` + writes into it. + + @tparam Target `bytes` (up to `N` bytes), `std::array` or a `fixed_target` + (exactly its size), `std::string` or `std::vector`. +*/ +template +[[nodiscard]] result decode_as(F const& format_value, + Text const& text_value) noexcept(decode_is_fixed) { + std::string_view const text_characters = text_view(text_value); + if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { + return *size_fault; + } + result const decoded_count = codec::decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count.error(); + } + std::size_t const byte_count = decoded_count.unsafe_value(); + Target target_value{}; + std::span output_span; + if constexpr (is_fixed_result) { + if (byte_count > Target::capacity()) { + return error::output_too_small; + } + output_span = fixed_access::writable(target_value).first(byte_count); + } else if constexpr (fixed_target) { + if (byte_count != fixed_byte_storage::size) { + return error::invalid_length; + } + output_span = fixed_byte_storage::writable(target_value); + } else if constexpr (is_byte_array) { + if (byte_count != std::tuple_size::value) { + return error::invalid_length; + } + output_span = std::span{target_value}; + } else { + target_value.resize(byte_count); + // A char is written through an unsigned char, which may alias any object. + output_span = std::span{reinterpret_cast(target_value.data()), + byte_count}; + } + result const written_count = + codec::decode(format_value, text_characters, output_span); + if (!written_count) { + return written_count.error(); + } + if constexpr (is_fixed_result) { + fixed_access::resize(target_value, written_count.unsafe_value()); + } + return target_value; +} + +} // namespace detail + +/** + Encodes `input_value` in `format_value` and returns the encoding, with the default result (D9): + `text` (or `bytes` for a value codec of bytes) when the input's size is known at compile + time or the value codec states `max_encoded_size`, `M` being the format's bound, and + `std::string` (or `std::vector`) otherwise. + + It is `noexcept` exactly when the result is a `text` or a `bytes`, which allocate nothing. An + input whose encoding does not fit in `std::size_t` is @ref error::input_too_long, before it is + read. A value codec of `F` and `Input` is used when it encodes, else `codec`. A pair that is + not @ref encodable stops the build with a message that the format does not convert this type. + + @tparam F The format's type. + @tparam Input The input's type: a byte input, or a value of a value codec. + @param format_value The format. + @param input_value The bytes, or the value, to encode. + @return The encoding, or the error. +*/ +template +[[nodiscard]] auto encode(F const& format_value, Input const& input_value) noexcept( + detail::is_fixed_result>) { + if constexpr (encodable) { + return detail::encode_as>(format_value, + input_value); + } else { + detail::refuse(); + return result{std::string{}}; + } +} + +/** + Encodes `input_value`, a value of a value codec of bytes, in `format_value` into the caller's + buffer, allocating nothing. + + The checks come first, and on every error nothing is written: an `output_buffer` shorter than + the exact size is @ref error::output_too_small. The bytes are then written at the start of + `output_buffer`, whose other bytes are unchanged. The errors the value codec returns reach the + caller unchanged. + + @tparam F The format's type. + @tparam Input The value's type, one `value_codec` encodes into bytes. + @param format_value The format. + @param input_value The value to encode. + @param output_buffer The buffer the bytes are written to. + @return The number of bytes written, or the error. +*/ +template + requires(detail::value_encodable && + value_codec::output == output_kind::bytes) +[[nodiscard]] result encode(F const& format_value, Input const& input_value, + std::span output_buffer) noexcept { + std::size_t const bytes_size = value_codec::encoded_size(format_value, input_value); + if (output_buffer.size() < bytes_size) { + return error::output_too_small; + } + return value_codec::encode(format_value, input_value, + output_buffer.first(bytes_size)); +} + +/** + Encodes `input_value`, a value of a value codec of text, in `format_value` into the caller's + buffer, allocating nothing. + + The checks come first, and on every error nothing is written: an `output_buffer` shorter than + the exact size is @ref error::output_too_small. The text is then written at the start of + `output_buffer`, whose other characters are unchanged. The errors the value codec returns reach + the caller unchanged. + + @tparam F The format's type. + @tparam Input The value's type, one `value_codec` encodes into text. + @param format_value The format. + @param input_value The value to encode. + @param output_buffer The buffer the text is written to. + @return The number of characters written, or the error. +*/ +template + requires(detail::value_encodable && + value_codec::output == output_kind::text) +[[nodiscard]] result encode(F const& format_value, Input const& input_value, + std::span output_buffer) noexcept { + std::size_t const text_size = value_codec::encoded_size(format_value, input_value); + if (output_buffer.size() < text_size) { + return error::output_too_small; + } + return value_codec::encode(format_value, input_value, output_buffer.first(text_size)); +} + +/** + Decodes `text_value` in `format_value` and returns the bytes, with the default result (D9): + `bytes` when the text's size is known at compile time (`text`, a `std::array`), + `M` being the format's bound, and `std::vector` otherwise. + + It is `noexcept` exactly when the result is a `bytes`, which allocates nothing. A text whose + bytes do not fit in `std::size_t` is @ref error::input_too_long, before it is read; the whole text + is then checked, and its data error with the lowest value of @ref error is returned. A format with + no `codec` specialization stops the build with a message that the format does not convert bytes + (named `webcpp::codecs::detail::decoded_bytes`). + + @tparam F The format's type. + @tparam Text The text's type: anything a `std::string_view` is made from, or a contiguous + sized range of `char`. + @param format_value The format. + @param text_value The text to decode; a string literal is read up to its terminating zero. + @return The bytes, or the error. +*/ +template +[[nodiscard]] auto decode(F const& format_value, Text const& text_value) noexcept( + detail::is_fixed_result>) { + if constexpr (detail::has_codec) { + return detail::decode_as>(format_value, text_value); + } else { + detail::refuse(); + return result>{std::vector{}}; + } +} + +/** + Decodes `input_value` in `format_value` into a `Value`, the type the caller names. + + `Value` is a type a value codec of `F` decodes (read from a byte input for a value codec of + bytes, a text input for one of text; its errors reach the caller unchanged), or a byte result of + a format with a `codec`: a `std::array`, which takes exactly `N` bytes, or a + type of `fixed_byte_storage`, which takes exactly its size (@ref error::invalid_length + otherwise); a `bytes`, which takes up to `N` bytes (@ref error::output_too_small otherwise); + a `std::string` or a `std::vector`, which take the heap. It is `noexcept` for every + one of these but the last two, which allocate. A pair `F` does not convert stops the build with a + message that the format does not convert this type. + + @tparam Value The type to decode into. + @tparam F The format's type. + @tparam Input The input's type. + @param format_value The format. + @param input_value The text, or the bytes of a value codec of bytes, to decode. + @return The value, or the error. +*/ +template +[[nodiscard]] result decode(F const& format_value, Input const& input_value) noexcept( + detail::typed_decode_is_fixed) { + if constexpr (detail::value_decodable) { + using value_type = value_codec; + if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { + return value_type::decode(format_value, detail::input_bytes(input_value)); + } else if constexpr (value_type::output == output_kind::text && detail::text_input) { + return value_type::decode(format_value, detail::text_view(input_value)); + } else { + detail::refuse(); + return make_error_code(error::invalid_length); + } + } else if constexpr (detail::byte_result && detail::has_codec && + detail::text_input) { + return detail::decode_as(format_value, input_value); + } else { + detail::refuse(); + return make_error_code(error::invalid_length); + } +} + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp new file mode 100644 index 0000000..90d1fa3 --- /dev/null +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -0,0 +1,175 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The fixed results of webcpp::codecs: `text` and `bytes`, which hold their elements in + place, and the specialization point `fixed_byte_storage` that lets a library's fixed type be the + target of a typed decode. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP +#define WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** The core's writes into the fixed results: their storage and their size. */ +struct fixed_access; + +} // namespace detail + +/** + The text of an encoding that fits `N` characters: the characters in place, and a size. + + It is a regular type that compares by content. The characters past `size()` are zero, so that a + default-constructed `text` holds `N` zero characters and a size of 0. It converts implicitly to + a `std::string_view` on an lvalue; the conversion of an rvalue is deleted, so that no view + outlives the text it looks at. + + @tparam N The most characters it holds. +*/ +template +class text { +public: + /** Constructs a text of size 0 whose `N` characters are zero. */ + constexpr text() noexcept = default; + + /** The number of characters, at most `N`. */ + [[nodiscard]] constexpr std::size_t size() const noexcept { return text_size_; } + + /** The characters, `N` of them, those past `size()` zero. */ + [[nodiscard]] constexpr char const* data() const noexcept { return characters_.data(); } + + /** The most characters it holds, `N`. */ + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + + /** The first `size()` characters, valid while this text is. */ + [[nodiscard]] constexpr std::string_view view() const& noexcept { + return {characters_.data(), text_size_}; + } + + /** Deleted on an rvalue: the view would dangle. */ + std::string_view view() const&& = delete; + + /** The first `size()` characters, valid while this text is; an lvalue only. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): implicit by design + // (B8) + constexpr operator std::string_view() const& noexcept { return view(); } + + /** Deleted on an rvalue: the view would dangle. */ + operator std::string_view() const&& = delete; + + /** Whether two texts hold the same characters. */ + friend constexpr bool operator==(text const& first_text, text const& second_text) noexcept { + return first_text.view() == second_text.view(); + } + +private: + friend struct detail::fixed_access; + + std::array characters_{}; + std::size_t text_size_ = 0; +}; + +/** + The bytes of a decoding that fit `N` bytes: the bytes in place, and a size. + + It is a regular type that compares by content. The bytes past `size()` are zero, so that a + default-constructed `bytes` holds `N` zero bytes and a size of 0. It converts implicitly to a + `std::span` on an lvalue; the conversion of an rvalue is deleted, so that no + view outlives the bytes it looks at. + + @tparam N The most bytes it holds. +*/ +template +class bytes { +public: + /** Constructs bytes of size 0 whose `N` bytes are zero. */ + constexpr bytes() noexcept = default; + + /** The number of bytes, at most `N`. */ + [[nodiscard]] constexpr std::size_t size() const noexcept { return bytes_size_; } + + /** The bytes, `N` of them, those past `size()` zero. */ + [[nodiscard]] constexpr std::uint8_t const* data() const noexcept { return held_bytes_.data(); } + + /** The most bytes it holds, `N`. */ + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + + /** The first `size()` bytes, valid while these bytes are. */ + [[nodiscard]] constexpr std::span view() const& noexcept { + return {held_bytes_.data(), bytes_size_}; + } + + /** Deleted on an rvalue: the view would dangle. */ + std::span view() const&& = delete; + + /** The first `size()` bytes, valid while these bytes are; an lvalue only. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): implicit by design + // (B8) + constexpr operator std::span() const& noexcept { return view(); } + + /** Deleted on an rvalue: the view would dangle. */ + operator std::span() const&& = delete; + + /** Whether two values hold the same bytes. */ + friend constexpr bool operator==(bytes const& first_bytes, bytes const& second_bytes) noexcept { + return std::ranges::equal(first_bytes.view(), second_bytes.view()); + } + +private: + friend struct detail::fixed_access; + + std::array held_bytes_{}; + std::size_t bytes_size_ = 0; +}; + +namespace detail { + +/** The core's writes into the fixed results: their storage and their size. */ +struct fixed_access { + /** The whole storage of a `text`, to write the first `size` characters of. */ + template + [[nodiscard]] static constexpr std::span writable(text& fixed_text) noexcept { + return std::span{fixed_text.characters_}; + } + + /** The whole storage of a `bytes`, to write the first `size` bytes of. */ + template + [[nodiscard]] static constexpr std::span writable( + bytes& fixed_bytes) noexcept { + return std::span{fixed_bytes.held_bytes_}; + } + + /** Sets the size of a `text` whose first `new_size` characters were written. */ + template + static constexpr void resize(text& fixed_text, std::size_t new_size) noexcept { + fixed_text.text_size_ = new_size; + } + + /** Sets the size of a `bytes` whose first `new_size` bytes were written. */ + template + static constexpr void resize(bytes& fixed_bytes, std::size_t new_size) noexcept { + fixed_bytes.bytes_size_ = new_size; + } +}; + +} // namespace detail + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index edecf28..89d8f27 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -138,7 +138,8 @@ template `output_buffer`, whose other characters are unchanged. A format with no `codec` specialization stops the build with a message that the format does not - convert this type. + convert this type. A type a value codec of `F` encodes takes the value codec's buffer form + instead (operations.hpp). @tparam F The format's type. @tparam Input The input's type: a contiguous sized range of `std::uint8_t`, `unsigned char`, @@ -150,6 +151,7 @@ template @return The number of characters written, or the error. */ template + requires(!detail::value_encodable) [[nodiscard]] result encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept { if constexpr (detail::has_codec) { diff --git a/test/Jamfile b/test/Jamfile index a2756a5..0fd9dd3 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -46,6 +46,14 @@ codecs-run error : error_test.cpp ; codecs-run contract : contract_test.cpp ; # The sizes and the buffer forms: B23's order, nothing written on an error. codecs-run sizes : sizes_test.cpp ; +# The fixed results text and bytes: regular, by content, a view of an lvalue only. +codecs-run results : results_test.cpp ; +# The default result of encode and decode without a token (D9). +codecs-run default_result : default_result_test.cpp ; +# The typed decode into fixed byte types, the heap, and a value of a value codec. +codecs-run typed_decode : typed_decode_test.cpp ; +# Value codecs: the concepts, the default result, the buffer forms. +codecs-run value_codec : value_codec_test.cpp ; # The forms that allocate nothing leave a counting operator new where it was. codecs-run allocation : allocation_test.cpp ; # Every form that allocates nothing is noexcept, and one that allocates is not. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index b4fb11c..cba8630 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -12,6 +12,7 @@ #include "support/counting.hpp" +#include "support/be16.hpp" #include "support/letters.hpp" #include "support/saturating.hpp" @@ -34,6 +35,31 @@ namespace { namespace codecs = webcpp::codecs; namespace test = webcpp::codecs::test; +/** A library's fixed type of two bytes, a typed decode's target. */ +struct key_pair { + /** The bytes. */ + std::array held_bytes{}; +}; +} // namespace + +namespace webcpp::codecs { + +/** key_pair is a decode's target of exactly two bytes. */ +template <> +struct fixed_byte_storage<::key_pair> { + /** The size. */ + static constexpr std::size_t size = 2; + + /** The bytes a decode fills. */ + static std::span writable(::key_pair& target_key) noexcept { + return target_key.held_bytes; + } +}; + +} // namespace webcpp::codecs + +namespace { + constexpr std::size_t big = 64; constexpr std::align_val_t aligned{big}; @@ -188,11 +214,81 @@ void check_buffer_forms() { static_cast(sink); } +/** The fixed results, the default results that are fixed, and the typed decodes into fixed types + (Task 3): nothing is allocated, on any path. */ +void check_fixed_results() { + std::array const wide_input{}; + std::array const input{0x01, 0xff}; + std::array output{}; + std::array output_bytes{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + expect_no_allocation("encode to a fixed text", [&] { + auto const encoded = codecs::encode(test::letters, wide_input); + verdict = encoded.has_value(); + sink = encoded.value().size(); + }); + BOOST_TEST(verdict); + expect_no_allocation("the fixed results", [&] { + codecs::text<8> first_text; + codecs::text<8> const second_text = first_text; + codecs::bytes<4> const first_bytes; + verdict = first_text == second_text && first_bytes == codecs::bytes<4>{} && + first_text.view().empty() && first_bytes.view().empty(); + }); + BOOST_TEST(verdict); + auto const fixed_text = codecs::encode(test::letters, input); // built before the window + BOOST_TEST(fixed_text.has_value()); + expect_no_allocation("decode of a fixed text", [&] { + auto const decoded = codecs::decode(test::letters, fixed_text.value()); + verdict = decoded.has_value(); + sink = decoded.value().size(); + }); + BOOST_TEST(verdict); + expect_no_allocation("typed decode into an array", [&] { + verdict = codecs::decode>(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("typed decode into fixed bytes", [&] { + verdict = codecs::decode>(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("typed decode into a library's fixed type", [&] { + verdict = codecs::decode(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("typed decodes that are refused", [&] { + verdict = codecs::decode>(test::letters, "ab").has_value() || + codecs::decode>(test::letters, "abpp").has_value() || + codecs::decode(test::letters, "abpq").has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("a value codec's default result and buffer forms", [&] { + auto const encoded = codecs::encode(test::be16, test::number{0x1234}); + verdict = encoded.has_value() && + codecs::encode(test::be16, test::number{0x1234}, output_bytes).has_value() && + codecs::decode(test::be16, input).has_value(); + sink = encoded.value().size(); + }); + BOOST_TEST(verdict); + expect_no_allocation("a value codec's refused buffer", [&] { + verdict = + codecs::encode(test::be16, test::number{0x1234}, + std::span{output_bytes}.first(1)) + .has_value() || + codecs::decode(test::be16, std::array{}).has_value(); + }); + BOOST_TEST(!verdict); + static_cast(output); + static_cast(sink); +} + } // namespace int main() { std::printf("c_allocations_counted=%d\n", test::c_allocations_counted ? 1 : 0); control_counts_every_form(); check_buffer_forms(); + check_fixed_results(); return boost::report_errors(); } diff --git a/test/default_result_test.cpp b/test/default_result_test.cpp new file mode 100644 index 0000000..893f9af --- /dev/null +++ b/test/default_result_test.cpp @@ -0,0 +1,182 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The default result (D9): encode and decode without a token return the fixed result when the +// size is known at compile time, the heap one otherwise, and a typed value gives a fixed result +// when its value codec states a bound. + +#include "support/be16.hpp" +#include "support/letters.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +template +constexpr bool returns = std::is_same_v; + +// NOLINTBEGIN(modernize-avoid-c-arrays): the kind of input under test +using byte_array_32 = std::array; +using byte_c_array_32 = std::uint8_t[32]; +// NOLINTEND(modernize-avoid-c-arrays) + +// Encode of bytes of static size N: text. +static_assert( + returns>, + decltype(codecs::encode(test::letters, std::declval()))>); +static_assert(returns>, + decltype(codecs::encode(test::letters, + std::declval>()))>); +static_assert(returns>, + decltype(codecs::encode(test::letters, std::declval()))>); +static_assert(returns>, + decltype(codecs::encode(test::letters, + std::declval const&>()))>); +static_assert( + returns>, + decltype(codecs::encode(test::letters, std::declval const&>()))>); +static_assert( + returns>, + decltype(codecs::encode(test::letters, std::declval const&>()))>); +// Anything else: the heap. +static_assert(returns, + decltype(codecs::encode(test::letters, + std::declval const&>()))>); +static_assert(returns, + decltype(codecs::encode(test::letters, + std::declval>()))>); +static_assert(returns, + decltype(codecs::encode(test::letters, std::declval()))>); +// A string literal is read as a std::string_view, its size not static (B5). +static_assert(returns, decltype(codecs::encode(test::letters, "ab"))>); + +// Decode of a text of static size N: bytes; otherwise the heap. +static_assert( + returns>, + decltype(codecs::decode(test::letters, std::declval const&>()))>); +static_assert( + returns>, + decltype(codecs::decode(test::letters, std::declval>()))>); +static_assert(returns>, + decltype(codecs::decode(test::letters, std::declval()))>); +static_assert(returns>, + decltype(codecs::decode(test::letters, std::declval()))>); +static_assert(returns>, + decltype(codecs::decode(test::letters, "abpp"))>); + +// A typed value whose value codec states a bound: bytes<2>. +static_assert(returns>, + decltype(codecs::encode(test::be16, std::declval()))>); + +void encodes_to_a_fixed_text() { + byte_array_32 input_bytes{}; + input_bytes[0] = 0x01; + input_bytes[31] = 0xff; + auto const array_text = codecs::encode(test::letters, input_bytes); + BOOST_TEST(array_text.has_value()); + BOOST_TEST_EQ(array_text.value().size(), 64U); + BOOST_TEST(array_text.value().view().starts_with("ab")); + BOOST_TEST(array_text.value().view().ends_with("pp")); + auto const span_text = + codecs::encode(test::letters, std::span{input_bytes}); + BOOST_TEST(span_text.has_value()); + BOOST_TEST(span_text.value() == array_text.value()); + byte_c_array_32 c_array_bytes{}; + c_array_bytes[0] = 0x01; + c_array_bytes[31] = 0xff; + auto const c_array_text = codecs::encode(test::letters, c_array_bytes); + BOOST_TEST(c_array_text.has_value()); + BOOST_TEST(c_array_text.value() == array_text.value()); +} + +void encodes_to_the_heap() { + std::vector const heap_bytes{0x01, 0xff}; + auto const heap_text = codecs::encode(test::letters, heap_bytes); + BOOST_TEST(heap_text.has_value()); + BOOST_TEST(heap_text.value() == "abpp"); + auto const literal_text = codecs::encode(test::letters, "ab"); + BOOST_TEST(literal_text.has_value()); + BOOST_TEST_EQ(literal_text.value().size(), 4U); + auto const empty_text = codecs::encode(test::letters, std::vector{}); + BOOST_TEST(empty_text.has_value()); + BOOST_TEST(empty_text.value().empty()); +} + +void encodes_a_typed_value() { + auto const encoded = codecs::encode(test::be16, test::number{0x1234}); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(encoded.value().size(), 2U); + BOOST_TEST_EQ(encoded.value().data()[0], 0x12); + BOOST_TEST_EQ(encoded.value().data()[1], 0x34); +} + +void a_fixed_text_round_trips_with_no_heap() { + byte_array_32 input_bytes{}; + for (std::size_t index = 0; index < input_bytes.size(); ++index) { + input_bytes[index] = static_cast(index * 7U); + } + auto const encoded = codecs::encode(test::letters, input_bytes); + BOOST_TEST(encoded.has_value()); + auto const decoded = codecs::decode(test::letters, encoded.value()); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), 32U); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input_bytes)); + // A view of the fixed text is a text of run-time size: the heap. + auto const from_view = codecs::decode(test::letters, encoded.value().view()); + BOOST_TEST(from_view.has_value()); + BOOST_TEST(std::ranges::equal(from_view.value(), input_bytes)); +} + +void decodes_to_the_heap() { + auto const decoded = codecs::decode(test::letters, std::string{"abpp"}); + BOOST_TEST(decoded.has_value()); + std::vector const expected{0x01, 0xff}; + BOOST_TEST(decoded.value() == expected); + auto const from_literal = codecs::decode(test::letters, "abpp"); + BOOST_TEST(from_literal.has_value()); + BOOST_TEST(from_literal.value() == expected); +} + +void the_errors_reach_the_caller() { + auto const odd = codecs::decode(test::letters, std::string{"abp"}); + BOOST_TEST(!odd.has_value()); + BOOST_TEST(odd.error() == codecs::error::invalid_length); + auto const foreign = codecs::decode(test::letters, std::string{"abq"}); + BOOST_TEST(!foreign.has_value()); + BOOST_TEST(foreign.error() == codecs::error::invalid_character); + // An empty fixed text decodes to no bytes. + auto const empty_fixed = codecs::decode(test::letters, codecs::text<4>{}); + BOOST_TEST(empty_fixed.has_value()); + BOOST_TEST_EQ(empty_fixed.value().size(), 0U); +} + +} // namespace + +int main() { + encodes_to_a_fixed_text(); + encodes_to_the_heap(); + encodes_a_typed_value(); + a_fixed_text_round_trips_with_no_heap(); + decodes_to_the_heap(); + the_errors_reach_the_caller(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 8803d9e..926b0bb 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -14,3 +14,6 @@ build-project forgotten_header ; build-project refused_size ; build-project refused_decode ; +build-project refused_pair ; +build-project refused_encode ; +build-project refused_encode_only ; diff --git a/test/messages/refused_encode/Jamfile b/test/messages/refused_encode/Jamfile new file mode 100644 index 0000000..65c5cbf --- /dev/null +++ b/test/messages/refused_encode/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_encode : refused_encode.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_encode_refused : refused_encode.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_encode/refused_encode.cpp b/test/messages/refused_encode/refused_encode.cpp new file mode 100644 index 0000000..f88d557 --- /dev/null +++ b/test/messages/refused_encode/refused_encode.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that encodes a type the format does not convert, without a token, stops in the +// core's refusal, whose requirement names the type and the format's type (ruling R2). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const encoded = codecs::encode(codecs::test::letters, 42); + return encoded.has_value() ? 0 : 1; +} diff --git a/test/messages/refused_encode_only/Jamfile b/test/messages/refused_encode_only/Jamfile new file mode 100644 index 0000000..5dff655 --- /dev/null +++ b/test/messages/refused_encode_only/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_encode_only : refused_encode_only.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_encode_only_refused : refused_encode_only.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_encode_only/refused_encode_only.cpp b/test/messages/refused_encode_only/refused_encode_only.cpp new file mode 100644 index 0000000..42df547 --- /dev/null +++ b/test/messages/refused_encode_only/refused_encode_only.cpp @@ -0,0 +1,62 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that decodes into a value whose value codec only encodes stops in the core's refusal, +// whose requirement names the value's type and the format's type (ruling R2). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/be16.hpp" + +#include + +#include +#include +#include +#include + +/** A value that only encodes, in be16. */ +struct encode_only_number { + /** The bits. */ + std::uint16_t value; +}; + +namespace webcpp::codecs { + +/** A value codec that encodes only. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Two bytes. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + encode_only_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes. */ + static result encode(test::be16_t const& /*format*/, + encode_only_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + auto const decoded = + codecs::decode(codecs::test::be16, std::array{}); + return decoded.has_value() ? 0 : 1; +} diff --git a/test/messages/refused_pair/Jamfile b/test/messages/refused_pair/Jamfile new file mode 100644 index 0000000..d3ea182 --- /dev/null +++ b/test/messages/refused_pair/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_pair : refused_pair.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_pair_refused : refused_pair.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_pair/refused_pair.cpp b/test/messages/refused_pair/refused_pair.cpp new file mode 100644 index 0000000..a503ccc --- /dev/null +++ b/test/messages/refused_pair/refused_pair.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that decodes into a type the format does not convert stops in the core's refusal, +// whose requirement names the type and the format's type (ruling R2). The type is printed +// differently by libc++ and libstdc++, so the directive matches both. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error-re@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts>, webcpp::codecs::test::letters_t>': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const decoded = + codecs::decode(codecs::test::letters, std::string_view{"ab"}); + return decoded.has_value() ? 0 : 1; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index c55b574..d3f66b2 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -8,6 +8,7 @@ // allocates is not, so that an allocator's exception propagates (owner decision 24). Later tasks // add their rows, both ways. +#include "support/be16.hpp" #include "support/letters.hpp" #include @@ -15,7 +16,9 @@ #include #include #include +#include #include +#include #include namespace { @@ -33,4 +36,24 @@ static_assert(noexcept(codecs::decode(test::letters, std::string_view{}, static_assert(noexcept(codecs::encoded_size(test::letters, std::array{}))); static_assert(noexcept(codecs::max_decoded_size(test::letters, std::string_view{}))); +// The fixed results and the typed decodes (Task 3): a result that holds its elements in place is +// noexcept, a heap one is not. +static_assert(noexcept(codecs::encode(test::letters, std::array{}))); +static_assert(noexcept(codecs::encode(test::letters, + std::declval>()))); +static_assert(!noexcept(codecs::encode(test::letters, std::vector{}))); +static_assert(!noexcept(codecs::encode(test::letters, std::string_view{}))); +static_assert(!noexcept(codecs::encode(test::letters, "ab"))); +static_assert(noexcept(codecs::encode(test::be16, test::number{}))); +static_assert(noexcept(codecs::decode(test::letters, codecs::text<64>{}))); +static_assert(!noexcept(codecs::decode(test::letters, std::string{}))); +static_assert(!noexcept(codecs::decode(test::letters, std::string_view{}))); +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode(test::be16, std::array{}))); +static_assert(!noexcept(codecs::decode(test::letters, "ab"))); +static_assert(!noexcept(codecs::decode>(test::letters, "ab"))); +// The buffer forms of a value codec. +static_assert(noexcept(codecs::encode(test::be16, test::number{}, std::span{}))); + } // namespace diff --git a/test/results_test.cpp b/test/results_test.cpp new file mode 100644 index 0000000..4e3a67f --- /dev/null +++ b/test/results_test.cpp @@ -0,0 +1,174 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The fixed results: text and bytes hold their elements in place with a size, compare by +// content, read as a view on an lvalue only (B8), and are zero past their size. + +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +// The view of an lvalue converts; the view of an rvalue does not (B8). A requires-expression is +// only a check when it is dependent, so the probes are concepts. +template +concept views_as_text = requires { std::string_view{std::declval()}; }; +template +concept views_as_bytes = requires { std::span{std::declval()}; }; +template +concept has_view = requires { std::declval().view(); }; + +static_assert(views_as_text const&>); +static_assert(!views_as_text>); +static_assert(has_view const&>); +static_assert(!has_view>); +static_assert(views_as_bytes const&>); +static_assert(!views_as_bytes>); +static_assert(has_view const&>); +static_assert(!has_view>); +static_assert(std::convertible_to const&, std::string_view>); +static_assert(!std::convertible_to, std::string_view>); +static_assert(std::convertible_to const&, std::span>); +static_assert(!std::convertible_to, std::span>); + +// Regular, and the capacity is the template argument. +static_assert(std::regular>); +static_assert(std::regular>); +static_assert(std::is_nothrow_default_constructible_v>); +static_assert(std::is_trivially_copyable_v>); +static_assert(std::is_trivially_copyable_v>); +static_assert(codecs::text<8>::capacity() == 8); +static_assert(codecs::bytes<4>::capacity() == 4); +static_assert(noexcept(codecs::text<8>{}.size())); +static_assert(noexcept(std::declval const&>().view())); + +// Both are inputs of a known size, their capacity (D7). +static_assert(codecs::static_input_size_v> == 8); +static_assert(codecs::static_input_size_v const&> == 4); +static_assert(codecs::detail::byte_input>); +static_assert(codecs::detail::byte_input>); +static_assert(codecs::detail::text_input>); +static_assert(!codecs::detail::text_input>); + +// The members are constexpr. +constexpr codecs::text<8> empty_text{}; +static_assert(empty_text.size() == 0); +static_assert(empty_text.view().empty()); +static_assert(empty_text == codecs::text<8>{}); +constexpr codecs::bytes<4> empty_bytes{}; +static_assert(empty_bytes.size() == 0); +static_assert(empty_bytes.view().empty()); +static_assert(empty_bytes == codecs::bytes<4>{}); + +/** The text<8> of the four bytes 0x01 0xff 0x00 0x7a in letters: the default result of encode. */ +codecs::text<8> letters_text(std::array const& input_bytes) { + auto const encoded = codecs::encode(test::letters, input_bytes); + BOOST_TEST(encoded.has_value()); + return encoded.value(); +} + +void text_holds_eight_letters() { + codecs::text<8> const first_text = letters_text({0x01, 0xff, 0x00, 0x7a}); + BOOST_TEST_EQ(first_text.size(), 8U); + BOOST_TEST_EQ(first_text.capacity(), 8U); + BOOST_TEST(first_text.view() == "abppaahk"); + BOOST_TEST(std::string_view{first_text} == "abppaahk"); + BOOST_TEST(std::string_view(first_text.data(), first_text.size()) == "abppaahk"); + codecs::text<8> const same_text = letters_text({0x01, 0xff, 0x00, 0x7a}); + codecs::text<8> const other_text = letters_text({0x01, 0xff, 0x00, 0x7b}); + BOOST_TEST(first_text == same_text); + BOOST_TEST(!(first_text != same_text)); + BOOST_TEST(first_text != other_text); + // A copy is equal, and the copy is regular. + codecs::text<8> copied_text = first_text; + BOOST_TEST(copied_text == first_text); + copied_text = other_text; + BOOST_TEST(copied_text == other_text); +} + +void default_text_is_zero() { + codecs::text<8> const empty_value{}; + BOOST_TEST_EQ(empty_value.size(), 0U); + BOOST_TEST_EQ(empty_value.capacity(), 8U); + BOOST_TEST(empty_value.view().empty()); + BOOST_TEST(std::ranges::all_of(std::span{empty_value.data(), 8}, + [](char held_character) { return held_character == '\0'; })); +} + +void text_past_its_size_is_zero() { + // A text written short keeps the characters past its size zero. + codecs::text<8> narrow_text{}; + codecs::detail::fixed_access::writable(narrow_text)[0] = 'a'; + codecs::detail::fixed_access::resize(narrow_text, 1); + BOOST_TEST(narrow_text.view() == "a"); + BOOST_TEST_EQ(narrow_text.data()[1], '\0'); + BOOST_TEST_EQ(narrow_text.data()[7], '\0'); + BOOST_TEST(narrow_text != codecs::text<8>{}); +} + +void bytes_hold_four_bytes() { + codecs::bytes<4> const first_bytes = + codecs::decode(test::letters, letters_text({1, 2, 3, 4})).value(); + BOOST_TEST_EQ(first_bytes.size(), 4U); + BOOST_TEST_EQ(first_bytes.capacity(), 4U); + constexpr std::array expected{1, 2, 3, 4}; + BOOST_TEST(std::ranges::equal(first_bytes.view(), expected)); + BOOST_TEST(std::ranges::equal(std::span{first_bytes}, expected)); + codecs::bytes<4> const same_bytes = + codecs::decode(test::letters, letters_text({1, 2, 3, 4})).value(); + codecs::bytes<4> const other_bytes = + codecs::decode(test::letters, letters_text({1, 2, 3, 5})).value(); + BOOST_TEST(first_bytes == same_bytes); + BOOST_TEST(first_bytes != other_bytes); +} + +void default_bytes_are_zero() { + codecs::bytes<4> const empty_value{}; + BOOST_TEST_EQ(empty_value.size(), 0U); + BOOST_TEST(empty_value.view().empty()); + BOOST_TEST(std::ranges::all_of(std::span{empty_value.data(), 4}, + [](std::uint8_t held_byte) { return held_byte == 0; })); +} + +// Equal sizes with different contents past the size cannot occur: a smaller decode of the same +// capacity differs by size. +void equality_reads_the_size() { + auto const short_bytes = codecs::decode>(test::letters, "abab"); + auto const long_bytes = codecs::decode>(test::letters, "ababab"); + BOOST_TEST(short_bytes.has_value()); + BOOST_TEST(long_bytes.has_value()); + BOOST_TEST_EQ(short_bytes.value().size(), 2U); + BOOST_TEST_EQ(long_bytes.value().size(), 3U); + BOOST_TEST(short_bytes.value() != long_bytes.value()); +} + +} // namespace + +int main() { + text_holds_eight_letters(); + default_text_is_zero(); + text_past_its_size_is_zero(); + bytes_hold_four_bytes(); + default_bytes_are_zero(); + equality_reads_the_size(); + return boost::report_errors(); +} diff --git a/test/support/be16.hpp b/test/support/be16.hpp new file mode 100644 index 0000000..61b5682 --- /dev/null +++ b/test/support/be16.hpp @@ -0,0 +1,83 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// be16, a format of the tests' own for a typed value: a `number` is written as two bytes, big +// endian, by a value codec of bytes that states its bound, so that the default result is a fixed +// one. Decoding any other length is invalid_length. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The type of the format be16. */ +struct be16_t { + /** The format's name. */ + static constexpr std::string_view name = "be16"; +}; + +/** The format be16. */ +inline constexpr be16_t be16{}; + +/** A value of be16: sixteen bits. */ +struct number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(number const&) const = default; +}; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The value codec of be16 for a `number`. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + test::number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte into `output_bytes`, which must hold them. */ + static result encode(test::be16_t const& /*format*/, + test::number const& held_value, + std::span output_bytes) noexcept { + if (output_bytes.size() < 2) { + return error::output_too_small; + } + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } + + /** Reads two bytes, big endian; any other length is invalid_length. */ + static result decode(test::be16_t const& /*format*/, + std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return error::invalid_length; + } + return test::number{static_cast((input_bytes[0] << 8U) | input_bytes[1])}; + } +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP diff --git a/test/typed_decode_test.cpp b/test/typed_decode_test.cpp new file mode 100644 index 0000000..b4a3e9a --- /dev/null +++ b/test/typed_decode_test.cpp @@ -0,0 +1,177 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The typed decode: into std::array (exactly N bytes), bytes (up to N), a library's fixed type +// (exactly its size), the heap types, and a value of a value codec. + +#include "support/be16.hpp" +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** A library's fixed type of sixteen bytes. */ +struct key16 { + /** The bytes. */ + std::array held_bytes{}; +}; + +} // namespace + +namespace webcpp::codecs { + +/** key16 is a decode's target of exactly sixteen bytes. */ +template <> +struct fixed_byte_storage { + /** The size. */ + static constexpr std::size_t size = 16; + + /** The bytes a decode fills. */ + static std::span writable(key16& target_key) noexcept { + return target_key.held_bytes; + } +}; + +} // namespace webcpp::codecs + +namespace { + +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable); +static_assert(!codecs::decodable); +static_assert(!codecs::decodable); + +// A fixed target and a value codec do not throw; the heap types may. +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode(test::letters, "ab"))); +static_assert(noexcept(codecs::decode(test::be16, std::array{}))); +static_assert(!noexcept(codecs::decode(test::letters, "ab"))); +static_assert(!noexcept(codecs::decode>(test::letters, "ab"))); + +void into_an_array() { + auto const decoded = codecs::decode>(test::letters, "abpp"); + BOOST_TEST(decoded.has_value()); + BOOST_TEST((decoded.value() == std::array{0x01, 0xff})); + auto const too_short = codecs::decode>(test::letters, "ab"); + BOOST_TEST(!too_short.has_value()); + BOOST_TEST(too_short.error() == codecs::error::invalid_length); + auto const too_long = codecs::decode>(test::letters, "abppab"); + BOOST_TEST(!too_long.has_value()); + BOOST_TEST(too_long.error() == codecs::error::invalid_length); + // The data error comes before the length. + auto const foreign = codecs::decode>(test::letters, "aq"); + BOOST_TEST(!foreign.has_value()); + BOOST_TEST(foreign.error() == codecs::error::invalid_character); + // From a string, a view and a fixed text alike. + using two_bytes = std::array; + BOOST_TEST(codecs::decode(test::letters, std::string{"abpp"}).has_value()); + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abpp"}).has_value()); + auto const fixed_text = codecs::encode(test::letters, two_bytes{0x01, 0xff}); + BOOST_TEST(fixed_text.has_value()); + auto const from_fixed = codecs::decode(test::letters, fixed_text.value()); + BOOST_TEST(from_fixed.has_value()); +} + +void into_fixed_bytes() { + auto const decoded = codecs::decode>(test::letters, "abpp"); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), 2U); + BOOST_TEST_EQ(decoded.value().capacity(), 4U); + BOOST_TEST_EQ(decoded.value().data()[0], 0x01); + BOOST_TEST_EQ(decoded.value().data()[1], 0xff); + BOOST_TEST_EQ(decoded.value().data()[2], 0x00); + auto const exact = codecs::decode>(test::letters, "abpp"); + BOOST_TEST(exact.has_value()); + auto const too_small = codecs::decode>(test::letters, "abpp"); + BOOST_TEST(!too_small.has_value()); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + auto const empty = codecs::decode>(test::letters, ""); + BOOST_TEST(empty.has_value()); + BOOST_TEST_EQ(empty.value().size(), 0U); + // The data error comes before the capacity. + auto const foreign = codecs::decode>(test::letters, "abpq"); + BOOST_TEST(!foreign.has_value()); + BOOST_TEST(foreign.error() == codecs::error::invalid_character); +} + +void into_a_library_type() { + std::string const thirty_two(32, 'b'); + auto const decoded = codecs::decode(test::letters, thirty_two); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::all_of(decoded.value().held_bytes, + [](std::uint8_t held_byte) { return held_byte == 0x11; })); + std::string const thirty(30, 'b'); + auto const refused = codecs::decode(test::letters, thirty); + BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused.error() == codecs::error::invalid_length); + std::string const thirty_four(34, 'b'); + BOOST_TEST(codecs::decode(test::letters, thirty_four).error() == + codecs::error::invalid_length); +} + +void into_a_value() { + auto const decoded = + codecs::decode(test::be16, std::array{0x12, 0x34}); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(decoded.value() == test::number{0x1234}); + auto const three = codecs::decode(test::be16, std::array{}); + BOOST_TEST(!three.has_value()); + BOOST_TEST(three.error() == codecs::error::invalid_length); + std::vector const heap_bytes{0xab, 0xcd}; + BOOST_TEST(codecs::decode(test::be16, heap_bytes).value() == + test::number{0xabcd}); + codecs::bytes<2> const fixed_bytes = codecs::encode(test::be16, test::number{0x0102}).value(); + BOOST_TEST(codecs::decode(test::be16, fixed_bytes).value() == + test::number{0x0102}); + auto const one = codecs::decode( + test::be16, std::span{heap_bytes.data(), 1}); + BOOST_TEST(one.error() == codecs::error::invalid_length); +} + +void into_the_heap() { + auto const text_value = codecs::decode(test::letters, "abpp"); + BOOST_TEST(text_value.has_value()); + BOOST_TEST_EQ(text_value.value().size(), 2U); + BOOST_TEST_EQ(static_cast(text_value.value()[0]), 0x01U); + BOOST_TEST_EQ(static_cast(text_value.value()[1]), 0xffU); + auto const vector_value = codecs::decode>(test::letters, "abpp"); + BOOST_TEST(vector_value.has_value()); + BOOST_TEST((vector_value.value() == std::vector{0x01, 0xff})); + BOOST_TEST(codecs::decode(test::letters, "ab!").error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(test::letters, "").value().empty()); +} + +} // namespace + +int main() { + into_an_array(); + into_fixed_bytes(); + into_a_library_type(); + into_a_value(); + into_the_heap(); + return boost::report_errors(); +} diff --git a/test/value_codec_test.cpp b/test/value_codec_test.cpp new file mode 100644 index 0000000..1878923 --- /dev/null +++ b/test/value_codec_test.cpp @@ -0,0 +1,224 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Value codecs: the concepts look at each function, the default result follows the stated bound, +// and the buffer forms write into the caller's bytes or characters, noexcept and allocating +// nothing. The refusal of a typed decode with no decode is a message case (refused_encode_only). + +#include "support/be16.hpp" +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** A value that only encodes, in be16. */ +struct encode_only_number { + /** The bits. */ + std::uint16_t value; +}; + +/** A value of text with no stated bound, in be16: its four hexadecimal digits. */ +struct hex_number { + /** The bits. */ + std::uint16_t value; +}; + +} // namespace + +namespace webcpp::codecs { + +/** A value codec that encodes only. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Two bytes. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + encode_only_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes. */ + static result encode(test::be16_t const& /*format*/, + encode_only_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } +}; + +/** A value codec of text, with no stated bound. */ +template <> +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + + /** Four characters. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + hex_number const& /*held_value*/) noexcept { + return 4; + } + + /** Writes the four digits. */ + static result encode(test::be16_t const& /*format*/, hex_number const& held_value, + std::span output_characters) noexcept { + constexpr std::string_view digits = "0123456789abcdef"; + for (std::size_t index = 0; index < 4; ++index) { + output_characters[index] = digits[(held_value.value >> (12U - (4U * index))) & 15U]; + } + return std::size_t{4}; + } + + /** Reads four digits. */ + static result decode(test::be16_t const& /*format*/, + std::string_view text_value) noexcept { + if (text_value.size() != 4) { + return error::invalid_length; + } + unsigned bits = 0; + constexpr std::string_view digits = "0123456789abcdef"; + for (char const digit : text_value) { + auto const position = digits.find(digit); + if (position == std::string_view::npos) { + return error::invalid_character; + } + bits = (bits << 4U) | static_cast(position); + } + return hex_number{static_cast(bits)}; + } +}; + +} // namespace webcpp::codecs + +namespace { + +static_assert(codecs::encodable); +static_assert(codecs::decodable); +// Only the functions the value codec has: encode alone is not decode. +static_assert(codecs::encodable); +static_assert(!codecs::decodable); +// Another format has no value codec of the value, and no codec either. +static_assert(!codecs::encodable); +static_assert(!codecs::decodable); +// Text: decode only reads text, encode writes text. +static_assert(codecs::encodable); +static_assert(codecs::decodable); + +// The default result: a stated bound is a fixed result; none is the heap. +static_assert(std::is_same_v>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v>); +static_assert(noexcept(codecs::encode(test::be16, test::number{}))); +static_assert(!noexcept(codecs::encode(test::be16, encode_only_number{}))); +static_assert(!noexcept(codecs::encode(test::be16, hex_number{}))); + +// The buffer forms: bytes for a value codec of bytes, characters for one of text; noexcept. +static_assert(noexcept(codecs::encode(test::be16, test::number{}, std::span{}))); +static_assert(noexcept(codecs::encode(test::be16, hex_number{}, std::span{}))); +template +concept encodes_into = requires(Value held_value, Buffer output_buffer) { + codecs::encode(test::be16, held_value, output_buffer); +}; +static_assert(encodes_into>); +static_assert(!encodes_into>); +static_assert(encodes_into>); +static_assert(!encodes_into>); + +void the_size_is_the_value_codecs() { + BOOST_TEST_EQ(codecs::encoded_size(test::be16, test::number{}), 2U); + BOOST_TEST_EQ(codecs::encoded_size(test::be16, hex_number{}), 4U); +} + +void the_buffer_form_of_bytes() { + std::array output_bytes{0xee, 0xee, 0xee, 0xee}; + auto const written = codecs::encode(test::be16, test::number{0x1234}, output_bytes); + BOOST_TEST(written.has_value()); + BOOST_TEST_EQ(written.value(), 2U); + BOOST_TEST_EQ(output_bytes[0], 0x12); + BOOST_TEST_EQ(output_bytes[1], 0x34); + BOOST_TEST_EQ(output_bytes[2], 0xee); + BOOST_TEST_EQ(output_bytes[3], 0xee); + // Too small: refused, nothing written. + std::array short_bytes{0xee}; + auto const refused = codecs::encode(test::be16, test::number{0x1234}, short_bytes); + BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(short_bytes[0], 0xee); +} + +void the_buffer_form_of_text() { + std::array output_characters{'-', '-', '-', '-', '-', '-'}; + auto const written = codecs::encode(test::be16, hex_number{0xbeef}, output_characters); + BOOST_TEST(written.has_value()); + BOOST_TEST_EQ(written.value(), 4U); + BOOST_TEST((std::string_view{output_characters.data(), 6} == "beef--")); + std::array short_characters{'-', '-', '-'}; + auto const refused = codecs::encode(test::be16, hex_number{0xbeef}, short_characters); + BOOST_TEST(refused.error() == codecs::error::output_too_small); + BOOST_TEST((std::string_view{short_characters.data(), 3} == "---")); +} + +void the_default_results() { + auto const fixed_bytes = codecs::encode(test::be16, test::number{0x1234}); + BOOST_TEST(fixed_bytes.has_value()); + BOOST_TEST_EQ(fixed_bytes.value().size(), 2U); + auto const heap_bytes = codecs::encode(test::be16, encode_only_number{0x1234}); + BOOST_TEST(heap_bytes.has_value()); + BOOST_TEST((heap_bytes.value() == std::vector{0x12, 0x34})); + auto const heap_text = codecs::encode(test::be16, hex_number{0x0a1f}); + BOOST_TEST(heap_text.has_value()); + BOOST_TEST(heap_text.value() == "0a1f"); +} + +void a_value_of_text_decodes_from_text() { + auto const decoded = codecs::decode(test::be16, "0a1f"); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().value, 0x0a1fU); + auto const wrong_length = codecs::decode(test::be16, std::string{"0a1"}); + BOOST_TEST(wrong_length.error() == codecs::error::invalid_length); + auto const wrong_digit = codecs::decode(test::be16, std::string_view{"0a1g"}); + BOOST_TEST(wrong_digit.error() == codecs::error::invalid_character); +} + +void the_round_trip() { + auto const encoded = codecs::encode(test::be16, test::number{0xa1b2}); + BOOST_TEST(encoded.has_value()); + auto const decoded = codecs::decode(test::be16, encoded.value()); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(decoded.value() == test::number{0xa1b2}); +} + +} // namespace + +int main() { + the_size_is_the_value_codecs(); + the_buffer_form_of_bytes(); + the_buffer_form_of_text(); + the_default_results(); + a_value_of_text_decodes_from_text(); + the_round_trip(); + return boost::report_errors(); +} From 4201fb35e45b9f843ed11c5b7f26baea91465614 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 09:30:48 -0300 Subject: [PATCH 010/157] codecs: the fixed results and typed decode lint fix --- .../webcpp/codecs/detail/core/operations.hpp | 18 ++++++++++++------ include/webcpp/codecs/detail/core/results.hpp | 15 ++++++++------- test/Jamfile | 5 +++-- test/allocation_test.cpp | 4 +--- test/default_result_test.cpp | 5 +++-- test/support/be16.hpp | 3 ++- test/value_codec_test.cpp | 3 ++- 7 files changed, 31 insertions(+), 22 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 324f7c3..8ed3403 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -76,7 +76,7 @@ constexpr auto default_encode_type() noexcept { /** The type `encode` returns for `Input` in `F`, without a token. */ template -using default_encode_result = typename decltype(default_encode_type())::type; +using default_encode_result = decltype(default_encode_type())::type; /** The type `decode` returns, without a token, for the text `Text` in `F` (D9): `bytes` when the @@ -93,7 +93,7 @@ constexpr auto default_decode_type() noexcept { /** The type `decode` returns for the text `Text` in `F`, without a token. */ template -using default_decode_result = typename decltype(default_decode_type())::type; +using default_decode_result = decltype(default_decode_type())::type; /** Whether `T` is a `std::array` of `std::uint8_t`. */ template @@ -123,18 +123,24 @@ template [[nodiscard]] result encode_as(F const& format_value, Input const& input_value) noexcept(is_fixed_result) { std::size_t output_size = 0; - [[maybe_unused]] std::span input_view; + std::span const input_view = [&] { + if constexpr (value_encodable) { + return std::span{}; + } else { + return input_bytes(input_value); + } + }(); + std::size_t output_size = 0; if constexpr (value_encodable) { output_size = value_codec::encoded_size(format_value, input_value); } else { - input_view = input_bytes(input_value); if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; } output_size = codec::encoded_size(format_value, input_view); } Result output_value{}; - auto output_span = [&] { + auto const output_span = [&] { if constexpr (is_fixed_result) { return fixed_access::writable(output_value).first(output_size); } else { @@ -195,7 +201,7 @@ template } output_span = fixed_byte_storage::writable(target_value); } else if constexpr (is_byte_array) { - if (byte_count != std::tuple_size::value) { + if (byte_count != std::tuple_size_v) { return error::invalid_length; } output_span = std::span{target_value}; diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp index 90d1fa3..8d4f3bd 100644 --- a/include/webcpp/codecs/detail/core/results.hpp +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -63,14 +63,15 @@ class text { } /** Deleted on an rvalue: the view would dangle. */ - std::string_view view() const&& = delete; + [[nodiscard]] std::string_view view() const&& = delete; - /** The first `size()` characters, valid while this text is; an lvalue only. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): implicit by design - // (B8) + /** The first `size()` characters, valid while this text is; an lvalue only, and implicit (B8). + */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) constexpr operator std::string_view() const& noexcept { return view(); } /** Deleted on an rvalue: the view would dangle. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) operator std::string_view() const&& = delete; /** Whether two texts hold the same characters. */ @@ -116,14 +117,14 @@ class bytes { } /** Deleted on an rvalue: the view would dangle. */ - std::span view() const&& = delete; + [[nodiscard]] std::span view() const&& = delete; /** The first `size()` bytes, valid while these bytes are; an lvalue only. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): implicit by design - // (B8) + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) constexpr operator std::span() const& noexcept { return view(); } /** Deleted on an rvalue: the view would dangle. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) operator std::span() const&& = delete; /** Whether two values hold the same bytes. */ diff --git a/test/Jamfile b/test/Jamfile index 0fd9dd3..a0f9c62 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -46,11 +46,12 @@ codecs-run error : error_test.cpp ; codecs-run contract : contract_test.cpp ; # The sizes and the buffer forms: B23's order, nothing written on an error. codecs-run sizes : sizes_test.cpp ; -# The fixed results text and bytes: regular, by content, a view of an lvalue only. +# The fixed results text and bytes: regular, by content, the view of +# an lvalue only. codecs-run results : results_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; -# The typed decode into fixed byte types, the heap, and a value of a value codec. +# The typed decode into fixed byte types, the heap and a value codec's value. codecs-run typed_decode : typed_decode_test.cpp ; # Value codecs: the concepts, the default result, the buffer forms. codecs-run value_codec : value_codec_test.cpp ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index cba8630..4906ff3 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -219,7 +219,6 @@ void check_buffer_forms() { void check_fixed_results() { std::array const wide_input{}; std::array const input{0x01, 0xff}; - std::array output{}; std::array output_bytes{}; std::size_t volatile sink = 0; bool volatile verdict = false; @@ -230,7 +229,7 @@ void check_fixed_results() { }); BOOST_TEST(verdict); expect_no_allocation("the fixed results", [&] { - codecs::text<8> first_text; + codecs::text<8> const first_text; codecs::text<8> const second_text = first_text; codecs::bytes<4> const first_bytes; verdict = first_text == second_text && first_bytes == codecs::bytes<4>{} && @@ -279,7 +278,6 @@ void check_fixed_results() { codecs::decode(test::be16, std::array{}).has_value(); }); BOOST_TEST(!verdict); - static_cast(output); static_cast(sink); } diff --git a/test/default_result_test.cpp b/test/default_result_test.cpp index 893f9af..dadb8ad 100644 --- a/test/default_result_test.cpp +++ b/test/default_result_test.cpp @@ -94,8 +94,9 @@ void encodes_to_a_fixed_text() { auto const array_text = codecs::encode(test::letters, input_bytes); BOOST_TEST(array_text.has_value()); BOOST_TEST_EQ(array_text.value().size(), 64U); - BOOST_TEST(array_text.value().view().starts_with("ab")); - BOOST_TEST(array_text.value().view().ends_with("pp")); + std::string_view const array_view = array_text.value().view(); + BOOST_TEST(array_view.starts_with("ab")); + BOOST_TEST(array_view.ends_with("pp")); auto const span_text = codecs::encode(test::letters, std::span{input_bytes}); BOOST_TEST(span_text.has_value()); diff --git a/test/support/be16.hpp b/test/support/be16.hpp index 61b5682..cecdc85 100644 --- a/test/support/be16.hpp +++ b/test/support/be16.hpp @@ -74,7 +74,8 @@ struct value_codec { if (input_bytes.size() != 2) { return error::invalid_length; } - return test::number{static_cast((input_bytes[0] << 8U) | input_bytes[1])}; + return test::number{static_cast( + (static_cast(input_bytes[0]) << 8U) | input_bytes[1])}; } }; diff --git a/test/value_codec_test.cpp b/test/value_codec_test.cpp index 1878923..5c2bf94 100644 --- a/test/value_codec_test.cpp +++ b/test/value_codec_test.cpp @@ -84,7 +84,8 @@ struct value_codec { std::span output_characters) noexcept { constexpr std::string_view digits = "0123456789abcdef"; for (std::size_t index = 0; index < 4; ++index) { - output_characters[index] = digits[(held_value.value >> (12U - (4U * index))) & 15U]; + output_characters[index] = + digits[(static_cast(held_value.value) >> (12U - (4U * index))) & 15U]; } return std::size_t{4}; } From eb6a7ea0aaaf6d6cc3b382e8e70ad2253a2190af Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 09:35:54 -0300 Subject: [PATCH 011/157] codecs: the fixed results and typed decode lint fix, the duplicate size removed --- include/webcpp/codecs/detail/core/operations.hpp | 1 - 1 file changed, 1 deletion(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 8ed3403..43e933f 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -122,7 +122,6 @@ inline constexpr bool typed_decode_is_fixed = template [[nodiscard]] result encode_as(F const& format_value, Input const& input_value) noexcept(is_fixed_result) { - std::size_t output_size = 0; std::span const input_view = [&] { if constexpr (value_encodable) { return std::span{}; From 42afea08ce4281c3b1bafb2ea72514740f0a8b03 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 09:50:45 -0300 Subject: [PATCH 012/157] codecs: the fixed results lint fix, the conversions' suppressions and be16's decode --- include/webcpp/codecs/detail/core/results.hpp | 13 ++++++------- test/support/be16.hpp | 4 ++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp index 8d4f3bd..286991b 100644 --- a/include/webcpp/codecs/detail/core/results.hpp +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -65,13 +65,12 @@ class text { /** Deleted on an rvalue: the view would dangle. */ [[nodiscard]] std::string_view view() const&& = delete; - /** The first `size()` characters, valid while this text is; an lvalue only, and implicit (B8). - */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) + /** The first `size()` characters; implicit, on an lvalue only (B8). */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::string_view() const& noexcept { return view(); } /** Deleted on an rvalue: the view would dangle. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) operator std::string_view() const&& = delete; /** Whether two texts hold the same characters. */ @@ -119,12 +118,12 @@ class bytes { /** Deleted on an rvalue: the view would dangle. */ [[nodiscard]] std::span view() const&& = delete; - /** The first `size()` bytes, valid while these bytes are; an lvalue only. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) + /** The first `size()` bytes; implicit, on an lvalue only (B8). */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::span() const& noexcept { return view(); } /** Deleted on an rvalue: the view would dangle. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions) + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) operator std::span() const&& = delete; /** Whether two values hold the same bytes. */ diff --git a/test/support/be16.hpp b/test/support/be16.hpp index cecdc85..53022ce 100644 --- a/test/support/be16.hpp +++ b/test/support/be16.hpp @@ -74,8 +74,8 @@ struct value_codec { if (input_bytes.size() != 2) { return error::invalid_length; } - return test::number{static_cast( - (static_cast(input_bytes[0]) << 8U) | input_bytes[1])}; + unsigned const bits = (static_cast(input_bytes[0]) << 8U) | input_bytes[1]; + return test::number{static_cast(bits)}; } }; From 071996476448bfb146eef0fc3c1b6aad1b4c00a4 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 10:14:13 -0300 Subject: [PATCH 013/157] codecs: Task 3's review fixes: heap results hold what was written, the input refusal names the input, the typed decode's noexcept follows the value codec, saturating bounds of static inputs, the text buffer form's rows --- .../webcpp/codecs/detail/core/contract.hpp | 10 +- .../webcpp/codecs/detail/core/operations.hpp | 62 +++++++++--- include/webcpp/codecs/detail/core/results.hpp | 4 +- test/allocation_test.cpp | 52 ++++++++++ test/default_result_test.cpp | 75 +++++++++++++++ test/messages/Jamfile | 1 + test/messages/refused_input/Jamfile | 16 ++++ test/messages/refused_input/refused_input.cpp | 37 ++++++++ test/noexcept_test.cpp | 3 + test/support/be16.hpp | 58 ++++++++++- test/support/shrinking.hpp | 95 +++++++++++++++++++ test/typed_decode_test.cpp | 80 ++++++++++++++++ test/value_codec_test.cpp | 76 +++------------ 13 files changed, 487 insertions(+), 82 deletions(-) create mode 100644 test/messages/refused_input/Jamfile create mode 100644 test/messages/refused_input/refused_input.cpp create mode 100644 test/support/shrinking.hpp diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index fce32df..eec28ab 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -329,8 +329,9 @@ concept value_decodable = requires { specialized, or `value_codec` is specialized with `encode` and `encoded_size`. A byte input is a contiguous sized range of `std::uint8_t`, `unsigned char`, `char` or - `std::byte`, or a type with a static constexpr `size()` that converts to - `std::span`, as `secure::secret`. + `std::byte`, a type with a static constexpr `size()` that converts to + `std::span`, as `secure::secret`, or a fixed result (`text`, + `bytes`), which is read through its `view()`. @tparam V The value's type. @tparam F The format's type. @@ -341,8 +342,9 @@ concept encodable = /** Whether a value of type `V` decodes from the format `F`: `V` is a byte result the core builds - (`std::string`, `std::vector`, `std::array`) and `codec` is - specialized, or `value_codec` is specialized with `decode`. + (`std::string`, `std::vector`, `std::array`, `bytes`, or a + library's fixed type with a `fixed_byte_storage`) and `codec` is specialized, or + `value_codec` is specialized with `decode`. @tparam V The value's type. @tparam F The format's type. diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 43e933f..95f5873 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -68,7 +69,13 @@ constexpr auto default_encode_type() noexcept { } } else if constexpr (byte_input && has_codec && static_input_size_v != std::dynamic_extent) { - return std::type_identity::max_encoded_size(static_input_size_v)>>{}; + constexpr std::size_t bound = codec::max_encoded_size(static_input_size_v); + // A bound that saturates is no size to hold in place: the run-time path refuses the input. + if constexpr (bound != std::numeric_limits::max()) { + return std::type_identity>{}; + } else { + return std::type_identity{}; + } } else { return std::type_identity{}; } @@ -85,7 +92,13 @@ using default_encode_result = decltype(default_encode_type())::type; template constexpr auto default_decode_type() noexcept { if constexpr (has_codec && static_input_size_v != std::dynamic_extent) { - return std::type_identity::max_decoded_size(static_input_size_v)>>{}; + constexpr std::size_t bound = codec::max_decoded_size(static_input_size_v); + // A bound that saturates is no size to hold in place: the run-time path refuses the text. + if constexpr (bound != std::numeric_limits::max()) { + return std::type_identity>{}; + } else { + return std::type_identity>{}; + } } else { return std::type_identity>{}; } @@ -108,10 +121,20 @@ template inline constexpr bool decode_is_fixed = is_fixed_result || fixed_target || is_byte_array; -/** Whether a typed decode into `Value` allocates nothing and cannot throw. */ +/** + Whether a typed decode into `Value` in `F` cannot throw: a value codec's decode is `noexcept` as + the value codec declares it, so that an allocating value codec's exception propagates (owner + decision 24); a byte result is when it holds its bytes in place. +*/ template -inline constexpr bool typed_decode_is_fixed = - value_decodable || (has_codec && decode_is_fixed); +constexpr bool typed_decode_is_noexcept() noexcept { + if constexpr (value_decodable) { + return noexcept(value_codec::decode(std::declval(), + std::declval>())); + } else { + return has_codec && decode_is_fixed; + } +} /** Encodes into a `Result`, which `encode` picked for the pair (D9): the exact size is asked, the @@ -161,8 +184,11 @@ template if (!written_size) { return written_size.error(); } + // Read unchecked: the error was returned above. if constexpr (is_fixed_result) { fixed_access::resize(output_value, written_size.unsafe_value()); + } else { + output_value.resize(written_size.unsafe_value()); } return output_value; } @@ -217,6 +243,8 @@ template } if constexpr (is_fixed_result) { fixed_access::resize(target_value, written_count.unsafe_value()); + } else if constexpr (!fixed_target && !is_byte_array) { + target_value.resize(written_count.unsafe_value()); } return target_value; } @@ -346,9 +374,11 @@ template a format with a `codec`: a `std::array`, which takes exactly `N` bytes, or a type of `fixed_byte_storage`, which takes exactly its size (@ref error::invalid_length otherwise); a `bytes`, which takes up to `N` bytes (@ref error::output_too_small otherwise); - a `std::string` or a `std::vector`, which take the heap. It is `noexcept` for every - one of these but the last two, which allocate. A pair `F` does not convert stops the build with a - message that the format does not convert this type. + a `std::string` or a `std::vector`, which take the heap. It is `noexcept` for the + fixed byte results, and for a value codec as the value codec's `decode` is declared; the heap + types allocate and are not. A pair `F` does not convert stops the build with a message that the + format does not convert this type, and an input the pair does not read (a byte input given to a + decode of text, a value codec of bytes given a text) with one that names the input's type. @tparam Value The type to decode into. @tparam F The format's type. @@ -359,7 +389,7 @@ template */ template [[nodiscard]] result decode(F const& format_value, Input const& input_value) noexcept( - detail::typed_decode_is_fixed) { + detail::typed_decode_is_noexcept()) { if constexpr (detail::value_decodable) { using value_type = value_codec; if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { @@ -367,12 +397,18 @@ template } else if constexpr (value_type::output == output_kind::text && detail::text_input) { return value_type::decode(format_value, detail::text_view(input_value)); } else { - detail::refuse(); + // The pair converts; this input is not what the value codec reads. + detail::refuse(); + return make_error_code(error::invalid_length); + } + } else if constexpr (detail::byte_result && detail::has_codec) { + if constexpr (detail::text_input) { + return detail::decode_as(format_value, input_value); + } else { + // The pair converts; this input is not a text. + detail::refuse(); return make_error_code(error::invalid_length); } - } else if constexpr (detail::byte_result && detail::has_codec && - detail::text_input) { - return detail::decode_as(format_value, input_value); } else { detail::refuse(); return make_error_code(error::invalid_length); diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp index 286991b..737e492 100644 --- a/include/webcpp/codecs/detail/core/results.hpp +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -6,8 +6,8 @@ /** The fixed results of webcpp::codecs: `text` and `bytes`, which hold their elements in - place, and the specialization point `fixed_byte_storage` that lets a library's fixed type be the - target of a typed decode. + place and are inputs too. The specialization point `fixed_byte_storage`, which lets a library's + fixed type be the target of a typed decode, is declared in contract.hpp. */ #ifndef WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP #define WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 4906ff3..9ec050a 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -278,9 +279,59 @@ void check_fixed_results() { codecs::decode(test::be16, std::array{}).has_value(); }); BOOST_TEST(!verdict); + // The buffer form of a value codec of text (F16): characters, nothing allocated. + std::array output_characters{}; + expect_no_allocation("a value codec of text's buffer form", [&] { + verdict = + codecs::encode(test::be16, test::hex_number{0x1234}, output_characters).has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("a value codec of text's refused buffer", [&] { + verdict = codecs::encode(test::be16, test::hex_number{0x1234}, + std::span{output_characters}.first(3)) + .has_value(); + }); + BOOST_TEST(!verdict); static_cast(sink); } +/** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they + allocate anything: the heap results are never built. */ +void check_saturating_refusals() { + std::vector const long_bytes(test::saturating_t::most_bytes + 1); + std::string const long_text(test::saturating_t::most_characters + 1, 'a'); + std::array const long_array{}; + std::array long_characters{}; + long_characters.fill('a'); + bool volatile verdict = true; + expect_no_allocation("default encode of an input whose bound saturates", [&] { + verdict = codecs::encode(test::saturating, long_bytes).has_value() || + codecs::encode(test::saturating, long_array).has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("default decode of a text whose bound saturates", [&] { + verdict = codecs::decode(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_characters).has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("typed decode of a text whose bound saturates", [&] { + verdict = + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_text).has_value() || + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_text).has_value(); + }); + BOOST_TEST(!verdict); + // The refusals are input_too_long, so that none of the format's own functions ran. + BOOST_TEST(codecs::encode(test::saturating, long_bytes).error() == + codecs::error::input_too_long); + BOOST_TEST(codecs::decode(test::saturating, long_text).error() == + codecs::error::input_too_long); + BOOST_TEST(codecs::decode(test::saturating, long_text).error() == + codecs::error::input_too_long); +} + } // namespace int main() { @@ -288,5 +339,6 @@ int main() { control_counts_every_form(); check_buffer_forms(); check_fixed_results(); + check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/default_result_test.cpp b/test/default_result_test.cpp index dadb8ad..d9f8fff 100644 --- a/test/default_result_test.cpp +++ b/test/default_result_test.cpp @@ -10,6 +10,8 @@ #include "support/be16.hpp" #include "support/letters.hpp" +#include "support/saturating.hpp" +#include "support/shrinking.hpp" #include #include @@ -83,6 +85,17 @@ static_assert(returns>, static_assert(returns>, decltype(codecs::decode(test::letters, "abpp"))>); +// An empty input of static size: text<0>; a bound that saturates is not a size held in place. +static_assert(returns>, + decltype(codecs::encode( + test::letters, std::declval const&>()))>); +static_assert(returns, + decltype(codecs::encode( + test::saturating, std::declval const&>()))>); +static_assert(returns>, + decltype(codecs::decode(test::saturating, + std::declval const&>()))>); + // A typed value whose value codec states a bound: bytes<2>. static_assert(returns>, decltype(codecs::encode(test::be16, std::declval()))>); @@ -157,6 +170,65 @@ void decodes_to_the_heap() { BOOST_TEST(from_literal.value() == expected); } +void empty_inputs_give_empty_results() { + auto const empty_fixed_text = codecs::encode(test::letters, std::array{}); + BOOST_TEST(empty_fixed_text.has_value()); + BOOST_TEST_EQ(empty_fixed_text.value().size(), 0U); + BOOST_TEST(empty_fixed_text.value().view().empty()); + auto const empty_heap_bytes = codecs::decode(test::letters, ""); + BOOST_TEST(empty_heap_bytes.has_value()); + BOOST_TEST(empty_heap_bytes.value().empty()); + auto const empty_string_bytes = codecs::decode(test::letters, std::string{}); + BOOST_TEST(empty_string_bytes.has_value()); + BOOST_TEST(empty_string_bytes.value().empty()); +} + +void an_input_whose_bound_saturates_is_too_long() { + // The format's bound saturates past 4 bytes and 8 characters; its functions, which write `!` + // and report checksum_mismatch, are never reached. + auto const heap_input = codecs::encode( + test::saturating, std::vector(test::saturating_t::most_bytes + 1)); + BOOST_TEST(!heap_input.has_value()); + BOOST_TEST(heap_input.error() == codecs::error::input_too_long); + auto const static_input = codecs::encode( + test::saturating, std::array{}); + BOOST_TEST(!static_input.has_value()); + BOOST_TEST(static_input.error() == codecs::error::input_too_long); + std::string const long_string(test::saturating_t::most_characters + 1, 'a'); + auto const heap_text = codecs::decode(test::saturating, long_string); + BOOST_TEST(!heap_text.has_value()); + BOOST_TEST(heap_text.error() == codecs::error::input_too_long); + auto const static_text = codecs::decode( + test::saturating, std::array{}); + BOOST_TEST(!static_text.has_value()); + BOOST_TEST(static_text.error() == codecs::error::input_too_long); + // Up to the bound the format's own functions run. + auto const at_bound = + codecs::encode(test::saturating, std::vector(test::saturating_t::most_bytes)); + BOOST_TEST(at_bound.error() == codecs::error::checksum_mismatch); +} + +void a_heap_result_holds_what_was_written() { + // shrinking asks for one element more than it writes: every result holds the written count, + // the fixed ones and the heap ones. + std::vector const heap_bytes{0x01, 0xff}; + auto const heap_text = codecs::encode(test::shrinking, heap_bytes); + BOOST_TEST(heap_text.has_value()); + BOOST_TEST_EQ(heap_text.value().size(), 4U); + BOOST_TEST(heap_text.value() == "abpp"); + auto const fixed_text = + codecs::encode(test::shrinking, std::array{0x01, 0xff}); + BOOST_TEST(fixed_text.has_value()); + BOOST_TEST_EQ(fixed_text.value().size(), 4U); + BOOST_TEST(fixed_text.value().view() == "abpp"); + auto const heap_decoded = codecs::decode(test::shrinking, std::string{"abpp"}); + BOOST_TEST(heap_decoded.has_value()); + BOOST_TEST((heap_decoded.value() == heap_bytes)); + auto const fixed_decoded = codecs::decode(test::shrinking, codecs::text<4>{}); + BOOST_TEST(fixed_decoded.has_value()); + BOOST_TEST_EQ(fixed_decoded.value().size(), 0U); +} + void the_errors_reach_the_caller() { auto const odd = codecs::decode(test::letters, std::string{"abp"}); BOOST_TEST(!odd.has_value()); @@ -178,6 +250,9 @@ int main() { encodes_a_typed_value(); a_fixed_text_round_trips_with_no_heap(); decodes_to_the_heap(); + empty_inputs_give_empty_results(); + an_input_whose_bound_saturates_is_too_long(); + a_heap_result_holds_what_was_written(); the_errors_reach_the_caller(); return boost::report_errors(); } diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 926b0bb..1f18f42 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -17,3 +17,4 @@ build-project refused_decode ; build-project refused_pair ; build-project refused_encode ; build-project refused_encode_only ; +build-project refused_input ; diff --git a/test/messages/refused_input/Jamfile b/test/messages/refused_input/Jamfile new file mode 100644 index 0000000..00b5b9a --- /dev/null +++ b/test/messages/refused_input/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_input : refused_input.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_input_refused : refused_input.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_input/refused_input.cpp b/test/messages/refused_input/refused_input.cpp new file mode 100644 index 0000000..7bed671 --- /dev/null +++ b/test/messages/refused_input/refused_input.cpp @@ -0,0 +1,37 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A typed decode of a pair that converts, given an input the pair does not read, stops in the +// core's refusal, whose requirement names the input's type and the format's type (ruling R2): a +// type that is no text given to a decode into bytes, and a type that is no byte input given to a +// value codec of bytes. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/be16.hpp" +#include "../../support/letters.hpp" + +#include + +#include +#include + +/** A type that is neither a text nor a byte input. */ +struct not_an_input {}; + +int main() { + namespace codecs = webcpp::codecs; + auto const bytes_decoded = + codecs::decode>(codecs::test::letters, not_an_input{}); + auto const value_decoded = + codecs::decode(codecs::test::be16, not_an_input{}); + return bytes_decoded.has_value() || value_decoded.has_value() ? 1 : 0; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index d3f66b2..0906345 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -55,5 +55,8 @@ static_assert(!noexcept(codecs::decode(test::letters, "ab"))); static_assert(!noexcept(codecs::decode>(test::letters, "ab"))); // The buffer forms of a value codec. static_assert(noexcept(codecs::encode(test::be16, test::number{}, std::span{}))); +static_assert(noexcept(codecs::encode(test::be16, test::hex_number{}, std::span{}))); +// The default result of a value codec of text with no stated bound is the heap. +static_assert(!noexcept(codecs::encode(test::be16, test::hex_number{}))); } // namespace diff --git a/test/support/be16.hpp b/test/support/be16.hpp index 53022ce..ffbb4ff 100644 --- a/test/support/be16.hpp +++ b/test/support/be16.hpp @@ -6,7 +6,8 @@ // be16, a format of the tests' own for a typed value: a `number` is written as two bytes, big // endian, by a value codec of bytes that states its bound, so that the default result is a fixed -// one. Decoding any other length is invalid_length. +// one. Decoding any other length is invalid_length. A `hex_number` is written as four hexadecimal +// digits by a value codec of text that states no bound, so that the default result is a string. #ifndef WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP #define WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP @@ -38,6 +39,15 @@ struct number { bool operator==(number const&) const = default; }; +/** A value of be16 that is text: sixteen bits, as four lowercase hexadecimal digits. */ +struct hex_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(hex_number const&) const = default; +}; + } // namespace webcpp::codecs::test namespace webcpp::codecs { @@ -79,6 +89,52 @@ struct value_codec { } }; +/** The value codec of be16 for a `hex_number`: text with no stated bound. */ +template <> +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + + /** Four characters. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + test::hex_number const& /*held_value*/) noexcept { + return 4; + } + + /** Writes the four digits into `output_characters`, which must hold them. */ + static result encode(test::be16_t const& /*format*/, + test::hex_number const& held_value, + std::span output_characters) noexcept { + if (output_characters.size() < 4) { + return error::output_too_small; + } + constexpr std::string_view digits = "0123456789abcdef"; + for (std::size_t index = 0; index < 4; ++index) { + output_characters[index] = + digits[(static_cast(held_value.value) >> (12U - (4U * index))) & 15U]; + } + return std::size_t{4}; + } + + /** Reads four digits: another length is invalid_length, another character invalid_character. */ + static result decode(test::be16_t const& /*format*/, + std::string_view text_value) noexcept { + if (text_value.size() != 4) { + return error::invalid_length; + } + unsigned bits = 0; + constexpr std::string_view digits = "0123456789abcdef"; + for (char const digit : text_value) { + auto const position = digits.find(digit); + if (position == std::string_view::npos) { + return error::invalid_character; + } + bits = (bits << 4U) | static_cast(position); + } + return test::hex_number{static_cast(bits)}; + } +}; + } // namespace webcpp::codecs #endif // WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP diff --git a/test/support/shrinking.hpp b/test/support/shrinking.hpp new file mode 100644 index 0000000..b4d5e2f --- /dev/null +++ b/test/support/shrinking.hpp @@ -0,0 +1,95 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// shrinking, a format of the tests' own that breaks the contract's exactness on purpose: its +// `encoded_size` and `decoded_size` report one more than its `encode` and `decode` write (and +// return), so that a test sees that a result holds the count the format wrote, not the size it was +// asked for. Its bytes are letters', two letters a byte, `a` to `p`. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_SHRINKING_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_SHRINKING_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The type of the format shrinking. */ +struct shrinking_t { + /** The format's name. */ + static constexpr std::string_view name = "shrinking"; +}; + +/** The format shrinking. */ +inline constexpr shrinking_t shrinking{}; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The codec of shrinking: sizes one past what the functions write. */ +template <> +struct codec { + /** Not constant time. */ + static constexpr bool constant_time = false; + + /** Two letters a byte, and one more. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return detail::saturating_add(detail::saturating_multiply(input_size, 2), 1); + } + + /** One byte every two letters, and one more. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return detail::saturating_add(text_size / 2, 1); + } + + /** The bound itself: one more than `encode` writes. */ + static constexpr std::size_t encoded_size(test::shrinking_t const& /*format*/, + std::span input_bytes) noexcept { + return max_encoded_size(input_bytes.size()); + } + + /** One more than `decode` writes; the text is not checked. */ + static result decoded_size(test::shrinking_t const& /*format*/, + std::string_view text_characters) noexcept { + return max_decoded_size(text_characters.size()); + } + + /** Writes two letters a byte, returns that count. */ + static result encode(test::shrinking_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + std::size_t character_index = 0; + for (std::uint8_t const input_byte : input_bytes) { + output_characters[character_index] = static_cast('a' + (input_byte >> 4U)); + output_characters[character_index + 1] = static_cast('a' + (input_byte & 15U)); + character_index += 2; + } + return character_index; + } + + /** Writes a byte every two letters, returns that count. */ + static result decode(test::shrinking_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + std::size_t const byte_count = text_characters.size() / 2; + for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) { + auto const high_half = static_cast(text_characters[2 * byte_index] - 'a'); + auto const low_half = + static_cast(text_characters[(2 * byte_index) + 1] - 'a'); + output_bytes[byte_index] = static_cast((high_half << 4U) | low_half); + } + return byte_count; + } +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_TEST_SUPPORT_SHRINKING_HPP diff --git a/test/typed_decode_test.cpp b/test/typed_decode_test.cpp index b4a3e9a..657e3f8 100644 --- a/test/typed_decode_test.cpp +++ b/test/typed_decode_test.cpp @@ -9,6 +9,8 @@ #include "support/be16.hpp" #include "support/letters.hpp" +#include "support/saturating.hpp" +#include "support/shrinking.hpp" #include @@ -18,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +31,12 @@ namespace { namespace codecs = webcpp::codecs; namespace test = webcpp::codecs::test; +/** A value whose value codec allocates: its decode is not `noexcept`. */ +struct heap_number { + /** The bits. */ + std::uint16_t value; +}; + /** A library's fixed type of sixteen bytes. */ struct key16 { /** The bytes. */ @@ -38,6 +47,30 @@ struct key16 { namespace webcpp::codecs { +/** A value codec whose decode may throw, as one that allocates does. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Reads two bytes, big endian; the byte 0xff stands for an allocation that fails. */ + static result decode(test::be16_t const& /*format*/, + std::span input_bytes) { + if (input_bytes.size() != 2) { + return error::invalid_length; + } + if (input_bytes[0] == 0xff) { +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + throw std::bad_alloc(); +#else + return error::invalid_length; +#endif + } + unsigned const bits = (static_cast(input_bytes[0]) << 8U) | input_bytes[1]; + return heap_number{static_cast(bits)}; + } +}; + /** key16 is a decode's target of exactly sixteen bytes. */ template <> struct fixed_byte_storage { @@ -69,6 +102,9 @@ static_assert(noexcept(codecs::decode>(test::letters, "ab"))); static_assert(noexcept(codecs::decode(test::letters, "ab"))); static_assert(noexcept(codecs::decode(test::be16, std::array{}))); static_assert(!noexcept(codecs::decode(test::letters, "ab"))); +// A value codec's decode is as noexcept as the value codec declares it: an allocating one is not. +static_assert(codecs::decodable); +static_assert(!noexcept(codecs::decode(test::be16, std::array{}))); static_assert(!noexcept(codecs::decode>(test::letters, "ab"))); void into_an_array() { @@ -151,6 +187,23 @@ void into_a_value() { BOOST_TEST(one.error() == codecs::error::invalid_length); } +void a_value_codecs_exception_propagates() { + auto const decoded = + codecs::decode(test::be16, std::array{0x12, 0x34}); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().value, 0x1234U); +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + bool thrown = false; + try { + BOOST_TEST(!codecs::decode(test::be16, std::array{0xff, 0}) + .has_value()); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST(thrown); +#endif +} + void into_the_heap() { auto const text_value = codecs::decode(test::letters, "abpp"); BOOST_TEST(text_value.has_value()); @@ -163,6 +216,31 @@ void into_the_heap() { BOOST_TEST(codecs::decode(test::letters, "ab!").error() == codecs::error::invalid_character); BOOST_TEST(codecs::decode(test::letters, "").value().empty()); + BOOST_TEST(codecs::decode>(test::letters, "").value().empty()); + // A heap result holds what the format wrote, not the size it was asked for. + auto const shrunk = codecs::decode>(test::shrinking, "abpp"); + BOOST_TEST(shrunk.has_value()); + BOOST_TEST((shrunk.value() == std::vector{0x01, 0xff})); + auto const shrunk_string = codecs::decode(test::shrinking, "abpp"); + BOOST_TEST(shrunk_string.has_value()); + BOOST_TEST_EQ(shrunk_string.value().size(), 2U); +} + +void an_input_whose_bound_saturates_is_too_long() { + // Past 8 characters the format's bound saturates: every typed decode refuses before it reads. + std::string const long_text(test::saturating_t::most_characters + 1, 'a'); + auto const refused_vector = + codecs::decode>(test::saturating, long_text); + BOOST_TEST(refused_vector.error() == codecs::error::input_too_long); + auto const refused_string = codecs::decode(test::saturating, long_text); + BOOST_TEST(refused_string.error() == codecs::error::input_too_long); + auto const refused_array = + codecs::decode>(test::saturating, long_text); + BOOST_TEST(refused_array.error() == codecs::error::input_too_long); + auto const refused_bytes = codecs::decode>(test::saturating, long_text); + BOOST_TEST(refused_bytes.error() == codecs::error::input_too_long); + auto const refused_key = codecs::decode(test::saturating, long_text); + BOOST_TEST(refused_key.error() == codecs::error::input_too_long); } } // namespace @@ -172,6 +250,8 @@ int main() { into_fixed_bytes(); into_a_library_type(); into_a_value(); + a_value_codecs_exception_propagates(); into_the_heap(); + an_input_whose_bound_saturates_is_too_long(); return boost::report_errors(); } diff --git a/test/value_codec_test.cpp b/test/value_codec_test.cpp index 5c2bf94..625d527 100644 --- a/test/value_codec_test.cpp +++ b/test/value_codec_test.cpp @@ -35,12 +35,6 @@ struct encode_only_number { std::uint16_t value; }; -/** A value of text with no stated bound, in be16: its four hexadecimal digits. */ -struct hex_number { - /** The bits. */ - std::uint16_t value; -}; - } // namespace namespace webcpp::codecs { @@ -67,48 +61,6 @@ struct value_codec { } }; -/** A value codec of text, with no stated bound. */ -template <> -struct value_codec { - /** Text. */ - static constexpr output_kind output = output_kind::text; - - /** Four characters. */ - static std::size_t encoded_size(test::be16_t const& /*format*/, - hex_number const& /*held_value*/) noexcept { - return 4; - } - - /** Writes the four digits. */ - static result encode(test::be16_t const& /*format*/, hex_number const& held_value, - std::span output_characters) noexcept { - constexpr std::string_view digits = "0123456789abcdef"; - for (std::size_t index = 0; index < 4; ++index) { - output_characters[index] = - digits[(static_cast(held_value.value) >> (12U - (4U * index))) & 15U]; - } - return std::size_t{4}; - } - - /** Reads four digits. */ - static result decode(test::be16_t const& /*format*/, - std::string_view text_value) noexcept { - if (text_value.size() != 4) { - return error::invalid_length; - } - unsigned bits = 0; - constexpr std::string_view digits = "0123456789abcdef"; - for (char const digit : text_value) { - auto const position = digits.find(digit); - if (position == std::string_view::npos) { - return error::invalid_character; - } - bits = (bits << 4U) | static_cast(position); - } - return hex_number{static_cast(bits)}; - } -}; - } // namespace webcpp::codecs namespace { @@ -122,35 +74,35 @@ static_assert(!codecs::decodable); static_assert(!codecs::encodable); static_assert(!codecs::decodable); // Text: decode only reads text, encode writes text. -static_assert(codecs::encodable); -static_assert(codecs::decodable); +static_assert(codecs::encodable); +static_assert(codecs::decodable); // The default result: a stated bound is a fixed result; none is the heap. static_assert(std::is_same_v>>); static_assert(std::is_same_v>>); -static_assert(std::is_same_v>); static_assert(noexcept(codecs::encode(test::be16, test::number{}))); static_assert(!noexcept(codecs::encode(test::be16, encode_only_number{}))); -static_assert(!noexcept(codecs::encode(test::be16, hex_number{}))); +static_assert(!noexcept(codecs::encode(test::be16, test::hex_number{}))); // The buffer forms: bytes for a value codec of bytes, characters for one of text; noexcept. static_assert(noexcept(codecs::encode(test::be16, test::number{}, std::span{}))); -static_assert(noexcept(codecs::encode(test::be16, hex_number{}, std::span{}))); +static_assert(noexcept(codecs::encode(test::be16, test::hex_number{}, std::span{}))); template concept encodes_into = requires(Value held_value, Buffer output_buffer) { codecs::encode(test::be16, held_value, output_buffer); }; static_assert(encodes_into>); static_assert(!encodes_into>); -static_assert(encodes_into>); -static_assert(!encodes_into>); +static_assert(encodes_into>); +static_assert(!encodes_into>); void the_size_is_the_value_codecs() { BOOST_TEST_EQ(codecs::encoded_size(test::be16, test::number{}), 2U); - BOOST_TEST_EQ(codecs::encoded_size(test::be16, hex_number{}), 4U); + BOOST_TEST_EQ(codecs::encoded_size(test::be16, test::hex_number{}), 4U); } void the_buffer_form_of_bytes() { @@ -172,12 +124,12 @@ void the_buffer_form_of_bytes() { void the_buffer_form_of_text() { std::array output_characters{'-', '-', '-', '-', '-', '-'}; - auto const written = codecs::encode(test::be16, hex_number{0xbeef}, output_characters); + auto const written = codecs::encode(test::be16, test::hex_number{0xbeef}, output_characters); BOOST_TEST(written.has_value()); BOOST_TEST_EQ(written.value(), 4U); BOOST_TEST((std::string_view{output_characters.data(), 6} == "beef--")); std::array short_characters{'-', '-', '-'}; - auto const refused = codecs::encode(test::be16, hex_number{0xbeef}, short_characters); + auto const refused = codecs::encode(test::be16, test::hex_number{0xbeef}, short_characters); BOOST_TEST(refused.error() == codecs::error::output_too_small); BOOST_TEST((std::string_view{short_characters.data(), 3} == "---")); } @@ -189,18 +141,18 @@ void the_default_results() { auto const heap_bytes = codecs::encode(test::be16, encode_only_number{0x1234}); BOOST_TEST(heap_bytes.has_value()); BOOST_TEST((heap_bytes.value() == std::vector{0x12, 0x34})); - auto const heap_text = codecs::encode(test::be16, hex_number{0x0a1f}); + auto const heap_text = codecs::encode(test::be16, test::hex_number{0x0a1f}); BOOST_TEST(heap_text.has_value()); BOOST_TEST(heap_text.value() == "0a1f"); } void a_value_of_text_decodes_from_text() { - auto const decoded = codecs::decode(test::be16, "0a1f"); + auto const decoded = codecs::decode(test::be16, "0a1f"); BOOST_TEST(decoded.has_value()); BOOST_TEST_EQ(decoded.value().value, 0x0a1fU); - auto const wrong_length = codecs::decode(test::be16, std::string{"0a1"}); + auto const wrong_length = codecs::decode(test::be16, std::string{"0a1"}); BOOST_TEST(wrong_length.error() == codecs::error::invalid_length); - auto const wrong_digit = codecs::decode(test::be16, std::string_view{"0a1g"}); + auto const wrong_digit = codecs::decode(test::be16, std::string_view{"0a1g"}); BOOST_TEST(wrong_digit.error() == codecs::error::invalid_character); } From 69b97e3687abeae263d32bcb9e6f44af92d2d7a3 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 10:21:53 -0300 Subject: [PATCH 014/157] codecs: tokens, Boost.URL's and codecs' own, with allocators, the arena and the throwing allocator --- include/webcpp/codecs.hpp | 1 + .../webcpp/codecs/detail/core/operations.hpp | 305 +++++++++++++- include/webcpp/codecs/detail/core/tokens.hpp | 341 ++++++++++++++++ test/Jamfile | 14 + test/allocation_test.cpp | 42 ++ test/allocator_test.cpp | 229 +++++++++++ test/allocator_throw_test.cpp | 213 ++++++++++ test/messages/Jamfile | 2 + test/messages/refused_allocator/Jamfile | 16 + .../refused_allocator/refused_allocator.cpp | 31 ++ test/messages/refused_token/Jamfile | 16 + test/messages/refused_token/refused_token.cpp | 49 +++ test/noexcept_test.cpp | 39 ++ test/support/allocators.hpp | 205 ++++++++++ test/support/arena.hpp | 94 +++++ test/tokens_boost_url_test.cpp | 98 +++++ test/tokens_test.cpp | 383 ++++++++++++++++++ 17 files changed, 2074 insertions(+), 4 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/tokens.hpp create mode 100644 test/allocator_test.cpp create mode 100644 test/allocator_throw_test.cpp create mode 100644 test/messages/refused_allocator/Jamfile create mode 100644 test/messages/refused_allocator/refused_allocator.cpp create mode 100644 test/messages/refused_token/Jamfile create mode 100644 test/messages/refused_token/refused_token.cpp create mode 100644 test/support/allocators.hpp create mode 100644 test/support/arena.hpp create mode 100644 test/tokens_boost_url_test.cpp create mode 100644 test/tokens_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 70feb87..6353906 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -19,5 +19,6 @@ #include #include #include +#include #endif // WEBCPP_CODECS_HPP diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 95f5873..b269e2b 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -193,6 +194,32 @@ template return output_value; } +/** Whether `T` is a string or a vector of bytes, a result that takes an allocator. */ +template +struct heap_result_type : std::false_type {}; + +/** A string of `char`, whatever its traits and allocator. */ +template +struct heap_result_type> : std::true_type {}; + +/** A vector of `std::uint8_t`, whatever its allocator. */ +template +struct heap_result_type> : std::true_type {}; + +/** A byte result that lives on the heap, made with the caller's allocator or a default one. */ +template +concept heap_result = heap_result_type::value; + +/** The `Target` a decode fills, made with the caller's allocator when there is one. */ +template +[[nodiscard]] Target make_target(Allocators const&... allocator_values) { + if constexpr (sizeof...(Allocators) == 0) { + return Target{}; + } else { + return Target(allocator_values...); + } +} + /** Decodes the text into a `Target` that holds the bytes: the exact size is asked, the `Target` made to hold it (or refused as too small, or of the wrong length), and the format's own `decode` @@ -200,10 +227,12 @@ template @tparam Target `bytes` (up to `N` bytes), `std::array` or a `fixed_target` (exactly its size), `std::string` or `std::vector`. + @tparam Allocators None, or the allocator a heap `Target` is made with. */ -template -[[nodiscard]] result decode_as(F const& format_value, - Text const& text_value) noexcept(decode_is_fixed) { +template +[[nodiscard]] result decode_as( + F const& format_value, Text const& text_value, + Allocators const&... allocator_values) noexcept(decode_is_fixed) { std::string_view const text_characters = text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; @@ -213,7 +242,7 @@ template return decoded_count.error(); } std::size_t const byte_count = decoded_count.unsafe_value(); - Target target_value{}; + Target target_value = make_target(allocator_values...); std::span output_span; if constexpr (is_fixed_result) { if (byte_count > Target::capacity()) { @@ -249,6 +278,141 @@ template return target_value; } +/** A pointer a token's `prepare` returned, as the bytes a value codec of bytes writes. */ +template +[[nodiscard]] std::uint8_t* as_byte_pointer(Pointer prepared) noexcept { + if constexpr (std::same_as) { + return prepared; + } else { + // A one-byte element is written through an unsigned char, which may alias any object. + return reinterpret_cast(prepared); + } +} + +/** A pointer a token's `prepare` returned, as the characters a value codec of text writes. */ +template +[[nodiscard]] char* as_char_pointer(Pointer prepared) noexcept { + if constexpr (std::same_as) { + return prepared; + } else { + // A one-byte element is written through a char, which may alias any object. + return reinterpret_cast(prepared); + } +} + +/** + Encodes into `token_object`, a concrete token (B6): the checks of the input, then the token's + `capacity` against the exact size, then one `prepare` with that size, the format's `encode` into + what it returned, and one `result`. A token is untouched when a check fails. +*/ +template +[[nodiscard]] result encode_to( + F const& format_value, Input const& input_value, + Token& token_object) noexcept(token_is_noexcept) { + constexpr bool from_value = value_encodable; + std::span input_view{}; + std::size_t output_size = 0; + if constexpr (from_value) { + output_size = value_codec::encoded_size(format_value, input_value); + } else { + input_view = input_bytes(input_value); + if (auto const size_fault = input_size_fault(format_value, input_view.size())) { + return *size_fault; + } + output_size = codec::encoded_size(format_value, input_view); + } + if constexpr (has_token_capacity) { + if (output_size > Token::capacity) { + return error::output_too_small; + } + } + auto* const prepared = token_object.prepare(output_size); + result written_size = std::size_t{0}; + if constexpr (from_value) { + using value_type = value_codec; + if constexpr (value_type::output == output_kind::bytes) { + written_size = + value_type::encode(format_value, input_value, + std::span{as_byte_pointer(prepared), output_size}); + } else { + written_size = value_type::encode( + format_value, input_value, std::span{as_char_pointer(prepared), output_size}); + } + } else { + written_size = + codec::encode(format_value, input_view, std::span{prepared, output_size}); + } + if (!written_size) { + return written_size.error(); + } + return token_object.result(); +} + +/** + Decodes into `token_object`, a concrete token (B6): the checks of the text, the whole text + checked, then the token's `capacity` against the exact size, then one `prepare` with that size, + the format's `decode` into what it returned, and one `result`. A token is untouched when a check + fails. +*/ +template +[[nodiscard]] result decode_to( + F const& format_value, Text const& text_value, + Token& token_object) noexcept(token_is_noexcept) { + std::string_view const text_characters = text_view(text_value); + if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { + return *size_fault; + } + result const decoded_count = codec::decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count.error(); + } + // Read unchecked: the error was returned above. + std::size_t const byte_count = decoded_count.unsafe_value(); + if constexpr (has_token_capacity) { + if (byte_count > Token::capacity) { + return error::output_too_small; + } + } + auto* const prepared = token_object.prepare(byte_count); + result const written_count = + codec::decode(format_value, text_characters, + std::span{as_byte_pointer(prepared), byte_count}); + if (!written_count) { + return written_count.error(); + } + return token_object.result(); +} + +/** Whether `Input` is a value that a value codec of `F` encodes into bytes. */ +template +constexpr bool encodes_to_bytes() noexcept { + if constexpr (value_encodable) { + return value_codec>::output == output_kind::bytes; + } else { + return false; + } +} + +/** Whether an encode of `Input` in `F` into `Token`, as it was passed, cannot throw. */ +template +constexpr bool encode_token_is_noexcept() noexcept { + if constexpr (std::same_as, tokens::automatic>) { + return is_fixed_result>; + } else { + return token_is_noexcept(), Token>>; + } +} + +/** Whether a decode in `F` into `Token`, as it was passed, cannot throw. */ +template +constexpr bool decode_token_is_noexcept() noexcept { + if constexpr (std::same_as, tokens::automatic>) { + return is_fixed_result>; + } else { + return token_is_noexcept>; + } +} + } // namespace detail /** @@ -366,6 +530,100 @@ template } } +/** + Encodes `input_value` in `format_value` into `token`, which says where the result goes and what + it is. + + `token` is one of the tags of `codecs::tokens` (`automatic`, which is the default result of the + form without a token; `return_string` and `return_string(allocator)`, a string; `append_to` and + `assign_to` of a string, which return the string by reference; `fixed`, a `text`, or a + `bytes` for a value codec of bytes) or an object of the token contract of Boost.URL's string + tokens, used as given. The result is `result`. The order is that of + the buffer form's: every check of the input (an input whose encoding does not fit in + `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size + (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one + `result`. A token is untouched when a check fails. The forms that allocate are not `noexcept` + (an allocator's exception propagates, owner decision 24); `fixed` is. A pair that is not + @ref encodable stops the build with a message that the format does not convert this type, and a + token that does not take the pair's encoding (`append_to` of a vector, which is for decode) + with one that names the token's type. + + @tparam F The format's type. + @tparam Input The input's type: a byte input, or a value of a value codec. + @tparam Token A tag of `codecs::tokens`, or a text token (a byte token for a value codec). + @param format_value The format. + @param input_value The bytes, or the value, to encode. + @param token The token. + @return The token's result, or the error. +*/ +template + requires detail::token_argument +[[nodiscard]] auto encode(F const& format_value, Input const& input_value, Token&& token) noexcept( + detail::encode_token_is_noexcept()) { + if constexpr (std::same_as, tokens::automatic>) { + return encode(format_value, input_value); + } else if constexpr (encodable) { + constexpr bool to_bytes = detail::encodes_to_bytes(); + using concrete_type = detail::concrete_token_t; + if constexpr (detail::value_encodable ? detail::byte_token + : detail::text_token) { + auto&& concrete_token = detail::concrete_token(token); + return detail::encode_to(format_value, input_value, concrete_token); + } else { + detail::refuse, F>(); + return result{std::string{}}; + } + } else { + detail::refuse(); + return result{std::string{}}; + } +} + +/** + Decodes `text_value` in `format_value` into `token`, which says where the bytes go and what they + are. + + `token` is one of the tags of `codecs::tokens` (`automatic`, the default result of the form + without a token; `return_string` and `return_string(allocator)`, the bytes as a string; + `append_to` and `assign_to` of a string or a vector of `std::uint8_t`, which return the container + by reference; `fixed`, a `bytes`) or an object of the token contract (a byte token), used + as given. The result is `result`. The order is that of the buffer + form's: a text whose bytes do not fit in `std::size_t` is @ref error::input_too_long, the whole + text is checked and its data error with the lowest value of @ref error returned, then the token's + `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the + exact size, the conversion, one `result`. A token is untouched when a check fails. The forms that + allocate are not `noexcept`; `fixed` is. A format with no `codec` specialization stops the + build with a message that the format does not convert bytes (named + `webcpp::codecs::detail::decoded_bytes`), and a token that is not a byte token with one that + names the token's type. + + @tparam F The format's type. + @tparam Text The text's type: anything a `std::string_view` is made from, or a contiguous + sized range of `char`. + @tparam Token A tag of `codecs::tokens`, or a byte token. + @param format_value The format. + @param text_value The text to decode; a string literal is read up to its terminating zero. + @param token The token. + @return The token's result, or the error. +*/ +template + requires detail::token_argument +[[nodiscard]] auto decode(F const& format_value, Text const& text_value, Token&& token) noexcept( + detail::decode_token_is_noexcept()) { + if constexpr (!detail::has_codec) { + detail::refuse(); + return result>{std::vector{}}; + } else if constexpr (std::same_as, tokens::automatic>) { + return decode(format_value, text_value); + } else if constexpr (detail::byte_token>) { + auto&& concrete_token = detail::concrete_token(token); + return detail::decode_to(format_value, text_value, concrete_token); + } else { + detail::refuse, F>(); + return result>{std::vector{}}; + } +} + /** Decodes `input_value` in `format_value` into a `Value`, the type the caller names. @@ -415,6 +673,45 @@ template } } +/** + Decodes `input_value` in `format_value` into a `Value`, a string or a vector of `std::uint8_t` + that is made with `allocator_value`, as a standard container constructed with it is + (`decode>(format, text, allocator)`); the form without an + allocator makes a default-constructed one, so `decode>` uses the + default memory resource. + + The order and the errors are those of the typed decode without an allocator. It allocates, and + is not `noexcept`: the allocator's exception propagates (owner decision 24). A `Value` that is + not a heap result of a format with a `codec`, or that `allocator_value` does not construct, + stops the build with a message that the format does not convert this type, and an input that is + not a text with one that names the input's type. + + @tparam Value The string or vector to decode into. + @tparam F The format's type. + @tparam Input The text's type. + @tparam Allocator The allocator's type, one `Value` is constructed from. + @param format_value The format. + @param input_value The text to decode. + @param allocator_value The allocator the result is made with. + @return The value, or the error. +*/ +template +[[nodiscard]] result decode(F const& format_value, Input const& input_value, + Allocator const& allocator_value) { + if constexpr (detail::heap_result && detail::has_codec && + std::constructible_from) { + if constexpr (detail::text_input) { + return detail::decode_as(format_value, input_value, allocator_value); + } else { + detail::refuse(); + return make_error_code(error::invalid_length); + } + } else { + detail::refuse(); + return make_error_code(error::invalid_length); + } +} + } // namespace webcpp::codecs #endif // WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp new file mode 100644 index 0000000..09382c3 --- /dev/null +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -0,0 +1,341 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The tokens of webcpp::codecs: the contract of a token that receives a result, which Boost.URL's + string tokens also meet, and the tags of `codecs::tokens` that the core turns into the concrete + token of the direction. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_TOKENS_HPP +#define WEBCPP_CODECS_DETAIL_CORE_TOKENS_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** A pointer to a writable element of one byte: `char`, `unsigned char`, `std::uint8_t` or + * `std::byte`. */ +template +concept byte_pointer = std::is_pointer_v && !std::is_const_v> && + byte_element>; + +/** + A text token: `T::result_type`, `prepare(n)` returning a `char*` to `n` characters, and `result()` + that gives the `result_type`. Boost.URL's `string_token` types are text tokens. +*/ +template +concept text_token = requires(T& token_object, std::size_t size) { + typename T::result_type; + { token_object.prepare(size) } -> std::same_as; + { token_object.result() } -> std::convertible_to; +}; + +/** + A byte token: a text token whose `prepare` may return a pointer to any element of one byte + (`char`, `unsigned char`, `std::uint8_t` or `std::byte`), so that a Boost.URL token receives + decoded bytes as a `std::string`. +*/ +template +concept byte_token = requires(T& token_object, std::size_t size) { + typename T::result_type; + { token_object.prepare(size) } -> byte_pointer; + { token_object.result() } -> std::convertible_to; +}; + +/** Whether the token type states `static constexpr std::size_t capacity`. */ +template +concept has_token_capacity = requires { + { T::capacity } -> std::convertible_to; +}; + +} // namespace detail + +/** The tags of the tokens that codecs turns into the concrete token of a direction (B6). */ +namespace tokens { + +/** The default token (B7): the result of `encode` and `decode` is the default result (D9). */ +struct automatic {}; + +/** + The tag that gives the result as a `std::basic_string, A>`, both + ways (the bytes of a decode as characters), `A` the allocator rebound to `char`; also callable + with an allocator that it keeps (B40). + + @tparam Allocator The allocator of the string, `std::allocator` for the object + `return_string`. +*/ +template > +struct return_string_t { + /** The allocator the string is constructed with. */ + Allocator allocator; + + /** + A tag that gives the string over `other`, which is used through `std::allocator_traits`. + + @param other The allocator. + @return The tag. + */ + template + requires requires { typename std::allocator_traits::value_type; } + [[nodiscard]] constexpr return_string_t operator()(Other const& other) const noexcept { + return return_string_t{other}; + } +}; + +/** The tag `return_string`: a `std::string`, or with an allocator `return_string(allocator)`. */ +inline constexpr return_string_t<> return_string{}; + +/** + The tag that gives `N` elements in place: `text` from `encode`, `bytes` from `decode` + (a value codec of bytes encodes into `bytes`). A result that does not fit is + @ref error::output_too_small. + + @tparam N The most elements. +*/ +template +struct fixed { + /** The most elements. */ + static constexpr std::size_t capacity = N; +}; + +} // namespace tokens + +namespace detail { + +/** A token that appends the result to a string or a vector; its result is the container. */ +template +class appending_token { +public: + /** The container, by reference, as Boost.URL's `append_to` gives it. */ + using result_type = Container&; + + /** Constructs a token that appends to `target`, which outlives it. */ + explicit appending_token(Container& target) noexcept : target_(&target) {} + + /** Grows the container by `size` elements and returns a pointer to the new ones. */ + [[nodiscard]] auto* prepare(std::size_t size) { + std::size_t const old_size = target_->size(); + target_->resize(saturating_add(old_size, size)); + return target_->data() + old_size; + } + + /** The container. */ + [[nodiscard]] result_type result() noexcept { return *target_; } + +private: + Container* target_; +}; + +/** A token that replaces the content of a string or a vector with the result. */ +template +class assigning_token { +public: + /** The container, by reference, as Boost.URL's `assign_to` gives it. */ + using result_type = Container&; + + /** Constructs a token that assigns to `target`, which outlives it. */ + explicit assigning_token(Container& target) noexcept : target_(&target) {} + + /** Resizes the container to `size` elements and returns a pointer to them. */ + [[nodiscard]] auto* prepare(std::size_t size) { + target_->resize(size); + return target_->data(); + } + + /** The container. */ + [[nodiscard]] result_type result() noexcept { return *target_; } + +private: + Container* target_; +}; + +/** A token that gives a string of its own, made with the allocator it was constructed with. */ +template +class returning_token { +public: + /** The string. */ + using result_type = String; + + /** Constructs a token whose string is made with `allocator_value`. */ + explicit returning_token(typename String::allocator_type const& allocator_value) noexcept + : value_(allocator_value) {} + + /** Resizes the string to `size` characters and returns a pointer to them. */ + [[nodiscard]] char* prepare(std::size_t size) { + value_.resize(size); + return value_.data(); + } + + /** The string, moved out. */ + [[nodiscard]] result_type result() noexcept { return std::move(value_); } + +private: + String value_; +}; + +/** A token that gives `text` or `bytes`: the elements in place, nothing allocated. */ +template +class fixed_token { +public: + /** The fixed result. */ + using result_type = Fixed; + + /** The most elements. */ + static constexpr std::size_t capacity = Fixed::capacity(); + + /** Sets the size and returns a pointer to the elements, which the core made sure fit. */ + [[nodiscard]] auto* prepare(std::size_t size) noexcept { + fixed_access::resize(value_, size); + return fixed_access::writable(value_).data(); + } + + /** The fixed result. */ + [[nodiscard]] result_type result() noexcept { return value_; } + +private: + Fixed value_{}; +}; + +/** Whether `T` is a `return_string_t`. */ +template +inline constexpr bool is_return_string = false; + +/** A `return_string_t`. */ +template +inline constexpr bool is_return_string> = true; + +/** Whether `T` is a `tokens::fixed`. */ +template +inline constexpr bool is_fixed_tag = false; + +/** A `tokens::fixed`. */ +template +inline constexpr bool is_fixed_tag> = true; + +/** A tag of `codecs::tokens` that is no token of itself: the core makes the token of it. */ +template +concept token_tag = std::same_as || is_return_string || is_fixed_tag; + +/** What `encode` and `decode` take as a token: a tag, or an object of the token contract. */ +template +concept token_argument = + token_tag> || byte_token>; + +/** + The concrete token of a `return_string`: the string made with the tag's allocator, rebound to + `char`. +*/ +template +[[nodiscard]] auto concrete_token(tokens::return_string_t const& tag_value) { + using string_allocator = typename std::allocator_traits::template rebind_alloc; + using string_type = std::basic_string, string_allocator>; + return returning_token{string_allocator{tag_value.allocator}}; +} + +/** The concrete token of `fixed`: `text` for text, `bytes` for bytes. */ +template +[[nodiscard]] constexpr auto concrete_token(tokens::fixed const& /*tag_value*/) noexcept { + if constexpr (Bytes) { + return fixed_token>{}; + } else { + return fixed_token>{}; + } +} + +/** A token that is one already: used as given. */ +template + requires(byte_token && !token_tag) +[[nodiscard]] constexpr Token& concrete_token(Token& token_object) noexcept { + return token_object; +} + +/** The type of the concrete token of `Token`, the argument of the operation as it was passed. */ +template +using concrete_token_t = std::remove_cvref_t( + std::declval&>()))>; + +/** Whether using `Token`, a concrete token, cannot throw: its `prepare` and `result` do not. */ +template +inline constexpr bool token_is_noexcept = + noexcept(std::declval().prepare(std::size_t{0})) && + noexcept(std::declval().result()); + +} // namespace detail + +namespace tokens { + +/** + The tag that appends the result to `target`, a string of any traits and allocator, used with the + string's own allocator. The operation returns `target` by reference, as Boost.URL's does; the + bytes of a decode are appended as characters. The input must not be a part of `target`. + + @param target The string to append to. + @return The token. +*/ +template +[[nodiscard]] auto append_to(std::basic_string& target) noexcept { + return detail::appending_token>{target}; +} + +/** + The tag that appends the bytes of a decode to `target`, a vector of any allocator, used with the + vector's own allocator; decode only. The operation returns `target` by reference. + + @param target The vector to append to. + @return The token. +*/ +template +[[nodiscard]] auto append_to(std::vector& target) noexcept { + return detail::appending_token>{target}; +} + +/** + The tag that replaces the content of `target`, a string of any traits and allocator, with the + result, used with the string's own allocator. The operation returns `target` by reference. The + input must not be a part of `target`. + + @param target The string to assign to. + @return The token. +*/ +template +[[nodiscard]] auto assign_to(std::basic_string& target) noexcept { + return detail::assigning_token>{target}; +} + +/** + The tag that replaces the content of `target`, a vector of any allocator, with the bytes of a + decode, used with the vector's own allocator; decode only. The operation returns `target` by + reference. + + @param target The vector to assign to. + @return The token. +*/ +template +[[nodiscard]] auto assign_to(std::vector& target) noexcept { + return detail::assigning_token>{target}; +} + +} // namespace tokens + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_TOKENS_HPP diff --git a/test/Jamfile b/test/Jamfile index a0f9c62..8028f1c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -55,6 +55,20 @@ codecs-run default_result : default_result_test.cpp ; codecs-run typed_decode : typed_decode_test.cpp ; # Value codecs: the concepts, the default result, the buffer forms. codecs-run value_codec : value_codec_test.cpp ; +# The tokens: codecs' own tags in both directions, a token of the test's own, +# capacities, a value codec through a token. +codecs-run tokens : tokens_test.cpp ; +# Boost.URL's string tokens work as given; the program links Boost.URL, which +# percent's target brings. +codecs-run tokens_boost_url : tokens_boost_url_test.cpp + : /webcpp/codecs//percent ; +# Allocators: every allocation of a form that takes one goes through it, and the +# global operator new sees none. +codecs-run allocator : allocator_test.cpp ; +# An allocator that throws on its Nth allocation: its exception reaches the +# caller and the token's container is as it was. A program that needs +# exceptions, so with no _no_exceptions twin. +webcpp.run allocator_throw : allocator_throw_test.cpp : on ; # The forms that allocate nothing leave a counting operator new where it was. codecs-run allocation : allocation_test.cpp ; # Every form that allocates nothing is noexcept, and one that allocates is not. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 9ec050a..7fffdce 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -295,6 +295,47 @@ void check_fixed_results() { static_cast(sink); } +/** The token forms that hold their result in place (Task 4): `tokens::fixed` allocates nothing, + on every path. */ +void check_fixed_tokens() { + std::array const input{0x01, 0xff}; + std::vector const heap_input{0x01, 0xff}; // built before the window + bool volatile verdict = false; + expect_no_allocation("encode into fixed", [&] { + auto const from_array = codecs::encode(test::letters, input, codecs::tokens::fixed<8>{}); + auto const from_heap = + codecs::encode(test::letters, heap_input, codecs::tokens::fixed<8>{}); + verdict = from_array.has_value() && from_heap.has_value() && + from_array.value() == from_heap.value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("decode into fixed", [&] { + auto const decoded = codecs::decode(test::letters, "abpp", codecs::tokens::fixed<8>{}); + verdict = decoded.has_value() && decoded.value().size() == 2; + }); + BOOST_TEST(verdict); + expect_no_allocation("a value codec into fixed", [&] { + auto const encoded = + codecs::encode(test::be16, test::number{0x1234}, codecs::tokens::fixed<2>{}); + auto const text_encoded = + codecs::encode(test::be16, test::hex_number{0x1234}, codecs::tokens::fixed<4>{}); + verdict = encoded.has_value() && text_encoded.has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("fixed too small, and refused", [&] { + verdict = codecs::encode(test::letters, input, codecs::tokens::fixed<3>{}).has_value() || + codecs::decode(test::letters, "abpp", codecs::tokens::fixed<1>{}).has_value() || + codecs::decode(test::letters, "abpq", codecs::tokens::fixed<8>{}).has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("the default token of a fixed result", [&] { + verdict = codecs::encode(test::letters, input, codecs::tokens::automatic{}).has_value() && + codecs::decode(test::letters, codecs::text<4>{}, codecs::tokens::automatic{}) + .has_value(); + }); + BOOST_TEST(verdict); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -339,6 +380,7 @@ int main() { control_counts_every_form(); check_buffer_forms(); check_fixed_results(); + check_fixed_tokens(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp new file mode 100644 index 0000000..6a227e2 --- /dev/null +++ b/test/allocator_test.cpp @@ -0,0 +1,229 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The allocator rows of codecs (owner decision 23): every allocation of a form that takes an +// allocator, or whose token holds a container with one, goes through that allocator, and the +// global operator new, counted by support/counting.hpp, sees none. A recording memory resource is +// the arena; the allocators of the tests' own are checked against the standard's rules, too. Later +// tasks add their rows. + +#include "support/counting.hpp" + +#include "support/allocators.hpp" +#include "support/arena.hpp" +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +// Debug builds of the MSVC library allocate a proxy per container through the global operator +// new, whatever the container's allocator: the global counter is not asked there. +#if defined(_MSC_VER) && defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL != 0 +constexpr bool global_counter_is_asked = false; +#else +constexpr bool global_counter_is_asked = true; +#endif + +/** The allocations of the whole program so far: operator new's and the C library's. */ +std::size_t global_allocations() { + return test::counted_new.load() + test::counted_c.load(); +} + +/** Runs `body`, and checks that the global operator new saw nothing of it. */ +template +void expect_no_global_allocation(char const* what, Body body) { + std::size_t const before = global_allocations(); + body(); + std::size_t const after = global_allocations(); + if (global_counter_is_asked) { + if (after != before) { + std::printf("allocated globally: %s\n", what); + } + BOOST_TEST_EQ(after - before, 0U); + } +} + +/** 32 bytes, and the text the format letters gives for them. */ +std::array bytes_32() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast((index * 37U) + 1U); + } + return held_bytes; +} + +void return_string_over_an_arena() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const expected = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("return_string over an arena, encode", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::return_string(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + BOOST_TEST(arena.owns(encoded.value().data())); + BOOST_TEST(encoded.value().get_allocator().resource() == &arena); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_GE(arena.allocation(0).size, expected.size() + 1); + // The decode gives the bytes as a string of the same kind. + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("return_string over an arena, decode", [&] { + auto const decoded = + codecs::decode(test::letters, expected, tokens::return_string(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count() - before, 1U); +} + +void append_to_a_pmr_string() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const expected = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::string target{&arena}; + target = "kept"; + BOOST_TEST_EQ(arena.allocation_count(), 0U); // four characters stay in the string + expect_no_global_allocation("append_to a pmr string", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::append_to(target)); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &target); + }); + BOOST_TEST(std::string_view{target} == "kept" + expected); + BOOST_TEST(arena.allocation_count() >= 1U); + BOOST_TEST(arena.owns(target.data())); +} + +void assign_to_a_pmr_vector() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::vector target{&arena}; + expect_no_global_allocation("assign_to a pmr vector", [&] { + auto const decoded = codecs::decode(test::letters, text_value, tokens::assign_to(target)); + static_assert(std::is_same_v&> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(&decoded.value(), &target); + }); + BOOST_TEST_EQ(target.size(), input.size()); + BOOST_TEST(std::equal(input.begin(), input.end(), target.begin())); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST(arena.owns(target.data())); + // The same for append_to. + std::pmr::vector appended{&arena}; + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("append_to a pmr vector", [&] { + BOOST_TEST( + codecs::decode(test::letters, text_value, tokens::append_to(appended)).has_value()); + }); + BOOST_TEST_EQ(appended.size(), input.size()); + BOOST_TEST(arena.allocation_count() > before); +} + +void a_typed_decode_with_an_allocator() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("a typed decode into a pmr vector", [&] { + auto const decoded = + codecs::decode>(test::letters, text_value, allocator); + static_assert(std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + BOOST_TEST(decoded.value().get_allocator().resource() == &arena); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + // A string takes an allocator too, and a heap type of std::allocator takes its own. + std::pmr::polymorphic_allocator const char_allocator{&arena}; + auto const as_string = + codecs::decode(test::letters, text_value, char_allocator); + BOOST_TEST(as_string.has_value()); + BOOST_TEST_EQ(as_string.value().size(), input.size()); + BOOST_TEST(arena.owns(as_string.value().data())); + auto const plain = codecs::decode>(test::letters, text_value, + std::allocator{}); + BOOST_TEST(plain.has_value()); + BOOST_TEST_EQ(plain.value().size(), input.size()); + // The errors reach the caller, and the arena was given nothing. + std::size_t const before = arena.allocation_count(); + auto const refused = codecs::decode>( + test::letters, std::string_view{"abq"}, allocator); + BOOST_TEST(refused.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(arena.allocation_count(), before); +} + +void the_allocators_of_the_tests_own() { + // non_propagating_allocator: equal only to a copy. + test::non_propagating_allocator const first_allocator{1}; + test::non_propagating_allocator const second_allocator{2}; + BOOST_TEST(first_allocator == test::non_propagating_allocator{1}); + BOOST_TEST(!(first_allocator == second_allocator)); + static_assert( + !std::allocator_traits< + test::non_propagating_allocator>::propagate_on_container_move_assignment::value); + // wipe_checking_allocator: a block is counted, and a zero one is told from a written one. + test::wipe_checking_allocator checking; + std::uint8_t* const zeros = checking.allocate(16); + std::fill(zeros, zeros + 16, std::uint8_t{0}); + checking.deallocate(zeros, 16); + std::uint8_t* const written = checking.allocate(16); + std::fill(written, written + 16, std::uint8_t{0x5a}); + checking.deallocate(written, 16); + BOOST_TEST_EQ(checking.state()->allocations, 2U); + BOOST_TEST_EQ(checking.state()->deallocations, 2U); + BOOST_TEST_EQ(checking.state()->wiped_deallocations, 1U); + // The arena records sizes and pointers, and refuses past its buffer. + test::recording_resource arena; + void* const block = arena.allocate(100, 8); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_EQ(arena.allocation(0).size, 100U); + BOOST_TEST(arena.allocation(0).pointer == block); + BOOST_TEST(arena.owns(block)); + int on_the_stack = 0; + BOOST_TEST(!arena.owns(&on_the_stack)); + arena.deallocate(block, 100, 8); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); +} + +} // namespace + +int main() { + return_string_over_an_arena(); + append_to_a_pmr_string(); + assign_to_a_pmr_vector(); + a_typed_decode_with_an_allocator(); + the_allocators_of_the_tests_own(); + return boost::report_errors(); +} diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp new file mode 100644 index 0000000..218fd6a --- /dev/null +++ b/test/allocator_throw_test.cpp @@ -0,0 +1,213 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// An allocator that fails (owner decision 24): for every N, the Nth allocation of the operation +// throws std::bad_alloc, which reaches the caller unchanged; the token's container still holds +// what it held; and the first N that does not throw gives the right result. A program that needs +// exceptions, built with them on in every lane (the Jamfile). Later tasks add their rows. + +#include "support/allocators.hpp" +#include "support/letters.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using throwing_string = + std::basic_string, test::throwing_allocator>; +using throwing_bytes = std::vector>; + +/** More than a small string holds: the allocation cannot be avoided. */ +constexpr std::size_t input_size = 24; + +std::array input_bytes() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast((index * 11U) + 3U); + } + return held_bytes; +} + +/** The text letters gives for `input_bytes()`. */ +std::string expected_text() { + auto const held_bytes = input_bytes(); + return codecs::encode(test::letters, held_bytes, tokens::return_string).value(); +} + +void return_string_throws_through() { + auto const held_bytes = input_bytes(); + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::return_string(allocator)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + // Past the last allocation of the operation: it needed fewer than fail_at - 1 + 1. + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + BOOST_TEST_EQ(allocator.allocations(), fail_at); + ++attempts; + } + BOOST_TEST(attempts >= 1U); + // The same for a decode, which gives the bytes in a string. + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = + codecs::decode(test::letters, expected, tokens::return_string(allocator)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input_size); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + break; + } + } +} + +/** Whether `target` holds the characters of `expected`. */ +bool holds(throwing_string const& target, std::string_view expected) { + return std::string_view{target.data(), target.size()} == expected; +} + +void append_to_keeps_the_string() { + auto const held_bytes = input_bytes(); + std::string const expected = "kept" + expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::append_to(target)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &target); + BOOST_TEST(holds(target, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + // The failed append left the string as it was. + BOOST_TEST(holds(target, "kept")); + } + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void assign_to_keeps_the_string() { + auto const held_bytes = input_bytes(); + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::encode(test::letters, held_bytes, tokens::assign_to(target)).has_value()); + BOOST_TEST(holds(target, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, "kept")); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void decode_into_a_vector_keeps_it() { + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_bytes target{{9, 9}, allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::decode(test::letters, expected, tokens::append_to(target)).has_value()); + BOOST_TEST_EQ(target.size(), 2 + input_size); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST_EQ(target.size(), 2U); + BOOST_TEST_EQ(target[0], 9); + BOOST_TEST_EQ(target[1], 9); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void a_typed_decode_throws_through() { + std::string const expected = expected_text(); + auto const held_bytes = input_bytes(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = codecs::decode(test::letters, expected, allocator); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input_size); + BOOST_TEST(std::equal(held_bytes.begin(), held_bytes.end(), decoded.value().begin())); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +} // namespace + +int main() { + return_string_throws_through(); + append_to_keeps_the_string(); + assign_to_keeps_the_string(); + decode_into_a_vector_keeps_it(); + a_typed_decode_throws_through(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 1f18f42..06334dc 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -18,3 +18,5 @@ build-project refused_pair ; build-project refused_encode ; build-project refused_encode_only ; build-project refused_input ; +build-project refused_token ; +build-project refused_allocator ; diff --git a/test/messages/refused_allocator/Jamfile b/test/messages/refused_allocator/Jamfile new file mode 100644 index 0000000..0393bb5 --- /dev/null +++ b/test/messages/refused_allocator/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_allocator : refused_allocator.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_allocator_refused : refused_allocator.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_allocator/refused_allocator.cpp b/test/messages/refused_allocator/refused_allocator.cpp new file mode 100644 index 0000000..e54c011 --- /dev/null +++ b/test/messages/refused_allocator/refused_allocator.cpp @@ -0,0 +1,31 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A typed decode with an allocator into a type that is no string or vector of bytes stops in the +// core's refusal, whose requirement names the type and the format's type (ruling R2): only a heap +// result takes an allocator. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include + +/** A type that is no heap result. */ +struct not_a_heap_result {}; + +int main() { + namespace codecs = webcpp::codecs; + auto const decoded = + codecs::decode(codecs::test::letters, "ab", std::allocator{}); + return decoded.has_value() ? 0 : 1; +} diff --git a/test/messages/refused_token/Jamfile b/test/messages/refused_token/Jamfile new file mode 100644 index 0000000..ceb8515 --- /dev/null +++ b/test/messages/refused_token/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_token : refused_token.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_token_refused : refused_token.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_token/refused_token.cpp b/test/messages/refused_token/refused_token.cpp new file mode 100644 index 0000000..e880012 --- /dev/null +++ b/test/messages/refused_token/refused_token.cpp @@ -0,0 +1,49 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that encodes into a token that takes bytes but not text (a pointer to `unsigned char` +// from `prepare`, as `append_to` of a vector gives) stops in the core's refusal, whose requirement +// names the token's type and the format's type (ruling R2): the encoding of bytes is text. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include +#include +#include +#include + +/** A byte token that is no text token. */ +struct bytes_only_token { + /** What the token gives. */ + using result_type = std::vector; + + /** Makes room for `size` bytes. */ + std::uint8_t* prepare(std::size_t size) { + storage.assign(size, 0); + return storage.data(); + } + + /** The bytes. */ + result_type result() { return storage; } + + /** The bytes. */ + std::vector storage; +}; + +int main() { + namespace codecs = webcpp::codecs; + auto const encoded = + codecs::encode(codecs::test::letters, std::array{}, bytes_only_token{}); + return encoded.has_value() ? 0 : 1; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 0906345..b782b6f 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -15,6 +15,8 @@ #include #include +#include +#include #include #include #include @@ -59,4 +61,41 @@ static_assert(noexcept(codecs::encode(test::be16, test::hex_number{}, std::span< // The default result of a value codec of text with no stated bound is the heap. static_assert(!noexcept(codecs::encode(test::be16, test::hex_number{}))); +// The tokens (Task 4): the forms that allocate are not noexcept, fixed is; the default token +// follows the default result. +namespace tokens = webcpp::codecs::tokens; +static_assert(!noexcept(codecs::encode(test::letters, std::array{}, + tokens::return_string))); +static_assert(!noexcept(codecs::decode(test::letters, "ab", tokens::return_string))); +static_assert(!noexcept(codecs::encode(test::letters, std::array{}, + tokens::append_to(std::declval())))); +static_assert(!noexcept(codecs::encode(test::letters, std::array{}, + tokens::assign_to(std::declval())))); +static_assert(!noexcept(codecs::decode( + test::letters, "ab", tokens::append_to(std::declval&>())))); +static_assert(!noexcept(codecs::decode( + test::letters, "ab", tokens::assign_to(std::declval&>())))); +static_assert(noexcept(codecs::encode(test::letters, std::array{}, + tokens::fixed<8>{}))); +static_assert(noexcept(codecs::encode(test::letters, std::vector{}, + tokens::fixed<8>{}))); +static_assert(noexcept(codecs::decode(test::letters, "ab", tokens::fixed<8>{}))); +static_assert(noexcept(codecs::encode(test::be16, test::number{}, tokens::fixed<8>{}))); +static_assert(noexcept(codecs::encode(test::letters, std::array{}, + tokens::automatic{}))); +static_assert(!noexcept(codecs::encode(test::letters, std::vector{}, + tokens::automatic{}))); +// The forms with an allocator. +static_assert( + !noexcept(codecs::encode(test::letters, std::array{}, + tokens::return_string(std::pmr::polymorphic_allocator{})))); +static_assert(!noexcept(codecs::decode>( + test::letters, "ab", std::pmr::polymorphic_allocator{}))); +static_assert(!noexcept(codecs::decode(test::letters, "ab", std::allocator{}))); +// append_to of a vector is for decode, and a vector token is no text token. +static_assert(!codecs::detail::text_token< + decltype(tokens::append_to(std::declval&>()))>); +static_assert(codecs::detail::byte_token< + decltype(tokens::append_to(std::declval&>()))>); + } // namespace diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp new file mode 100644 index 0000000..1e46cb6 --- /dev/null +++ b/test/support/allocators.hpp @@ -0,0 +1,205 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The allocators of the tests' own, as the standard library's rules see them (owner decision 23): +// +// - throwing_allocator throws std::bad_alloc on its fail_at-th allocation, counted across +// every copy and rebinding of it (a shared counter), and succeeds on every other; it is not +// declared when exceptions are off. +// - non_propagating_allocator never propagates (on copy assignment, move assignment and swap) +// and compares equal only to a copy of itself, so that a container's move between two of them +// copies the bytes. +// - wipe_checking_allocator counts allocations and deallocations and records whether every +// byte it was given back read zero at deallocate. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + +/** The count a throwing_allocator and its copies share. */ +struct throwing_state { + /** The allocation that throws, counted from 1; 0 for none. */ + std::size_t fail_at; + /** The allocations made so far. */ + std::size_t allocations = 0; +}; + +/** An allocator that throws `std::bad_alloc` on its `fail_at`-th allocation. */ +template +class throwing_allocator { +public: + /** The element type. */ + using value_type = T; + + /** + Constructs an allocator whose `fail_at`-th allocation, counted from 1, throws; 0 is none. + */ + explicit throwing_allocator(std::size_t fail_at) + : state_(std::make_shared(throwing_state{fail_at})) {} + + /** Constructs the allocator of another element type that shares this one's count. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + throwing_allocator(throwing_allocator const& other) noexcept : state_(other.state()) {} + + /** Allocates `count` elements, or throws on the allocation that is to fail. */ + [[nodiscard]] T* allocate(std::size_t count) { + ++state_->allocations; + if (state_->allocations == state_->fail_at) { + throw std::bad_alloc(); + } + return std::allocator{}.allocate(count); + } + + /** Returns the elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** + Starts the count over for every copy: the `fail_at`-th allocation from now, counted from 1, + throws. A container built before the call is not counted. + */ + void arm(std::size_t fail_at) const noexcept { + state_->allocations = 0; + state_->fail_at = fail_at; + } + + /** The allocations made through this allocator and its copies. */ + [[nodiscard]] std::size_t allocations() const noexcept { return state_->allocations; } + + /** The shared count. */ + [[nodiscard]] std::shared_ptr const& state() const noexcept { return state_; } + + /** Equal when the count is shared. */ + template + [[nodiscard]] bool operator==(throwing_allocator const& other) const noexcept { + return state_ == other.state(); + } + +private: + std::shared_ptr state_; +}; + +#endif // WEBCPP_CODECS_NO_EXCEPTIONS + +/** An allocator that never propagates and is equal only to its own copies. */ +template +class non_propagating_allocator { +public: + /** The element type. */ + using value_type = T; + /** The allocator stays with its container on a copy assignment. */ + using propagate_on_container_copy_assignment = std::false_type; + /** The allocator stays with its container on a move assignment. */ + using propagate_on_container_move_assignment = std::false_type; + /** The allocator stays with its container on a swap. */ + using propagate_on_container_swap = std::false_type; + /** Two of them are not equal unless they are copies. */ + using is_always_equal = std::false_type; + + /** Constructs the allocator numbered `identity`; two with another number are unequal. */ + explicit non_propagating_allocator(int identity) noexcept : identity_(identity) {} + + /** Constructs the allocator of another element type with this one's number. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + non_propagating_allocator(non_propagating_allocator const& other) noexcept + : identity_(other.identity()) {} + + /** Allocates `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + /** Returns the elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** The number. */ + [[nodiscard]] int identity() const noexcept { return identity_; } + + /** Equal when the numbers are. */ + template + [[nodiscard]] bool operator==(non_propagating_allocator const& other) const noexcept { + return identity_ == other.identity(); + } + +private: + int identity_; +}; + +/** What a wipe_checking_allocator and its copies count. */ +struct wipe_state { + /** The allocations. */ + std::size_t allocations = 0; + /** The deallocations. */ + std::size_t deallocations = 0; + /** The deallocations whose every byte read zero. */ + std::size_t wiped_deallocations = 0; +}; + +/** An allocator that records whether each block was all zero when it was given back. */ +template +class wipe_checking_allocator { +public: + /** The element type. */ + using value_type = T; + + /** Constructs an allocator with a count of its own. */ + wipe_checking_allocator() : state_(std::make_shared()) {} + + /** Constructs the allocator of another element type that shares this one's count. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + wipe_checking_allocator(wipe_checking_allocator const& other) noexcept + : state_(other.state()) {} + + /** Allocates `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { + ++state_->allocations; + return std::allocator{}.allocate(count); + } + + /** Counts the block, whether it is all zero, and returns it. */ + void deallocate(T* pointer, std::size_t count) noexcept { + ++state_->deallocations; + auto const* const first_byte = reinterpret_cast(pointer); + bool all_zero = true; + for (std::size_t index = 0; index < count * sizeof(T); ++index) { + all_zero = all_zero && first_byte[index] == 0; + } + if (all_zero) { + ++state_->wiped_deallocations; + } + std::allocator{}.deallocate(pointer, count); + } + + /** The shared count. */ + [[nodiscard]] std::shared_ptr const& state() const noexcept { return state_; } + + /** Equal when the count is shared. */ + template + [[nodiscard]] bool operator==(wipe_checking_allocator const& other) const noexcept { + return state_ == other.state(); + } + +private: + std::shared_ptr state_; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP diff --git a/test/support/arena.hpp b/test/support/arena.hpp new file mode 100644 index 0000000..72965ce --- /dev/null +++ b/test/support/arena.hpp @@ -0,0 +1,94 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// recording_resource, a memory resource of the tests' own for the allocator tests: every +// allocation of a container made over it lands in a buffer of 64 KiB (a monotonic buffer resource +// over it, which refuses what does not fit), and the resource counts and records each allocation's +// size and pointer, so that a test sees which allocations went through the allocator it gave. The +// records are in place: the resource allocates nothing through the global operator new once built, +// which a test that counts the global allocations relies on. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A memory resource that records every allocation made through it. */ +class recording_resource : public std::pmr::memory_resource { +public: + /** The size of the buffer the allocations come from. */ + static constexpr std::size_t buffer_size = 64 * 1024; + /** The most allocations recorded; the count goes on past it. */ + static constexpr std::size_t most_records = 64; + + /** One allocation: its size and the pointer it returned. */ + struct record { + /** The bytes asked for. */ + std::size_t size; + /** What the resource returned. */ + void* pointer; + }; + + /** + Constructs a resource over a buffer of its own. The buffer is on the heap, so that the + resource is small on a stack; it is allocated here, not by an operation under test. + */ + recording_resource() + : buffer_(std::make_unique(buffer_size)), + upstream_(buffer_.get(), buffer_size, std::pmr::null_memory_resource()) {} + + /** The allocations made through this resource so far. */ + [[nodiscard]] std::size_t allocation_count() const noexcept { return allocation_count_; } + + /** The deallocations made through this resource so far. */ + [[nodiscard]] std::size_t deallocation_count() const noexcept { return deallocation_count_; } + + /** The `index`th allocation, for an index below `allocation_count()` and `most_records`. */ + [[nodiscard]] record const& allocation(std::size_t index) const noexcept { + return records_[index]; + } + + /** Whether `pointer` is inside the buffer: made by this resource, not by another one. */ + [[nodiscard]] bool owns(void const* pointer) const noexcept { + auto const* const first_byte = buffer_.get(); + auto const* const byte_pointer = static_cast(pointer); + return byte_pointer >= first_byte && byte_pointer < first_byte + buffer_size; + } + +private: + void* do_allocate(std::size_t size, std::size_t alignment) override { + void* const pointer = upstream_.allocate(size, alignment); + if (allocation_count_ < most_records) { + records_[allocation_count_] = record{size, pointer}; + } + ++allocation_count_; + return pointer; + } + + void do_deallocate(void* pointer, std::size_t size, std::size_t alignment) override { + ++deallocation_count_; + upstream_.deallocate(pointer, size, alignment); + } + + [[nodiscard]] bool do_is_equal(std::pmr::memory_resource const& other) const noexcept override { + return this == &other; + } + + std::unique_ptr buffer_; // NOLINT(modernize-avoid-c-arrays) + std::pmr::monotonic_buffer_resource upstream_; + std::array records_{}; + std::size_t allocation_count_ = 0; + std::size_t deallocation_count_ = 0; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP diff --git a/test/tokens_boost_url_test.cpp b/test/tokens_boost_url_test.cpp new file mode 100644 index 0000000..caee0bc --- /dev/null +++ b/test/tokens_boost_url_test.cpp @@ -0,0 +1,98 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Boost.URL's three string tokens, as given, in both directions (D8): `return_string`, +// `append_to` and `assign_to` of a `std::string`. The bytes of a decode arrive as a `std::string`, +// Boost.URL's model for every result. A text that does not decode leaves the string unchanged. +// This program links Boost.URL's compiled library, as percent's does. + +#include "support/letters.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace url_token = boost::urls::string_token; + +static_assert(codecs::detail::text_token); +static_assert(codecs::detail::text_token< + url_token::implementation_defined::append_to_t>>); +static_assert(codecs::detail::byte_token< + url_token::implementation_defined::assign_to_t>>); + +constexpr std::array two_bytes{0x01, 0xff}; + +void encode_with_boost_url_tokens() { + auto const returned = codecs::encode(test::letters, two_bytes, url_token::return_string{}); + static_assert(std::is_same_v const>); + BOOST_TEST(returned.has_value()); + BOOST_TEST(returned.value() == "abpp"); + std::string appended = "kept"; + auto const appended_result = + codecs::encode(test::letters, two_bytes, url_token::append_to(appended)); + static_assert(std::is_same_v const>); + BOOST_TEST(appended_result.has_value()); + BOOST_TEST_EQ(&appended_result.value(), &appended); + BOOST_TEST(appended == "keptabpp"); + std::string assigned = "kept"; + BOOST_TEST(codecs::encode(test::letters, std::vector{0x01, 0xff}, + url_token::assign_to(assigned)) + .has_value()); + BOOST_TEST(assigned == "abpp"); +} + +void decode_with_boost_url_tokens() { + // The bytes are a std::string, as Boost.URL gives every result. + auto const returned = codecs::decode(test::letters, "abpp", url_token::return_string{}); + static_assert(std::is_same_v const>); + BOOST_TEST(returned.has_value()); + BOOST_TEST_EQ(returned.value().size(), 2U); + BOOST_TEST_EQ(static_cast(returned.value()[0]), 0x01U); + BOOST_TEST_EQ(static_cast(returned.value()[1]), 0xffU); + std::string appended = "kept"; + BOOST_TEST(codecs::decode(test::letters, std::string{"abpp"}, url_token::append_to(appended)) + .has_value()); + BOOST_TEST_EQ(appended.size(), 6U); + BOOST_TEST(appended.starts_with("kept")); + BOOST_TEST_EQ(static_cast(appended[5]), 0xffU); + std::string assigned = "kept, replaced"; + BOOST_TEST(codecs::decode(test::letters, "abpp", url_token::assign_to(assigned)).has_value()); + BOOST_TEST_EQ(assigned.size(), 2U); + BOOST_TEST_EQ(static_cast(assigned[0]), 0x01U); +} + +void an_invalid_decode_leaves_the_string() { + std::string appended = "kept"; + auto const foreign = codecs::decode(test::letters, "abq", url_token::append_to(appended)); + BOOST_TEST(!foreign.has_value()); + BOOST_TEST(foreign.error() == codecs::error::invalid_character); + BOOST_TEST(appended == "kept"); + std::string assigned = "kept"; + auto const odd = codecs::decode(test::letters, "abp", url_token::assign_to(assigned)); + BOOST_TEST(odd.error() == codecs::error::invalid_length); + BOOST_TEST(assigned == "kept"); +} + +} // namespace + +int main() { + encode_with_boost_url_tokens(); + decode_with_boost_url_tokens(); + an_invalid_decode_leaves_the_string(); + return boost::report_errors(); +} diff --git a/test/tokens_test.cpp b/test/tokens_test.cpp new file mode 100644 index 0000000..e23a8e5 --- /dev/null +++ b/test/tokens_test.cpp @@ -0,0 +1,383 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The token forms of encode and decode (D8): each tag of codecs::tokens in both directions, the +// contract of a token of the test's own (every check before prepare, one prepare with the exact +// size, one result), a token's capacity, and a value codec through a token. + +#include "support/be16.hpp" +#include "support/letters.hpp" +#include "support/saturating.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +/** A text token of the test's own that counts how it is used. */ +struct counting_token { + /** What the token gives. */ + using result_type = std::string; + + /** Makes room for `size` characters, and counts. */ + char* prepare(std::size_t size) { + ++prepare_calls; + prepared_size = size; + storage.assign(size, '\0'); + return storage.data(); + } + + /** What was written, and counts. */ + result_type result() { + ++result_calls; + return storage; + } + + /** The calls of `prepare`. */ + int prepare_calls = 0; + /** The calls of `result`. */ + int result_calls = 0; + /** The size `prepare` was asked for. */ + std::size_t prepared_size = 0; + /** The characters. */ + std::string storage; +}; + +/** A token that states its capacity: 54 elements. */ +struct capped_token : counting_token { + /** The most elements. */ + static constexpr std::size_t capacity = 54; +}; + +/** A byte token whose `prepare` gives a pointer to `std::uint8_t`. */ +struct byte_vector_token { + /** What the token gives. */ + using result_type = std::vector; + + /** Makes room for `size` bytes. */ + std::uint8_t* prepare(std::size_t size) { + ++prepare_calls; + storage.assign(size, 0); + return storage.data(); + } + + /** The bytes. */ + result_type result() { return storage; } + + /** The calls of `prepare`. */ + int prepare_calls = 0; + /** The bytes. */ + std::vector storage; +}; + +/** A byte token whose `prepare` gives a pointer to `std::byte`. */ +struct std_byte_token { + /** What the token gives. */ + using result_type = std::vector; + + /** Makes room for `size` bytes. */ + std::byte* prepare(std::size_t size) { + storage.assign(size, std::byte{0}); + return storage.data(); + } + + /** The bytes. */ + result_type result() { return storage; } + + /** The bytes. */ + std::vector storage; +}; + +static_assert(codecs::detail::text_token); +static_assert(codecs::detail::byte_token); +static_assert(codecs::detail::byte_token); +static_assert(!codecs::detail::text_token); +static_assert(codecs::detail::byte_token); +static_assert(!codecs::detail::byte_token); +static_assert(!codecs::detail::byte_token>); + +constexpr std::array two_bytes{0x01, 0xff}; + +/** The characters of a string as bytes. */ +std::vector bytes_of(std::string_view characters) { + return {characters.begin(), characters.end()}; +} + +void return_string_both_ways() { + auto const encoded = codecs::encode(test::letters, two_bytes, tokens::return_string); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(encoded.value() == "abpp"); + // The heap input too, and a string literal. + BOOST_TEST( + codecs::encode(test::letters, std::vector{0x01, 0xff}, tokens::return_string) + .value() == "abpp"); + BOOST_TEST(codecs::encode(test::letters, "ab", tokens::return_string).value() == "gbgc"); + auto const decoded = codecs::decode(test::letters, "abpp", tokens::return_string); + static_assert(std::is_same_v const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), 2U); + BOOST_TEST_EQ(static_cast(decoded.value()[0]), 0x01U); + BOOST_TEST_EQ(static_cast(decoded.value()[1]), 0xffU); +} + +void append_to_a_string() { + std::string kept = "kept"; + auto const encoded = codecs::encode(test::letters, two_bytes, tokens::append_to(kept)); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &kept); + BOOST_TEST(kept == "keptabpp"); + // A second append goes after the first. + BOOST_TEST(codecs::encode(test::letters, two_bytes, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "keptabppabpp"); + std::string decoded_kept = "kept"; + auto const decoded = + codecs::decode(test::letters, std::string{"abpp"}, tokens::append_to(decoded_kept)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(&decoded.value(), &decoded_kept); + BOOST_TEST_EQ(decoded_kept.size(), 6U); + BOOST_TEST(decoded_kept.starts_with("kept")); + BOOST_TEST_EQ(static_cast(decoded_kept[5]), 0xffU); +} + +void append_to_a_vector_on_decode() { + std::vector kept{9}; + auto const decoded = codecs::decode(test::letters, "abpp", tokens::append_to(kept)); + static_assert( + std::is_same_v&> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(&decoded.value(), &kept); + BOOST_TEST((kept == std::vector{9, 0x01, 0xff})); +} + +void assign_to_replaces() { + std::string text_target = "kept, and longer than what replaces it"; + auto const encoded = codecs::encode(test::letters, two_bytes, tokens::assign_to(text_target)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &text_target); + BOOST_TEST(text_target == "abpp"); + std::string decoded_target = "kept"; + BOOST_TEST( + codecs::decode(test::letters, "abpp", tokens::assign_to(decoded_target)).has_value()); + BOOST_TEST(bytes_of(decoded_target) == (std::vector{0x01, 0xff})); + std::vector vector_target{7, 7, 7, 7}; + auto const decoded = codecs::decode(test::letters, "abpp", tokens::assign_to(vector_target)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(&decoded.value(), &vector_target); + BOOST_TEST((vector_target == std::vector{0x01, 0xff})); + // An empty result empties the target. + BOOST_TEST(codecs::decode(test::letters, "", tokens::assign_to(vector_target)).has_value()); + BOOST_TEST(vector_target.empty()); +} + +void fixed_gives_fixed_results() { + auto const encoded = codecs::encode(test::letters, two_bytes, tokens::fixed<8>{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(encoded.value().size(), 4U); + BOOST_TEST(encoded.value().view() == "abpp"); + auto const exact = codecs::encode(test::letters, two_bytes, tokens::fixed<4>{}); + BOOST_TEST(exact.has_value()); + auto const decoded = codecs::decode(test::letters, "abpp", tokens::fixed<8>{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), 2U); + BOOST_TEST_EQ(decoded.value().data()[0], 0x01); + BOOST_TEST_EQ(decoded.value().data()[1], 0xff); + BOOST_TEST_EQ(decoded.value().data()[2], 0x00); + // Too small: refused, whatever the input's size is known to be. + auto const too_small = codecs::encode(test::letters, two_bytes, tokens::fixed<3>{}); + BOOST_TEST(!too_small.has_value()); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + auto const decoded_too_small = codecs::decode(test::letters, "abpp", tokens::fixed<1>{}); + BOOST_TEST(decoded_too_small.error() == codecs::error::output_too_small); + // The data error comes before the capacity. + BOOST_TEST(codecs::decode(test::letters, "abpq", tokens::fixed<1>{}).error() == + codecs::error::invalid_character); + // The empty input. + auto const empty = + codecs::encode(test::letters, std::array{}, tokens::fixed<0>{}); + BOOST_TEST(empty.has_value()); + BOOST_TEST(empty.value().view().empty()); +} + +void automatic_is_the_default() { + auto const defaulted = codecs::encode(test::letters, two_bytes); + auto const tagged = codecs::encode(test::letters, two_bytes, tokens::automatic{}); + static_assert(std::is_same_v); + BOOST_TEST(defaulted.value() == tagged.value()); + auto const defaulted_decode = codecs::decode(test::letters, std::string{"abpp"}); + auto const tagged_decode = + codecs::decode(test::letters, std::string{"abpp"}, tokens::automatic{}); + static_assert(std::is_same_v); + BOOST_TEST(defaulted_decode.value() == tagged_decode.value()); +} + +void a_failed_decode_leaves_the_token_untouched() { + std::string kept = "kept"; + auto const foreign = codecs::decode(test::letters, "abq", tokens::append_to(kept)); + BOOST_TEST(!foreign.has_value()); + BOOST_TEST(foreign.error() == codecs::error::invalid_character); + BOOST_TEST(kept == "kept"); + auto const odd = codecs::decode(test::letters, "abp", tokens::assign_to(kept)); + BOOST_TEST(odd.error() == codecs::error::invalid_length); + BOOST_TEST(kept == "kept"); + counting_token counting; + auto const refused = codecs::decode(test::letters, "abq", counting); + BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(counting.prepare_calls, 0); + BOOST_TEST_EQ(counting.result_calls, 0); + // A text whose bound saturates is refused before it is read. + std::string const long_text(test::saturating_t::most_characters + 1, 'a'); + auto const too_long = codecs::decode(test::saturating, long_text, counting); + BOOST_TEST(too_long.error() == codecs::error::input_too_long); + BOOST_TEST_EQ(counting.prepare_calls, 0); + // The same for an encode. + auto const long_input = std::vector(test::saturating_t::most_bytes + 1); + auto const encode_too_long = codecs::encode(test::saturating, long_input, counting); + BOOST_TEST(encode_too_long.error() == codecs::error::input_too_long); + BOOST_TEST_EQ(counting.prepare_calls, 0); + BOOST_TEST_EQ(counting.result_calls, 0); +} + +void a_token_is_used_once_with_the_exact_size() { + counting_token decoding; + auto const decoded = codecs::decode(test::letters, "abpp", decoding); + static_assert(std::is_same_v const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoding.prepare_calls, 1); + BOOST_TEST_EQ(decoding.result_calls, 1); + BOOST_TEST_EQ(decoding.prepared_size, 2U); + counting_token encoding; + auto const encoded = codecs::encode(test::letters, two_bytes, encoding); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(encoding.prepare_calls, 1); + BOOST_TEST_EQ(encoding.result_calls, 1); + BOOST_TEST_EQ(encoding.prepared_size, 4U); + BOOST_TEST(encoded.value() == "abpp"); + // An empty input still calls prepare once, with 0. + counting_token empty; + BOOST_TEST(codecs::decode(test::letters, "", empty).has_value()); + BOOST_TEST_EQ(empty.prepare_calls, 1); + BOOST_TEST_EQ(empty.prepared_size, 0U); + BOOST_TEST_EQ(empty.result_calls, 1); + // A token passed as an rvalue is used as given. + BOOST_TEST(codecs::encode(test::letters, two_bytes, counting_token{}).value() == "abpp"); +} + +void a_capacity_is_compared_before_prepare() { + // The spec's scenario on letters: 40 bytes are 80 characters, past a capacity of 54. + capped_token capped; + std::vector const forty(40); + auto const too_small = codecs::encode(test::letters, forty, capped); + BOOST_TEST(!too_small.has_value()); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(capped.prepare_calls, 0); + BOOST_TEST_EQ(capped.result_calls, 0); + // 27 bytes are 54 characters: they fit exactly. + std::vector const twenty_seven(27); + auto const exact = codecs::encode(test::letters, twenty_seven, capped); + BOOST_TEST(exact.has_value()); + BOOST_TEST_EQ(capped.prepare_calls, 1); + BOOST_TEST_EQ(capped.prepared_size, 54U); + // A decode of 120 characters is 60 bytes: past 54. + capped_token decoding; + std::string const hundred_twenty(120, 'a'); + auto const decoded_too_small = codecs::decode(test::letters, hundred_twenty, decoding); + BOOST_TEST(decoded_too_small.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(decoding.prepare_calls, 0); + // The data error comes before the capacity. + std::string const foreign = hundred_twenty + "q"; + BOOST_TEST(codecs::decode(test::letters, foreign, decoding).error() == + codecs::error::invalid_character); + BOOST_TEST_EQ(decoding.prepare_calls, 0); +} + +void a_byte_token_receives_the_bytes() { + byte_vector_token vector_token; + auto const decoded = codecs::decode(test::letters, "abpp", vector_token); + static_assert( + std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST((decoded.value() == std::vector{0x01, 0xff})); + BOOST_TEST_EQ(vector_token.prepare_calls, 1); + std_byte_token byte_token; + auto const as_bytes = codecs::decode(test::letters, "abpp", byte_token); + BOOST_TEST(as_bytes.has_value()); + BOOST_TEST_EQ(static_cast(as_bytes.value()[0]), 0x01U); + BOOST_TEST_EQ(static_cast(as_bytes.value()[1]), 0xffU); +} + +void a_value_codec_goes_through_a_token() { + auto const text_value = codecs::encode(test::be16, test::number{0x1234}, tokens::return_string); + BOOST_TEST(text_value.has_value()); + BOOST_TEST(bytes_of(text_value.value()) == (std::vector{0x12, 0x34})); + auto const fixed_value = codecs::encode(test::be16, test::number{0x1234}, tokens::fixed<4>{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed_value.has_value()); + BOOST_TEST_EQ(fixed_value.value().size(), 2U); + BOOST_TEST_EQ(fixed_value.value().data()[1], 0x34); + auto const too_small = codecs::encode(test::be16, test::number{0x1234}, tokens::fixed<1>{}); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + std::string appended = "kept"; + BOOST_TEST(codecs::encode(test::be16, test::hex_number{0xbeef}, tokens::append_to(appended)) + .has_value()); + BOOST_TEST(appended == "keptbeef"); + auto const hex_fixed = codecs::encode(test::be16, test::hex_number{0xbeef}, tokens::fixed<4>{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(hex_fixed.value().view() == "beef"); + // A byte token takes a value codec of text, written through a char. + byte_vector_token vector_token; + BOOST_TEST(codecs::encode(test::be16, test::hex_number{0xbeef}, vector_token).has_value()); + BOOST_TEST_EQ(vector_token.storage.size(), 4U); +} + +void a_typed_decode_uses_the_default_resource() { + auto const decoded = codecs::decode>(test::letters, "abpp"); + static_assert( + std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST((decoded.value() == std::pmr::vector{0x01, 0xff})); + BOOST_TEST(decoded.value().get_allocator().resource() == std::pmr::get_default_resource()); + auto const text_decoded = codecs::decode(test::letters, "abpp"); + BOOST_TEST(text_decoded.has_value()); + BOOST_TEST_EQ(text_decoded.value().size(), 2U); +} + +} // namespace + +int main() { + return_string_both_ways(); + append_to_a_string(); + append_to_a_vector_on_decode(); + assign_to_replaces(); + fixed_gives_fixed_results(); + automatic_is_the_default(); + a_failed_decode_leaves_the_token_untouched(); + a_token_is_used_once_with_the_exact_size(); + a_capacity_is_compared_before_prepare(); + a_byte_token_receives_the_bytes(); + a_value_codec_goes_through_a_token(); + a_typed_decode_uses_the_default_resource(); + return boost::report_errors(); +} From 36179eaf2120cbefb3948b4f217baf381c47ffe9 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 10:43:45 -0300 Subject: [PATCH 015/157] codecs: tokens lint fix --- include/webcpp/codecs/detail/core/operations.hpp | 11 ++++++++--- include/webcpp/codecs/detail/core/tokens.hpp | 4 ++-- test/allocator_test.cpp | 6 ++++-- test/default_result_test.cpp | 3 ++- test/messages/refused_token/refused_token.cpp | 2 +- test/support/allocators.hpp | 13 ++++++++----- test/support/arena.hpp | 14 +++++++------- test/tokens_test.cpp | 14 ++++++++------ 8 files changed, 40 insertions(+), 27 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index b269e2b..551d7fd 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -242,7 +242,7 @@ template return decoded_count.error(); } std::size_t const byte_count = decoded_count.unsafe_value(); - Target target_value = make_target(allocator_values...); + auto target_value = make_target(allocator_values...); std::span output_span; if constexpr (is_fixed_result) { if (byte_count > Target::capacity()) { @@ -310,12 +310,17 @@ template F const& format_value, Input const& input_value, Token& token_object) noexcept(token_is_noexcept) { constexpr bool from_value = value_encodable; - std::span input_view{}; + std::span const input_view = [&] { + if constexpr (from_value) { + return std::span{}; + } else { + return input_bytes(input_value); + } + }(); std::size_t output_size = 0; if constexpr (from_value) { output_size = value_codec::encoded_size(format_value, input_value); } else { - input_view = input_bytes(input_value); if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; } diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 09382c3..e34f53d 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -176,7 +176,7 @@ class returning_token { using result_type = String; /** Constructs a token whose string is made with `allocator_value`. */ - explicit returning_token(typename String::allocator_type const& allocator_value) noexcept + explicit returning_token(String::allocator_type const& allocator_value) noexcept : value_(allocator_value) {} /** Resizes the string to `size` characters and returns a pointer to them. */ @@ -246,7 +246,7 @@ concept token_argument = */ template [[nodiscard]] auto concrete_token(tokens::return_string_t const& tag_value) { - using string_allocator = typename std::allocator_traits::template rebind_alloc; + using string_allocator = std::allocator_traits::template rebind_alloc; using string_type = std::basic_string, string_allocator>; return returning_token{string_allocator{tag_value.allocator}}; } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 6a227e2..f8daf84 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -84,7 +84,8 @@ void return_string_over_an_arena() { BOOST_TEST(encoded.has_value()); BOOST_TEST(std::string_view{encoded.value()} == expected); BOOST_TEST(arena.owns(encoded.value().data())); - BOOST_TEST(encoded.value().get_allocator().resource() == &arena); + auto const& encoded_string = encoded.value(); + BOOST_TEST(encoded_string.get_allocator().resource() == &arena); }); BOOST_TEST_EQ(arena.allocation_count(), 1U); BOOST_TEST_GE(arena.allocation(0).size, expected.size() + 1); @@ -161,7 +162,8 @@ void a_typed_decode_with_an_allocator() { codecs::result> const>); BOOST_TEST(decoded.has_value()); BOOST_TEST_EQ(decoded.value().size(), input.size()); - BOOST_TEST(decoded.value().get_allocator().resource() == &arena); + auto const& decoded_vector = decoded.value(); + BOOST_TEST(decoded_vector.get_allocator().resource() == &arena); BOOST_TEST(arena.owns(decoded.value().data())); }); BOOST_TEST_EQ(arena.allocation_count(), 1U); diff --git a/test/default_result_test.cpp b/test/default_result_test.cpp index d9f8fff..3703bdb 100644 --- a/test/default_result_test.cpp +++ b/test/default_result_test.cpp @@ -174,7 +174,8 @@ void empty_inputs_give_empty_results() { auto const empty_fixed_text = codecs::encode(test::letters, std::array{}); BOOST_TEST(empty_fixed_text.has_value()); BOOST_TEST_EQ(empty_fixed_text.value().size(), 0U); - BOOST_TEST(empty_fixed_text.value().view().empty()); + std::string_view const empty_view = empty_fixed_text.value().view(); + BOOST_TEST(empty_view.empty()); auto const empty_heap_bytes = codecs::decode(test::letters, ""); BOOST_TEST(empty_heap_bytes.has_value()); BOOST_TEST(empty_heap_bytes.value().empty()); diff --git a/test/messages/refused_token/refused_token.cpp b/test/messages/refused_token/refused_token.cpp index e880012..0c37b0b 100644 --- a/test/messages/refused_token/refused_token.cpp +++ b/test/messages/refused_token/refused_token.cpp @@ -35,7 +35,7 @@ struct bytes_only_token { } /** The bytes. */ - result_type result() { return storage; } + result_type result() const { return storage; } /** The bytes. */ std::vector storage; diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 1e46cb6..5af7dc4 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -32,7 +32,7 @@ namespace webcpp::codecs::test { /** The count a throwing_allocator and its copies share. */ struct throwing_state { /** The allocation that throws, counted from 1; 0 for none. */ - std::size_t fail_at; + std::size_t fail_at = 0; /** The allocations made so far. */ std::size_t allocations = 0; }; @@ -48,11 +48,12 @@ class throwing_allocator { Constructs an allocator whose `fail_at`-th allocation, counted from 1, throws; 0 is none. */ explicit throwing_allocator(std::size_t fail_at) - : state_(std::make_shared(throwing_state{fail_at})) {} + : state_(std::make_shared(throwing_state{.fail_at = fail_at})) {} /** Constructs the allocator of another element type that shares this one's count. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // rebinding throwing_allocator(throwing_allocator const& other) noexcept : state_(other.state()) {} /** Allocates `count` elements, or throws on the allocation that is to fail. */ @@ -116,7 +117,8 @@ class non_propagating_allocator { /** Constructs the allocator of another element type with this one's number. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // rebinding non_propagating_allocator(non_propagating_allocator const& other) noexcept : identity_(other.identity()) {} @@ -163,7 +165,8 @@ class wipe_checking_allocator { /** Constructs the allocator of another element type that shares this one's count. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions): rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // rebinding wipe_checking_allocator(wipe_checking_allocator const& other) noexcept : state_(other.state()) {} diff --git a/test/support/arena.hpp b/test/support/arena.hpp index 72965ce..6467fd5 100644 --- a/test/support/arena.hpp +++ b/test/support/arena.hpp @@ -16,8 +16,8 @@ #include #include -#include #include +#include namespace webcpp::codecs::test { @@ -25,7 +25,7 @@ namespace webcpp::codecs::test { class recording_resource : public std::pmr::memory_resource { public: /** The size of the buffer the allocations come from. */ - static constexpr std::size_t buffer_size = 64 * 1024; + static constexpr std::size_t buffer_size = std::size_t{64} * 1024; /** The most allocations recorded; the count goes on past it. */ static constexpr std::size_t most_records = 64; @@ -42,8 +42,8 @@ class recording_resource : public std::pmr::memory_resource { resource is small on a stack; it is allocated here, not by an operation under test. */ recording_resource() - : buffer_(std::make_unique(buffer_size)), - upstream_(buffer_.get(), buffer_size, std::pmr::null_memory_resource()) {} + : buffer_(buffer_size), + upstream_(buffer_.data(), buffer_.size(), std::pmr::null_memory_resource()) {} /** The allocations made through this resource so far. */ [[nodiscard]] std::size_t allocation_count() const noexcept { return allocation_count_; } @@ -58,7 +58,7 @@ class recording_resource : public std::pmr::memory_resource { /** Whether `pointer` is inside the buffer: made by this resource, not by another one. */ [[nodiscard]] bool owns(void const* pointer) const noexcept { - auto const* const first_byte = buffer_.get(); + auto const* const first_byte = buffer_.data(); auto const* const byte_pointer = static_cast(pointer); return byte_pointer >= first_byte && byte_pointer < first_byte + buffer_size; } @@ -67,7 +67,7 @@ class recording_resource : public std::pmr::memory_resource { void* do_allocate(std::size_t size, std::size_t alignment) override { void* const pointer = upstream_.allocate(size, alignment); if (allocation_count_ < most_records) { - records_[allocation_count_] = record{size, pointer}; + records_[allocation_count_] = record{.size = size, .pointer = pointer}; } ++allocation_count_; return pointer; @@ -82,7 +82,7 @@ class recording_resource : public std::pmr::memory_resource { return this == &other; } - std::unique_ptr buffer_; // NOLINT(modernize-avoid-c-arrays) + std::vector buffer_; std::pmr::monotonic_buffer_resource upstream_; std::array records_{}; std::size_t allocation_count_ = 0; diff --git a/test/tokens_test.cpp b/test/tokens_test.cpp index e23a8e5..e6e3fe3 100644 --- a/test/tokens_test.cpp +++ b/test/tokens_test.cpp @@ -80,7 +80,7 @@ struct byte_vector_token { } /** The bytes. */ - result_type result() { return storage; } + result_type result() const { return storage; } /** The calls of `prepare`. */ int prepare_calls = 0; @@ -100,7 +100,7 @@ struct std_byte_token { } /** The bytes. */ - result_type result() { return storage; } + result_type result() const { return storage; } /** The bytes. */ std::vector storage; @@ -214,10 +214,11 @@ void fixed_gives_fixed_results() { BOOST_TEST(codecs::decode(test::letters, "abpq", tokens::fixed<1>{}).error() == codecs::error::invalid_character); // The empty input. - auto const empty = - codecs::encode(test::letters, std::array{}, tokens::fixed<0>{}); + constexpr std::array no_bytes{}; + auto const empty = codecs::encode(test::letters, no_bytes, tokens::fixed<0>{}); BOOST_TEST(empty.has_value()); - BOOST_TEST(empty.value().view().empty()); + std::string_view const empty_view = empty.value().view(); + BOOST_TEST(empty_view.empty()); } void automatic_is_the_default() { @@ -358,7 +359,8 @@ void a_typed_decode_uses_the_default_resource() { std::is_same_v> const>); BOOST_TEST(decoded.has_value()); BOOST_TEST((decoded.value() == std::pmr::vector{0x01, 0xff})); - BOOST_TEST(decoded.value().get_allocator().resource() == std::pmr::get_default_resource()); + auto const& decoded_vector = decoded.value(); + BOOST_TEST(decoded_vector.get_allocator().resource() == std::pmr::get_default_resource()); auto const text_decoded = codecs::decode(test::letters, "abpp"); BOOST_TEST(text_decoded.has_value()); BOOST_TEST_EQ(text_decoded.value().size(), 2U); From 449a66fb37296c145896e7bb330bb44c2d04c6aa Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 10:55:05 -0300 Subject: [PATCH 016/157] codecs: tokens lint fix, the allocators' suppressions and the nodiscard results --- test/messages/refused_token/refused_token.cpp | 2 +- test/support/allocators.hpp | 9 +++------ test/tokens_test.cpp | 4 ++-- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/test/messages/refused_token/refused_token.cpp b/test/messages/refused_token/refused_token.cpp index 0c37b0b..6f1b9b6 100644 --- a/test/messages/refused_token/refused_token.cpp +++ b/test/messages/refused_token/refused_token.cpp @@ -35,7 +35,7 @@ struct bytes_only_token { } /** The bytes. */ - result_type result() const { return storage; } + [[nodiscard]] result_type result() const { return storage; } /** The bytes. */ std::vector storage; diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 5af7dc4..e8e1e3a 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -52,8 +52,7 @@ class throwing_allocator { /** Constructs the allocator of another element type that shares this one's count. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) throwing_allocator(throwing_allocator const& other) noexcept : state_(other.state()) {} /** Allocates `count` elements, or throws on the allocation that is to fail. */ @@ -117,8 +116,7 @@ class non_propagating_allocator { /** Constructs the allocator of another element type with this one's number. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) non_propagating_allocator(non_propagating_allocator const& other) noexcept : identity_(other.identity()) {} @@ -165,8 +163,7 @@ class wipe_checking_allocator { /** Constructs the allocator of another element type that shares this one's count. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // rebinding + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) wipe_checking_allocator(wipe_checking_allocator const& other) noexcept : state_(other.state()) {} diff --git a/test/tokens_test.cpp b/test/tokens_test.cpp index e6e3fe3..835be20 100644 --- a/test/tokens_test.cpp +++ b/test/tokens_test.cpp @@ -80,7 +80,7 @@ struct byte_vector_token { } /** The bytes. */ - result_type result() const { return storage; } + [[nodiscard]] result_type result() const { return storage; } /** The calls of `prepare`. */ int prepare_calls = 0; @@ -100,7 +100,7 @@ struct std_byte_token { } /** The bytes. */ - result_type result() const { return storage; } + [[nodiscard]] result_type result() const { return storage; } /** The bytes. */ std::vector storage; From 8dd95471afcda22d81cd5457e6fef9c758f9fcfb Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:10:27 -0300 Subject: [PATCH 017/157] codecs: tokens fix round 1: bookkeeping blocks left out of the arena and the throwing allocator, a failed conversion puts an appending token back, tokens hold what was written, a constant capacity, plain refusal messages --- .../webcpp/codecs/detail/core/contract.hpp | 36 +++++++++ .../webcpp/codecs/detail/core/operations.hpp | 49 ++++++++--- include/webcpp/codecs/detail/core/tokens.hpp | 41 ++++++++-- test/allocator_test.cpp | 25 +++--- test/allocator_throw_test.cpp | 6 +- .../refused_allocator/refused_allocator.cpp | 18 +++-- test/messages/refused_token/refused_token.cpp | 5 +- test/support/allocators.hpp | 15 +++- test/support/arena.hpp | 25 +++++- test/support/be16.hpp | 28 +++++++ test/support/bookkeeping.hpp | 81 +++++++++++++++++++ test/tokens_boost_url_test.cpp | 10 ++- test/tokens_test.cpp | 76 +++++++++++++++++ 13 files changed, 360 insertions(+), 55 deletions(-) create mode 100644 test/support/bookkeeping.hpp diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index eec28ab..12f2314 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -380,6 +380,42 @@ constexpr void refuse() noexcept { "header, or specialize webcpp::codecs::value_codec for the format and the type"); } +/** + The requirement of a token's refusal: false for every pair, so that its static assertion, which + names it, prints the token's type and the format's type. +*/ +template +inline constexpr bool token_accepted = false; + +/** + Stops the build: `Token` does not receive the result of the operation that calls this, which is + an encode of bytes (a token of text is needed) or a decode (a token of bytes). +*/ +template +constexpr void refuse_token() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::token_accepted, + "webcpp::codecs: this token does not take the result of this operation; give " + "encode a token whose prepare returns a char*, decode a token whose prepare " + "returns a pointer to a one-byte element, or a tag of webcpp::codecs::tokens"); +} + +/** The requirement of an allocator's refusal: false for every pair. */ +template +inline constexpr bool allocator_accepted = false; + +/** + Stops the build: `Value` is no string or vector of bytes that `Allocator` constructs, the only + results that take an allocator. +*/ +template +constexpr void refuse_allocator() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::allocator_accepted, + "webcpp::codecs: only a std::basic_string or a std::vector " + "takes an allocator, and the allocator must construct it"); +} + /** The characters of a text input; an array of `char` is read up to its first zero and never past its end, as a string literal is read as a `std::string_view` (B5), and another range of `char` diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 551d7fd..103cc39 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -303,7 +303,10 @@ template /** Encodes into `token_object`, a concrete token (B6): the checks of the input, then the token's `capacity` against the exact size, then one `prepare` with that size, the format's `encode` into - what it returned, and one `result`. A token is untouched when a check fails. + what it returned, and one `result`. A token is untouched when a check fails. When the conversion + itself fails after `prepare` (a value codec's own error), a token of codecs' that appends is put + back as it was; an assigning token has lost its old content and a token of a program's own is + left as `prepare` made it. A token of codecs' is cut to the count the format wrote. */ template [[nodiscard]] result encode_to( @@ -348,8 +351,14 @@ template codec::encode(format_value, input_view, std::span{prepared, output_size}); } if (!written_size) { + if constexpr (abandonable_token) { + token_object.abandon(); + } return written_size.error(); } + if constexpr (shrinkable_token) { + token_object.shrink_to(written_size.unsafe_value()); + } return token_object.result(); } @@ -383,8 +392,14 @@ template codec::decode(format_value, text_characters, std::span{as_byte_pointer(prepared), byte_count}); if (!written_count) { + if constexpr (abandonable_token) { + token_object.abandon(); + } return written_count.error(); } + if constexpr (shrinkable_token) { + token_object.shrink_to(written_count.unsafe_value()); + } return token_object.result(); } @@ -547,8 +562,11 @@ template the buffer form's: every check of the input (an input whose encoding does not fit in `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one - `result`. A token is untouched when a check fails. The forms that allocate are not `noexcept` - (an allocator's exception propagates, owner decision 24); `fixed` is. A pair that is not + `result`. A token is untouched when a check fails (an error of a value codec's own, found after + `prepare`, puts an `append_to` token back as it was; an `assign_to` token and a token of a + program's own are left as `prepare` made them). A token of codecs' holds what the format wrote. The + forms that allocate are not `noexcept` (an allocator's exception propagates, owner decision 24); + `fixed` is. A pair that is not @ref encodable stops the build with a message that the format does not convert this type, and a token that does not take the pair's encoding (`append_to` of a vector, which is for decode) with one that names the token's type. @@ -575,7 +593,7 @@ template auto&& concrete_token = detail::concrete_token(token); return detail::encode_to(format_value, input_value, concrete_token); } else { - detail::refuse, F>(); + detail::refuse_token, F>(); return result{std::string{}}; } } else { @@ -596,8 +614,9 @@ template form's: a text whose bytes do not fit in `std::size_t` is @ref error::input_too_long, the whole text is checked and its data error with the lowest value of @ref error returned, then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the - exact size, the conversion, one `result`. A token is untouched when a check fails. The forms that - allocate are not `noexcept`; `fixed` is. A format with no `codec` specialization stops the + exact size, the conversion, one `result`. A token is untouched when a check fails (a conversion + that fails after `prepare` puts an `append_to` token back; see `encode`). The forms that allocate + are not `noexcept`; `fixed` is. A format with no `codec` specialization stops the build with a message that the format does not convert bytes (named `webcpp::codecs::detail::decoded_bytes`), and a token that is not a byte token with one that names the token's type. @@ -624,7 +643,7 @@ template auto&& concrete_token = detail::concrete_token(token); return detail::decode_to(format_value, text_value, concrete_token); } else { - detail::refuse, F>(); + detail::refuse_token, F>(); return result>{std::vector{}}; } } @@ -687,9 +706,10 @@ template The order and the errors are those of the typed decode without an allocator. It allocates, and is not `noexcept`: the allocator's exception propagates (owner decision 24). A `Value` that is - not a heap result of a format with a `codec`, or that `allocator_value` does not construct, - stops the build with a message that the format does not convert this type, and an input that is - not a text with one that names the input's type. + not a string or a vector of bytes, or that `allocator_value` does not construct, stops the build + with a message that only those take an allocator that constructs them, a format with no `codec` + with one that the format does not convert bytes, and an input that is not a text with one that + names the input's type. @tparam Value The string or vector to decode into. @tparam F The format's type. @@ -703,8 +723,11 @@ template template [[nodiscard]] result decode(F const& format_value, Input const& input_value, Allocator const& allocator_value) { - if constexpr (detail::heap_result && detail::has_codec && - std::constructible_from) { + if constexpr (!detail::has_codec) { + detail::refuse(); + return make_error_code(error::invalid_length); + } else if constexpr (detail::heap_result && + std::constructible_from) { if constexpr (detail::text_input) { return detail::decode_as(format_value, input_value, allocator_value); } else { @@ -712,7 +735,7 @@ template return make_error_code(error::invalid_length); } } else { - detail::refuse(); + detail::refuse_allocator(); return make_error_code(error::invalid_length); } } diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index e34f53d..86d85ee 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -61,11 +61,22 @@ concept byte_token = requires(T& token_object, std::size_t size) { { token_object.result() } -> std::convertible_to; }; -/** Whether the token type states `static constexpr std::size_t capacity`. */ +/** + Whether the token type states `static constexpr std::size_t capacity`: a constant, not a data + member of an object. +*/ template -concept has_token_capacity = requires { - { T::capacity } -> std::convertible_to; -}; +concept has_token_capacity = + requires { typename std::integral_constant; }; + +/** Whether the token can cut what `prepare` gave it back to the `written` elements written. */ +template +concept shrinkable_token = + requires(T& token_object, std::size_t written) { token_object.shrink_to(written); }; + +/** Whether the token can undo what `prepare` did, as if it had not been called. */ +template +concept abandonable_token = requires(T& token_object) { token_object.abandon(); }; } // namespace detail @@ -133,16 +144,23 @@ class appending_token { /** Grows the container by `size` elements and returns a pointer to the new ones. */ [[nodiscard]] auto* prepare(std::size_t size) { - std::size_t const old_size = target_->size(); - target_->resize(saturating_add(old_size, size)); - return target_->data() + old_size; + old_size_ = target_->size(); + target_->resize(saturating_add(old_size_, size)); + return target_->data() + old_size_; } + /** Cuts the container to the `written` elements appended. */ + void shrink_to(std::size_t written) noexcept { target_->resize(old_size_ + written); } + + /** Puts the container back as it was before `prepare`. */ + void abandon() noexcept { target_->resize(old_size_); } + /** The container. */ [[nodiscard]] result_type result() noexcept { return *target_; } private: Container* target_; + std::size_t old_size_ = 0; }; /** A token that replaces the content of a string or a vector with the result. */ @@ -161,6 +179,9 @@ class assigning_token { return target_->data(); } + /** Cuts the container to the `written` elements. */ + void shrink_to(std::size_t written) noexcept { target_->resize(written); } + /** The container. */ [[nodiscard]] result_type result() noexcept { return *target_; } @@ -185,6 +206,9 @@ class returning_token { return value_.data(); } + /** Cuts the string to the `written` characters. */ + void shrink_to(std::size_t written) noexcept { value_.resize(written); } + /** The string, moved out. */ [[nodiscard]] result_type result() noexcept { return std::move(value_); } @@ -208,6 +232,9 @@ class fixed_token { return fixed_access::writable(value_).data(); } + /** Sets the size to the `written` elements. */ + void shrink_to(std::size_t written) noexcept { fixed_access::resize(value_, written); } + /** The fixed result. */ [[nodiscard]] result_type result() noexcept { return value_; } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index f8daf84..7f40a0b 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -7,8 +7,11 @@ // The allocator rows of codecs (owner decision 23): every allocation of a form that takes an // allocator, or whose token holds a container with one, goes through that allocator, and the // global operator new, counted by support/counting.hpp, sees none. A recording memory resource is -// the arena; the allocators of the tests' own are checked against the standard's rules, too. Later -// tasks add their rows. +// the arena; the allocators of the tests' own are checked against the standard's rules, too. A +// standard container's own block, which the MSVC STL's debug containers allocate through their +// allocator, is no allocation of an operation: the arena leaves it out (support/bookkeeping.hpp), +// as document's and trystero's tests do, and it reaches the global operator new never. Later tasks +// add their rows. #include "support/counting.hpp" @@ -20,9 +23,11 @@ #include +#include #include #include #include +#include #include #include #include @@ -36,14 +41,6 @@ namespace codecs = webcpp::codecs; namespace test = webcpp::codecs::test; namespace tokens = webcpp::codecs::tokens; -// Debug builds of the MSVC library allocate a proxy per container through the global operator -// new, whatever the container's allocator: the global counter is not asked there. -#if defined(_MSC_VER) && defined(_ITERATOR_DEBUG_LEVEL) && _ITERATOR_DEBUG_LEVEL != 0 -constexpr bool global_counter_is_asked = false; -#else -constexpr bool global_counter_is_asked = true; -#endif - /** The allocations of the whole program so far: operator new's and the C library's. */ std::size_t global_allocations() { return test::counted_new.load() + test::counted_c.load(); @@ -55,12 +52,10 @@ void expect_no_global_allocation(char const* what, Body body) { std::size_t const before = global_allocations(); body(); std::size_t const after = global_allocations(); - if (global_counter_is_asked) { - if (after != before) { - std::printf("allocated globally: %s\n", what); - } - BOOST_TEST_EQ(after - before, 0U); + if (after != before) { + std::printf("allocated globally: %s\n", what); } + BOOST_TEST_EQ(after - before, 0U); } /** 32 bytes, and the text the format letters gives for them. */ diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index 218fd6a..5806b84 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -7,7 +7,10 @@ // An allocator that fails (owner decision 24): for every N, the Nth allocation of the operation // throws std::bad_alloc, which reaches the caller unchanged; the token's container still holds // what it held; and the first N that does not throw gives the right result. A program that needs -// exceptions, built with them on in every lane (the Jamfile). Later tasks add their rows. +// exceptions, built with them on in every lane (the Jamfile). A standard container's own block +// (the MSVC STL's debug proxy, allocated in noexcept constructors) is neither counted nor failed by +// throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). Later tasks add +// their rows. #include "support/allocators.hpp" #include "support/letters.hpp" @@ -16,6 +19,7 @@ #include +#include #include #include #include diff --git a/test/messages/refused_allocator/refused_allocator.cpp b/test/messages/refused_allocator/refused_allocator.cpp index e54c011..88c3f04 100644 --- a/test/messages/refused_allocator/refused_allocator.cpp +++ b/test/messages/refused_allocator/refused_allocator.cpp @@ -4,14 +4,15 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A typed decode with an allocator into a type that is no string or vector of bytes stops in the -// core's refusal, whose requirement names the type and the format's type (ruling R2): only a heap -// result takes an allocator. +// A typed decode with an allocator into a type that is no string or vector of bytes, or into one +// the allocator does not construct, stops in the core's refusal, whose requirement names the type +// and the allocator's type: only a heap result takes an allocator, and one it constructs. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted>': webcpp::codecs: only a std::basic_string or a std::vector takes an allocator, and the allocator must construct it}} +// expected-error-re@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted<{{.*}}, unrelated_allocator>': webcpp::codecs: only a std::basic_string or a std::vector takes an allocator, and the allocator must construct it}} // clang-format on #include "../../support/letters.hpp" @@ -19,13 +20,20 @@ #include #include +#include +#include /** A type that is no heap result. */ struct not_a_heap_result {}; +/** An allocator that constructs no vector. */ +struct unrelated_allocator {}; + int main() { namespace codecs = webcpp::codecs; auto const decoded = codecs::decode(codecs::test::letters, "ab", std::allocator{}); - return decoded.has_value() ? 0 : 1; + auto const not_constructed = codecs::decode>( + codecs::test::letters, "ab", unrelated_allocator{}); + return decoded.has_value() || not_constructed.has_value() ? 0 : 1; } diff --git a/test/messages/refused_token/refused_token.cpp b/test/messages/refused_token/refused_token.cpp index 6f1b9b6..a49a4ea 100644 --- a/test/messages/refused_token/refused_token.cpp +++ b/test/messages/refused_token/refused_token.cpp @@ -6,12 +6,13 @@ // A program that encodes into a token that takes bytes but not text (a pointer to `unsigned char` // from `prepare`, as `append_to` of a vector gives) stops in the core's refusal, whose requirement -// names the token's type and the format's type (ruling R2): the encoding of bytes is text. +// names the token's type and the format's type (ruling R2) and whose message says what a token +// must be: the encoding of bytes is text. // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::token_accepted': webcpp::codecs: this token does not take the result of this operation; give encode a token whose prepare returns a char*, decode a token whose prepare returns a pointer to a one-byte element, or a tag of webcpp::codecs::tokens}} // clang-format on #include "../../support/letters.hpp" diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index e8e1e3a..51b9dbf 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -7,7 +7,8 @@ // The allocators of the tests' own, as the standard library's rules see them (owner decision 23): // // - throwing_allocator throws std::bad_alloc on its fail_at-th allocation, counted across -// every copy and rebinding of it (a shared counter), and succeeds on every other; it is not +// every copy and rebinding of it (a shared counter), and succeeds on every other; a standard +// container's own block (support/bookkeeping.hpp) is not counted; it is not // declared when exceptions are off. // - non_propagating_allocator never propagates (on copy assignment, move assignment and swap) // and compares equal only to a copy of itself, so that a container's move between two of them @@ -18,6 +19,8 @@ #ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP +#include "bookkeeping.hpp" + #include #include @@ -57,9 +60,13 @@ class throwing_allocator { /** Allocates `count` elements, or throws on the allocation that is to fail. */ [[nodiscard]] T* allocate(std::size_t count) { - ++state_->allocations; - if (state_->allocations == state_->fail_at) { - throw std::bad_alloc(); + // A standard container's own block (the MSVC STL's debug proxy) is neither counted nor + // failed: it is allocated in noexcept constructors, where a throw ends the program. + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->allocations; + if (state_->allocations == state_->fail_at) { + throw std::bad_alloc(); + } } return std::allocator{}.allocate(count); } diff --git a/test/support/arena.hpp b/test/support/arena.hpp index 6467fd5..1ec9f10 100644 --- a/test/support/arena.hpp +++ b/test/support/arena.hpp @@ -9,11 +9,16 @@ // over it, which refuses what does not fit), and the resource counts and records each allocation's // size and pointer, so that a test sees which allocations went through the allocator it gave. The // records are in place: the resource allocates nothing through the global operator new once built, -// which a test that counts the global allocations relies on. +// which a test that counts the global allocations relies on. A standard container's own block +// (support/bookkeeping.hpp, which the MSVC STL's debug containers allocate through their +// allocator) is not counted, recorded or owned-checked as one of an operation: it is no state of +// what a test measures; all_allocation_count() counts every block. #ifndef WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP #define WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP +#include "bookkeeping.hpp" + #include #include #include @@ -43,9 +48,14 @@ class recording_resource : public std::pmr::memory_resource { */ recording_resource() : buffer_(buffer_size), - upstream_(buffer_.data(), buffer_.size(), std::pmr::null_memory_resource()) {} + upstream_(buffer_.data(), buffer_.size(), std::pmr::null_memory_resource()) { + static_cast(bookkeeping()); // measured here, not inside a test's window + } + + /** Every allocation made through this resource, a container's own block included. */ + [[nodiscard]] std::size_t all_allocation_count() const noexcept { return all_count_; } - /** The allocations made through this resource so far. */ + /** The allocations made through this resource so far, a container's own block left out. */ [[nodiscard]] std::size_t allocation_count() const noexcept { return allocation_count_; } /** The deallocations made through this resource so far. */ @@ -66,6 +76,10 @@ class recording_resource : public std::pmr::memory_resource { private: void* do_allocate(std::size_t size, std::size_t alignment) override { void* const pointer = upstream_.allocate(size, alignment); + ++all_count_; + if (is_bookkeeping(size, alignment)) { + return pointer; + } if (allocation_count_ < most_records) { records_[allocation_count_] = record{.size = size, .pointer = pointer}; } @@ -74,7 +88,9 @@ class recording_resource : public std::pmr::memory_resource { } void do_deallocate(void* pointer, std::size_t size, std::size_t alignment) override { - ++deallocation_count_; + if (!is_bookkeeping(size, alignment)) { + ++deallocation_count_; + } upstream_.deallocate(pointer, size, alignment); } @@ -85,6 +101,7 @@ class recording_resource : public std::pmr::memory_resource { std::vector buffer_; std::pmr::monotonic_buffer_resource upstream_; std::array records_{}; + std::size_t all_count_ = 0; std::size_t allocation_count_ = 0; std::size_t deallocation_count_ = 0; }; diff --git a/test/support/be16.hpp b/test/support/be16.hpp index ffbb4ff..7e5a6c7 100644 --- a/test/support/be16.hpp +++ b/test/support/be16.hpp @@ -48,6 +48,12 @@ struct hex_number { bool operator==(hex_number const&) const = default; }; +/** A value of be16 whose encoding fails after its size is known: checksum_mismatch. */ +struct failing_number { + /** The bits. */ + std::uint16_t value; +}; + } // namespace webcpp::codecs::test namespace webcpp::codecs { @@ -89,6 +95,28 @@ struct value_codec { } }; +/** The value codec of be16 for a `failing_number`: two bytes, written, then a failure. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Two bytes. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + test::failing_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes of its own, then reports checksum_mismatch. */ + static result encode(test::be16_t const& /*format*/, + test::failing_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return error::checksum_mismatch; + } +}; + /** The value codec of be16 for a `hex_number`: text with no stated bound. */ template <> struct value_codec { diff --git a/test/support/bookkeeping.hpp b/test/support/bookkeeping.hpp new file mode 100644 index 0000000..deb9026 --- /dev/null +++ b/test/support/bookkeeping.hpp @@ -0,0 +1,81 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// What a standard container allocates for itself through its allocator, rebound, whatever it +// holds: the MSVC STL's checked iterators (_ITERATOR_DEBUG_LEVEL above 0, the default of a debug +// build) allocate a proxy for each container when it is constructed and when it is moved, in its +// noexcept constructors as well; the other standard libraries allocate nothing so. A test that +// counts an allocator's allocations exactly, or fails the Nth, leaves such a block out, as +// webcpp::document's and webcpp::trystero's tests do (libs/document/test/counting.hpp, +// libs/trystero/test/bookkeeping.hpp): it is no state of what the test measures. Measured once, on +// an empty std::pmr::vector. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_BOOKKEEPING_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_BOOKKEEPING_HPP + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The block one standard container allocates for itself; its size is 0 when there is none. */ +struct container_bookkeeping { + /** The size of the block, or 0. */ + std::size_t bytes = 0; + /** The alignment of the block, or 0. */ + std::size_t alignment = 0; +}; + +/** What a standard container allocates for itself on this standard library. */ +inline container_bookkeeping const& bookkeeping() { + /** A resource that records the first block asked of it. */ + class measuring final : public std::pmr::memory_resource { + public: + /** The first block asked for. */ + container_bookkeeping seen; + + private: + void* do_allocate(std::size_t bytes, std::size_t alignment) override { + if (seen.bytes == 0) { + seen = container_bookkeeping{.bytes = bytes, .alignment = alignment}; + } + return std::pmr::new_delete_resource()->allocate(bytes, alignment); + } + + void do_deallocate(void* pointer, std::size_t bytes, std::size_t alignment) override { + std::pmr::new_delete_resource()->deallocate(pointer, bytes, alignment); + } + + [[nodiscard]] bool do_is_equal( + std::pmr::memory_resource const& other) const noexcept override { + return this == &other; + } + }; + + static container_bookkeeping const measured = [] { + measuring resource; + { + std::pmr::vector const empty{&resource}; + } + return resource.seen; + }(); + return measured; +} + +/** + Whether a block of `bytes` at `alignment` may be a standard container's own, as @ref bookkeeping + measures it; never on a standard library that allocates none. +*/ +inline bool is_bookkeeping(std::size_t bytes, std::size_t alignment) { + container_bookkeeping const& own = bookkeeping(); + return own.bytes != 0 && bytes == own.bytes && alignment == own.alignment; +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_BOOKKEEPING_HPP diff --git a/test/tokens_boost_url_test.cpp b/test/tokens_boost_url_test.cpp index caee0bc..c3e5d80 100644 --- a/test/tokens_boost_url_test.cpp +++ b/test/tokens_boost_url_test.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include namespace { @@ -29,11 +30,12 @@ namespace codecs = webcpp::codecs; namespace test = webcpp::codecs::test; namespace url_token = boost::urls::string_token; +using append_token_type = decltype(url_token::append_to(std::declval())); +using assign_token_type = decltype(url_token::assign_to(std::declval())); + static_assert(codecs::detail::text_token); -static_assert(codecs::detail::text_token< - url_token::implementation_defined::append_to_t>>); -static_assert(codecs::detail::byte_token< - url_token::implementation_defined::assign_to_t>>); +static_assert(codecs::detail::text_token); +static_assert(codecs::detail::byte_token); constexpr std::array two_bytes{0x01, 0xff}; diff --git a/test/tokens_test.cpp b/test/tokens_test.cpp index 835be20..cf89c0c 100644 --- a/test/tokens_test.cpp +++ b/test/tokens_test.cpp @@ -11,6 +11,7 @@ #include "support/be16.hpp" #include "support/letters.hpp" #include "support/saturating.hpp" +#include "support/shrinking.hpp" #include @@ -114,6 +115,17 @@ static_assert(codecs::detail::byte_token); static_assert(!codecs::detail::byte_token); static_assert(!codecs::detail::byte_token>); +// A capacity is a constant; a data member of that name is none. +struct member_capacity_token : counting_token { + /** Not a constant: a member of each object. */ + std::size_t capacity = 3; +}; + +static_assert(codecs::detail::has_token_capacity); +static_assert(codecs::detail::has_token_capacity>); +static_assert(!codecs::detail::has_token_capacity); +static_assert(!codecs::detail::has_token_capacity); + constexpr std::array two_bytes{0x01, 0xff}; /** The characters of a string as bytes. */ @@ -295,6 +307,21 @@ void a_capacity_is_compared_before_prepare() { BOOST_TEST(too_small.error() == codecs::error::output_too_small); BOOST_TEST_EQ(capped.prepare_calls, 0); BOOST_TEST_EQ(capped.result_calls, 0); + // The same over a static size, which the spec's scenario names: 54 is short of 80. + capped_token capped_static; + auto const static_too_small = + codecs::encode(test::letters, std::array{}, capped_static); + BOOST_TEST(static_too_small.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(capped_static.prepare_calls, 0); + auto const fixed_too_small = + codecs::encode(test::letters, std::array{}, tokens::fixed<54>{}); + BOOST_TEST(!fixed_too_small.has_value()); + BOOST_TEST(fixed_too_small.error() == codecs::error::output_too_small); + auto const fixed_heap_too_small = codecs::encode(test::letters, forty, tokens::fixed<54>{}); + BOOST_TEST(fixed_heap_too_small.error() == codecs::error::output_too_small); + // A data member called capacity is no capacity: the token is used and not compared. + member_capacity_token member_token; + BOOST_TEST(codecs::encode(test::letters, forty, member_token).has_value()); // 27 bytes are 54 characters: they fit exactly. std::vector const twenty_seven(27); auto const exact = codecs::encode(test::letters, twenty_seven, capped); @@ -366,6 +393,53 @@ void a_typed_decode_uses_the_default_resource() { BOOST_TEST_EQ(text_decoded.value().size(), 2U); } +void a_failure_after_prepare_puts_an_appending_token_back() { + // The value codec writes its bytes and then fails: nothing of it stays in an appended string. + std::string kept = "kept"; + auto const failed = + codecs::encode(test::be16, test::failing_number{0x1234}, tokens::append_to(kept)); + BOOST_TEST(!failed.has_value()); + BOOST_TEST(failed.error() == codecs::error::checksum_mismatch); + BOOST_TEST(kept == "kept"); + std::vector bytes_kept{9}; + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::append_to(bytes_kept)) + .has_value()); + BOOST_TEST_EQ(bytes_kept.size(), 1U); + // A token of the program's own is left as prepare made it, which the page says. + byte_vector_token foreign; + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, foreign).has_value()); + BOOST_TEST_EQ(foreign.prepare_calls, 1); + // No error: the result is the bytes. + BOOST_TEST(codecs::encode(test::be16, test::number{0x1234}, tokens::append_to(bytes_kept)) + .has_value()); + BOOST_TEST_EQ(bytes_kept.size(), 3U); +} + +void a_result_holds_what_the_format_wrote() { + // shrinking asks for one element more than it writes: the tokens of codecs' hold the written + // count, as the heap results do. + std::vector const held_bytes{0x01, 0xff}; + auto const returned = codecs::encode(test::shrinking, held_bytes, tokens::return_string); + BOOST_TEST(returned.has_value()); + BOOST_TEST(returned.value() == "abpp"); + std::string kept = "kept"; + BOOST_TEST(codecs::encode(test::shrinking, held_bytes, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "keptabpp"); + std::string assigned = "kept, replaced"; + BOOST_TEST( + codecs::encode(test::shrinking, held_bytes, tokens::assign_to(assigned)).has_value()); + BOOST_TEST(assigned == "abpp"); + auto const fixed_text = codecs::encode(test::shrinking, held_bytes, tokens::fixed<8>{}); + BOOST_TEST_EQ(fixed_text.value().size(), 4U); + auto const decoded = codecs::decode(test::shrinking, "abpp", tokens::return_string); + BOOST_TEST_EQ(decoded.value().size(), 2U); + std::vector appended{9}; + BOOST_TEST(codecs::decode(test::shrinking, "abpp", tokens::append_to(appended)).has_value()); + BOOST_TEST_EQ(appended.size(), 3U); + auto const fixed_bytes = codecs::decode(test::shrinking, "abpp", tokens::fixed<8>{}); + BOOST_TEST_EQ(fixed_bytes.value().size(), 2U); +} + } // namespace int main() { @@ -381,5 +455,7 @@ int main() { a_byte_token_receives_the_bytes(); a_value_codec_goes_through_a_token(); a_typed_decode_uses_the_default_resource(); + a_failure_after_prepare_puts_an_appending_token_back(); + a_result_holds_what_the_format_wrote(); return boost::report_errors(); } From 679669583a8fb0779642f71b0afeb2d313eb9182 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:10:52 -0300 Subject: [PATCH 018/157] codecs: tokens lint fix, the restoring hooks of the tokens may throw as resize does --- include/webcpp/codecs/detail/core/tokens.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 86d85ee..f6616e3 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -150,10 +150,10 @@ class appending_token { } /** Cuts the container to the `written` elements appended. */ - void shrink_to(std::size_t written) noexcept { target_->resize(old_size_ + written); } + void shrink_to(std::size_t written) { target_->resize(old_size_ + written); } /** Puts the container back as it was before `prepare`. */ - void abandon() noexcept { target_->resize(old_size_); } + void abandon() { target_->resize(old_size_); } /** The container. */ [[nodiscard]] result_type result() noexcept { return *target_; } @@ -180,7 +180,7 @@ class assigning_token { } /** Cuts the container to the `written` elements. */ - void shrink_to(std::size_t written) noexcept { target_->resize(written); } + void shrink_to(std::size_t written) { target_->resize(written); } /** The container. */ [[nodiscard]] result_type result() noexcept { return *target_; } @@ -207,7 +207,7 @@ class returning_token { } /** Cuts the string to the `written` characters. */ - void shrink_to(std::size_t written) noexcept { value_.resize(written); } + void shrink_to(std::size_t written) { value_.resize(written); } /** The string, moved out. */ [[nodiscard]] result_type result() noexcept { return std::move(value_); } From 6f23f5aa516a67ca1706fea9d6ddc178289a6435 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:42:18 -0300 Subject: [PATCH 019/157] codecs: the reference builds again: one-sentence briefs, every @tparam, @param and @return of text, bytes, fixed_byte_storage and the tokens --- .../webcpp/codecs/detail/core/contract.hpp | 8 +- include/webcpp/codecs/detail/core/results.hpp | 76 ++++++++++++++++--- include/webcpp/codecs/detail/core/tokens.hpp | 36 ++++++--- 3 files changed, 94 insertions(+), 26 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 12f2314..f569465 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -113,9 +113,11 @@ template class bytes; /** - Lets a library's fixed type be the target of a typed decode: a specialization has - `static constexpr std::size_t size` and `static std::span writable(T&) - noexcept`, and the decode fills exactly `size` bytes. Declared by the core, never defined. + Lets a library's fixed type be the target of a typed decode. + + A specialization has `static constexpr std::size_t size` and + `static std::span writable(T&) noexcept`, and the decode fills exactly `size` + bytes. Declared by the core, never defined. @tparam T The library's fixed type. */ diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp index 737e492..54458ad 100644 --- a/include/webcpp/codecs/detail/core/results.hpp +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -48,16 +48,32 @@ class text { /** Constructs a text of size 0 whose `N` characters are zero. */ constexpr text() noexcept = default; - /** The number of characters, at most `N`. */ + /** + The number of characters, at most `N`. + + @return The size. + */ [[nodiscard]] constexpr std::size_t size() const noexcept { return text_size_; } - /** The characters, `N` of them, those past `size()` zero. */ + /** + The characters, `N` of them, those past `size()` zero. + + @return A pointer to the first character. + */ [[nodiscard]] constexpr char const* data() const noexcept { return characters_.data(); } - /** The most characters it holds, `N`. */ + /** + The most characters it holds, `N`. + + @return `N`. + */ [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } - /** The first `size()` characters, valid while this text is. */ + /** + The first `size()` characters, valid while this text is. + + @return A view of the characters. + */ [[nodiscard]] constexpr std::string_view view() const& noexcept { return {characters_.data(), text_size_}; } @@ -65,7 +81,11 @@ class text { /** Deleted on an rvalue: the view would dangle. */ [[nodiscard]] std::string_view view() const&& = delete; - /** The first `size()` characters; implicit, on an lvalue only (B8). */ + /** + The first `size()` characters; implicit, on an lvalue only (B8). + + @return A view of the characters. + */ // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::string_view() const& noexcept { return view(); } @@ -73,7 +93,13 @@ class text { // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) operator std::string_view() const&& = delete; - /** Whether two texts hold the same characters. */ + /** + Whether two texts hold the same characters. + + @param first_text A text. + @param second_text Another text. + @return Whether their characters are the same. + */ friend constexpr bool operator==(text const& first_text, text const& second_text) noexcept { return first_text.view() == second_text.view(); } @@ -101,16 +127,32 @@ class bytes { /** Constructs bytes of size 0 whose `N` bytes are zero. */ constexpr bytes() noexcept = default; - /** The number of bytes, at most `N`. */ + /** + The number of bytes, at most `N`. + + @return The size. + */ [[nodiscard]] constexpr std::size_t size() const noexcept { return bytes_size_; } - /** The bytes, `N` of them, those past `size()` zero. */ + /** + The bytes, `N` of them, those past `size()` zero. + + @return A pointer to the first byte. + */ [[nodiscard]] constexpr std::uint8_t const* data() const noexcept { return held_bytes_.data(); } - /** The most bytes it holds, `N`. */ + /** + The most bytes it holds, `N`. + + @return `N`. + */ [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } - /** The first `size()` bytes, valid while these bytes are. */ + /** + The first `size()` bytes, valid while these bytes are. + + @return A view of the bytes. + */ [[nodiscard]] constexpr std::span view() const& noexcept { return {held_bytes_.data(), bytes_size_}; } @@ -118,7 +160,11 @@ class bytes { /** Deleted on an rvalue: the view would dangle. */ [[nodiscard]] std::span view() const&& = delete; - /** The first `size()` bytes; implicit, on an lvalue only (B8). */ + /** + The first `size()` bytes; implicit, on an lvalue only (B8). + + @return A view of the bytes. + */ // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::span() const& noexcept { return view(); } @@ -126,7 +172,13 @@ class bytes { // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) operator std::span() const&& = delete; - /** Whether two values hold the same bytes. */ + /** + Whether two values hold the same bytes. + + @param first_bytes Bytes. + @param second_bytes Other bytes. + @return Whether their bytes are the same. + */ friend constexpr bool operator==(bytes const& first_bytes, bytes const& second_bytes) noexcept { return std::ranges::equal(first_bytes.view(), second_bytes.view()); } diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index f6616e3..291dfe9 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -102,6 +102,7 @@ struct return_string_t { /** A tag that gives the string over `other`, which is used through `std::allocator_traits`. + @tparam Other The type of the allocator. @param other The allocator. @return The tag. */ @@ -116,8 +117,9 @@ struct return_string_t { inline constexpr return_string_t<> return_string{}; /** - The tag that gives `N` elements in place: `text` from `encode`, `bytes` from `decode` - (a value codec of bytes encodes into `bytes`). A result that does not fit is + The tag that gives `N` elements in place: `text` from `encode`, `bytes` from `decode`. + + A value codec of bytes encodes into `bytes`. A result that does not fit is @ref error::output_too_small. @tparam N The most elements. @@ -311,10 +313,14 @@ inline constexpr bool token_is_noexcept = namespace tokens { /** - The tag that appends the result to `target`, a string of any traits and allocator, used with the - string's own allocator. The operation returns `target` by reference, as Boost.URL's does; the - bytes of a decode are appended as characters. The input must not be a part of `target`. + The tag that appends the result to `target`, a string of any traits and allocator. + + The string's own allocator is used. The operation returns `target` by reference, as Boost.URL's + does; the bytes of a decode are appended as characters. The input must not be a part of + `target`. + @tparam Traits The string's character traits. + @tparam Allocator The string's allocator. @param target The string to append to. @return The token. */ @@ -324,9 +330,11 @@ template } /** - The tag that appends the bytes of a decode to `target`, a vector of any allocator, used with the - vector's own allocator; decode only. The operation returns `target` by reference. + The tag that appends the bytes of a decode to `target`, a vector of any allocator; decode only. + + The vector's own allocator is used. The operation returns `target` by reference. + @tparam Allocator The vector's allocator. @param target The vector to append to. @return The token. */ @@ -337,9 +345,13 @@ template /** The tag that replaces the content of `target`, a string of any traits and allocator, with the - result, used with the string's own allocator. The operation returns `target` by reference. The - input must not be a part of `target`. + result. + The string's own allocator is used. The operation returns `target` by reference. The input must + not be a part of `target`. + + @tparam Traits The string's character traits. + @tparam Allocator The string's allocator. @param target The string to assign to. @return The token. */ @@ -350,9 +362,11 @@ template /** The tag that replaces the content of `target`, a vector of any allocator, with the bytes of a - decode, used with the vector's own allocator; decode only. The operation returns `target` by - reference. + decode; decode only. + + The vector's own allocator is used. The operation returns `target` by reference. + @tparam Allocator The vector's allocator. @param target The vector to assign to. @return The token. */ From 62e6c71d6303a223b9b6a033309b0bfb93c37176 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:42:22 -0300 Subject: [PATCH 020/157] codecs: the secret results, in place and on the heap with any allocator, every buffer wiped before it is returned --- include/webcpp/codecs.hpp | 1 + include/webcpp/codecs/detail/core/results.hpp | 37 +- .../codecs/detail/core/secret_types.hpp | 829 ++++++++++++++++++ test/Jamfile | 10 + test/allocation_test.cpp | 32 + test/allocator_test.cpp | 59 +- test/allocator_throw_test.cpp | 88 +- test/noexcept_test.cpp | 41 + test/secret_fixed_test.cpp | 233 +++++ test/secret_heap_test.cpp | 414 +++++++++ test/support/allocators.hpp | 46 +- test/support/wipe_recorder.hpp | 81 ++ 12 files changed, 1851 insertions(+), 20 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/secret_types.hpp create mode 100644 test/secret_fixed_test.cpp create mode 100644 test/secret_heap_test.cpp create mode 100644 test/support/wipe_recorder.hpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 6353906..5421b5d 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include diff --git a/include/webcpp/codecs/detail/core/results.hpp b/include/webcpp/codecs/detail/core/results.hpp index 54458ad..523e361 100644 --- a/include/webcpp/codecs/detail/core/results.hpp +++ b/include/webcpp/codecs/detail/core/results.hpp @@ -6,8 +6,10 @@ /** The fixed results of webcpp::codecs: `text` and `bytes`, which hold their elements in - place and are inputs too. The specialization point `fixed_byte_storage`, which lets a library's - fixed type be the target of a typed decode, is declared in contract.hpp. + place and are inputs too, and the core's one door to the storage and the size of every fixed + result, the secret ones of secret_types.hpp included. The specialization point + `fixed_byte_storage`, which lets a library's fixed type be the target of a typed decode, is + declared in contract.hpp. */ #ifndef WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP #define WEBCPP_CODECS_DETAIL_CORE_RESULTS_HPP @@ -25,6 +27,12 @@ namespace webcpp::codecs { +template +class secret_text; + +template +class secret_bytes; + namespace detail { /** The core's writes into the fixed results: their storage and their size. */ @@ -218,6 +226,31 @@ struct fixed_access { static constexpr void resize(bytes& fixed_bytes, std::size_t new_size) noexcept { fixed_bytes.bytes_size_ = new_size; } + + /** The whole storage of a `secret_text`, to write the first `size` characters of. */ + template + [[nodiscard]] static std::span writable(secret_text& fixed_text) noexcept { + return std::span{fixed_text.characters_}; + } + + /** The whole storage of a `secret_bytes`, to write the first `size` bytes of. */ + template + [[nodiscard]] static std::span writable( + secret_bytes& fixed_bytes) noexcept { + return std::span{fixed_bytes.held_bytes_}; + } + + /** Sets the size of a `secret_text` whose first `new_size` characters were written. */ + template + static void resize(secret_text& fixed_text, std::size_t new_size) noexcept { + fixed_text.text_size_ = new_size; + } + + /** Sets the size of a `secret_bytes` whose first `new_size` bytes were written. */ + template + static void resize(secret_bytes& fixed_bytes, std::size_t new_size) noexcept { + fixed_bytes.bytes_size_ = new_size; + } }; } // namespace detail diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp new file mode 100644 index 0000000..1da9f80 --- /dev/null +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -0,0 +1,829 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The secret results of webcpp::codecs (D10, D22): `secret_text` and `secret_bytes`, which + hold their elements in place, and `basic_secret_string` and + `basic_secret_byte_vector`, which hold them on the heap through any allocator, with + their `std::allocator` aliases `secret_string` and `secret_byte_vector` and their + `codecs::pmr` aliases. Each is move-only, copied only by `clone()`, has no `operator==`, and + wipes every byte it held by `secure::erase_secret` before its storage goes. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_SECRET_TYPES_HPP +#define WEBCPP_CODECS_DETAIL_CORE_SECRET_TYPES_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The text of a secret encoding that fits `N` characters: the characters in place, and a size. + + It is move-only: a copy is asked for by name, with `clone()`. Its characters are wiped by + `secure::erase_secret` when it is destroyed and, the source's, when it is moved from; a moved-from + text is empty. It has no `operator==`, whose time would tell where two secrets differ. The + characters past `size()` are zero. The wipe covers the object's own storage only: a move or a + `clone` may leave copies of the characters in registers or temporaries, which the library does + not reach. + + @tparam N The most characters it holds. +*/ +template +class secret_text { +public: + /** Constructs a text of size 0 whose `N` characters are zero. */ + secret_text() noexcept = default; + + /** + Takes the characters of `moved_text`, which is wiped and left empty. + + @param moved_text The text to take the characters of. + */ + secret_text(secret_text&& moved_text) noexcept + : characters_(moved_text.characters_), text_size_(moved_text.text_size_) { + moved_text.wipe(); + } + + /** + Wipes these characters, then takes those of `moved_text`, which is wiped and left empty; a + move to itself changes nothing. + + @param moved_text The text to take the characters of. + @return This text. + */ + secret_text& operator=(secret_text&& moved_text) noexcept { + if (this != &moved_text) { + wipe(); + characters_ = moved_text.characters_; + text_size_ = moved_text.text_size_; + moved_text.wipe(); + } + return *this; + } + + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret_text(secret_text const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret_text& operator=(secret_text const&) = delete; + + /** Wipes the characters. */ + ~secret_text() { wipe(); } + + /** + The number of characters, at most `N`. + + @return The size. + */ + [[nodiscard]] std::size_t size() const noexcept { return text_size_; } + + /** + The characters, `N` of them, those past `size()` zero. + + @return A pointer to the first character. + */ + [[nodiscard]] char const* data() const noexcept { return characters_.data(); } + + /** + The most characters it holds, `N`. + + @return `N`. + */ + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + + /** + The first `size()` characters, valid while this text is. + + @return A view of the characters. + */ + [[nodiscard]] std::string_view view() const& noexcept { + return {characters_.data(), text_size_}; + } + + /** Deleted on an rvalue: the view would dangle. */ + [[nodiscard]] std::string_view view() const&& = delete; + + /** + A copy of the characters, which the caller then owns. + + @return A secret text of the same characters. + */ + [[nodiscard]] secret_text clone() const noexcept { + secret_text text_copy; + text_copy.characters_ = characters_; + text_copy.text_size_ = text_size_; + return text_copy; + } + +private: + friend struct detail::fixed_access; + + /** Zeroes every character, and the size. */ + void wipe() noexcept { + secure::erase_secret(characters_); + text_size_ = 0; + } + + std::array characters_{}; + std::size_t text_size_ = 0; +}; + +/** + The bytes of a secret decoding that fit `N` bytes: the bytes in place, and a size. + + It is move-only: a copy is asked for by name, with `clone()`. Its bytes are wiped by + `secure::erase_secret` when it is destroyed and, the source's, when it is moved from; moved-from + bytes are empty. It has no `operator==`, whose time would tell where two secrets differ. The bytes + past `size()` are zero. The wipe covers the object's own storage only: a move or a `clone` may + leave copies of the bytes in registers or temporaries, which the library does not reach. + + @tparam N The most bytes it holds. +*/ +template +class secret_bytes { +public: + /** Constructs bytes of size 0 whose `N` bytes are zero. */ + secret_bytes() noexcept = default; + + /** + Takes the bytes of `moved_bytes`, which are wiped and left empty. + + @param moved_bytes The bytes to take. + */ + secret_bytes(secret_bytes&& moved_bytes) noexcept + : held_bytes_(moved_bytes.held_bytes_), bytes_size_(moved_bytes.bytes_size_) { + moved_bytes.wipe(); + } + + /** + Wipes these bytes, then takes those of `moved_bytes`, which are wiped and left empty; a move + to itself changes nothing. + + @param moved_bytes The bytes to take. + @return These bytes. + */ + secret_bytes& operator=(secret_bytes&& moved_bytes) noexcept { + if (this != &moved_bytes) { + wipe(); + held_bytes_ = moved_bytes.held_bytes_; + bytes_size_ = moved_bytes.bytes_size_; + moved_bytes.wipe(); + } + return *this; + } + + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret_bytes(secret_bytes const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret_bytes& operator=(secret_bytes const&) = delete; + + /** Wipes the bytes. */ + ~secret_bytes() { wipe(); } + + /** + The number of bytes, at most `N`. + + @return The size. + */ + [[nodiscard]] std::size_t size() const noexcept { return bytes_size_; } + + /** + The bytes, `N` of them, those past `size()` zero. + + @return A pointer to the first byte. + */ + [[nodiscard]] std::uint8_t const* data() const noexcept { return held_bytes_.data(); } + + /** + The most bytes it holds, `N`. + + @return `N`. + */ + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + + /** + The first `size()` bytes, valid while these bytes are. + + @return A view of the bytes. + */ + [[nodiscard]] std::span view() const& noexcept { + return {held_bytes_.data(), bytes_size_}; + } + + /** Deleted on an rvalue: the view would dangle. */ + [[nodiscard]] std::span view() const&& = delete; + + /** + A copy of the bytes, which the caller then owns. + + @return Secret bytes of the same bytes. + */ + [[nodiscard]] secret_bytes clone() const noexcept { + secret_bytes bytes_copy; + bytes_copy.held_bytes_ = held_bytes_; + bytes_copy.bytes_size_ = bytes_size_; + return bytes_copy; + } + +private: + friend struct detail::fixed_access; + + /** Zeroes every byte, and the size. */ + void wipe() noexcept { + secure::erase_secret(held_bytes_); + bytes_size_ = 0; + } + + std::array held_bytes_{}; + std::size_t bytes_size_ = 0; +}; + +namespace detail { + +/** + The heap storage of the secret strings and byte vectors: `Element`s in one buffer of + `Allocator`'s, used through `std::allocator_traits`, with the standard library's propagation. + + Every buffer is wiped by `secure::erase_secret`, its whole capacity, before it is given back to + the allocator, and the elements cut off are wiped when the size goes down. A growth allocates the + new buffer first, the only call that may throw, then copies the elements and wipes and gives back + the old one: an allocation that throws leaves the value as it was, and no buffer of the growth + has held a byte. The elements are bytes, written as `std::basic_string` writes its characters, + with no call of the allocator's `construct`. + + @tparam Element `char` or `std::uint8_t`. + @tparam Allocator An allocator of `Element`. +*/ +template +class secret_buffer { + using traits = std::allocator_traits; + using pointer = traits::pointer; + +public: + /** Constructs an empty buffer that allocates through `allocator_value`. */ + explicit secret_buffer(Allocator const& allocator_value) noexcept + : allocator_(allocator_value) {} + + /** Takes the buffer and the allocator of `moved_buffer`, which is left empty. */ + secret_buffer(secret_buffer&& moved_buffer) noexcept + : allocator_(std::move(moved_buffer.allocator_)), + elements_(std::exchange(moved_buffer.elements_, nullptr)), + element_count_(std::exchange(moved_buffer.element_count_, 0)), + element_capacity_(std::exchange(moved_buffer.element_capacity_, 0)) {} + + /** + Gives back this buffer, wiped, and takes `moved_buffer`'s, with its allocator when the + allocator propagates on move assignment; between unequal allocators that do not, copies the + elements into this buffer (a new one of this allocator when they do not fit) and gives back + `moved_buffer`'s, wiped. `moved_buffer` is left empty; a move to itself changes nothing. When + the copy's allocation throws, neither changed. + */ + secret_buffer& operator=(secret_buffer&& moved_buffer) noexcept( + traits::propagate_on_container_move_assignment::value || traits::is_always_equal::value) { + if (this == &moved_buffer) { + return *this; + } + if constexpr (traits::propagate_on_container_move_assignment::value) { + release(); + allocator_ = std::move(moved_buffer.allocator_); + take(moved_buffer); + } else { + if (shares_allocator(moved_buffer)) { + release(); + take(moved_buffer); + } else { + assign(moved_buffer.view()); + moved_buffer.release(); + } + } + return *this; + } + + /** Not copyable: a copy is made by `clone`. */ + secret_buffer(secret_buffer const&) = delete; + /** Not copyable: a copy is made by `clone`. */ + secret_buffer& operator=(secret_buffer const&) = delete; + + /** Wipes the buffer and gives it back. */ + ~secret_buffer() { release(); } + + /** A buffer of the same elements, of the allocator the standard library gives a copy. */ + [[nodiscard]] secret_buffer clone() const { + secret_buffer buffer_copy{traits::select_on_container_copy_construction(allocator_)}; + buffer_copy.append(view()); + return buffer_copy; + } + + /** The number of elements. */ + [[nodiscard]] std::size_t size() const noexcept { return element_count_; } + + /** The number of elements the buffer holds without allocating. */ + [[nodiscard]] std::size_t capacity() const noexcept { return element_capacity_; } + + /** The elements, or null when there is no buffer. */ + [[nodiscard]] Element* data() noexcept { return std::to_address(elements_); } + + /** The elements, or null when there is no buffer. */ + [[nodiscard]] Element const* data() const noexcept { return std::to_address(elements_); } + + /** The elements, valid until the buffer changes. */ + [[nodiscard]] std::span view() const noexcept { + return {data(), element_count_}; + } + + /** A copy of the allocator. */ + [[nodiscard]] Allocator get_allocator() const noexcept { return allocator_; } + + /** Appends `appended`, which may be elements of this buffer. */ + void append(std::span appended) { + std::size_t const appended_count = appended.size(); + if (appended_count > element_capacity_ - element_count_) { + move_to_new_buffer(grown_capacity(saturating_add(element_count_, appended_count)), + appended); + } else { + std::ranges::copy(appended, data() + element_count_); + } + element_count_ += appended_count; + } + + /** Makes room for `new_capacity` elements; a smaller one changes nothing. */ + void reserve(std::size_t new_capacity) { + if (new_capacity > element_capacity_) { + move_to_new_buffer(new_capacity, {}); + } + } + + /** + Sets the size to `new_size`: the elements past the old size are left to be written, and those + cut off are wiped. + */ + void resize_for_overwrite(std::size_t new_size) { + if (new_size > element_capacity_) { + move_to_new_buffer(grown_capacity(new_size), {}); + } else if (new_size < element_count_) { + secure::erase_secret(std::span{data() + new_size, element_count_ - new_size}); + } + element_count_ = new_size; + } + + /** Wipes the elements; the buffer stays. */ + void clear() noexcept { + secure::erase_secret(std::span{data(), element_count_}); + element_count_ = 0; + } + + /** Moves the elements to a buffer of their size, or gives the buffer back when empty. */ + void shrink_to_fit() { + if (element_capacity_ == element_count_) { + return; + } + if (element_count_ == 0) { + release(); + } else { + move_to_new_buffer(element_count_, {}); + } + } + +private: + /** Whether `other`'s buffer may be given back through this allocator. */ + [[nodiscard]] bool shares_allocator(secret_buffer const& other) const noexcept { + if constexpr (traits::is_always_equal::value) { + return true; + } else { + return allocator_ == other.allocator_; + } + } + + /** The capacity of a growth to `needed` elements: twice the old one, or `needed` if more. */ + [[nodiscard]] std::size_t grown_capacity(std::size_t needed) const noexcept { + std::size_t const doubled = + element_capacity_ <= traits::max_size(allocator_) / 2 ? element_capacity_ * 2 : needed; + return std::max(needed, doubled); + } + + /** + Allocates a buffer of `new_capacity` elements, copies the elements and then `appended` into + it, and gives back the old one, wiped; the size is the caller's to set. The allocation comes + first: when it throws, nothing changed. + */ + void move_to_new_buffer(std::size_t new_capacity, std::span appended) { + pointer const fresh = traits::allocate(allocator_, new_capacity); + Element* const fresh_elements = std::to_address(fresh); + std::ranges::copy(view(), fresh_elements); + std::ranges::copy(appended, fresh_elements + element_count_); + std::size_t const kept_count = element_count_; + release(); + elements_ = fresh; + element_count_ = kept_count; + element_capacity_ = new_capacity; + } + + /** + Copies `source`, elements of another buffer, into this one, in a new buffer when they do not + fit, and wipes the elements of this one past them. The allocation comes first: when it throws, + nothing changed. + */ + void assign(std::span source) { + std::size_t const source_count = source.size(); + if (source_count > element_capacity_) { + pointer const fresh = traits::allocate(allocator_, source_count); + release(); + elements_ = fresh; + element_capacity_ = source_count; + } else if (element_count_ > source_count) { + secure::erase_secret( + std::span{data() + source_count, element_count_ - source_count}); + } + std::ranges::copy(source, data()); + element_count_ = source_count; + } + + /** Takes the buffer of `other`, which is left empty; this one has none. */ + void take(secret_buffer& other) noexcept { + elements_ = std::exchange(other.elements_, nullptr); + element_count_ = std::exchange(other.element_count_, 0); + element_capacity_ = std::exchange(other.element_capacity_, 0); + } + + /** Wipes the whole buffer, gives it back, and leaves this one empty. */ + void release() noexcept { + if (elements_ != nullptr) { + secure::erase_secret(std::span{data(), element_capacity_}); + traits::deallocate(allocator_, elements_, element_capacity_); + elements_ = nullptr; + } + element_count_ = 0; + element_capacity_ = 0; + } + + Allocator allocator_; + pointer elements_ = nullptr; + std::size_t element_count_ = 0; + std::size_t element_capacity_ = 0; +}; + +} // namespace detail + +/** + A secret string on the heap, of any allocator: the text of a secret encoding whose size is not + known at compile time. + + It is move-only: a copy is asked for by name, with `clone()`. Every buffer it held is wiped by + `secure::erase_secret`, its whole capacity, before the allocator gets it back: on destruction, on + `shrink_to_fit`, and the old buffer when it grows, with any allocator, an arena's included. It is + never a `std::basic_string`, whose small buffer no allocator can wipe. The allocator is used + through `std::allocator_traits` and propagates as the standard library's containers' does; a move + assignment between unequal allocators that do not propagate copies the characters into the + target's memory and wipes the source's. The allocating members may throw what the allocator + throws, and then leave the value as it was; codecs throws nothing of its own. It has no + `operator==`, whose time would tell where two secrets differ. + + @tparam Allocator An allocator of `char`; `std::allocator` for `secret_string`. +*/ +template > +class basic_secret_string { + static_assert(std::is_same_v::value_type, char>, + "webcpp::codecs: the allocator of a basic_secret_string allocates char."); + +public: + /** The allocator type. */ + using allocator_type = Allocator; + + /** + Constructs an empty string, which allocates nothing until it holds a character. + + @param allocator The allocator of its buffers. + */ + explicit basic_secret_string(Allocator const& allocator = Allocator()) noexcept + : buffer_(allocator) {} + + /** + Takes the buffer and the allocator of `moved_string`, which is left empty. + + @param moved_string The string to take the buffer of. + */ + basic_secret_string(basic_secret_string&& moved_string) noexcept = default; + + /** + Gives back this buffer, wiped, and takes `moved_string`'s, as `std::allocator_traits` says. + + It takes the allocator too when the allocator propagates on move assignment; between unequal + allocators that do not, it copies the characters into this string's memory and wipes + `moved_string`'s. `moved_string` is left empty. + + @param moved_string The string to take the characters of. + @return This string. + */ + basic_secret_string& operator=(basic_secret_string&& moved_string) = default; + + /** Not copyable: a copy is asked for by name, with `clone`. */ + basic_secret_string(basic_secret_string const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + basic_secret_string& operator=(basic_secret_string const&) = delete; + + /** Wipes the buffer, its whole capacity, and gives it back. */ + ~basic_secret_string() = default; + + /** + A copy of the characters in a buffer of their size, which the caller then owns, of the + allocator `std::allocator_traits` gives a copy. + + @return A secret string of the same characters. + */ + [[nodiscard]] basic_secret_string clone() const { return basic_secret_string{buffer_.clone()}; } + + /** + The number of characters. + + @return The size. + */ + [[nodiscard]] std::size_t size() const noexcept { return buffer_.size(); } + + /** + The number of characters the string holds without allocating. + + @return The capacity. + */ + [[nodiscard]] std::size_t capacity() const noexcept { return buffer_.capacity(); } + + /** + Whether there is no character. + + @return Whether the size is 0. + */ + [[nodiscard]] bool empty() const noexcept { return buffer_.size() == 0; } + + /** + The characters, or null when there is no buffer. + + @return A pointer to the first character, or null. + */ + [[nodiscard]] char* data() noexcept { return buffer_.data(); } + + /** + The characters, or null when there is no buffer. + + @return A pointer to the first character, or null. + */ + [[nodiscard]] char const* data() const noexcept { return buffer_.data(); } + + /** + The characters, valid until the string changes. + + @return A view of the characters. + */ + [[nodiscard]] std::string_view view() const& noexcept { + return {buffer_.data(), buffer_.size()}; + } + + /** Deleted on an rvalue: the view would dangle. */ + [[nodiscard]] std::string_view view() const&& = delete; + + /** + The allocator. + + @return A copy of the allocator. + */ + [[nodiscard]] Allocator get_allocator() const noexcept { return buffer_.get_allocator(); } + + /** + Appends `appended`, which may be characters of this string. + + Past the capacity, a buffer at least twice as large is allocated, and the old one wiped and + given back. + + @param appended The characters. + */ + void append(std::string_view appended) { + buffer_.append(std::span{appended.data(), appended.size()}); + } + + /** + Makes room for `new_capacity` characters, in a new buffer, the old one wiped and given back; a + smaller capacity changes nothing. + + @param new_capacity The characters to hold without allocating. + */ + void reserve(std::size_t new_capacity) { buffer_.reserve(new_capacity); } + + /** + Sets the size to `new_size`: the characters past the old size are left for the caller to + write through `data()`, and those cut off are wiped. + + @param new_size The number of characters. + */ + void resize_for_overwrite(std::size_t new_size) { buffer_.resize_for_overwrite(new_size); } + + /** Wipes the characters and sets the size to 0; the buffer stays. */ + void clear() noexcept { buffer_.clear(); } + + /** Moves the characters to a buffer of their size, the old one wiped and given back. */ + void shrink_to_fit() { buffer_.shrink_to_fit(); } + +private: + explicit basic_secret_string(detail::secret_buffer&& cloned_buffer) noexcept + : buffer_(std::move(cloned_buffer)) {} + + detail::secret_buffer buffer_; +}; + +/** + Secret bytes on the heap, of any allocator: the bytes of a secret decoding whose size is not + known at compile time. + + It is move-only: a copy is asked for by name, with `clone()`. Every buffer it held is wiped by + `secure::erase_secret`, its whole capacity, before the allocator gets it back: on destruction, on + `shrink_to_fit`, and the old buffer when it grows, with any allocator, an arena's included. The + allocator is used through `std::allocator_traits` and propagates as the standard library's + containers' does; a move assignment between unequal allocators that do not propagate copies the + bytes into the target's memory and wipes the source's. The allocating members may throw what the + allocator throws, and then leave the value as it was; codecs throws nothing of its own. It has no + `operator==`, whose time would tell where two secrets differ. + + @tparam Allocator An allocator of `std::uint8_t`; `std::allocator` for + `secret_byte_vector`. +*/ +template > +class basic_secret_byte_vector { + static_assert( + std::is_same_v::value_type, std::uint8_t>, + "webcpp::codecs: the allocator of a basic_secret_byte_vector allocates std::uint8_t."); + +public: + /** The allocator type. */ + using allocator_type = Allocator; + + /** + Constructs empty bytes, which allocate nothing until they hold a byte. + + @param allocator The allocator of their buffers. + */ + explicit basic_secret_byte_vector(Allocator const& allocator = Allocator()) noexcept + : buffer_(allocator) {} + + /** + Takes the buffer and the allocator of `moved_bytes`, which are left empty. + + @param moved_bytes The bytes to take the buffer of. + */ + basic_secret_byte_vector(basic_secret_byte_vector&& moved_bytes) noexcept = default; + + /** + Gives back this buffer, wiped, and takes `moved_bytes`'s, as `std::allocator_traits` says. + + It takes the allocator too when the allocator propagates on move assignment; between unequal + allocators that do not, it copies the bytes into this vector's memory and wipes + `moved_bytes`'s. `moved_bytes` are left empty. + + @param moved_bytes The bytes to take. + @return These bytes. + */ + basic_secret_byte_vector& operator=(basic_secret_byte_vector&& moved_bytes) = default; + + /** Not copyable: a copy is asked for by name, with `clone`. */ + basic_secret_byte_vector(basic_secret_byte_vector const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + basic_secret_byte_vector& operator=(basic_secret_byte_vector const&) = delete; + + /** Wipes the buffer, its whole capacity, and gives it back. */ + ~basic_secret_byte_vector() = default; + + /** + A copy of the bytes in a buffer of their size, which the caller then owns, of the allocator + `std::allocator_traits` gives a copy. + + @return Secret bytes of the same bytes. + */ + [[nodiscard]] basic_secret_byte_vector clone() const { + return basic_secret_byte_vector{buffer_.clone()}; + } + + /** + The number of bytes. + + @return The size. + */ + [[nodiscard]] std::size_t size() const noexcept { return buffer_.size(); } + + /** + The number of bytes the vector holds without allocating. + + @return The capacity. + */ + [[nodiscard]] std::size_t capacity() const noexcept { return buffer_.capacity(); } + + /** + Whether there is no byte. + + @return Whether the size is 0. + */ + [[nodiscard]] bool empty() const noexcept { return buffer_.size() == 0; } + + /** + The bytes, or null when there is no buffer. + + @return A pointer to the first byte, or null. + */ + [[nodiscard]] std::uint8_t* data() noexcept { return buffer_.data(); } + + /** + The bytes, or null when there is no buffer. + + @return A pointer to the first byte, or null. + */ + [[nodiscard]] std::uint8_t const* data() const noexcept { return buffer_.data(); } + + /** + The bytes, valid until the vector changes. + + @return A view of the bytes. + */ + [[nodiscard]] std::span view() const& noexcept { return buffer_.view(); } + + /** Deleted on an rvalue: the view would dangle. */ + [[nodiscard]] std::span view() const&& = delete; + + /** + The allocator. + + @return A copy of the allocator. + */ + [[nodiscard]] Allocator get_allocator() const noexcept { return buffer_.get_allocator(); } + + /** + Appends `appended`, which may be bytes of this vector. + + Past the capacity, a buffer at least twice as large is allocated, and the old one wiped and + given back. + + @param appended The bytes. + */ + void append(std::span appended) { buffer_.append(appended); } + + /** + Makes room for `new_capacity` bytes, in a new buffer, the old one wiped and given back; a + smaller capacity changes nothing. + + @param new_capacity The bytes to hold without allocating. + */ + void reserve(std::size_t new_capacity) { buffer_.reserve(new_capacity); } + + /** + Sets the size to `new_size`: the bytes past the old size are left for the caller to write + through `data()`, and those cut off are wiped. + + @param new_size The number of bytes. + */ + void resize_for_overwrite(std::size_t new_size) { buffer_.resize_for_overwrite(new_size); } + + /** Wipes the bytes and sets the size to 0; the buffer stays. */ + void clear() noexcept { buffer_.clear(); } + + /** Moves the bytes to a buffer of their size, the old one wiped and given back. */ + void shrink_to_fit() { buffer_.shrink_to_fit(); } + +private: + explicit basic_secret_byte_vector( + detail::secret_buffer&& cloned_buffer) noexcept + : buffer_(std::move(cloned_buffer)) {} + + detail::secret_buffer buffer_; +}; + +/** A secret string of `std::allocator`. */ +using secret_string = basic_secret_string<>; + +/** Secret bytes of `std::allocator`. */ +using secret_byte_vector = basic_secret_byte_vector<>; + +/** The secret heap types over `std::pmr::polymorphic_allocator`, as `std::pmr`'s containers. */ +namespace pmr { + +/** A secret string of a memory resource. */ +using secret_string = basic_secret_string>; + +/** Secret bytes of a memory resource. */ +using secret_byte_vector = basic_secret_byte_vector>; + +} // namespace pmr + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_SECRET_TYPES_HPP diff --git a/test/Jamfile b/test/Jamfile index 8028f1c..32c0f6c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -49,6 +49,16 @@ codecs-run sizes : sizes_test.cpp ; # The fixed results text and bytes: regular, by content, the view of # an lvalue only. codecs-run results : results_test.cpp ; +# The secret results in place, secret_text and secret_bytes: move-only, +# copied by clone(), wiped on a move and on destruction, as secure's wipe seam +# records it. +codecs-run secret_fixed : secret_fixed_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The secret results on the heap, with any allocator: every buffer wiped before +# the allocator gets it back, the old one on growth included; the propagation of +# std::allocator_traits; the approved spellings. +codecs-run secret_heap : secret_heap_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 7fffdce..c5e0714 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include namespace { @@ -336,6 +337,36 @@ void check_fixed_tokens() { BOOST_TEST(verdict); } +/** The secret results in place (Task 5) allocate nothing, nor does a heap one that holds nothing. + */ +void check_secret_results() { + bool volatile verdict = false; + expect_no_allocation("the fixed secret results", [&] { + codecs::secret_text<64> held_text; + codecs::detail::fixed_access::writable(held_text)[0] = 's'; + codecs::detail::fixed_access::resize(held_text, 1); + codecs::secret_text<64> const moved_text{std::move(held_text)}; + codecs::secret_text<64> const cloned_text = moved_text.clone(); + codecs::secret_bytes<32> held_bytes; + codecs::detail::fixed_access::writable(held_bytes)[0] = 0x5a; + codecs::detail::fixed_access::resize(held_bytes, 1); + codecs::secret_bytes<32> moved_bytes; + moved_bytes = std::move(held_bytes); + codecs::secret_bytes<32> const cloned_bytes = moved_bytes.clone(); + verdict = cloned_text.view() == "s" && cloned_bytes.view()[0] == 0x5a; + }); + BOOST_TEST(verdict); + expect_no_allocation("an empty secret on the heap", [&] { + codecs::secret_byte_vector empty_bytes; + empty_bytes.append(std::span{}); + codecs::secret_string empty_text; + empty_text.clear(); + codecs::secret_string const moved_text{std::move(empty_text)}; + verdict = empty_bytes.empty() && moved_text.empty() && empty_bytes.clone().empty(); + }); + BOOST_TEST(verdict); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -381,6 +412,7 @@ int main() { check_buffer_forms(); check_fixed_results(); check_fixed_tokens(); + check_secret_results(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 7f40a0b..82ffa17 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -10,8 +10,8 @@ // the arena; the allocators of the tests' own are checked against the standard's rules, too. A // standard container's own block, which the MSVC STL's debug containers allocate through their // allocator, is no allocation of an operation: the arena leaves it out (support/bookkeeping.hpp), -// as document's and trystero's tests do, and it reaches the global operator new never. Later tasks -// add their rows. +// as document's and trystero's tests do, and it reaches the global operator new never. The secret +// heap types over the arena give it back every buffer wiped. Later tasks add their rows. #include "support/counting.hpp" @@ -181,6 +181,60 @@ void a_typed_decode_with_an_allocator() { BOOST_TEST_EQ(arena.allocation_count(), before); } +/** The secret heap types over the arena (Task 5): every buffer, the old ones of a growth too, comes + from the arena and goes back to it wiped, and the global operator new sees none. */ +void secret_types_over_an_arena() { + test::recording_resource arena; + auto const input = bytes_32(); + expect_no_global_allocation("pmr::secret_byte_vector", [&] { + codecs::pmr::secret_byte_vector secret{&arena}; + secret.append(input); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST(arena.owns(secret.data())); + secret.append(input); // past the capacity: a second buffer of the arena's + BOOST_TEST_EQ(arena.allocation_count(), 2U); + BOOST_TEST(arena.owns(secret.data())); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); + BOOST_TEST_EQ(secret.size(), 2 * input.size()); + // A clone takes the allocator std::allocator_traits gives a copy: for a + // polymorphic_allocator, the default memory resource, as a std::pmr container's copy. + std::array copy_storage{}; + std::pmr::monotonic_buffer_resource copies{copy_storage.data(), copy_storage.size(), + std::pmr::null_memory_resource()}; + std::pmr::memory_resource* const previous = std::pmr::set_default_resource(&copies); + auto const copy = secret.clone(); + std::pmr::set_default_resource(previous); + BOOST_TEST(copy.get_allocator().resource() == &copies); + BOOST_TEST(std::ranges::equal(copy.view(), secret.view())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 2U); + BOOST_TEST_EQ(arena.deallocation_count(), 2U); + // A monotonic arena never reuses what it is given back: each buffer still reads zero in it. + for (std::size_t index = 0; index < arena.allocation_count(); ++index) { + auto const& block = arena.allocation(index); + auto const* const first_byte = static_cast(block.pointer); + BOOST_TEST(std::all_of(first_byte, first_byte + block.size, + [](unsigned char byte_value) { return byte_value == 0; })); + } + std::string const characters(40, 's'); + expect_no_global_allocation("pmr::secret_string", [&] { + codecs::pmr::secret_string secret{&arena}; + secret.append(characters); + BOOST_TEST(arena.owns(secret.data())); + BOOST_TEST(secret.view() == characters); + BOOST_TEST(secret.get_allocator().resource() == &arena); + // A move assignment between two strings of the same arena takes the buffer. + codecs::pmr::secret_string target{&arena}; + target = std::move(secret); + BOOST_TEST(target.view() == characters); + }); + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + // With no allocator, the default memory resource, as std::pmr's containers. + codecs::pmr::secret_byte_vector const defaulted; + BOOST_TEST(defaulted.get_allocator().resource() == std::pmr::get_default_resource()); +} + void the_allocators_of_the_tests_own() { // non_propagating_allocator: equal only to a copy. test::non_propagating_allocator const first_allocator{1}; @@ -221,6 +275,7 @@ int main() { append_to_a_pmr_string(); assign_to_a_pmr_vector(); a_typed_decode_with_an_allocator(); + secret_types_over_an_arena(); the_allocators_of_the_tests_own(); return boost::report_errors(); } diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index 5806b84..bbd61f9 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -9,8 +9,9 @@ // what it held; and the first N that does not throw gives the right result. A program that needs // exceptions, built with them on in every lane (the Jamfile). A standard container's own block // (the MSVC STL's debug proxy, allocated in noexcept constructors) is neither counted nor failed by -// throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). Later tasks add -// their rows. +// throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). A secret heap +// type whose allocation throws keeps its value, and every buffer it gives back reads zero. Later +// tasks add their rows. #include "support/allocators.hpp" #include "support/letters.hpp" @@ -24,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +39,7 @@ namespace tokens = webcpp::codecs::tokens; using throwing_string = std::basic_string, test::throwing_allocator>; using throwing_bytes = std::vector>; +using throwing_secret = codecs::basic_secret_byte_vector>; /** More than a small string holds: the allocation cannot be avoided. */ constexpr std::size_t input_size = 24; @@ -205,6 +208,85 @@ void a_typed_decode_throws_through() { BOOST_TEST(attempts >= 1U); } +/** Whether `secret` holds `expected`. */ +bool holds(throwing_secret const& secret, std::span expected) { + return std::ranges::equal(secret.view(), expected); +} + +void a_secret_growth_keeps_its_bytes() { + auto const all_bytes = input_bytes(); + auto const held = std::span{all_bytes}.first(16); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + std::vector expected(held.begin(), held.end()); + bool thrown = false; + { + throwing_secret secret{allocator}; + secret.append(held); + allocator.arm(fail_at); + try { + // Each call allocates once: a growth past the capacity, a larger capacity, a + // buffer of the size, a copy. + secret.append(all_bytes); + expected.insert(expected.end(), all_bytes.begin(), all_bytes.end()); + secret.reserve(secret.capacity() + 1); + secret.shrink_to_fit(); + auto const copy = secret.clone(); + BOOST_TEST(holds(copy, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + } + // The value is the one before the call that threw. + BOOST_TEST(holds(secret, expected)); + } + // Every buffer came back, and none of them held a byte. + BOOST_TEST(allocator.state()->deallocations >= 1U); + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 4U); +} + +void a_secret_move_between_unequal_allocators_keeps_both() { + auto const all_bytes = input_bytes(); + auto const target_bytes = std::span{all_bytes}.first(4); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const target_allocator{0}; + test::throwing_allocator const source_allocator{0}; + bool thrown = false; + { + throwing_secret target{target_allocator}; + target.append(target_bytes); + throwing_secret source{source_allocator}; + source.append(all_bytes); + target_allocator.arm(fail_at); + try { + // Unequal and not propagating: a copy into a buffer of the target's allocator. + target = std::move(source); + BOOST_TEST(holds(target, all_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, target_bytes)); + // NOLINTNEXTLINE(bugprone-use-after-move): a move that threw left it whole + BOOST_TEST(holds(source, all_bytes)); + } + } + BOOST_TEST_EQ(target_allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(source_allocator.state()->unwiped_deallocations, 0U); + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 1U); +} + } // namespace int main() { @@ -213,5 +295,7 @@ int main() { assign_to_keeps_the_string(); decode_into_a_vector_keeps_it(); a_typed_decode_throws_through(); + a_secret_growth_keeps_its_bytes(); + a_secret_move_between_unequal_allocators_keeps_both(); return boost::report_errors(); } diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index b782b6f..634c2a2 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -92,6 +93,46 @@ static_assert( static_assert(!noexcept(codecs::decode>( test::letters, "ab", std::pmr::polymorphic_allocator{}))); static_assert(!noexcept(codecs::decode(test::letters, "ab", std::allocator{}))); +// The secret results (Task 5): every member of the fixed ones is noexcept, a move of a heap one +// is, and the members of a heap one that allocate are not. +static_assert(std::is_nothrow_default_constructible_v>); +static_assert(std::is_nothrow_move_constructible_v>); +static_assert(std::is_nothrow_move_assignable_v>); +static_assert(std::is_nothrow_destructible_v>); +static_assert(noexcept(std::declval const&>().size())); +static_assert(noexcept(std::declval const&>().data())); +static_assert(noexcept(codecs::secret_text<64>::capacity())); +static_assert(noexcept(std::declval const&>().view())); +static_assert(noexcept(std::declval const&>().clone())); +static_assert(std::is_nothrow_default_constructible_v>); +static_assert(std::is_nothrow_move_constructible_v>); +static_assert(std::is_nothrow_move_assignable_v>); +static_assert(std::is_nothrow_destructible_v>); +static_assert(noexcept(std::declval const&>().size())); +static_assert(noexcept(std::declval const&>().data())); +static_assert(noexcept(codecs::secret_bytes<32>::capacity())); +static_assert(noexcept(std::declval const&>().view())); +static_assert(noexcept(std::declval const&>().clone())); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_destructible_v); +static_assert(noexcept(codecs::secret_byte_vector{std::allocator{}})); +static_assert(noexcept(codecs::pmr::secret_string{std::pmr::polymorphic_allocator{}})); +static_assert(noexcept(std::declval().clear())); +static_assert(noexcept(std::declval().view())); +static_assert(noexcept(std::declval().size())); +static_assert(noexcept(std::declval().get_allocator())); +static_assert( + !noexcept(std::declval().append(std::span{}))); +static_assert(!noexcept(std::declval().reserve(1))); +static_assert(!noexcept(std::declval().resize_for_overwrite(1))); +static_assert(!noexcept(std::declval().shrink_to_fit())); +static_assert(!noexcept(std::declval().clone())); +static_assert(!noexcept(std::declval().append(std::string_view{}))); +static_assert(!noexcept(std::declval().reserve(1))); +static_assert(!noexcept(std::declval().clone())); + // append_to of a vector is for decode, and a vector token is no text token. static_assert(!codecs::detail::text_token< decltype(tokens::append_to(std::declval&>()))>); diff --git a/test/secret_fixed_test.cpp b/test/secret_fixed_test.cpp new file mode 100644 index 0000000..27fb81a --- /dev/null +++ b/test/secret_fixed_test.cpp @@ -0,0 +1,233 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The secret results in place: secret_text and secret_bytes are move-only and copied only +// by clone(), have no operator==, read as a view on an lvalue only, and wipe their storage by +// secure::erase_secret on destruction and, the source's, on a move. The wipes are read through +// secure's test seam (support/wipe_recorder.hpp), as the spec's scenario "A secret type encodes +// to a wiped text" reads its storage after its destruction. + +#include "support/wipe_recorder.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +using secret_text_64 = codecs::secret_text<64>; +using secret_bytes_32 = codecs::secret_bytes<32>; + +// Move-only: a copy is asked for by name, with clone(). +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_default_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_default_constructible_v); + +// No comparison: an == over secret bytes would answer in a time that tells where they differ. +static_assert(!std::equality_comparable); +static_assert(!std::equality_comparable); + +// The view of an lvalue only, as text's; no conversion to a view at all. +template +concept has_view = requires { std::declval().view(); }; +static_assert(has_view); +static_assert(!has_view); +static_assert(has_view); +static_assert(!has_view); +static_assert( + std::is_same_v().view()), std::string_view>); +static_assert(std::is_same_v().view()), + std::span>); +static_assert(!std::convertible_to); +static_assert(!std::convertible_to>); + +// The capacity is the template argument, and the storage is the object's. +static_assert(secret_text_64::capacity() == 64); +static_assert(secret_bytes_32::capacity() == 32); +static_assert(sizeof(secret_text_64) >= 64); +static_assert(sizeof(secret_bytes_32) >= 32); + +constexpr std::string_view secret_characters = "a secret of thirty-six characters..."; + +/** A secret text holding `secret_characters`, written as the core writes a fixed result. */ +secret_text_64 filled_text() { + secret_text_64 filled; + std::ranges::copy(secret_characters, codecs::detail::fixed_access::writable(filled).begin()); + codecs::detail::fixed_access::resize(filled, secret_characters.size()); + return filled; +} + +/** 20 secret bytes, 1 to 20. */ +std::array secret_values() { + std::array values{}; + for (std::size_t index = 0; index < values.size(); ++index) { + values[index] = static_cast(index + 1); + } + return values; +} + +/** Secret bytes holding `secret_values()`. */ +secret_bytes_32 filled_bytes() { + secret_bytes_32 filled; + auto const values = secret_values(); + std::ranges::copy(values, codecs::detail::fixed_access::writable(filled).begin()); + codecs::detail::fixed_access::resize(filled, values.size()); + return filled; +} + +/** Whether every one of the `count` bytes from `first` reads zero. */ +bool all_zero(void const* first, std::size_t count) { + auto const* const first_byte = static_cast(first); + return std::all_of(first_byte, first_byte + count, + [](unsigned char byte_value) { return byte_value == 0; }); +} + +void default_constructed_is_empty_and_zero() { + secret_text_64 const empty_text; + BOOST_TEST_EQ(empty_text.size(), 0U); + BOOST_TEST(empty_text.view().empty()); + BOOST_TEST(all_zero(empty_text.data(), secret_text_64::capacity())); + secret_bytes_32 const empty_bytes; + BOOST_TEST_EQ(empty_bytes.size(), 0U); + BOOST_TEST(empty_bytes.view().empty()); + BOOST_TEST(all_zero(empty_bytes.data(), secret_bytes_32::capacity())); + // A capacity of 0 is a valid secret too: an encoding of nothing. + codecs::secret_text<0> const nothing; + BOOST_TEST(nothing.view().empty()); +} + +void a_move_wipes_the_source() { + secret_text_64 source = filled_text(); + void const* const source_storage = source.data(); + test::clear_wipes(); + secret_text_64 const taken{std::move(source)}; + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(test::wipes.entries[0].address == source_storage); + BOOST_TEST_EQ(test::wipes.entries[0].size, 64U); + BOOST_TEST(test::wipes.entries[0].zero); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + BOOST_TEST(taken.view() == secret_characters); + + secret_bytes_32 byte_source = filled_bytes(); + void const* const byte_storage = byte_source.data(); + test::clear_wipes(); + secret_bytes_32 const byte_taken{std::move(byte_source)}; + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(test::wipes.entries[0].address == byte_storage); + BOOST_TEST_EQ(test::wipes.entries[0].size, 32U); + BOOST_TEST(test::wipes.entries[0].zero); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(byte_source.size(), 0U); + BOOST_TEST(std::ranges::equal(byte_taken.view(), secret_values())); +} + +void a_move_assignment_wipes_the_target_then_the_source() { + secret_text_64 source = filled_text(); + secret_text_64 target = filled_text(); + codecs::detail::fixed_access::resize(target, 3); + void const* const source_storage = source.data(); + void const* const target_storage = target.data(); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(test::wipes.count, 2U); + BOOST_TEST(test::wipes.entries[0].address == target_storage); + BOOST_TEST(test::wipes.entries[1].address == source_storage); + BOOST_TEST(test::wipes.entries[0].zero && test::wipes.entries[1].zero); + BOOST_TEST(target.view() == secret_characters); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + + secret_bytes_32 byte_source = filled_bytes(); + secret_bytes_32 byte_target; + test::clear_wipes(); + byte_target = std::move(byte_source); + BOOST_TEST_EQ(test::wipes.count, 2U); + BOOST_TEST(std::ranges::equal(byte_target.view(), secret_values())); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(byte_source.size(), 0U); +} + +/** Moves `moved` into `target`, which may be the same object; a function so that the compiler + does not see a self-move. */ +template +void move_into(Secret& target, Secret& moved) { + target = std::move(moved); +} + +void a_move_to_itself_changes_nothing() { + secret_text_64 kept = filled_text(); + test::clear_wipes(); + move_into(kept, kept); + BOOST_TEST_EQ(test::wipes.count, 0U); + BOOST_TEST(kept.view() == secret_characters); +} + +void clone_copies_the_value() { + secret_text_64 const original = filled_text(); + secret_text_64 const copy = original.clone(); + BOOST_TEST(copy.view() == original.view()); + BOOST_TEST(copy.data() != original.data()); + secret_bytes_32 const original_bytes = filled_bytes(); + secret_bytes_32 const copied_bytes = original_bytes.clone(); + BOOST_TEST(std::ranges::equal(copied_bytes.view(), original_bytes.view())); +} + +/** Destroys a `Secret` filled by `fill` in storage of the test's own, and checks the one wipe of + that storage, zero when it was reported. */ +template +void check_destruction_wipes(Fill fill, std::size_t capacity) { + alignas(Secret) std::array storage{}; + auto* const placed = new (storage.data()) Secret{fill()}; + BOOST_TEST(placed->size() > 0U); + test::clear_wipes(); + std::destroy_at(placed); + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(test::wipes.entries[0].address == storage.data()); + BOOST_TEST_EQ(test::wipes.entries[0].size, capacity); + BOOST_TEST(test::wipes.entries[0].zero); + // The characters, which start the object, read zero after it. + BOOST_TEST(all_zero(storage.data(), capacity)); +} + +void destruction_wipes_the_storage() { + check_destruction_wipes(filled_text, 64); + check_destruction_wipes(filled_bytes, 32); +} + +} // namespace + +int main() { + default_constructed_is_empty_and_zero(); + a_move_wipes_the_source(); + a_move_assignment_wipes_the_target_then_the_source(); + a_move_to_itself_changes_nothing(); + clone_copies_the_value(); + destruction_wipes_the_storage(); + return boost::report_errors(); +} diff --git a/test/secret_heap_test.cpp b/test/secret_heap_test.cpp new file mode 100644 index 0000000..b711aed --- /dev/null +++ b/test/secret_heap_test.cpp @@ -0,0 +1,414 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The secret results on the heap (owner decision 23, D22): basic_secret_byte_vector and +// basic_secret_string wipe every buffer by secure::erase_secret, its whole capacity, before the +// allocator gets it back: on destruction, on shrink_to_fit, and the old buffer when they grow, +// one allocation for each growth past the capacity. A wipe-checking counting allocator sees every +// buffer zero at deallocate (the spec's scenario "A secret type's buffers are wiped before +// deallocate, also on growth", here given 32 bytes; Task 13 adds the one decoded from 64 hex +// digits), and secure's test seam (support/wipe_recorder.hpp) sees the wipes the allocator cannot: +// clear(), a cut, and the source's buffer of a move between unequal allocators that do not +// propagate, which copies the bytes into the target's memory. The propagation follows +// std::allocator_traits, and the approved spellings are the std::allocator aliases. + +#include "support/wipe_recorder.hpp" + +#include "support/allocators.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +using checked_bytes = codecs::basic_secret_byte_vector>; +using checked_string = codecs::basic_secret_string>; +using separate_bytes = + codecs::basic_secret_byte_vector>; + +// The approved spellings are unchanged (the spec's scenario "The approved spelling is +// unchanged"), and the pmr aliases are over std::pmr::polymorphic_allocator. +static_assert( + std::is_same_v>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v, codecs::secret_string>); +static_assert(std::is_same_v, codecs::secret_byte_vector>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v< + codecs::pmr::secret_byte_vector, + codecs::basic_secret_byte_vector>>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); + +// Move-only, and a move construction never allocates; a move assignment cannot throw when the +// allocator propagates or is always equal, and may copy, so allocate, when it is neither. +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_nothrow_move_assignable_v); +static_assert(!std::is_nothrow_move_assignable_v); +static_assert(std::is_move_assignable_v); + +// No comparison, and the view of an lvalue only. +static_assert(!std::equality_comparable); +static_assert(!std::equality_comparable); +template +concept has_view = requires { std::declval().view(); }; +static_assert(has_view); +static_assert(!has_view); +static_assert(has_view); +static_assert(!has_view); +static_assert(std::is_same_v().view()), + std::string_view>); +static_assert(std::is_same_v().view()), + std::span>); + +/** `count` bytes from `first_value` up, wrapping. */ +std::vector byte_run(std::size_t count, unsigned first_value) { + std::vector run(count); + for (std::size_t index = 0; index < count; ++index) { + run[index] = static_cast(first_value + index); + } + return run; +} + +/** `count` characters, letters from `first_letter` on, wrapping. */ +std::string letter_run(std::size_t count, char first_letter) { + std::string run(count, ' '); + for (std::size_t index = 0; index < count; ++index) { + run[index] = static_cast('a' + ((first_letter - 'a' + index) % 26)); + } + return run; +} + +/** Whether `secret` holds `expected`, by its view. */ +template +bool holds(Secret const& secret, Expected const& expected) { + return std::ranges::equal(secret.view(), expected); +} + +void the_buffers_of_a_byte_vector_are_wiped_on_growth_and_destruction() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + std::vector expected = byte_run(32, 1); + { + checked_bytes secret{allocator}; + BOOST_TEST_EQ(counts.allocations, 0U); // nothing allocated before a byte is held + secret.append(expected); + BOOST_TEST_EQ(counts.allocations, 1U); + BOOST_TEST_EQ(secret.capacity(), 32U); + // Past the capacity: one allocation, and the old buffer comes back wiped. + auto const one_more = byte_run(1, 0xa0); + secret.append(one_more); + expected.insert(expected.end(), one_more.begin(), one_more.end()); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + BOOST_TEST(secret.capacity() > 32U); + // Past the capacity again. + auto const many_more = byte_run(secret.capacity(), 0x40); + secret.append(many_more); + expected.insert(expected.end(), many_more.begin(), many_more.end()); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, expected)); + BOOST_TEST_EQ(secret.size(), expected.size()); + } + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +void the_buffers_of_a_string_are_wiped_on_growth_and_destruction() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + std::string expected = letter_run(32, 'a'); + { + checked_string secret{allocator}; + secret.append(expected); + BOOST_TEST_EQ(counts.allocations, 1U); + secret.append("z"); + expected += "z"; + BOOST_TEST_EQ(counts.allocations, 2U); + std::string const many_more = letter_run(secret.capacity(), 'k'); + secret.append(many_more); + expected += many_more; + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST(secret.view() == expected); + } + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +void every_wipe_covers_the_whole_capacity() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + secret.reserve(48); + BOOST_TEST_EQ(secret.capacity(), 48U); + secret.append(byte_run(10, 1)); + void const* const buffer = secret.data(); + test::clear_wipes(); + { + checked_bytes const ending{std::move(secret)}; + BOOST_TEST(ending.data() == buffer); // a move construction takes the buffer + BOOST_TEST_EQ(test::wipes.count, 0U); + } + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(test::wiped(buffer, 48)); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); +} + +void reserve_and_shrink_to_fit_wipe_the_old_buffer() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + auto const held = byte_run(20, 7); + checked_bytes secret{allocator}; + secret.append(held); + secret.reserve(10); // no smaller: nothing happens + BOOST_TEST_EQ(counts.allocations, 1U); + secret.reserve(100); + BOOST_TEST_EQ(secret.capacity(), 100U); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + BOOST_TEST(holds(secret, held)); + secret.shrink_to_fit(); + BOOST_TEST_EQ(secret.capacity(), 20U); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, held)); + secret.shrink_to_fit(); // it fits: nothing happens + BOOST_TEST_EQ(counts.allocations, 3U); + // Emptied, shrink_to_fit gives the buffer back, wiped. + secret.clear(); + secret.shrink_to_fit(); + BOOST_TEST_EQ(secret.capacity(), 0U); + BOOST_TEST(secret.data() == nullptr); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +void clear_and_a_cut_wipe_the_bytes() { + test::wipe_checking_allocator const allocator; + checked_string secret{allocator}; + secret.append(letter_run(30, 'c')); + void const* const buffer = secret.data(); + std::size_t const capacity = secret.capacity(); + // A cut by resize_for_overwrite wipes the characters cut off. + test::clear_wipes(); + secret.resize_for_overwrite(12); + BOOST_TEST_EQ(secret.size(), 12U); + BOOST_TEST(secret.view() == letter_run(12, 'c')); + BOOST_TEST(test::wiped(secret.data() + 12, 18)); + // clear wipes the characters and keeps the buffer. + test::clear_wipes(); + secret.clear(); + BOOST_TEST(secret.empty()); + BOOST_TEST_EQ(secret.size(), 0U); + BOOST_TEST_EQ(secret.capacity(), capacity); + BOOST_TEST(secret.data() == buffer); + BOOST_TEST(test::wiped(buffer, 12)); + BOOST_TEST_EQ(allocator.state()->deallocations, 0U); +} + +void resize_for_overwrite_gives_room_to_write() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + secret.append(byte_run(4, 1)); + secret.resize_for_overwrite(40); // past the capacity: one allocation, the bytes kept + BOOST_TEST_EQ(secret.size(), 40U); + BOOST_TEST(secret.capacity() >= 40U); + BOOST_TEST_EQ(allocator.state()->allocations, 2U); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, 1U); + auto const kept = byte_run(4, 1); + BOOST_TEST(std::equal(kept.begin(), kept.end(), secret.data())); + std::fill(secret.data() + 4, secret.data() + 40, std::uint8_t{0x77}); + BOOST_TEST_EQ(secret.view()[39], 0x77); + secret.resize_for_overwrite(40); // the same size: nothing happens + BOOST_TEST_EQ(allocator.state()->allocations, 2U); +} + +void an_append_of_its_own_bytes() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + auto const held = byte_run(16, 3); + secret.append(held); + BOOST_TEST_EQ(secret.capacity(), 16U); + // Its own view, appended past its capacity: read before the old buffer goes. + secret.append(secret.view()); + std::vector twice = held; + twice.insert(twice.end(), held.begin(), held.end()); + BOOST_TEST(holds(secret, twice)); + // And within its capacity. + secret.reserve(64); + secret.append(secret.view().first(4)); + twice.insert(twice.end(), held.begin(), held.begin() + 4); + BOOST_TEST(holds(secret, twice)); + // Nothing appended, nothing allocated. + checked_bytes empty_secret{allocator}; + std::size_t const before = allocator.state()->allocations; + empty_secret.append(std::span{}); + BOOST_TEST_EQ(allocator.state()->allocations, before); + BOOST_TEST(empty_secret.empty()); + BOOST_TEST(empty_secret.view().empty()); +} + +void a_move_takes_the_buffer() { + test::wipe_checking_allocator const allocator; + auto const held = byte_run(24, 9); + checked_bytes source{allocator}; + source.append(held); + void const* const buffer = source.data(); + checked_bytes taken{std::move(source)}; + BOOST_TEST(taken.data() == buffer); + BOOST_TEST(holds(taken, held)); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + BOOST_TEST_EQ(source.capacity(), 0U); + BOOST_TEST(source.data() == nullptr); + // NOLINTEND(bugprone-use-after-move) + BOOST_TEST_EQ(allocator.state()->allocations, 1U); + // A move assignment between equal allocators takes the buffer, and wipes the target's own. + checked_bytes target{allocator}; + target.append(byte_run(8, 1)); + target = std::move(taken); + BOOST_TEST(target.data() == buffer); + BOOST_TEST(holds(target, held)); + BOOST_TEST_EQ(allocator.state()->deallocations, 1U); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, 1U); + // std::allocator propagates: the buffer is taken. + codecs::secret_byte_vector standard_source; + standard_source.append(held); + void const* const standard_buffer = standard_source.data(); + codecs::secret_byte_vector standard_target; + standard_target.append(byte_run(100, 1)); + standard_target = std::move(standard_source); + BOOST_TEST(standard_target.data() == standard_buffer); + BOOST_TEST(holds(standard_target, held)); +} + +void a_move_between_unequal_allocators_copies_and_wipes_the_source() { + test::non_propagating_allocator const first_allocator{1}; + test::non_propagating_allocator const second_allocator{2}; + auto const held = byte_run(40, 5); + // A target too small for the bytes: a buffer of its allocator's. + { + separate_bytes source{second_allocator}; + source.append(held); + void const* const source_buffer = source.data(); + std::size_t const source_capacity = source.capacity(); + separate_bytes target{first_allocator}; + target.append(byte_run(3, 1)); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(target.get_allocator().identity(), 1); + BOOST_TEST(target.data() != source_buffer); + BOOST_TEST(holds(target, held)); + BOOST_TEST(test::wiped(source_buffer, source_capacity)); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + BOOST_TEST_EQ(source.capacity(), 0U); + BOOST_TEST_EQ(source.get_allocator().identity(), 2); + // NOLINTEND(bugprone-use-after-move) + } + // A target with room: the bytes are copied into its buffer, the rest of its bytes wiped. + { + separate_bytes source{second_allocator}; + source.append(std::span{held}.first(10)); + void const* const source_buffer = source.data(); + std::size_t const source_capacity = source.capacity(); + separate_bytes target{first_allocator}; + target.append(byte_run(60, 1)); + void const* const target_buffer = target.data(); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST(target.data() == target_buffer); + BOOST_TEST(holds(target, std::span{held}.first(10))); + BOOST_TEST(test::wiped(target.data() + 10, 50)); + BOOST_TEST(test::wiped(source_buffer, source_capacity)); + } + // Equal allocators that do not propagate: the buffer is taken. + { + separate_bytes source{first_allocator}; + source.append(held); + void const* const source_buffer = source.data(); + separate_bytes target{first_allocator}; + target = std::move(source); + BOOST_TEST(target.data() == source_buffer); + BOOST_TEST(holds(target, held)); + } +} + +void clone_copies_with_the_allocator() { + test::wipe_checking_allocator const allocator; + checked_string original{allocator}; + original.append("a string longer than any small buffer would hold"); + std::size_t const before = allocator.state()->allocations; + checked_string const copy = original.clone(); + BOOST_TEST(copy.view() == original.view()); + BOOST_TEST(copy.data() != original.data()); + BOOST_TEST(copy.get_allocator() == allocator); + BOOST_TEST_EQ(copy.capacity(), copy.size()); + BOOST_TEST_EQ(allocator.state()->allocations - before, 1U); + // An empty one allocates nothing. + checked_string const empty_secret{allocator}; + checked_string const empty_copy = empty_secret.clone(); + BOOST_TEST(empty_copy.empty()); + BOOST_TEST_EQ(allocator.state()->allocations - before, 1U); +} + +void the_default_allocator() { + codecs::secret_string secret; + BOOST_TEST(secret.empty()); + BOOST_TEST(secret.get_allocator() == std::allocator{}); + secret.append("kept"); + BOOST_TEST(secret.view() == "kept"); + codecs::secret_byte_vector bytes; + bytes.append(byte_run(3, 1)); + BOOST_TEST_EQ(bytes.size(), 3U); +} + +} // namespace + +int main() { + the_buffers_of_a_byte_vector_are_wiped_on_growth_and_destruction(); + the_buffers_of_a_string_are_wiped_on_growth_and_destruction(); + every_wipe_covers_the_whole_capacity(); + reserve_and_shrink_to_fit_wipe_the_old_buffer(); + clear_and_a_cut_wipe_the_bytes(); + resize_for_overwrite_gives_room_to_write(); + an_append_of_its_own_bytes(); + a_move_takes_the_buffer(); + a_move_between_unequal_allocators_copies_and_wipes_the_source(); + clone_copies_with_the_allocator(); + the_default_allocator(); + return boost::report_errors(); +} diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 51b9dbf..33c9223 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -7,14 +7,15 @@ // The allocators of the tests' own, as the standard library's rules see them (owner decision 23): // // - throwing_allocator throws std::bad_alloc on its fail_at-th allocation, counted across -// every copy and rebinding of it (a shared counter), and succeeds on every other; a standard -// container's own block (support/bookkeeping.hpp) is not counted; it is not -// declared when exceptions are off. +// every copy and rebinding of it (a shared counter), and succeeds on every other; it counts the +// blocks given back and those of them that did not read zero; a standard container's own block +// (support/bookkeeping.hpp) is not counted; it is not declared when exceptions are off. // - non_propagating_allocator never propagates (on copy assignment, move assignment and swap) // and compares equal only to a copy of itself, so that a container's move between two of them // copies the bytes. // - wipe_checking_allocator counts allocations and deallocations and records whether every -// byte it was given back read zero at deallocate. +// byte it was given back read zero at deallocate; a standard container's own block +// (support/bookkeeping.hpp), which holds no byte of a value, is not counted. #ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP @@ -23,6 +24,7 @@ #include +#include #include #include #include @@ -30,6 +32,13 @@ namespace webcpp::codecs::test { +/** Whether the `count` bytes at `block` all read zero. */ +inline bool reads_zero(void const* block, std::size_t count) noexcept { + auto const* const first_byte = static_cast(block); + return std::all_of(first_byte, first_byte + count, + [](unsigned char byte_value) { return byte_value == 0; }); +} + #ifndef WEBCPP_CODECS_NO_EXCEPTIONS /** The count a throwing_allocator and its copies share. */ @@ -38,6 +47,10 @@ struct throwing_state { std::size_t fail_at = 0; /** The allocations made so far. */ std::size_t allocations = 0; + /** The blocks given back. */ + std::size_t deallocations = 0; + /** The blocks given back with a byte that did not read zero. */ + std::size_t unwiped_deallocations = 0; }; /** An allocator that throws `std::bad_alloc` on its `fail_at`-th allocation. */ @@ -71,8 +84,14 @@ class throwing_allocator { return std::allocator{}.allocate(count); } - /** Returns the elements. */ + /** Counts the block, and whether a byte of it was not zero, and returns it. */ void deallocate(T* pointer, std::size_t count) noexcept { + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->deallocations; + if (!reads_zero(pointer, count * sizeof(T))) { + ++state_->unwiped_deallocations; + } + } std::allocator{}.deallocate(pointer, count); } @@ -176,20 +195,19 @@ class wipe_checking_allocator { /** Allocates `count` elements. */ [[nodiscard]] T* allocate(std::size_t count) { - ++state_->allocations; + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->allocations; + } return std::allocator{}.allocate(count); } /** Counts the block, whether it is all zero, and returns it. */ void deallocate(T* pointer, std::size_t count) noexcept { - ++state_->deallocations; - auto const* const first_byte = reinterpret_cast(pointer); - bool all_zero = true; - for (std::size_t index = 0; index < count * sizeof(T); ++index) { - all_zero = all_zero && first_byte[index] == 0; - } - if (all_zero) { - ++state_->wiped_deallocations; + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->deallocations; + if (reads_zero(pointer, count * sizeof(T))) { + ++state_->wiped_deallocations; + } } std::allocator{}.deallocate(pointer, count); } diff --git a/test/support/wipe_recorder.hpp b/test/support/wipe_recorder.hpp new file mode 100644 index 0000000..1c56506 --- /dev/null +++ b/test/support/wipe_recorder.hpp @@ -0,0 +1,81 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The wipe's test seam of webcpp::secure, recorded (secure's wipe_record_test, in a header of +// codecs' tests): a program built with WEBCPP_SECURE_TEST_WIPE_RECORD (its Jamfile line) includes +// this header first, in one translation unit only, since it defines the seam's function. Every +// wipe of secure::erase_secret and of secure::secret then reports here, once its bytes are +// zero: where, how many bytes, and whether they read zero when it was reported. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_WIPE_RECORDER_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_WIPE_RECORDER_HPP + +#ifndef WEBCPP_SECURE_TEST_WIPE_RECORD +#error "the program is built with WEBCPP_SECURE_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +#include + +#include +#include + +namespace webcpp::codecs::test { + +/** One wipe. */ +struct wipe_entry { + /** The first byte wiped, or null for none. */ + void const* address = nullptr; + /** How many bytes. */ + std::size_t size = 0; + /** Whether every byte read zero when the wipe was reported. */ + bool zero = false; +}; + +/** The wipes reported since the last @ref clear_wipes: the first 64 of them, and their count. */ +struct wipe_log { + /** The wipes, in order. */ + std::array entries{}; + /** How many were reported, also past the entries kept. */ + std::size_t count = 0; +}; + +/** The seam's record, which secure's wipe reaches through the function below. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline wipe_log wipes; + +/** Forgets the wipes reported so far. */ +inline void clear_wipes() noexcept { + wipes = wipe_log{}; +} + +/** Whether a wipe of `size` bytes at `address`, all zero, was reported. */ +inline bool wiped(void const* address, std::size_t size) noexcept { + for (std::size_t index = 0; index < wipes.count && index < wipes.entries.size(); ++index) { + wipe_entry const& entry = wipes.entries[index]; + if (entry.address == address && entry.size == size && entry.zero) { + return true; + } + } + return false; +} + +} // namespace webcpp::codecs::test + +void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_count) noexcept { + bool all_zero = true; + auto const* const wiped_bytes = static_cast(wiped_data); + for (std::size_t index = 0; index < byte_count; ++index) { + all_zero = all_zero && wiped_bytes[index] == 0; + } + codecs::test::wipe_log& log = codecs::test::wipes; + if (log.count < log.entries.size()) { + log.entries[log.count] = + codecs::test::wipe_entry{.address = wiped_data, .size = byte_count, .zero = all_zero}; + } + ++log.count; +} + +#endif // WEBCPP_CODECS_TEST_SUPPORT_WIPE_RECORDER_HPP From f9ff288e56715921f665707b5d55747c4ff98367 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:47:16 -0300 Subject: [PATCH 021/157] codecs: the secret results lint fix, the allocator by value and the move assignments that may copy --- .../codecs/detail/core/secret_types.hpp | 21 +++++++++++++++---- test/secret_heap_test.cpp | 2 +- test/support/wipe_recorder.hpp | 2 ++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp index 1da9f80..5d6db70 100644 --- a/include/webcpp/codecs/detail/core/secret_types.hpp +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -278,8 +278,8 @@ class secret_buffer { public: /** Constructs an empty buffer that allocates through `allocator_value`. */ - explicit secret_buffer(Allocator const& allocator_value) noexcept - : allocator_(allocator_value) {} + explicit secret_buffer(Allocator allocator_value) noexcept + : allocator_(std::move(allocator_value)) {} /** Takes the buffer and the allocator of `moved_buffer`, which is left empty. */ secret_buffer(secret_buffer&& moved_buffer) noexcept @@ -295,6 +295,9 @@ class secret_buffer { `moved_buffer`'s, wiped. `moved_buffer` is left empty; a move to itself changes nothing. When the copy's allocation throws, neither changed. */ + // It is noexcept for allocators that propagate or are always equal, which take no copy, the + // one path that allocates and so may throw what the allocator throws (owner decision 24). + // NOLINTNEXTLINE(bugprone-exception-escape) secret_buffer& operator=(secret_buffer&& moved_buffer) noexcept( traits::propagate_on_container_move_assignment::value || traits::is_always_equal::value) { if (this == &moved_buffer) { @@ -526,11 +529,16 @@ class basic_secret_string { It takes the allocator too when the allocator propagates on move assignment; between unequal allocators that do not, it copies the characters into this string's memory and wipes - `moved_string`'s. `moved_string` is left empty. + `moved_string`'s. `moved_string` is left empty. The copy allocates, and may throw what the + allocator throws, which leaves both strings as they were; it is `noexcept` for an allocator + that propagates on move assignment or is always equal, `std::allocator` among them. @param moved_string The string to take the characters of. @return This string. */ + // It is noexcept for allocators that propagate or are always equal, which take no copy, the + // one path that allocates and so may throw what the allocator throws (owner decision 24). + // NOLINTNEXTLINE(bugprone-exception-escape) basic_secret_string& operator=(basic_secret_string&& moved_string) = default; /** Not copyable: a copy is asked for by name, with `clone`. */ @@ -690,11 +698,16 @@ class basic_secret_byte_vector { It takes the allocator too when the allocator propagates on move assignment; between unequal allocators that do not, it copies the bytes into this vector's memory and wipes - `moved_bytes`'s. `moved_bytes` are left empty. + `moved_bytes`'s. `moved_bytes` are left empty. The copy allocates, and may throw what the + allocator throws, which leaves both as they were; it is `noexcept` for an allocator that + propagates on move assignment or is always equal, `std::allocator` among them. @param moved_bytes The bytes to take. @return These bytes. */ + // It is noexcept for allocators that propagate or are always equal, which take no copy, the + // one path that allocates and so may throw what the allocator throws (owner decision 24). + // NOLINTNEXTLINE(bugprone-exception-escape) basic_secret_byte_vector& operator=(basic_secret_byte_vector&& moved_bytes) = default; /** Not copyable: a copy is asked for by name, with `clone`. */ diff --git a/test/secret_heap_test.cpp b/test/secret_heap_test.cpp index b711aed..4cf92c5 100644 --- a/test/secret_heap_test.cpp +++ b/test/secret_heap_test.cpp @@ -156,7 +156,7 @@ void the_buffers_of_a_string_are_wiped_on_growth_and_destruction() { secret.append(expected); BOOST_TEST_EQ(counts.allocations, 1U); secret.append("z"); - expected += "z"; + expected += 'z'; BOOST_TEST_EQ(counts.allocations, 2U); std::string const many_more = letter_run(secret.capacity(), 'k'); secret.append(many_more); diff --git a/test/support/wipe_recorder.hpp b/test/support/wipe_recorder.hpp index 1c56506..38bcc78 100644 --- a/test/support/wipe_recorder.hpp +++ b/test/support/wipe_recorder.hpp @@ -64,6 +64,8 @@ inline bool wiped(void const* address, std::size_t size) noexcept { } // namespace webcpp::codecs::test +// The seam's one definition, in a header that one translation unit of a program includes. +// NOLINTNEXTLINE(misc-definitions-in-headers) void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_count) noexcept { bool all_zero = true; auto const* const wiped_bytes = static_cast(wiped_data); From a6e2268e451c3685377b931508efdeba71e6f518 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 11:59:50 -0300 Subject: [PATCH 022/157] codecs: the secret results lint fix, the allocator by reference as the standard containers take it, a doc reference without a colon --- include/webcpp/codecs/detail/core/secret_types.hpp | 7 +++++-- test/support/wipe_recorder.hpp | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp index 5d6db70..4675938 100644 --- a/include/webcpp/codecs/detail/core/secret_types.hpp +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -278,8 +278,11 @@ class secret_buffer { public: /** Constructs an empty buffer that allocates through `allocator_value`. */ - explicit secret_buffer(Allocator allocator_value) noexcept - : allocator_(std::move(allocator_value)) {} + // The allocator is taken by reference to const and copied, as the standard containers take + // it: an allocator's copy cannot throw, and is cheap. + // NOLINTNEXTLINE(modernize-pass-by-value) + explicit secret_buffer(Allocator const& allocator_value) noexcept + : allocator_(allocator_value) {} /** Takes the buffer and the allocator of `moved_buffer`, which is left empty. */ secret_buffer(secret_buffer&& moved_buffer) noexcept diff --git a/test/support/wipe_recorder.hpp b/test/support/wipe_recorder.hpp index 38bcc78..5965bf7 100644 --- a/test/support/wipe_recorder.hpp +++ b/test/support/wipe_recorder.hpp @@ -34,7 +34,7 @@ struct wipe_entry { bool zero = false; }; -/** The wipes reported since the last @ref clear_wipes: the first 64 of them, and their count. */ +/** The first 64 wipes since @ref clear_wipes was last called, and how many there were. */ struct wipe_log { /** The wipes, in order. */ std::array entries{}; From 368565e328a5573a62c929d2c6f3bc919465a756 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:18:24 -0300 Subject: [PATCH 023/157] codecs: Task 5's review minors: the heap secret types' default constructor not explicit (LWG 2193), swap as std::allocator_traits says, the test allocators' moves keep their source, the wipes of the pmr string and of the secret bytes' move checked --- .../codecs/detail/core/secret_types.hpp | 97 ++++++++++- test/allocator_test.cpp | 19 ++- test/secret_fixed_test.cpp | 5 + test/secret_heap_test.cpp | 150 ++++++++++++++++++ test/support/allocators.hpp | 47 ++++++ 5 files changed, 308 insertions(+), 10 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp index 4675938..ea6004e 100644 --- a/include/webcpp/codecs/detail/core/secret_types.hpp +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -21,6 +21,8 @@ #include #include +#include + #include #include #include @@ -330,6 +332,26 @@ class secret_buffer { /** Wipes the buffer and gives it back. */ ~secret_buffer() { release(); } + /** + Exchanges the buffers of this and `other_buffer`, and their allocators when the allocator + propagates on swap; between allocators that do not, they must be equal, the standard + containers' precondition. Nothing is copied, allocated or wiped. + */ + void swap(secret_buffer& other_buffer) noexcept(traits::propagate_on_container_swap::value || + traits::is_always_equal::value) { + if constexpr (traits::propagate_on_container_swap::value) { + using std::swap; + swap(allocator_, other_buffer.allocator_); + } else { + // The standard's precondition: unequal allocators that stay could not give back each + // other's buffer. + BOOST_ASSERT(shares_allocator(other_buffer)); + } + std::swap(elements_, other_buffer.elements_); + std::swap(element_count_, other_buffer.element_count_); + std::swap(element_capacity_, other_buffer.element_capacity_); + } + /** A buffer of the same elements, of the allocator the standard library gives a copy. */ [[nodiscard]] secret_buffer clone() const { secret_buffer buffer_copy{traits::select_on_container_copy_construction(allocator_)}; @@ -512,13 +534,21 @@ class basic_secret_string { /** The allocator type. */ using allocator_type = Allocator; + /** + Constructs an empty string of a default-constructed allocator, which allocates nothing until + it holds a character. + + It is not `explicit`, as the standard containers' default constructor (LWG 2193), so that + `return {};` and a member initialized by `{}` make one. + */ + basic_secret_string() noexcept(noexcept(Allocator())) : basic_secret_string(Allocator()) {} + /** Constructs an empty string, which allocates nothing until it holds a character. @param allocator The allocator of its buffers. */ - explicit basic_secret_string(Allocator const& allocator = Allocator()) noexcept - : buffer_(allocator) {} + explicit basic_secret_string(Allocator const& allocator) noexcept : buffer_(allocator) {} /** Takes the buffer and the allocator of `moved_string`, which is left empty. @@ -648,6 +678,31 @@ class basic_secret_string { /** Moves the characters to a buffer of their size, the old one wiped and given back. */ void shrink_to_fit() { buffer_.shrink_to_fit(); } + /** + Exchanges the characters and the buffers of this string and `other_string`, and their + allocators when the allocator propagates on swap (`propagate_on_container_swap`); between + allocators that do not, they must be equal, as the standard containers require. Nothing is + copied, allocated or wiped. + + @param other_string The string to exchange with. + */ + void swap(basic_secret_string& other_string) noexcept( + noexcept(buffer_.swap(other_string.buffer_))) { + buffer_.swap(other_string.buffer_); + } + + /** + Exchanges the characters of two strings, as their member `swap`. + + @param first_string A string. + @param second_string Another string. + */ + friend void swap( + basic_secret_string& first_string, + basic_secret_string& second_string) noexcept(noexcept(first_string.swap(second_string))) { + first_string.swap(second_string); + } + private: explicit basic_secret_string(detail::secret_buffer&& cloned_buffer) noexcept : buffer_(std::move(cloned_buffer)) {} @@ -681,13 +736,22 @@ class basic_secret_byte_vector { /** The allocator type. */ using allocator_type = Allocator; + /** + Constructs empty bytes of a default-constructed allocator, which allocate nothing until they + hold a byte. + + It is not `explicit`, as the standard containers' default constructor (LWG 2193), so that + `return {};` and a member initialized by `{}` make one. + */ + basic_secret_byte_vector() noexcept(noexcept(Allocator())) + : basic_secret_byte_vector(Allocator()) {} + /** Constructs empty bytes, which allocate nothing until they hold a byte. @param allocator The allocator of their buffers. */ - explicit basic_secret_byte_vector(Allocator const& allocator = Allocator()) noexcept - : buffer_(allocator) {} + explicit basic_secret_byte_vector(Allocator const& allocator) noexcept : buffer_(allocator) {} /** Takes the buffer and the allocator of `moved_bytes`, which are left empty. @@ -815,6 +879,31 @@ class basic_secret_byte_vector { /** Moves the bytes to a buffer of their size, the old one wiped and given back. */ void shrink_to_fit() { buffer_.shrink_to_fit(); } + /** + Exchanges the bytes and the buffers of these bytes and `other_bytes`, and their allocators + when the allocator propagates on swap (`propagate_on_container_swap`); between allocators that + do not, they must be equal, as the standard containers require. Nothing is copied, allocated + or wiped. + + @param other_bytes The bytes to exchange with. + */ + void swap(basic_secret_byte_vector& other_bytes) noexcept( + noexcept(buffer_.swap(other_bytes.buffer_))) { + buffer_.swap(other_bytes.buffer_); + } + + /** + Exchanges the bytes of two byte vectors, as their member `swap`. + + @param first_bytes Bytes. + @param second_bytes Other bytes. + */ + friend void swap( + basic_secret_byte_vector& first_bytes, + basic_secret_byte_vector& second_bytes) noexcept(noexcept(first_bytes.swap(second_bytes))) { + first_bytes.swap(second_bytes); + } + private: explicit basic_secret_byte_vector( detail::secret_buffer&& cloned_buffer) noexcept diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 82ffa17..95ad22b 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -181,6 +181,16 @@ void a_typed_decode_with_an_allocator() { BOOST_TEST_EQ(arena.allocation_count(), before); } +/** Checks that every block the arena gave out reads zero in it now. */ +void expect_every_block_zero(test::recording_resource const& arena) { + for (std::size_t index = 0; index < arena.allocation_count(); ++index) { + auto const& block = arena.allocation(index); + auto const* const first_byte = static_cast(block.pointer); + BOOST_TEST(std::all_of(first_byte, first_byte + block.size, + [](unsigned char byte_value) { return byte_value == 0; })); + } +} + /** The secret heap types over the arena (Task 5): every buffer, the old ones of a growth too, comes from the arena and goes back to it wiped, and the global operator new sees none. */ void secret_types_over_an_arena() { @@ -210,12 +220,7 @@ void secret_types_over_an_arena() { BOOST_TEST_EQ(arena.allocation_count(), 2U); BOOST_TEST_EQ(arena.deallocation_count(), 2U); // A monotonic arena never reuses what it is given back: each buffer still reads zero in it. - for (std::size_t index = 0; index < arena.allocation_count(); ++index) { - auto const& block = arena.allocation(index); - auto const* const first_byte = static_cast(block.pointer); - BOOST_TEST(std::all_of(first_byte, first_byte + block.size, - [](unsigned char byte_value) { return byte_value == 0; })); - } + expect_every_block_zero(arena); std::string const characters(40, 's'); expect_no_global_allocation("pmr::secret_string", [&] { codecs::pmr::secret_string secret{&arena}; @@ -230,6 +235,8 @@ void secret_types_over_an_arena() { }); BOOST_TEST_EQ(arena.allocation_count(), 3U); BOOST_TEST_EQ(arena.deallocation_count(), 3U); + // The string's buffer, the third block, reads zero too. + expect_every_block_zero(arena); // With no allocator, the default memory resource, as std::pmr's containers. codecs::pmr::secret_byte_vector const defaulted; BOOST_TEST(defaulted.get_allocator().resource() == std::pmr::get_default_resource()); diff --git a/test/secret_fixed_test.cpp b/test/secret_fixed_test.cpp index 27fb81a..160cf90 100644 --- a/test/secret_fixed_test.cpp +++ b/test/secret_fixed_test.cpp @@ -165,9 +165,14 @@ void a_move_assignment_wipes_the_target_then_the_source() { secret_bytes_32 byte_source = filled_bytes(); secret_bytes_32 byte_target; + void const* const byte_source_storage = byte_source.data(); + void const* const byte_target_storage = byte_target.data(); test::clear_wipes(); byte_target = std::move(byte_source); BOOST_TEST_EQ(test::wipes.count, 2U); + BOOST_TEST(test::wipes.entries[0].address == byte_target_storage); + BOOST_TEST(test::wipes.entries[1].address == byte_source_storage); + BOOST_TEST(test::wipes.entries[0].zero && test::wipes.entries[1].zero); BOOST_TEST(std::ranges::equal(byte_target.view(), secret_values())); // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from state is what is checked BOOST_TEST_EQ(byte_source.size(), 0U); diff --git a/test/secret_heap_test.cpp b/test/secret_heap_test.cpp index 4cf92c5..2f902e3 100644 --- a/test/secret_heap_test.cpp +++ b/test/secret_heap_test.cpp @@ -92,6 +92,66 @@ static_assert(std::is_same_v static_assert(std::is_same_v().view()), std::span>); +// The default constructor is not explicit (LWG 2193), as the standard containers': `return {};` +// and a member initialized by `{}` make an empty one, and it is noexcept when the allocator's +// default construction is. +static_assert(std::is_nothrow_default_constructible_v); +static_assert(std::is_nothrow_default_constructible_v); +static_assert(!std::is_convertible_v, codecs::secret_string>); +static_assert(!std::is_convertible_v, codecs::secret_byte_vector>); + +/** An aggregate whose members are made by `{}`, a copy-list-initialization. */ +struct secret_pair { + /** Characters. */ + codecs::secret_string characters; + /** Bytes. */ + codecs::pmr::secret_byte_vector held_bytes; +}; + +/** An empty string, by `return {};`. */ +codecs::secret_string empty_string() { + return {}; +} + +/** An allocator that propagates on swap, numbered so that a swap of two of them shows. */ +template +class swapping_allocator { +public: + /** The element type. */ + using value_type = T; + /** The allocator goes with its buffer on a swap. */ + using propagate_on_container_swap = std::true_type; + + /** Constructs the allocator numbered `identity`. */ + explicit swapping_allocator(int identity) noexcept : identity_(identity) {} + + /** Constructs the allocator of another element type with this one's number. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + swapping_allocator(swapping_allocator const& other) noexcept + : identity_(other.identity()) {} + + /** Allocates `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + /** Returns the elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** The number. */ + [[nodiscard]] int identity() const noexcept { return identity_; } + + /** Any two give back each other's memory: std::allocator's. */ + template + [[nodiscard]] bool operator==(swapping_allocator const& /*other*/) const noexcept { + return true; + } + +private: + int identity_; +}; + /** `count` bytes from `first_value` up, wrapping. */ std::vector byte_run(std::size_t count, unsigned first_value) { std::vector run(count); @@ -385,6 +445,93 @@ void clone_copies_with_the_allocator() { BOOST_TEST_EQ(allocator.state()->allocations - before, 1U); } +void the_default_constructor_is_not_explicit() { + codecs::secret_string const made = empty_string(); + BOOST_TEST(made.empty()); + secret_pair const pair{}; + BOOST_TEST(pair.characters.empty()); + BOOST_TEST(pair.held_bytes.empty()); + BOOST_TEST(pair.held_bytes.get_allocator().resource() == std::pmr::get_default_resource()); +} + +void swap_exchanges_the_buffers() { + // Equal allocators that do not propagate: the buffers change hands, nothing is copied. + test::wipe_checking_allocator const allocator; + checked_string first_string{allocator}; + first_string.append(letter_run(40, 'a')); + checked_string second_string{allocator}; + second_string.append(letter_run(3, 'x')); + char const* const first_buffer = first_string.data(); + char const* const second_buffer = second_string.data(); + std::size_t const allocations = allocator.state()->allocations; + test::clear_wipes(); + first_string.swap(second_string); + BOOST_TEST(first_string.view() == letter_run(3, 'x')); + BOOST_TEST(second_string.view() == letter_run(40, 'a')); + BOOST_TEST(first_string.data() == second_buffer); + BOOST_TEST(second_string.data() == first_buffer); + BOOST_TEST_EQ(allocator.state()->allocations, allocations); + BOOST_TEST_EQ(test::wipes.count, 0U); + // The free swap, found by argument-dependent lookup. + using std::swap; + swap(first_string, second_string); + BOOST_TEST(first_string.view() == letter_run(40, 'a')); + // An allocator that propagates on swap goes with its buffer. + using swapping_bytes = codecs::basic_secret_byte_vector>; + swapping_bytes first_bytes{swapping_allocator{1}}; + first_bytes.append(byte_run(5, 1)); + swapping_bytes second_bytes{swapping_allocator{2}}; + swap(first_bytes, second_bytes); + BOOST_TEST(first_bytes.empty()); + BOOST_TEST(holds(second_bytes, byte_run(5, 1))); + BOOST_TEST_EQ(first_bytes.get_allocator().identity(), 2); + BOOST_TEST_EQ(second_bytes.get_allocator().identity(), 1); + // Equal non-propagating allocators keep their places. + separate_bytes kept_first{test::non_propagating_allocator{7}}; + kept_first.append(byte_run(2, 9)); + separate_bytes kept_second{test::non_propagating_allocator{7}}; + kept_first.swap(kept_second); + BOOST_TEST(holds(kept_second, byte_run(2, 9))); + BOOST_TEST(kept_first.empty()); + static_assert(noexcept( + std::declval().swap(std::declval()))); + static_assert(noexcept(swap(std::declval(), std::declval()))); + static_assert( + !noexcept(swap(std::declval(), std::declval()))); +} + +void a_moved_allocator_stays_equal() { + // The allocator requirements: a move leaves the source equal to what it was. + test::wipe_checking_allocator const original; + test::wipe_checking_allocator source{original}; + test::wipe_checking_allocator const moved{std::move(source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(source == original); + BOOST_TEST(moved == original); + test::wipe_checking_allocator assigned; + test::wipe_checking_allocator assigned_source{original}; + assigned = std::move(assigned_source); + BOOST_TEST(assigned == original); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(assigned_source == original); + // A secret string moved with its allocator keeps a source that can still allocate. + checked_string string_source{original}; + string_source.append("kept"); + checked_string const string_target{std::move(string_source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from string is reused + string_source.append("again"); + BOOST_TEST(string_source.view() == "again"); + BOOST_TEST(string_target.view() == "kept"); +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + test::throwing_allocator const throwing{0}; + test::throwing_allocator throwing_source{throwing}; + test::throwing_allocator const throwing_moved{std::move(throwing_source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(throwing_source == throwing); + BOOST_TEST(throwing_moved == throwing); +#endif +} + void the_default_allocator() { codecs::secret_string secret; BOOST_TEST(secret.empty()); @@ -409,6 +556,9 @@ int main() { a_move_takes_the_buffer(); a_move_between_unequal_allocators_copies_and_wipes_the_source(); clone_copies_with_the_allocator(); + the_default_constructor_is_not_explicit(); + swap_exchanges_the_buffers(); + a_moved_allocator_stays_equal(); the_default_allocator(); return boost::report_errors(); } diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 33c9223..1f94f2b 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -16,6 +16,9 @@ // - wipe_checking_allocator counts allocations and deallocations and records whether every // byte it was given back read zero at deallocate; a standard container's own block // (support/bookkeeping.hpp), which holds no byte of a value, is not counted. +// +// A move of throwing_allocator or wipe_checking_allocator is a copy: the source keeps the shared +// count and stays equal to what it was, as the allocator requirements ask. #ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP @@ -66,6 +69,28 @@ class throwing_allocator { explicit throwing_allocator(std::size_t fail_at) : state_(std::make_shared(throwing_state{.fail_at = fail_at})) {} + /** A copy shares the count. */ + throwing_allocator(throwing_allocator const& other) noexcept = default; + + /** + A move is a copy: the source keeps the shared count and stays equal to what it was, as the + allocator requirements ask; the implicit move would leave it with none. + */ + // NOLINTNEXTLINE(performance-move-constructor-init): the copy is the intent, as above + throwing_allocator(throwing_allocator&& other) noexcept : state_(other.state_) {} + + /** A copy shares the count. */ + throwing_allocator& operator=(throwing_allocator const& other) noexcept = default; + + /** A move is a copy, as the move constructor's. */ + throwing_allocator& operator=(throwing_allocator&& other) noexcept { + state_ = other.state_; + return *this; + } + + /** Leaves the count to the other copies. */ + ~throwing_allocator() = default; + /** Constructs the allocator of another element type that shares this one's count. */ template // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) @@ -187,6 +212,28 @@ class wipe_checking_allocator { /** Constructs an allocator with a count of its own. */ wipe_checking_allocator() : state_(std::make_shared()) {} + /** A copy shares the count. */ + wipe_checking_allocator(wipe_checking_allocator const& other) noexcept = default; + + /** + A move is a copy: the source keeps the shared count and stays equal to what it was, as the + allocator requirements ask; the implicit move would leave it with none. + */ + // NOLINTNEXTLINE(performance-move-constructor-init): the copy is the intent, as above + wipe_checking_allocator(wipe_checking_allocator&& other) noexcept : state_(other.state_) {} + + /** A copy shares the count. */ + wipe_checking_allocator& operator=(wipe_checking_allocator const& other) noexcept = default; + + /** A move is a copy, as the move constructor's. */ + wipe_checking_allocator& operator=(wipe_checking_allocator&& other) noexcept { + state_ = other.state_; + return *this; + } + + /** Leaves the count to the other copies. */ + ~wipe_checking_allocator() = default; + /** Constructs the allocator of another element type that shares this one's count. */ template // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) From afa90245f75db6f5e36623972a93369dd5e3f8f2 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:28:21 -0300 Subject: [PATCH 024/157] codecs: the heap secret types' default constructor only for an allocator that has one, noexcept by the trait as the standard containers' --- include/webcpp/codecs/detail/core/secret_types.hpp | 14 ++++++++++---- test/secret_heap_test.cpp | 2 ++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp index ea6004e..6696a5e 100644 --- a/include/webcpp/codecs/detail/core/secret_types.hpp +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -539,9 +540,12 @@ class basic_secret_string { it holds a character. It is not `explicit`, as the standard containers' default constructor (LWG 2193), so that - `return {};` and a member initialized by `{}` make one. + `return {};` and a member initialized by `{}` make one; it exists when the allocator is + default-constructible. */ - basic_secret_string() noexcept(noexcept(Allocator())) : basic_secret_string(Allocator()) {} + basic_secret_string() noexcept(std::is_nothrow_default_constructible_v) + requires std::default_initializable + : basic_secret_string(Allocator()) {} /** Constructs an empty string, which allocates nothing until it holds a character. @@ -741,9 +745,11 @@ class basic_secret_byte_vector { hold a byte. It is not `explicit`, as the standard containers' default constructor (LWG 2193), so that - `return {};` and a member initialized by `{}` make one. + `return {};` and a member initialized by `{}` make one; it exists when the allocator is + default-constructible. */ - basic_secret_byte_vector() noexcept(noexcept(Allocator())) + basic_secret_byte_vector() noexcept(std::is_nothrow_default_constructible_v) + requires std::default_initializable : basic_secret_byte_vector(Allocator()) {} /** diff --git a/test/secret_heap_test.cpp b/test/secret_heap_test.cpp index 2f902e3..4798e6d 100644 --- a/test/secret_heap_test.cpp +++ b/test/secret_heap_test.cpp @@ -99,6 +99,8 @@ static_assert(std::is_nothrow_default_constructible_v); static_assert(std::is_nothrow_default_constructible_v); static_assert(!std::is_convertible_v, codecs::secret_string>); static_assert(!std::is_convertible_v, codecs::secret_byte_vector>); +// An allocator that has no default constructor gives none. +static_assert(!std::is_default_constructible_v); /** An aggregate whose members are made by `{}`, a copy-list-initialization. */ struct secret_pair { From a94424b255fb6f819888ea210f5bce77669be5fe Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:28:31 -0300 Subject: [PATCH 025/157] codecs: secret operations, by the value's type, the value codec, the token or the requested type, under secure's guard, every temporary wiped --- include/webcpp/codecs.hpp | 1 + .../webcpp/codecs/detail/core/contract.hpp | 9 +- .../webcpp/codecs/detail/core/operations.hpp | 617 ++++++++++++------ include/webcpp/codecs/detail/core/secrecy.hpp | 311 +++++++++ include/webcpp/codecs/detail/core/sizes.hpp | 80 ++- include/webcpp/codecs/detail/core/tokens.hpp | 45 +- test/Jamfile | 10 + test/allocation_test.cpp | 24 + test/allocator_test.cpp | 42 +- test/allocator_throw_test.cpp | 52 +- test/default_result_test.cpp | 3 +- .../refused_allocator/refused_allocator.cpp | 4 +- test/noexcept_test.cpp | 27 + test/secret_operation_test.cpp | 527 +++++++++++++++ test/support/tagged_letters.hpp | 143 ++++ test/support/timing_dit.hpp | 39 ++ test/support/timing_seam.hpp | 137 ++++ test/timing_test.cpp | 225 +++++++ 18 files changed, 2073 insertions(+), 223 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/secrecy.hpp create mode 100644 test/secret_operation_test.cpp create mode 100644 test/support/tagged_letters.hpp create mode 100644 test/support/timing_dit.hpp create mode 100644 test/support/timing_seam.hpp create mode 100644 test/timing_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 5421b5d..96701d6 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index f569465..a72ff43 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -407,15 +407,16 @@ template inline constexpr bool allocator_accepted = false; /** - Stops the build: `Value` is no string or vector of bytes that `Allocator` constructs, the only - results that take an allocator. + Stops the build: `Value` is no string or vector of bytes, public or secret, that `Allocator` + constructs, the only results that take an allocator. */ template constexpr void refuse_allocator() noexcept { // Qualified, so that the compiler's message names the requirement as the core's. static_assert(webcpp::codecs::detail::allocator_accepted, - "webcpp::codecs: only a std::basic_string or a std::vector " - "takes an allocator, and the allocator must construct it"); + "webcpp::codecs: only a string or a vector of bytes, a std::basic_string, " + "a std::vector or a secret one, takes an allocator, and the " + "allocator must construct it"); } /** diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 103cc39..b741e4b 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -7,7 +7,9 @@ /** The operations of webcpp::codecs that return their result: `encode` and `decode` with the default result, the typed `decode` into the type the caller names, and the buffer forms of `encode` for a - value codec. + value codec. A secret operation (D10) holds secure's timing guard in the function that runs it, + returns D9's secret column, runs the format's secret arithmetic where it has one (R7) and wipes + every temporary of the core. */ #ifndef WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP #define WEBCPP_CODECS_DETAIL_CORE_OPERATIONS_HPP @@ -17,14 +19,18 @@ #include #include #include +#include +#include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -36,116 +42,226 @@ namespace webcpp::codecs { namespace detail { -/** Whether `T` is `text` or `bytes`: a result that holds its elements in place. */ +/** + Whether `T` holds its elements in place: `text`, `bytes`, `secret_text` or + `secret_bytes`. +*/ template inline constexpr bool is_fixed_result = fixed_result_type::value; +/** A `secret_text`. */ +template +inline constexpr bool is_fixed_result> = true; + +/** A `secret_bytes`. */ +template +inline constexpr bool is_fixed_result> = true; + /** Whether `Codec`, a value codec, states `max_encoded_size`: its result is a fixed one. */ template concept has_encoded_bound = requires { { Codec::max_encoded_size } -> std::convertible_to; }; +/** Whether `Input` is a value that a value codec of `F` encodes into bytes. */ +template +constexpr bool encodes_to_bytes() noexcept { + if constexpr (value_encodable) { + return value_codec>::output == output_kind::bytes; + } else { + return false; + } +} + /** - The type `encode` returns, without a token, for `Input` in `F` (D9): `text` or `bytes` - when the size is known at compile time, `std::string` or `std::vector` otherwise. - A pair that is not `encodable` gets `std::string`, which its refusal never returns. + The bound on the encoding of `Input` in `F` when it is known at compile time (D9): the value + codec's `max_encoded_size`, or the format's bound for an input of a static size; else + `std::dynamic_extent`, also for a bound that saturates, which is no size to hold in place (the + run-time path refuses such an input). */ template -constexpr auto default_encode_type() noexcept { +constexpr std::size_t static_encoded_bound() noexcept { if constexpr (value_encodable) { using value_type = value_codec>; - constexpr bool writes_bytes = value_type::output == output_kind::bytes; if constexpr (has_encoded_bound) { - constexpr std::size_t bound = value_type::max_encoded_size; - if constexpr (writes_bytes) { - return std::type_identity>{}; - } else { - return std::type_identity>{}; - } - } else if constexpr (writes_bytes) { - return std::type_identity>{}; + return value_type::max_encoded_size; } else { - return std::type_identity{}; + return std::dynamic_extent; } } else if constexpr (byte_input && has_codec && static_input_size_v != std::dynamic_extent) { constexpr std::size_t bound = codec::max_encoded_size(static_input_size_v); - // A bound that saturates is no size to hold in place: the run-time path refuses the input. if constexpr (bound != std::numeric_limits::max()) { - return std::type_identity>{}; + return bound; } else { - return std::type_identity{}; + return std::dynamic_extent; } } else { - return std::type_identity{}; + return std::dynamic_extent; } } -/** The type `encode` returns for `Input` in `F`, without a token. */ -template -using default_encode_result = decltype(default_encode_type())::type; - /** - The type `decode` returns, without a token, for the text `Text` in `F` (D9): `bytes` when the - text's size is known at compile time, `std::vector` otherwise. + The bound on the bytes of the text `Text` in `F` when the text's size is known at compile time + (`text`, a `std::array`), else `std::dynamic_extent`, also for a bound that saturates. */ template -constexpr auto default_decode_type() noexcept { +constexpr std::size_t static_decoded_bound() noexcept { if constexpr (has_codec && static_input_size_v != std::dynamic_extent) { constexpr std::size_t bound = codec::max_decoded_size(static_input_size_v); - // A bound that saturates is no size to hold in place: the run-time path refuses the text. if constexpr (bound != std::numeric_limits::max()) { - return std::type_identity>{}; + return bound; + } else { + return std::dynamic_extent; + } + } else { + return std::dynamic_extent; + } +} + +/** + The result of D9's table: in place when `Bound` is known (`text` or `bytes`, or + `secret_text` or `secret_bytes` when `Secret`), else on the heap with `Allocator` + rebound to the element (`std::basic_string` or `std::vector`, or + `basic_secret_string` or `basic_secret_byte_vector` when `Secret`). + + @tparam Bytes Whether the result holds bytes rather than characters. + @tparam Secret Whether the operation is secret. + @tparam Bound The most elements, or `std::dynamic_extent` when not known at compile time. + @tparam Allocator The allocator of a heap result, rebound to its element. +*/ +template +constexpr auto table_result_type() noexcept { + if constexpr (Bound != std::dynamic_extent) { + if constexpr (Secret && Bytes) { + return std::type_identity>{}; + } else if constexpr (Secret) { + return std::type_identity>{}; + } else if constexpr (Bytes) { + return std::type_identity>{}; } else { - return std::type_identity>{}; + return std::type_identity>{}; } } else { - return std::type_identity>{}; + using element_type = std::conditional_t; + using element_allocator = + std::allocator_traits::template rebind_alloc; + if constexpr (Secret && Bytes) { + return std::type_identity>{}; + } else if constexpr (Secret) { + return std::type_identity>{}; + } else if constexpr (Bytes) { + return std::type_identity>{}; + } else { + return std::type_identity< + std::basic_string, element_allocator>>{}; + } } } -/** The type `decode` returns for the text `Text` in `F`, without a token. */ +/** The result of D9's table, as `table_result_type` gives it. */ +template +using table_result = decltype(table_result_type())::type; + +/** + The type `encode` returns, without a token, for `Input` in `F` (D9): `text` or `bytes` + when the size is known at compile time, `std::string` or `std::vector` otherwise, + and their secret column when the operation is secret. A pair that is not `encodable` gets + `std::string` (or `secret_string`), which its refusal never returns. +*/ +template +using default_encode_result = + table_result(), secret_operation_v, + static_encoded_bound(), std::allocator>; + +/** + The type `decode` returns, without a token, for the text `Text` in `F` (D9): `bytes` when the + text's size is known at compile time, `std::vector` otherwise; a decode is secret + through its token or its requested type alone. +*/ template -using default_decode_result = decltype(default_decode_type())::type; +using default_decode_result = + table_result(), std::allocator>; -/** Whether `T` is a `std::array` of `std::uint8_t`. */ +/** + The type an encode of `Input` in `F` into the tag `tokens::secret_t` returns: D9's + secret column, in place when the bound is static (the allocator ignored), else on the heap of the + tag's allocator. +*/ +template +using secret_encode_result = + table_result(), true, static_encoded_bound(), Allocator>; + +/** + The type a decode of `Text` in `F` into the tag `tokens::secret_t` returns: + `secret_bytes` when the text's size is static, else `basic_secret_byte_vector` of the tag's + allocator. +*/ +template +using secret_decode_result = table_result(), Allocator>; + +/** Whether `T` is a string or a vector of bytes, public or secret: a result that takes an + * allocator. */ template -inline constexpr bool is_byte_array = false; +struct heap_result_type : std::false_type {}; -/** An array of `N` bytes. */ -template -inline constexpr bool is_byte_array> = true; +/** A string of `char`, whatever its traits and allocator. */ +template +struct heap_result_type> : std::true_type {}; -/** Whether a decode of text into `Target`, a byte result, allocates nothing and cannot throw. */ -template -inline constexpr bool decode_is_fixed = - is_fixed_result || fixed_target || is_byte_array; +/** A vector of `std::uint8_t`, whatever its allocator. */ +template +struct heap_result_type> : std::true_type {}; + +/** A secret string on the heap, whatever its allocator. */ +template +struct heap_result_type> : std::true_type {}; + +/** Secret bytes on the heap, whatever their allocator. */ +template +struct heap_result_type> : std::true_type {}; + +/** A byte result that lives on the heap, made with the caller's allocator or a default one. */ +template +concept heap_result = heap_result_type::value; + +/** The `Target` an operation fills, made with the caller's allocator when there is one. */ +template +[[nodiscard]] Target make_target(Allocators const&... allocator_values) { + if constexpr (sizeof...(Allocators) == 0) { + return Target{}; + } else { + return Target(allocator_values...); + } +} /** - Whether a typed decode into `Value` in `F` cannot throw: a value codec's decode is `noexcept` as - the value codec declares it, so that an allocating value codec's exception propagates (owner - decision 24); a byte result is when it holds its bytes in place. + Sizes `heap_value`, a heap result, to `element_count` elements for the conversion to write (a + secret one by `resize_for_overwrite`, which wipes what it cuts), and returns them. */ -template -constexpr bool typed_decode_is_noexcept() noexcept { - if constexpr (value_decodable) { - return noexcept(value_codec::decode(std::declval(), - std::declval>())); +template +[[nodiscard]] auto heap_elements(Heap& heap_value, std::size_t element_count) { + if constexpr (requires { heap_value.resize_for_overwrite(element_count); }) { + heap_value.resize_for_overwrite(element_count); } else { - return has_codec && decode_is_fixed; + heap_value.resize(element_count); } + return std::span{heap_value.data(), element_count}; } /** Encodes into a `Result`, which `encode` picked for the pair (D9): the exact size is asked, the - `Result` made to hold it, and the format's own `encode` writes into it. + `Result` made to hold it (with the caller's allocator when there is one), and the format's own + `encode` writes into it; its secret arithmetic when `Secret` and it has one (R7). - @tparam Result `text`, `bytes`, `std::string` or `std::vector`. + @tparam Result `text`, `bytes`, `secret_text`, `secret_bytes`, or a heap result. + @tparam Secret Whether the operation is secret. + @tparam Allocators None, or the allocator a heap `Result` is made with. */ -template -[[nodiscard]] result encode_as(F const& format_value, - Input const& input_value) noexcept(is_fixed_result) { +template +[[nodiscard]] result encode_as( + F const& format_value, Input const& input_value, + Allocators const&... allocator_values) noexcept(is_fixed_result) { std::span const input_view = [&] { if constexpr (value_encodable) { return std::span{}; @@ -160,27 +276,26 @@ template if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; } - output_size = codec::encoded_size(format_value, input_view); + output_size = codec_encoded_size(format_value, input_view); + } + if constexpr (is_fixed_result) { + if (output_size > Result::capacity()) { + return error::output_too_small; + } } - Result output_value{}; + auto output_value = make_target(allocator_values...); auto const output_span = [&] { if constexpr (is_fixed_result) { return fixed_access::writable(output_value).first(output_size); } else { - output_value.resize(output_size); - return std::span{output_value}; + return heap_elements(output_value, output_size); } }; - if constexpr (is_fixed_result) { - if (output_size > Result::capacity()) { - return error::output_too_small; - } - } result written_size = std::size_t{0}; if constexpr (value_encodable) { written_size = value_codec::encode(format_value, input_value, output_span()); } else { - written_size = codec::encode(format_value, input_view, output_span()); + written_size = codec_encode(format_value, input_view, output_span()); } if (!written_size) { return written_size.error(); @@ -189,47 +304,64 @@ template if constexpr (is_fixed_result) { fixed_access::resize(output_value, written_size.unsafe_value()); } else { - output_value.resize(written_size.unsafe_value()); + static_cast(heap_elements(output_value, written_size.unsafe_value())); } return output_value; } -/** Whether `T` is a string or a vector of bytes, a result that takes an allocator. */ +/** Whether `T` is a `std::array` of `std::uint8_t`. */ template -struct heap_result_type : std::false_type {}; +inline constexpr bool is_byte_array = false; -/** A string of `char`, whatever its traits and allocator. */ -template -struct heap_result_type> : std::true_type {}; +/** An array of `N` bytes. */ +template +inline constexpr bool is_byte_array> = true; -/** A vector of `std::uint8_t`, whatever its allocator. */ -template -struct heap_result_type> : std::true_type {}; +/** Whether a decode of text into `Target`, a byte result, allocates nothing and cannot throw. */ +template +inline constexpr bool decode_is_fixed = + is_fixed_result || fixed_target || is_byte_array; -/** A byte result that lives on the heap, made with the caller's allocator or a default one. */ -template -concept heap_result = heap_result_type::value; +/** + Whether a typed decode into `Value` in `F` cannot throw: a value codec's decode is `noexcept` as + the value codec declares it, so that an allocating value codec's exception propagates (owner + decision 24); a byte result is when it holds its bytes in place. +*/ +template +constexpr bool typed_decode_is_noexcept() noexcept { + if constexpr (value_decodable) { + return noexcept(value_codec::decode(std::declval(), + std::declval>())); + } else { + return has_codec && decode_is_fixed; + } +} -/** The `Target` a decode fills, made with the caller's allocator when there is one. */ -template -[[nodiscard]] Target make_target(Allocators const&... allocator_values) { - if constexpr (sizeof...(Allocators) == 0) { - return Target{}; +/** The whole storage of `target_value`, a byte result that holds its bytes in place. */ +template +[[nodiscard]] std::span fixed_storage(Target& target_value) noexcept { + if constexpr (is_fixed_result) { + return fixed_access::writable(target_value); + } else if constexpr (fixed_target) { + return fixed_byte_storage::writable(target_value); } else { - return Target(allocator_values...); + return std::span{target_value}; } } /** Decodes the text into a `Target` that holds the bytes: the exact size is asked, the `Target` made to hold it (or refused as too small, or of the wrong length), and the format's own `decode` - writes into it. + writes into it; its secret arithmetic when `Secret` and it has one (R7). In a secret operation a + `Target` in place is the core's temporary until it is moved into the result: a scope guard wipes + it then, also when the decode fails. - @tparam Target `bytes` (up to `N` bytes), `std::array` or a `fixed_target` - (exactly its size), `std::string` or `std::vector`. + @tparam Target `bytes` or `secret_bytes` (up to `N` bytes), `std::array` + or a `fixed_target` (exactly its size), or a heap result. + @tparam Secret Whether the operation is secret. @tparam Allocators None, or the allocator a heap `Target` is made with. */ -template +template [[nodiscard]] result decode_as( F const& format_value, Text const& text_value, Allocators const&... allocator_values) noexcept(decode_is_fixed) { @@ -237,12 +369,23 @@ template if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; } - result const decoded_count = codec::decoded_size(format_value, text_characters); + result const decoded_count = + codec_decoded_size(format_value, text_characters); if (!decoded_count) { return decoded_count.error(); } + // Read unchecked: the error was returned above. std::size_t const byte_count = decoded_count.unsafe_value(); auto target_value = make_target(allocator_values...); + // A heap secret result wipes its own buffers; a public operation wipes nothing. + constexpr bool wipes_temporary = Secret && decode_is_fixed; + [[maybe_unused]] temporary_wipe const target_wipe{[&] { + if constexpr (wipes_temporary) { + return fixed_storage(target_value); + } else { + return std::span{}; + } + }()}; std::span output_span; if constexpr (is_fixed_result) { if (byte_count > Target::capacity()) { @@ -260,20 +403,20 @@ template } output_span = std::span{target_value}; } else { - target_value.resize(byte_count); + auto const heap_span = heap_elements(target_value, byte_count); // A char is written through an unsigned char, which may alias any object. - output_span = std::span{reinterpret_cast(target_value.data()), - byte_count}; + output_span = + std::span{reinterpret_cast(heap_span.data()), byte_count}; } result const written_count = - codec::decode(format_value, text_characters, output_span); + codec_decode(format_value, text_characters, output_span); if (!written_count) { return written_count.error(); } if constexpr (is_fixed_result) { fixed_access::resize(target_value, written_count.unsafe_value()); } else if constexpr (!fixed_target && !is_byte_array) { - target_value.resize(written_count.unsafe_value()); + static_cast(heap_elements(target_value, written_count.unsafe_value())); } return target_value; } @@ -303,12 +446,13 @@ template /** Encodes into `token_object`, a concrete token (B6): the checks of the input, then the token's `capacity` against the exact size, then one `prepare` with that size, the format's `encode` into - what it returned, and one `result`. A token is untouched when a check fails. When the conversion - itself fails after `prepare` (a value codec's own error), a token of codecs' that appends is put - back as it was; an assigning token has lost its old content and a token of a program's own is - left as `prepare` made it. A token of codecs' is cut to the count the format wrote. + what it returned (its secret arithmetic when `Secret` and it has one, R7), and one `result`. A + token is untouched when a check fails. When the conversion itself fails after `prepare` (a value + codec's own error), a token of codecs' that appends is put back as it was; an assigning token has + lost its old content and a token of a program's own is left as `prepare` made it. A token of + codecs' is cut to the count the format wrote. */ -template +template [[nodiscard]] result encode_to( F const& format_value, Input const& input_value, Token& token_object) noexcept(token_is_noexcept) { @@ -327,7 +471,7 @@ template if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; } - output_size = codec::encoded_size(format_value, input_view); + output_size = codec_encoded_size(format_value, input_view); } if constexpr (has_token_capacity) { if (output_size > Token::capacity) { @@ -348,7 +492,7 @@ template } } else { written_size = - codec::encode(format_value, input_view, std::span{prepared, output_size}); + codec_encode(format_value, input_view, std::span{prepared, output_size}); } if (!written_size) { if constexpr (abandonable_token) { @@ -365,10 +509,10 @@ template /** Decodes into `token_object`, a concrete token (B6): the checks of the text, the whole text checked, then the token's `capacity` against the exact size, then one `prepare` with that size, - the format's `decode` into what it returned, and one `result`. A token is untouched when a check - fails. + the format's `decode` into what it returned (its secret arithmetic when `Secret` and it has one, + R7), and one `result`. A token is untouched when a check fails. */ -template +template [[nodiscard]] result decode_to( F const& format_value, Text const& text_value, Token& token_object) noexcept(token_is_noexcept) { @@ -376,7 +520,8 @@ template if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; } - result const decoded_count = codec::decoded_size(format_value, text_characters); + result const decoded_count = + codec_decoded_size(format_value, text_characters); if (!decoded_count) { return decoded_count.error(); } @@ -389,8 +534,8 @@ template } auto* const prepared = token_object.prepare(byte_count); result const written_count = - codec::decode(format_value, text_characters, - std::span{as_byte_pointer(prepared), byte_count}); + codec_decode(format_value, text_characters, + std::span{as_byte_pointer(prepared), byte_count}); if (!written_count) { if constexpr (abandonable_token) { token_object.abandon(); @@ -403,21 +548,39 @@ template return token_object.result(); } -/** Whether `Input` is a value that a value codec of `F` encodes into bytes. */ -template -constexpr bool encodes_to_bytes() noexcept { - if constexpr (value_encodable) { - return value_codec>::output == output_kind::bytes; - } else { - return false; +/** + Encodes into `token`, as it was passed, a token or a tag of `codecs::tokens` the core turns into + one (B6), under the guard of the public function that calls it. +*/ +template +[[nodiscard]] auto encode_into(F const& format_value, Input const& input_value, Token& token) { + auto&& concrete_token = detail::concrete_token()>(token); + return encode_to(format_value, input_value, concrete_token); +} + +/** + Encodes `input_value`, a value of a value codec, into the caller's buffer: the exact size checked + against the buffer's, then the value codec's `encode` into the first elements. +*/ +template +[[nodiscard]] result encode_value_into_buffer( + F const& format_value, Input const& input_value, std::span output_buffer) noexcept { + std::size_t const output_size = value_codec::encoded_size(format_value, input_value); + if (output_buffer.size() < output_size) { + return error::output_too_small; } + return value_codec::encode(format_value, input_value, + output_buffer.first(output_size)); } /** Whether an encode of `Input` in `F` into `Token`, as it was passed, cannot throw. */ template constexpr bool encode_token_is_noexcept() noexcept { - if constexpr (std::same_as, tokens::automatic>) { + using tag_type = std::remove_cvref_t; + if constexpr (std::same_as) { return is_fixed_result>; + } else if constexpr (is_secret_tag) { + return is_fixed_result>; } else { return token_is_noexcept(), Token>>; } @@ -426,8 +589,11 @@ constexpr bool encode_token_is_noexcept() noexcept { /** Whether a decode in `F` into `Token`, as it was passed, cannot throw. */ template constexpr bool decode_token_is_noexcept() noexcept { - if constexpr (std::same_as, tokens::automatic>) { + using tag_type = std::remove_cvref_t; + if constexpr (std::same_as) { return is_fixed_result>; + } else if constexpr (is_secret_tag) { + return is_fixed_result>; } else { return token_is_noexcept>; } @@ -441,7 +607,12 @@ constexpr bool decode_token_is_noexcept() noexcept { time or the value codec states `max_encoded_size`, `M` being the format's bound, and `std::string` (or `std::vector`) otherwise. - It is `noexcept` exactly when the result is a `text` or a `bytes`, which allocate nothing. An + A secret operation (D10: the input's `is_secret_v`, or the value codec's `secret`) gives the + secret column instead, `secret_text` (or `secret_bytes`) and `secret_string` (or + `secret_byte_vector`), holds secure's timing guard for its duration and runs the format's secret + arithmetic where it has one. + + It is `noexcept` exactly when the result is held in place, which allocates nothing. An input whose encoding does not fit in `std::size_t` is @ref error::input_too_long, before it is read. A value codec of `F` and `Input` is used when it encodes, else `codec`. A pair that is not @ref encodable stops the build with a message that the format does not convert this type. @@ -455,12 +626,15 @@ constexpr bool decode_token_is_noexcept() noexcept { template [[nodiscard]] auto encode(F const& format_value, Input const& input_value) noexcept( detail::is_fixed_result>) { - if constexpr (encodable) { - return detail::encode_as>(format_value, - input_value); - } else { + using result_type = detail::default_encode_result; + if constexpr (!encodable) { detail::refuse(); return result{std::string{}}; + } else if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::encode_as(format_value, input_value); + } else { + return detail::encode_as(format_value, input_value); } } @@ -471,7 +645,8 @@ template The checks come first, and on every error nothing is written: an `output_buffer` shorter than the exact size is @ref error::output_too_small. The bytes are then written at the start of `output_buffer`, whose other bytes are unchanged. The errors the value codec returns reach the - caller unchanged. + caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds secure's + timing guard while the value codec runs. @tparam F The format's type. @tparam Input The value's type, one `value_codec` encodes into bytes. @@ -485,12 +660,12 @@ template value_codec::output == output_kind::bytes) [[nodiscard]] result encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept { - std::size_t const bytes_size = value_codec::encoded_size(format_value, input_value); - if (output_buffer.size() < bytes_size) { - return error::output_too_small; + if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + } else { + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } - return value_codec::encode(format_value, input_value, - output_buffer.first(bytes_size)); } /** @@ -500,7 +675,8 @@ template The checks come first, and on every error nothing is written: an `output_buffer` shorter than the exact size is @ref error::output_too_small. The text is then written at the start of `output_buffer`, whose other characters are unchanged. The errors the value codec returns reach - the caller unchanged. + the caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds + secure's timing guard while the value codec runs. @tparam F The format's type. @tparam Input The value's type, one `value_codec` encodes into text. @@ -514,11 +690,12 @@ template value_codec::output == output_kind::text) [[nodiscard]] result encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept { - std::size_t const text_size = value_codec::encoded_size(format_value, input_value); - if (output_buffer.size() < text_size) { - return error::output_too_small; + if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + } else { + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } - return value_codec::encode(format_value, input_value, output_buffer.first(text_size)); } /** @@ -543,7 +720,8 @@ template [[nodiscard]] auto decode(F const& format_value, Text const& text_value) noexcept( detail::is_fixed_result>) { if constexpr (detail::has_codec) { - return detail::decode_as>(format_value, text_value); + return detail::decode_as, false>(format_value, + text_value); } else { detail::refuse(); return result>{std::vector{}}; @@ -557,19 +735,24 @@ template `token` is one of the tags of `codecs::tokens` (`automatic`, which is the default result of the form without a token; `return_string` and `return_string(allocator)`, a string; `append_to` and `assign_to` of a string, which return the string by reference; `fixed`, a `text`, or a - `bytes` for a value codec of bytes) or an object of the token contract of Boost.URL's string - tokens, used as given. The result is `result`. The order is that of - the buffer form's: every check of the input (an input whose encoding does not fit in - `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size + `bytes` for a value codec of bytes; `secret` and `secret(allocator)`, D9's secret column, in + place when the bound is known at compile time and on the heap of the allocator otherwise) or an + object of the token contract of Boost.URL's string tokens, used as given. The result is + `result`. The order is that of the buffer form's: every check of the + input (an input whose encoding does not fit in `std::size_t` is @ref error::input_too_long), then + the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A token is untouched when a check fails (an error of a value codec's own, found after `prepare`, puts an `append_to` token back as it was; an `assign_to` token and a token of a program's own are left as `prepare` made them). A token of codecs' holds what the format wrote. The forms that allocate are not `noexcept` (an allocator's exception propagates, owner decision 24); - `fixed` is. A pair that is not - @ref encodable stops the build with a message that the format does not convert this type, and a - token that does not take the pair's encoding (`append_to` of a vector, which is for decode) - with one that names the token's type. + `fixed` is, and `secret` when its result is in place. The operation is secret (D10) when the + input's `is_secret_v`, the value codec's `secret` or the token's `secret` says so: it then holds + secure's timing guard and runs the format's secret arithmetic where it has one, and the result is + the token's (a secret input into `return_string` gives a `std::string`, as the caller asked). A + pair that is not @ref encodable stops the build with a message that the format does not convert + this type, and a token that does not take the pair's encoding (`append_to` of a vector, which is + for decode) with one that names the token's type. @tparam F The format's type. @tparam Input The input's type: a byte input, or a value of a value codec. @@ -583,22 +766,34 @@ template requires detail::token_argument [[nodiscard]] auto encode(F const& format_value, Input const& input_value, Token&& token) noexcept( detail::encode_token_is_noexcept()) { - if constexpr (std::same_as, tokens::automatic>) { + using tag_type = std::remove_cvref_t; + if constexpr (std::same_as) { return encode(format_value, input_value); - } else if constexpr (encodable) { + } else if constexpr (!encodable) { + detail::refuse(); + return result{std::string{}}; + } else if constexpr (detail::is_secret_tag) { + using result_type = detail::secret_encode_result; + secure::timing_guard const timing_scope{true}; + if constexpr (detail::is_fixed_result) { + return detail::encode_as(format_value, input_value); + } else { + return detail::encode_as( + format_value, input_value, typename result_type::allocator_type(token.allocator)); + } + } else { constexpr bool to_bytes = detail::encodes_to_bytes(); using concrete_type = detail::concrete_token_t; - if constexpr (detail::value_encodable ? detail::byte_token - : detail::text_token) { - auto&& concrete_token = detail::concrete_token(token); - return detail::encode_to(format_value, input_value, concrete_token); - } else { - detail::refuse_token, F>(); + if constexpr (!(detail::value_encodable ? detail::byte_token + : detail::text_token)) { + detail::refuse_token(); return result{std::string{}}; + } else if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::encode_into(format_value, input_value, token); + } else { + return detail::encode_into(format_value, input_value, token); } - } else { - detail::refuse(); - return result{std::string{}}; } } @@ -609,17 +804,20 @@ template `token` is one of the tags of `codecs::tokens` (`automatic`, the default result of the form without a token; `return_string` and `return_string(allocator)`, the bytes as a string; `append_to` and `assign_to` of a string or a vector of `std::uint8_t`, which return the container - by reference; `fixed`, a `bytes`) or an object of the token contract (a byte token), used - as given. The result is `result`. The order is that of the buffer - form's: a text whose bytes do not fit in `std::size_t` is @ref error::input_too_long, the whole - text is checked and its data error with the lowest value of @ref error returned, then the token's - `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the - exact size, the conversion, one `result`. A token is untouched when a check fails (a conversion - that fails after `prepare` puts an `append_to` token back; see `encode`). The forms that allocate - are not `noexcept`; `fixed` is. A format with no `codec` specialization stops the - build with a message that the format does not convert bytes (named - `webcpp::codecs::detail::decoded_bytes`), and a token that is not a byte token with one that - names the token's type. + by reference; `fixed`, a `bytes`; `secret` and `secret(allocator)`, `secret_bytes` for a + text of a size known at compile time and `basic_secret_byte_vector` of the allocator otherwise) + or an object of the token contract (a byte token), used as given. The result is `result`. The order is that of the buffer form's: a text whose bytes do not fit in + `std::size_t` is @ref error::input_too_long, the whole text is checked and its data error with the + lowest value of @ref error returned, then the token's `capacity` against the exact size (@ref + error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A + token is untouched when a check fails (a conversion that fails after `prepare` puts an `append_to` + token back; see `encode`). The forms that allocate are not `noexcept`; `fixed` is, and `secret` + when its result is in place. A decode is secret (D10) through its token alone (`secret`, or a token + whose `secret` is true): it then holds secure's timing guard and runs the format's secret + arithmetic where it has one. A format with no `codec` specialization stops the build with a message + that the format does not convert bytes (named `webcpp::codecs::detail::decoded_bytes`), and a token + that is not a byte token with one that names the token's type. @tparam F The format's type. @tparam Text The text's type: anything a `std::string_view` is made from, or a contiguous @@ -634,17 +832,31 @@ template requires detail::token_argument [[nodiscard]] auto decode(F const& format_value, Text const& text_value, Token&& token) noexcept( detail::decode_token_is_noexcept()) { + using tag_type = std::remove_cvref_t; if constexpr (!detail::has_codec) { detail::refuse(); return result>{std::vector{}}; - } else if constexpr (std::same_as, tokens::automatic>) { + } else if constexpr (std::same_as) { return decode(format_value, text_value); - } else if constexpr (detail::byte_token>) { + } else if constexpr (detail::is_secret_tag) { + using result_type = detail::secret_decode_result; + secure::timing_guard const timing_scope{true}; + if constexpr (detail::is_fixed_result) { + return detail::decode_as(format_value, text_value); + } else { + return detail::decode_as( + format_value, text_value, typename result_type::allocator_type(token.allocator)); + } + } else if constexpr (!detail::byte_token>) { + detail::refuse_token(); + return result>{std::vector{}}; + } else if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; auto&& concrete_token = detail::concrete_token(token); - return detail::decode_to(format_value, text_value, concrete_token); + return detail::decode_to(format_value, text_value, concrete_token); } else { - detail::refuse_token, F>(); - return result>{std::vector{}}; + auto&& concrete_token = detail::concrete_token(token); + return detail::decode_to(format_value, text_value, concrete_token); } } @@ -655,12 +867,17 @@ template bytes, a text input for one of text; its errors reach the caller unchanged), or a byte result of a format with a `codec`: a `std::array`, which takes exactly `N` bytes, or a type of `fixed_byte_storage`, which takes exactly its size (@ref error::invalid_length - otherwise); a `bytes`, which takes up to `N` bytes (@ref error::output_too_small otherwise); - a `std::string` or a `std::vector`, which take the heap. It is `noexcept` for the - fixed byte results, and for a value codec as the value codec's `decode` is declared; the heap - types allocate and are not. A pair `F` does not convert stops the build with a message that the - format does not convert this type, and an input the pair does not read (a byte input given to a - decode of text, a value codec of bytes given a text) with one that names the input's type. + otherwise), `secure::secret` among them; a `bytes` or a `secret_bytes`, which take up + to `N` bytes (@ref error::output_too_small otherwise); a `std::string`, a + `std::vector`, a `basic_secret_string` or a `basic_secret_byte_vector`, which take + the heap. It is `noexcept` for the fixed byte results, and for a value codec as the value codec's + `decode` is declared; the heap types allocate and are not. The operation is secret (D10) when + `Value`'s `is_secret_v` or the value codec's `secret` says so: it then holds secure's timing + guard, runs the format's secret arithmetic where it has one, and wipes the temporary it decodes + into before it returns, by `secure::erase_secret`. A pair `F` does not convert stops the build with + a message that the format does not convert this type, and an input the pair does not read (a byte + input given to a decode of text, a value codec of bytes given a text) with one that names the + input's type. @tparam Value The type to decode into. @tparam F The format's type. @@ -672,24 +889,38 @@ template template [[nodiscard]] result decode(F const& format_value, Input const& input_value) noexcept( detail::typed_decode_is_noexcept()) { + constexpr bool secret = detail::secret_operation_v; if constexpr (detail::value_decodable) { using value_type = value_codec; if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { - return value_type::decode(format_value, detail::input_bytes(input_value)); + if constexpr (secret) { + secure::timing_guard const timing_scope{true}; + return value_type::decode(format_value, detail::input_bytes(input_value)); + } else { + return value_type::decode(format_value, detail::input_bytes(input_value)); + } } else if constexpr (value_type::output == output_kind::text && detail::text_input) { - return value_type::decode(format_value, detail::text_view(input_value)); + if constexpr (secret) { + secure::timing_guard const timing_scope{true}; + return value_type::decode(format_value, detail::text_view(input_value)); + } else { + return value_type::decode(format_value, detail::text_view(input_value)); + } } else { // The pair converts; this input is not what the value codec reads. detail::refuse(); return make_error_code(error::invalid_length); } } else if constexpr (detail::byte_result && detail::has_codec) { - if constexpr (detail::text_input) { - return detail::decode_as(format_value, input_value); - } else { + if constexpr (!detail::text_input) { // The pair converts; this input is not a text. detail::refuse(); return make_error_code(error::invalid_length); + } else if constexpr (secret) { + secure::timing_guard const timing_scope{true}; + return detail::decode_as(format_value, input_value); + } else { + return detail::decode_as(format_value, input_value); } } else { detail::refuse(); @@ -698,18 +929,19 @@ template } /** - Decodes `input_value` in `format_value` into a `Value`, a string or a vector of `std::uint8_t` - that is made with `allocator_value`, as a standard container constructed with it is - (`decode>(format, text, allocator)`); the form without an + Decodes `input_value` in `format_value` into a `Value`, a string or a vector of `std::uint8_t`, + public or secret, that is made with `allocator_value`, as a standard container constructed with + it is (`decode>(format, text, allocator)`); the form without an allocator makes a default-constructed one, so `decode>` uses the default memory resource. - The order and the errors are those of the typed decode without an allocator. It allocates, and - is not `noexcept`: the allocator's exception propagates (owner decision 24). A `Value` that is - not a string or a vector of bytes, or that `allocator_value` does not construct, stops the build - with a message that only those take an allocator that constructs them, a format with no `codec` - with one that the format does not convert bytes, and an input that is not a text with one that - names the input's type. + The order and the errors are those of the typed decode without an allocator, and a secret `Value` + (`basic_secret_byte_vector`, `basic_secret_string`) makes the operation secret as there. It + allocates, and is not `noexcept`: the allocator's exception propagates (owner decision 24). A + `Value` that is not a string or a vector of bytes, or that `allocator_value` does not construct, + stops the build with a message that only those take an allocator that constructs them, a format + with no `codec` with one that the format does not convert bytes, and an input that is not a text + with one that names the input's type. @tparam Value The string or vector to decode into. @tparam F The format's type. @@ -728,11 +960,14 @@ template return make_error_code(error::invalid_length); } else if constexpr (detail::heap_result && std::constructible_from) { - if constexpr (detail::text_input) { - return detail::decode_as(format_value, input_value, allocator_value); - } else { + if constexpr (!detail::text_input) { detail::refuse(); return make_error_code(error::invalid_length); + } else if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::decode_as(format_value, input_value, allocator_value); + } else { + return detail::decode_as(format_value, input_value, allocator_value); } } else { detail::refuse_allocator(); diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp new file mode 100644 index 0000000..5d8abc1 --- /dev/null +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -0,0 +1,311 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The secrecy of webcpp::codecs (D10): the trait `is_secret`, its specializations for secure's + `secret` and codecs' secret results, `secure::secret` as the target of a typed decode, when + an operation is secret, and the core's call of a format's secret arithmetic (ruling R7). +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_SECRECY_HPP +#define WEBCPP_CODECS_DETAIL_CORE_SECRECY_HPP + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +template +class secret_text; + +template +class secret_bytes; + +template +class basic_secret_string; + +template +class basic_secret_byte_vector; + +/** + Whether values of `T` are secret: false unless a library specializes it for its secret types, + which makes every operation on such a value secret (D10). + + codecs specializes it for `secure::secret` and for its own secret results. A specialization + derives from `std::true_type`. + + @tparam T The type, cv-unqualified and not a reference. +*/ +template +struct is_secret : std::false_type {}; + +/** + Whether values of `T` are secret, `T`'s references and `const` ignored. + + @tparam T The type. +*/ +template +inline constexpr bool is_secret_v = is_secret>::value; + +/** secure's secret is secret. */ +template +struct is_secret> : std::true_type {}; + +/** The text of a secret encoding is secret. */ +template +struct is_secret> : std::true_type {}; + +/** The bytes of a secret decoding are secret. */ +template +struct is_secret> : std::true_type {}; + +/** A secret string on the heap is secret. */ +template +struct is_secret> : std::true_type {}; + +/** Secret bytes on the heap are secret. */ +template +struct is_secret> : std::true_type {}; + +/** + `secure::secret` is the target of a typed decode of exactly `N` bytes, written through its + `writable()` (owner decision 14). + + @tparam N The size of the secret. +*/ +template +struct fixed_byte_storage> { + /** The bytes a decode fills. */ + static constexpr std::size_t size = N; + + /** + The storage of `target_secret`, which the decode fills. + + @param target_secret The secret decoded into. + @return Its bytes. + */ + [[nodiscard]] static std::span writable( + secure::secret& target_secret) noexcept { + return target_secret.writable(); + } +}; + +namespace detail { + +/** `secret_bytes`: a decode fills up to `N` bytes. */ +template +struct byte_result_type> : std::true_type {}; + +/** Secret bytes on the heap, whatever their allocator. */ +template +struct byte_result_type> : std::true_type {}; + +/** A secret string on the heap, whatever its allocator: the bytes as characters. */ +template +struct byte_result_type> : std::true_type {}; + +/** Whether `Codec`, a value codec, states `secret`, a constant. */ +template +concept states_secret = requires { + { std::bool_constant(Codec::secret)>{} }; +}; + +/** Whether the value codec of `Format` and `Value` exists and says that its values are secret. */ +template +constexpr bool value_codec_is_secret() noexcept { + using value_type = std::remove_cvref_t; + if constexpr (requires { sizeof(value_codec); }) { + if constexpr (states_secret>) { + return static_cast(value_codec::secret); + } else { + return false; + } + } else { + return false; + } +} + +/** Whether the token type states `static constexpr bool secret`, true (D8). */ +template +constexpr bool token_is_secret() noexcept { + using token_type = std::remove_cvref_t; + if constexpr (states_secret) { + return static_cast(token_type::secret); + } else { + return false; + } +} + +/** + Whether an operation of the format `Format` on `Value` into `Token` is secret (D10): the value's + `is_secret_v`, the value codec's `secret` or the token's `secret` says so. + + `Value` is the input of an encode and the requested type of a typed decode; a decode into a token + is secret through its token alone, and names `decoded_bytes` as its value. A secret operation + returns D9's secret column, holds secure's timing guard and wipes every temporary of the core. + + @tparam Format The format's type. + @tparam Value The value's type. + @tparam Token The token's type, as it was passed; `tokens::automatic` for none. +*/ +template +inline constexpr bool secret_operation_v = + is_secret_v || value_codec_is_secret() || token_is_secret(); + +/** + The tag a format's codec takes first in the overloads of its functions whose arithmetic differs + when the operation is secret (ruling R7): base58's, whose public arithmetic exits early. The core + calls such an overload of `encoded_size`, `decoded_size`, `encode` or `decode` in a secret + operation when it exists, and the format's function of D3 otherwise. +*/ +struct secret_tag { + /** Constructed by name only, so that `{}` never stands for it. */ + explicit secret_tag() = default; +}; + +/** Whether `codec` has an `encoded_size` that takes `secret_tag` first. */ +template +concept has_secret_encoded_size = + requires(F const& format_value, std::span input_view) { + { + codec::encoded_size(secret_tag{}, format_value, input_view) + } -> std::same_as; + }; + +/** Whether `codec` has a `decoded_size` that takes `secret_tag` first. */ +template +concept has_secret_decoded_size = + requires(F const& format_value, std::string_view text_characters) { + { + codec::decoded_size(secret_tag{}, format_value, text_characters) + } -> std::same_as>; + }; + +/** Whether `codec` has an `encode` that takes `secret_tag` first. */ +template +concept has_secret_encode = requires( + F const& format_value, std::span input_view, std::span output_span) { + { + codec::encode(secret_tag{}, format_value, input_view, output_span) + } -> std::same_as>; +}; + +/** Whether `codec` has a `decode` that takes `secret_tag` first. */ +template +concept has_secret_decode = requires(F const& format_value, std::string_view text_characters, + std::span output_span) { + { + codec::decode(secret_tag{}, format_value, text_characters, output_span) + } -> std::same_as>; +}; + +/** + The exact size of the text of `input_view`: the format's secret arithmetic in a secret operation + when it has one (R7), its `encoded_size` otherwise. +*/ +template +[[nodiscard]] constexpr std::size_t codec_encoded_size( + F const& format_value, std::span input_view) noexcept { + if constexpr (Secret && has_secret_encoded_size) { + return codec::encoded_size(secret_tag{}, format_value, input_view); + } else { + return codec::encoded_size(format_value, input_view); + } +} + +/** + The exact size of the bytes of `text_characters`, the whole text checked: the format's secret + arithmetic in a secret operation when it has one (R7), its `decoded_size` otherwise. +*/ +template +[[nodiscard]] constexpr result codec_decoded_size( + F const& format_value, std::string_view text_characters) noexcept { + if constexpr (Secret && has_secret_decoded_size) { + return codec::decoded_size(secret_tag{}, format_value, text_characters); + } else { + return codec::decoded_size(format_value, text_characters); + } +} + +/** + Writes the text of `input_view` into `output_span`: the format's secret arithmetic in a secret + operation when it has one (R7), its `encode` otherwise. +*/ +template +[[nodiscard]] constexpr result codec_encode(F const& format_value, + std::span input_view, + std::span output_span) noexcept { + if constexpr (Secret && has_secret_encode) { + return codec::encode(secret_tag{}, format_value, input_view, output_span); + } else { + return codec::encode(format_value, input_view, output_span); + } +} + +/** + Writes the bytes of `text_characters` into `output_span`: the format's secret arithmetic in a + secret operation when it has one (R7), its `decode` otherwise. +*/ +template +[[nodiscard]] constexpr result codec_decode( + F const& format_value, std::string_view text_characters, + std::span output_span) noexcept { + if constexpr (Secret && has_secret_decode) { + return codec::decode(secret_tag{}, format_value, text_characters, output_span); + } else { + return codec::decode(format_value, text_characters, output_span); + } +} + +/** + Wipes `wiped` by `secure::erase_secret` when it goes, when `Engaged`: the scope guard of a secret + operation's temporary, which wipes it also when the operation returns early or an allocation + throws (owner decision 24). + + @tparam Engaged Whether the operation is secret; a public one wipes nothing. + @tparam Element The temporary's element type. +*/ +template +class temporary_wipe { +public: + /** Wipes `wiped`, when `Engaged`, at the end of the scope. */ + explicit temporary_wipe(std::span wiped) noexcept : wiped_(wiped) {} + + /** Not copyable: one guard for one temporary. */ + temporary_wipe(temporary_wipe const&) = delete; + /** Not copyable: one guard for one temporary. */ + temporary_wipe& operator=(temporary_wipe const&) = delete; + /** Not movable: the guard is the scope's. */ + temporary_wipe(temporary_wipe&&) = delete; + /** Not movable: the guard is the scope's. */ + temporary_wipe& operator=(temporary_wipe&&) = delete; + + /** Wipes the temporary, when `Engaged`. */ + ~temporary_wipe() { + if constexpr (Engaged) { + secure::erase_secret(wiped_); + } + } + +private: + std::span wiped_; +}; + +} // namespace detail + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_SECRECY_HPP diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index 89d8f27..cedc801 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -6,7 +6,8 @@ /** The sizes of webcpp::codecs, the exact size of an encoding and the bound of a decoding, and the - buffer forms, which convert into the caller's buffer. + buffer forms, which convert into the caller's buffer; of a secret input, they hold secure's timing + guard and run the format's secret arithmetic (D10, R7). */ #ifndef WEBCPP_CODECS_DETAIL_CORE_SIZES_HPP #define WEBCPP_CODECS_DETAIL_CORE_SIZES_HPP @@ -15,6 +16,8 @@ #include #include +#include +#include #include #include @@ -71,6 +74,40 @@ template return std::nullopt; } +/** + The exact size of what `encode` writes for the secret `input_value`: the format's secret + arithmetic (R7), under secure's timing guard, which a constant expression cannot hold. +*/ +template +[[nodiscard]] std::size_t secret_encoded_size(F const& format_value, + Input const& input_value) noexcept { + secure::timing_guard const timing_scope{true}; + if constexpr (value_encodable) { + return value_codec::encoded_size(format_value, input_value); + } else { + return codec_encoded_size(format_value, input_bytes(input_value)); + } +} + +/** + Encodes the bytes of `input_value` into `output_buffer`, with the format's secret arithmetic + where `Secret` and the format has one (R7): the buffer form's checks, then the conversion. +*/ +template +[[nodiscard]] result encode_into_buffer(F const& format_value, + Input const& input_value, + std::span output_buffer) noexcept { + std::span const input_view = input_bytes(input_value); + if (auto const size_fault = input_size_fault(format_value, input_view.size())) { + return *size_fault; + } + std::size_t const text_size = codec_encoded_size(format_value, input_view); + if (output_buffer.size() < text_size) { + return error::output_too_small; + } + return codec_encode(format_value, input_view, output_buffer.first(text_size)); +} + } // namespace detail /** @@ -79,7 +116,9 @@ template It is a constant expression where the format and the input are, and the input's bytes are `std::uint8_t` or `unsigned char` (or the input is a value of a value codec whose `encoded_size` - is `constexpr`). A value codec of `F` and `Input` is used when it encodes, else `codec`. + is `constexpr`), and the input is not secret. A value codec of `F` and `Input` is used when it + encodes, else `codec`. Of a secret input (`is_secret_v`, or a value codec's `secret`) it holds + secure's timing guard and runs the format's secret arithmetic where it has one (D10). A pair that is not @ref encodable stops the build with a message that the format does not convert this type. @@ -93,13 +132,15 @@ template template [[nodiscard]] constexpr std::size_t encoded_size(F const& format_value, Input const& input_value) noexcept { - if constexpr (detail::value_encodable) { - return value_codec::encoded_size(format_value, input_value); - } else if constexpr (detail::byte_input && detail::has_codec) { - return codec::encoded_size(format_value, detail::input_bytes(input_value)); - } else { + if constexpr (!encodable) { detail::refuse(); return 0; + } else if constexpr (detail::secret_operation_v) { + return detail::secret_encoded_size(format_value, input_value); + } else if constexpr (detail::value_encodable) { + return value_codec::encoded_size(format_value, input_value); + } else { + return codec::encoded_size(format_value, detail::input_bytes(input_value)); } } @@ -137,9 +178,11 @@ template than the exact size is @ref error::output_too_small. The text is then written at the start of `output_buffer`, whose other characters are unchanged. - A format with no `codec` specialization stops the build with a message that the format does not - convert this type. A type a value codec of `F` encodes takes the value codec's buffer form - instead (operations.hpp). + A secret input (`is_secret_v`, as `secure::secret`) makes the operation secret: it holds + secure's timing guard and runs the format's secret arithmetic where it has one (D10). A format + with no `codec` specialization stops the build with a message that the format does not convert + this type. A type a value codec of `F` encodes takes the value codec's buffer form instead + (operations.hpp). @tparam F The format's type. @tparam Input The input's type: a contiguous sized range of `std::uint8_t`, `unsigned char`, @@ -154,19 +197,14 @@ template requires(!detail::value_encodable) [[nodiscard]] result encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept { - if constexpr (detail::has_codec) { - std::span const input_view = detail::input_bytes(input_value); - if (auto const size_fault = detail::input_size_fault(format_value, input_view.size())) { - return *size_fault; - } - std::size_t const text_size = codec::encoded_size(format_value, input_view); - if (output_buffer.size() < text_size) { - return error::output_too_small; - } - return codec::encode(format_value, input_view, output_buffer.first(text_size)); - } else { + if constexpr (!detail::has_codec) { detail::refuse(); return std::size_t{0}; + } else if constexpr (detail::secret_operation_v) { + secure::timing_guard const timing_scope{true}; + return detail::encode_into_buffer(format_value, input_value, output_buffer); + } else { + return detail::encode_into_buffer(format_value, input_value, output_buffer); } } diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 291dfe9..793f70f 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -116,6 +116,40 @@ struct return_string_t { /** The tag `return_string`: a `std::string`, or with an allocator `return_string(allocator)`. */ inline constexpr return_string_t<> return_string{}; +/** + The tag that makes the operation secret (D10) and gives D9's secret result: `secret_text` from + `encode` (`secret_bytes` for a value codec of bytes) and `secret_bytes` from `decode` when + the bound is known at compile time, ignoring the allocator, and otherwise + `basic_secret_string` (`basic_secret_byte_vector` for bytes), `A` the allocator rebound to + the element; also callable with an allocator that it keeps (B40). + + @tparam Allocator The allocator of a heap result, `std::allocator` for the object `secret`. +*/ +template > +struct secret_t { + /** The operation is secret (D8). */ + static constexpr bool secret = true; + + /** The allocator a heap result is constructed with, rebound to its element. */ + Allocator allocator; + + /** + A tag that gives a heap result over `other`, which is used through `std::allocator_traits`. + + @tparam Other The type of the allocator. + @param other The allocator. + @return The tag. + */ + template + requires requires { typename std::allocator_traits::value_type; } + [[nodiscard]] constexpr secret_t operator()(Other const& other) const noexcept { + return secret_t{other}; + } +}; + +/** The tag `secret`: a secret result, or with an allocator `secret(allocator)`. */ +inline constexpr secret_t<> secret{}; + /** The tag that gives `N` elements in place: `text` from `encode`, `bytes` from `decode`. @@ -260,9 +294,18 @@ inline constexpr bool is_fixed_tag = false; template inline constexpr bool is_fixed_tag> = true; +/** Whether `T` is a `tokens::secret_t`. */ +template +inline constexpr bool is_secret_tag = false; + +/** A `tokens::secret_t`. */ +template +inline constexpr bool is_secret_tag> = true; + /** A tag of `codecs::tokens` that is no token of itself: the core makes the token of it. */ template -concept token_tag = std::same_as || is_return_string || is_fixed_tag; +concept token_tag = std::same_as || is_return_string || is_fixed_tag || + is_secret_tag; /** What `encode` and `decode` take as a token: a tag, or an object of the token contract. */ template diff --git a/test/Jamfile b/test/Jamfile index 32c0f6c..369e740 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -59,6 +59,16 @@ codecs-run secret_fixed : secret_fixed_test.cpp # std::allocator_traits; the approved spellings. codecs-run secret_heap : secret_heap_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# Secret operations (D10): by the value, the value codec, the token or the +# requested type; D9's secret column; a format's secret_tag overloads (R7); +# every temporary of the core wiped, as secure's wipe seam records it; the fixed +# secret forms allocate nothing. +codecs-run secret_operation : secret_operation_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The timing guard of a secret operation: one guard of codecs' for each, none +# for a public one, as secure's timing seam records it; DIT set inside where the +# CPU has it. +codecs-run timing : timing_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index c5e0714..a7cce85 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -17,6 +17,7 @@ #include "support/saturating.hpp" #include +#include #include @@ -367,6 +368,28 @@ void check_secret_results() { BOOST_TEST(verdict); } +/** The fixed secret operations (Task 6) allocate nothing: the secret results in place, secure's + secret as a decode's target, tokens::secret of a static bound. */ +void check_secret_operations() { + webcpp::secure::secret<2> const key; + std::array const input{0x01, 0xff}; + bool volatile verdict = false; + expect_no_allocation("the fixed secret operations", [&] { + auto const encoded = codecs::encode(test::letters, key); + auto const through_token = codecs::encode(test::letters, input, codecs::tokens::secret); + auto const decoded = codecs::decode>(test::letters, "abpp"); + auto const into_bytes = codecs::decode>(test::letters, "abpp"); + auto const fixed_back = + codecs::decode(test::letters, codecs::text<4>{}, codecs::tokens::secret); + std::array buffer{}; + auto const buffered = codecs::encode(test::letters, key, std::span{buffer}); + verdict = encoded.has_value() && through_token.has_value() && decoded.has_value() && + into_bytes.has_value() && fixed_back.has_value() && buffered.has_value() && + codecs::encoded_size(test::letters, key) == 4; + }); + BOOST_TEST(verdict); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -413,6 +436,7 @@ int main() { check_fixed_results(); check_fixed_tokens(); check_secret_results(); + check_secret_operations(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 95ad22b..5dbc63b 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -11,7 +11,8 @@ // standard container's own block, which the MSVC STL's debug containers allocate through their // allocator, is no allocation of an operation: the arena leaves it out (support/bookkeeping.hpp), // as document's and trystero's tests do, and it reaches the global operator new never. The secret -// heap types over the arena give it back every buffer wiped. Later tasks add their rows. +// heap types over the arena, and tokens::secret with the arena's allocator, give it back every +// buffer wiped. Later tasks add their rows. #include "support/counting.hpp" @@ -242,6 +243,44 @@ void secret_types_over_an_arena() { BOOST_TEST(defaulted.get_allocator().resource() == std::pmr::get_default_resource()); } +/** tokens::secret with an allocator (Task 6): a secret result on the arena, both ways, its buffers + given back wiped, and a typed decode into a pmr secret type likewise. */ +void the_secret_token_over_an_arena() { + test::recording_resource arena; + std::vector const input(40, 0x5a); // a size known at run time: the heap + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("tokens::secret over an arena, encode", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::secret(allocator)); + static_assert( + std::is_same_v const>); + BOOST_TEST(encoded.value().view() == text_value); + BOOST_TEST(arena.owns(encoded.value().data())); + BOOST_TEST(encoded.value().get_allocator().resource() == &arena); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); + // The decode rebinds the allocator to the bytes. + expect_no_global_allocation("tokens::secret over an arena, decode", [&] { + auto const decoded = codecs::decode(test::letters, text_value, tokens::secret(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 2U); + expect_no_global_allocation("a typed decode into a pmr secret", [&] { + auto const decoded = codecs::decode( + test::letters, text_value, std::pmr::polymorphic_allocator{&arena}); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + expect_every_block_zero(arena); +} + void the_allocators_of_the_tests_own() { // non_propagating_allocator: equal only to a copy. test::non_propagating_allocator const first_allocator{1}; @@ -283,6 +322,7 @@ int main() { assign_to_a_pmr_vector(); a_typed_decode_with_an_allocator(); secret_types_over_an_arena(); + the_secret_token_over_an_arena(); the_allocators_of_the_tests_own(); return boost::report_errors(); } diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index bbd61f9..b49b89b 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -10,8 +10,9 @@ // exceptions, built with them on in every lane (the Jamfile). A standard container's own block // (the MSVC STL's debug proxy, allocated in noexcept constructors) is neither counted nor failed by // throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). A secret heap -// type whose allocation throws keeps its value, and every buffer it gives back reads zero. Later -// tasks add their rows. +// type whose allocation throws keeps its value, and every buffer it gives back reads zero; so does +// every buffer of a secret operation through tokens::secret(allocator). Later tasks add their +// rows. #include "support/allocators.hpp" #include "support/letters.hpp" @@ -287,6 +288,52 @@ void a_secret_move_between_unequal_allocators_keeps_both() { BOOST_TEST_EQ(attempts, 1U); } +void the_secret_token_throws_through() { + // A secret encode through tokens::secret(allocator): the allocator's exception reaches the + // caller, and every buffer the operation had allocated was given back zero. + std::vector const held_bytes(input_size, 0x5a); // the heap: not a static size + std::string const expected = + codecs::encode(test::letters, held_bytes, tokens::return_string).value(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::secret(allocator)); + BOOST_TEST(encoded.value().view() == expected); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 1U); + // The same for a decode, and a typed decode into a secret vector of the allocator. + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = codecs::decode(test::letters, expected, tokens::secret(allocator)); + BOOST_TEST(holds(decoded.value(), held_bytes)); + auto const typed = codecs::decode(test::letters, expected, allocator); + BOOST_TEST(holds(typed.value(), held_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + } +} + } // namespace int main() { @@ -297,5 +344,6 @@ int main() { a_typed_decode_throws_through(); a_secret_growth_keeps_its_bytes(); a_secret_move_between_unequal_allocators_keeps_both(); + the_secret_token_throws_through(); return boost::report_errors(); } diff --git a/test/default_result_test.cpp b/test/default_result_test.cpp index 3703bdb..7a1b23d 100644 --- a/test/default_result_test.cpp +++ b/test/default_result_test.cpp @@ -50,7 +50,8 @@ static_assert(returns>, std::declval>()))>); static_assert(returns>, decltype(codecs::encode(test::letters, std::declval()))>); -static_assert(returns>, +// secure's secret is secret (D10): the same bound, in D9's secret column. +static_assert(returns>, decltype(codecs::encode(test::letters, std::declval const&>()))>); static_assert( diff --git a/test/messages/refused_allocator/refused_allocator.cpp b/test/messages/refused_allocator/refused_allocator.cpp index 88c3f04..2182f4d 100644 --- a/test/messages/refused_allocator/refused_allocator.cpp +++ b/test/messages/refused_allocator/refused_allocator.cpp @@ -11,8 +11,8 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted>': webcpp::codecs: only a std::basic_string or a std::vector takes an allocator, and the allocator must construct it}} -// expected-error-re@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted<{{.*}}, unrelated_allocator>': webcpp::codecs: only a std::basic_string or a std::vector takes an allocator, and the allocator must construct it}} +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted>': webcpp::codecs: only a string or a vector of bytes, a std::basic_string, a std::vector or a secret one, takes an allocator, and the allocator must construct it}} +// expected-error-re@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::allocator_accepted<{{.*}}, unrelated_allocator>': webcpp::codecs: only a string or a vector of bytes, a std::basic_string, a std::vector or a secret one, takes an allocator, and the allocator must construct it}} // clang-format on #include "../../support/letters.hpp" diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 634c2a2..96ba2d5 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -12,6 +12,7 @@ #include "support/letters.hpp" #include +#include #include #include @@ -133,6 +134,32 @@ static_assert(!noexcept(std::declval().append(std::strin static_assert(!noexcept(std::declval().reserve(1))); static_assert(!noexcept(std::declval().clone())); +// The secret operations (Task 6): a secret result in place is noexcept, a heap one is not. +static_assert(noexcept(codecs::encode(test::letters, std::declval>()))); +static_assert(noexcept(codecs::encode(test::letters, std::array{}, + tokens::secret))); +static_assert(noexcept(codecs::encode(test::letters, std::array{}, + tokens::secret(std::pmr::polymorphic_allocator{})))); +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode>(test::letters, "ab"))); +static_assert(noexcept(codecs::decode(test::letters, codecs::text<64>{}, tokens::secret))); +static_assert(noexcept(codecs::encode(test::letters, std::declval>(), + std::span{}))); +static_assert(noexcept(codecs::encoded_size(test::letters, + std::declval>()))); +static_assert(!noexcept(codecs::encode(test::letters, std::vector{}, + tokens::secret))); +static_assert(!noexcept(codecs::decode(test::letters, std::string_view{}, tokens::secret))); +static_assert(!noexcept(codecs::decode(test::letters, "ab"))); +static_assert(!noexcept(codecs::decode( + test::letters, "ab", std::pmr::polymorphic_allocator{}))); +// The heap secret types' swap, as the standard containers': noexcept when the allocator +// propagates on swap or is always equal. +static_assert( + noexcept(std::declval().swap(std::declval()))); +static_assert(!noexcept(std::declval().swap( + std::declval()))); + // append_to of a vector is for decode, and a vector token is no text token. static_assert(!codecs::detail::text_token< decltype(tokens::append_to(std::declval&>()))>); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp new file mode 100644 index 0000000..1c0b421 --- /dev/null +++ b/test/secret_operation_test.cpp @@ -0,0 +1,527 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Secret operations (D10): an operation is secret by the value's is_secret, the value codec's +// secret, the token's secret or the requested type of a typed decode, and then returns D9's secret +// column, runs a format's secret_tag overloads where it has them (ruling R7), and wipes every +// temporary of the core, as secure's wipe seam (support/wipe_recorder.hpp) records it. The fixed +// secret forms allocate nothing, as support/counting.hpp's operator new sees. The spec's scenarios +// "A secret type encodes to a wiped text", "secure's secret is secret" and "A secret result type +// is secret", here on the format letters (Task 13 adds hex's). + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/letters.hpp" +#include "support/tagged_letters.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +namespace secret_operation { + +/** A secret type of the test's own: 32 bytes of a constant size, a byte input. */ +class key32 { +public: + /** The size. */ + static constexpr std::size_t size() noexcept { return 32; } + + /** The bytes. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + operator std::span() const& noexcept { return held_bytes; } + + /** The bytes, written by the test. */ + std::array held_bytes{}; +}; + +/** A library's fixed secret type whose move does not wipe: a typed decode's target. */ +struct plain_key { + /** The bytes. */ + std::array held_bytes{}; +}; + +/** A secret run of bytes of a size known at run time, a contiguous range. */ +struct secret_run { + /** The bytes. */ + std::vector held_bytes; + + /** The first byte. */ + [[nodiscard]] std::uint8_t const* begin() const noexcept { return held_bytes.data(); } + + /** Past the last byte. */ + [[nodiscard]] std::uint8_t const* end() const noexcept { + return held_bytes.data() + held_bytes.size(); + } +}; + +/** A value of a secret value codec of bytes, with a stated bound: sixteen bits. */ +struct secret_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(secret_number const&) const = default; +}; + +/** A value of a secret value codec of text with no stated bound. */ +struct secret_word { + /** The characters. */ + std::string characters; +}; + +/** The format of the secret value codecs. */ +struct secret_values_t { + /** The format's name. */ + static constexpr std::string_view name = "secret values"; +}; + +/** The format of the secret value codecs. */ +inline constexpr secret_values_t secret_values{}; + +} // namespace secret_operation + +namespace webcpp::codecs { + +/** key32 is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** plain_key is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** plain_key is a decode's target of exactly 32 bytes. */ +template <> +struct fixed_byte_storage { + /** The size. */ + static constexpr std::size_t size = 32; + + /** The bytes a decode fills. */ + static std::span writable( + secret_operation::plain_key& target_key) noexcept { + return target_key.held_bytes; + } +}; + +/** secret_run is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** The secret value codec of bytes: two bytes, big endian. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size( + secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } + + /** Reads two bytes, big endian. */ + static result decode( + secret_operation::secret_values_t const& /*format*/, + std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return error::invalid_length; + } + unsigned const bits = (static_cast(input_bytes[0]) << 8U) | input_bytes[1]; + return secret_operation::secret_number{static_cast(bits)}; + } +}; + +/** The secret value codec of text: the characters as they are. */ +template <> +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + /** The value is secret. */ + static constexpr bool secret = true; + + /** The characters. */ + static std::size_t encoded_size(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_word const& held_value) noexcept { + return held_value.characters.size(); + } + + /** Writes the characters. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_word const& held_value, + std::span output_characters) noexcept { + std::ranges::copy(held_value.characters, output_characters.begin()); + return held_value.characters.size(); + } +}; + +} // namespace webcpp::codecs + +namespace secret_operation { +namespace { + +using codecs::detail::secret_operation_v; + +// is_secret: false by default, true for secure's secret and the secret results, read through +// std::remove_cvref_t. +static_assert(!codecs::is_secret_v>); +static_assert(!codecs::is_secret_v>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v const&>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v); +static_assert(codecs::is_secret_v); +static_assert(codecs::is_secret_v); + +// The operation is secret by the value, the value codec, the token or the requested type (D10). +static_assert( + !secret_operation_v, tokens::automatic>); +static_assert(secret_operation_v); +static_assert(secret_operation_v const&, tokens::automatic>); +static_assert(secret_operation_v); +static_assert( + secret_operation_v, tokens::secret_t<> const&>); +static_assert(secret_operation_v, tokens::automatic>); +static_assert( + !secret_operation_v, tokens::return_string_t<>>); + +// tokens::secret: a tag of both directions, also callable with an allocator, that it keeps. +static_assert(tokens::secret_t<>::secret); +static_assert(std::is_same_v const>); +static_assert( + std::is_same_v{})), + tokens::secret_t>>); + +// D9's secret column. +static_assert(std::is_same_v())), + codecs::result>>); +static_assert( + std::is_same_v>())), + codecs::result>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v())), + codecs::result>); +static_assert(std::is_same_v())), + codecs::result>); +static_assert( + std::is_same_v>(), + tokens::secret)), + codecs::result>); +static_assert(std::is_same_v>(), + tokens::secret)), + codecs::result>>); +// A static bound gives the fixed form and ignores the allocator. +static_assert(std::is_same_v< + decltype(codecs::encode(test::letters, std::declval>(), + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>>); +static_assert(std::is_same_v>(), + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v>(), tokens::secret)), + codecs::result>>); +static_assert(std::is_same_v< + decltype(codecs::decode(test::letters, std::string_view{}, + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>); +// A typed decode into a secret type, and the value codec's own type. +static_assert(std::is_same_v>(test::letters, "ab")), + codecs::result>>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +// The text of a secret encoding is no text input: its view is passed by name. +static_assert(!codecs::detail::text_input>); + +/** The 32 bytes the tests encode, 0x00 to 0xff by steps of 8 (every letter appears). */ +std::array key_bytes() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast(index * 8U); + } + return held_bytes; +} + +/** The letters of `key_bytes()`. */ +std::string key_text() { + return codecs::encode(test::letters, key_bytes(), tokens::return_string).value(); +} + +/** A key32 of `key_bytes()`. */ +key32 make_key32() { + key32 made; + made.held_bytes = key_bytes(); + return made; +} + +/** A secure::secret<32> of `key_bytes()`. */ +secure::secret<32> make_secret() { + secure::secret<32> made; + std::ranges::copy(key_bytes(), made.writable().begin()); + return made; +} + +/** Whether a wipe of `size` bytes, all zero, was recorded somewhere other than `kept`. */ +bool wiped_elsewhere(void const* kept, std::size_t size) { + for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); + ++index) { + test::wipe_entry const& entry = test::wipes.entries[index]; + if (entry.address != kept && entry.size == size && entry.zero) { + return true; + } + } + return false; +} + +void a_secret_type_encodes_to_a_wiped_text() { + key32 const key = make_key32(); + void const* storage = nullptr; + { + auto const encoded = codecs::encode(test::letters, key); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(encoded.value().view() == key_text()); + storage = encoded.value().data(); + test::clear_wipes(); + } + // After its destruction its storage read zero through the seam. + BOOST_TEST(test::wiped(storage, 64)); +} + +void secures_secret_is_secret() { + secure::secret<32> const key = make_secret(); + auto const encoded = codecs::encode(test::letters, key); + BOOST_TEST(encoded.value().view() == key_text()); + // The decode into secure's secret: no heap, its temporary wiped. + test::clear_wipes(); + auto const decoded = codecs::decode>(test::letters, encoded.value().view()); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::equal(decoded.value().bytes(), key_bytes())); + BOOST_TEST(wiped_elsewhere(decoded.value().bytes().data(), 32)); + // The errors reach the caller. + BOOST_TEST(codecs::decode>(test::letters, "abq").error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode>(test::letters, "abab").error() == + codecs::error::invalid_length); +} + +void a_libraries_secret_type_has_its_temporary_wiped() { + // plain_key's move copies its bytes and wipes nothing: the core's scope guard wipes the + // temporary it decoded into. + std::string const text_value = key_text(); + test::clear_wipes(); + auto const decoded = codecs::decode(test::letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(decoded.value().held_bytes == key_bytes()); + BOOST_TEST(wiped_elsewhere(decoded.value().held_bytes.data(), 32)); + // Also when the decode fails after the temporary is made. + test::clear_wipes(); + BOOST_TEST(codecs::decode(test::letters, "abab").error() == + codecs::error::invalid_length); +} + +void a_secret_result_type_is_secret() { + std::string const text_value = key_text(); + test::tagged_calls.reset(); + test::clear_wipes(); + auto const decoded = codecs::decode>(test::tagged_letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::equal(decoded.value().view(), key_bytes())); + // A secret operation: the format's secret arithmetic ran, and the temporary was wiped. + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST(wiped_elsewhere(decoded.value().data(), 32)); + // Up to N bytes, as bytes. + auto const too_small = codecs::decode>(test::letters, text_value); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + auto const heap = codecs::decode(test::letters, text_value); + BOOST_TEST(std::ranges::equal(heap.value().view(), key_bytes())); + auto const characters = codecs::decode(test::letters, "gbgc"); + BOOST_TEST(characters.value().view() == "ab"); +} + +void the_secret_token_both_ways() { + std::string const text_value = key_text(); + // A text of a size known at run time: the heap. + auto const decoded = codecs::decode(test::letters, text_value, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), key_bytes())); + // A text<64>: the fixed form. + auto const fixed_text = codecs::encode(test::letters, key_bytes()); + auto const fixed_decoded = codecs::decode(test::letters, fixed_text.value(), tokens::secret); + BOOST_TEST(std::ranges::equal(fixed_decoded.value().view(), key_bytes())); + // An encode of public bytes through the token. + std::array const held_bytes = key_bytes(); + std::vector const heap_input(held_bytes.begin(), held_bytes.end()); + auto const encoded = codecs::encode(test::letters, heap_input, tokens::secret); + BOOST_TEST(encoded.value().view() == text_value); + auto const fixed_encoded = codecs::encode(test::letters, key_bytes(), tokens::secret); + BOOST_TEST(fixed_encoded.value().view() == text_value); + // The errors reach the caller, the token untouched. + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abq"}, tokens::secret).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(test::letters, codecs::text<4>{}, tokens::secret).has_value()); +} + +void a_secret_value_codec() { + auto const encoded = codecs::encode(secret_values, secret_number{0x1234}); + BOOST_TEST_EQ(encoded.value().size(), 2U); + BOOST_TEST_EQ(encoded.value().view()[0], 0x12); + BOOST_TEST_EQ(encoded.value().view()[1], 0x34); + auto const decoded = codecs::decode(secret_values, encoded.value().view()); + BOOST_TEST(decoded.value() == secret_number{0x1234}); + auto const word = codecs::encode(secret_values, secret_word{"open sesame"}); + BOOST_TEST(word.value().view() == "open sesame"); + // The buffer form of a secret value codec. + std::array buffer{}; + BOOST_TEST_EQ(codecs::encode(secret_values, secret_number{0xabcd}, std::span{buffer}).value(), + 2U); + BOOST_TEST_EQ(buffer[0], 0xab); + // A run of a size known at run time: the heap. + secret_run const run{.held_bytes = {0x01, 0xff}}; + auto const run_text = codecs::encode(test::letters, run); + BOOST_TEST(run_text.value().view() == "abpp"); +} + +void the_secret_arithmetic_runs_in_a_secret_operation_alone() { + // A public operation runs the format's public arithmetic. + test::tagged_calls.reset(); + std::array const public_bytes = key_bytes(); + std::string const text_value = key_text(); + BOOST_TEST(codecs::encode(test::tagged_letters, public_bytes).has_value()); + BOOST_TEST(codecs::decode(test::tagged_letters, text_value).has_value()); + BOOST_TEST( + codecs::encode(test::tagged_letters, public_bytes, tokens::return_string).has_value()); + BOOST_TEST((codecs::decode>(test::tagged_letters, text_value) + .has_value())); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + // Each secret operation runs its secret arithmetic, once each. + secure::secret<32> const key = make_secret(); + auto const encoded = codecs::encode(test::tagged_letters, key); + BOOST_TEST(encoded.value().view() == text_value); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + test::tagged_calls.reset(); + auto const decoded = codecs::decode>(test::tagged_letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + test::tagged_calls.reset(); + auto const through_token = + codecs::decode(test::tagged_letters, std::string_view{text_value}, tokens::secret); + BOOST_TEST(through_token.has_value()); + auto const heap_encoded = + codecs::encode(test::tagged_letters, std::vector(2), tokens::secret); + BOOST_TEST(heap_encoded.value().view() == "aaaa"); + BOOST_TEST_EQ(test::tagged_calls.total(), 4U); + // The sizes and the buffer form of a secret input. + test::tagged_calls.reset(); + BOOST_TEST_EQ(codecs::encoded_size(test::tagged_letters, key), 64U); + std::array buffer{}; + BOOST_TEST_EQ(codecs::encode(test::tagged_letters, key, std::span{buffer}).value(), 64U); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 2U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + // A format with no secret overloads runs its own arithmetic in a secret operation. + auto const plain_encoded = codecs::encode(test::letters, key); + BOOST_TEST(plain_encoded.value().view() == text_value); +} + +/** Runs `body` and checks that the counting operator new saw nothing of it. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const new_before = test::counted_new.load(); + std::size_t const c_before = test::counted_c.load(); + body(); + std::size_t const new_after = test::counted_new.load(); + std::size_t const c_after = test::counted_c.load(); + if (new_after != new_before || c_after != c_before) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(new_after - new_before, 0U); + BOOST_TEST_EQ(c_after - c_before, 0U); +} + +void the_fixed_secret_forms_allocate_nothing() { + key32 const key = make_key32(); + secure::secret<32> const secret_key = make_secret(); + std::array const public_bytes = key_bytes(); + auto const fixed_text = codecs::encode(test::letters, public_bytes); + bool volatile verdict = false; + expect_no_allocation("the fixed secret forms", [&] { + auto const from_key = codecs::encode(test::letters, key); + auto const from_secret = codecs::encode(test::letters, secret_key); + auto const through_token = codecs::encode(test::letters, public_bytes, tokens::secret); + auto const into_secret = + codecs::decode>(test::letters, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(test::letters, fixed_text.value().view()); + auto const into_key = codecs::decode(test::letters, fixed_text.value().view()); + auto const back = codecs::decode(test::letters, fixed_text.value(), tokens::secret); + auto const number = codecs::encode(secret_values, secret_number{7}); + verdict = from_key.has_value() && from_secret.has_value() && through_token.has_value() && + into_secret.has_value() && into_bytes.has_value() && into_key.has_value() && + back.has_value() && number.has_value(); + }); + BOOST_TEST(verdict); +} + +} // namespace +} // namespace secret_operation + +int main() { + secret_operation::a_secret_type_encodes_to_a_wiped_text(); + secret_operation::secures_secret_is_secret(); + secret_operation::a_libraries_secret_type_has_its_temporary_wiped(); + secret_operation::a_secret_result_type_is_secret(); + secret_operation::the_secret_token_both_ways(); + secret_operation::a_secret_value_codec(); + secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); + secret_operation::the_fixed_secret_forms_allocate_nothing(); + return boost::report_errors(); +} diff --git a/test/support/tagged_letters.hpp b/test/support/tagged_letters.hpp new file mode 100644 index 0000000..0c11d98 --- /dev/null +++ b/test/support/tagged_letters.hpp @@ -0,0 +1,143 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// tagged_letters, a format of the tests' own whose arithmetic differs when the operation is secret, +// as base58's does (ruling R7): its codec is letters' six functions, and it also offers the +// overloads of encoded_size, decoded_size, encode and decode that take detail::secret_tag first, +// which the core calls in a secret operation. Each overload counts its calls in tagged_calls and +// then converts as letters does, so that a test sees which arithmetic an operation ran. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_TAGGED_LETTERS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_TAGGED_LETTERS_HPP + +#include "letters.hpp" + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The type of the format tagged_letters. */ +struct tagged_letters_t { + /** The format's name. */ + static constexpr std::string_view name = "tagged letters"; +}; + +/** The format tagged_letters: letters, with the overloads of a secret operation. */ +inline constexpr tagged_letters_t tagged_letters{}; + +/** The calls of the overloads that take `detail::secret_tag`, since the last `reset`. */ +struct tagged_call_counts { + /** The calls of `encoded_size`. */ + std::size_t encoded_size = 0; + /** The calls of `decoded_size`. */ + std::size_t decoded_size = 0; + /** The calls of `encode`. */ + std::size_t encode = 0; + /** The calls of `decode`. */ + std::size_t decode = 0; + + /** Forgets the calls so far. */ + void reset() noexcept { *this = tagged_call_counts{}; } + + /** Every call. */ + [[nodiscard]] std::size_t total() const noexcept { + return encoded_size + decoded_size + encode + decode; + } +}; + +/** The calls of the secret overloads. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +inline tagged_call_counts tagged_calls; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The codec of tagged_letters: letters', and the overloads of a secret operation. */ +template <> +struct codec { + /** letters branches on its data. */ + static constexpr bool constant_time = false; + + /** The letters of `input_size` bytes. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return codec::max_encoded_size(input_size); + } + + /** The bytes of `text_size` letters. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return codec::max_decoded_size(text_size); + } + + /** The letters of `input_bytes`. */ + static constexpr std::size_t encoded_size(test::tagged_letters_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::letters, input_bytes); + } + + /** The bytes of `text_characters`, as letters checks them. */ + static result decoded_size(test::tagged_letters_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::letters, text_characters); + } + + /** Writes the letters of `input_bytes`. */ + static result encode(test::tagged_letters_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::letters, input_bytes, output_characters); + } + + /** Writes the bytes of `text_characters`. */ + static result decode(test::tagged_letters_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::letters, text_characters, output_bytes); + } + + /** The secret operation's `encoded_size`: counted, then letters'. */ + static std::size_t encoded_size(detail::secret_tag /*secret*/, + test::tagged_letters_t const& format_value, + std::span input_bytes) noexcept { + ++test::tagged_calls.encoded_size; + return encoded_size(format_value, input_bytes); + } + + /** The secret operation's `decoded_size`: counted, then letters'. */ + static result decoded_size(detail::secret_tag /*secret*/, + test::tagged_letters_t const& format_value, + std::string_view text_characters) noexcept { + ++test::tagged_calls.decoded_size; + return decoded_size(format_value, text_characters); + } + + /** The secret operation's `encode`: counted, then letters'. */ + static result encode(detail::secret_tag /*secret*/, + test::tagged_letters_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { + ++test::tagged_calls.encode; + return encode(format_value, input_bytes, output_characters); + } + + /** The secret operation's `decode`: counted, then letters'. */ + static result decode(detail::secret_tag /*secret*/, + test::tagged_letters_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { + ++test::tagged_calls.decode; + return decode(format_value, text_characters, output_bytes); + } +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_TEST_SUPPORT_TAGGED_LETTERS_HPP diff --git a/test/support/timing_dit.hpp b/test/support/timing_dit.hpp new file mode 100644 index 0000000..e117526 --- /dev/null +++ b/test/support/timing_dit.hpp @@ -0,0 +1,39 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Copied from webcpp::secure's test/support/timing_dit.hpp at 951401a (pre-flight F27, the +// design's O5), with its namespace webcpp::secure::test renamed webcpp::codecs::test and its +// include guard renamed; secure's names it calls are qualified with secure::, which its own +// namespace made unneeded. Nothing else differs. What follows is secure's comment. +// +// A test's control of the thread's DIT: force_dit sets or clears it, as a program can, so that a +// check starts from a known state. A test that defines the seam of webcpp::secure::timing_guard +// ("support/timing_seam.hpp") includes it before this header, which includes the guard's. + +#ifndef WEBCPP_TEST_CODECS_SUPPORT_TIMING_DIT_HPP +#define WEBCPP_TEST_CODECS_SUPPORT_TIMING_DIT_HPP + +#include + +namespace webcpp::codecs::test { + +/** + * Sets or clears DIT for this thread, as a program can; only where the CPU has DIT, since the + * instruction traps on a CPU without it, and nothing where the guard does not act. + * + * @param set Whether to set DIT. + */ +inline void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (secure::cpu_has_dit()) { + secure::detail::write_dit(set ? secure::detail::dit_bit : 0); + } +#endif +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_TEST_CODECS_SUPPORT_TIMING_DIT_HPP diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp new file mode 100644 index 0000000..038a587 --- /dev/null +++ b/test/support/timing_seam.hpp @@ -0,0 +1,137 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Copied from webcpp::secure's test/support/timing_seam.hpp at 951401a (pre-flight F27, the +// design's O5: codecs keeps its own test support, as secure does, until webcpp::core holds it), +// with its namespace webcpp::secure::test renamed webcpp::codecs::test, its include guard renamed, +// timing_library set to "codecs" and the seam's macro calling codecs' recorder; nothing else +// differs. What follows is secure's comment, "the library" being codecs. +// +// The seam of webcpp::secure::timing_guard, recorded for secure's tests: a test includes this +// header before any webcpp header, so that the seam is defined before +// is first read and every engaged guard a call enters is +// counted, on every target, also where DIT does not apply. A guard is the library's own when one of +// the library's headers declares it: its source_location's file_name() holds +// include/webcpp//, with `/` or `\` around each word (MSVC writes backslashes, and joins +// an include directory to a header's path with either); the include root keeps a checkout whose +// own folders read webcpp// from counting a test file's guard. timing_entries counts the +// library's own guards and timing_all_entries every guard: another library's, which a call may +// enter inside its own, and a test's own. timing_first_entry and timing_last_entry keep the +// function of the first guard since a reset and of the last, which a library's checks read. + +#ifndef WEBCPP_TEST_CODECS_SUPPORT_TIMING_SEAM_HPP +#define WEBCPP_TEST_CODECS_SUPPORT_TIMING_SEAM_HPP + +#ifdef WEBCPP_SECURE_TIMING_GUARD_HPP +#error "\"support/timing_seam.hpp\" must be included before any webcpp header" +#endif + +#include +#include +#include + +namespace webcpp::codecs::test { + +/** Every timing guard this thread entered: the library's, another's, a test's. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_all_entries = 0; + +/** The timing guards of the library's headers this thread has entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_entries = 0; + +/** + * The `function_name()` of the first guard, of any file, this thread entered since it was last + * reset to null: the function that holds that guard, as the compiler spells it. + */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_first_entry = nullptr; + +/** The `function_name()` of the last guard, of any file, this thread entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_last_entry = nullptr; + +/** The library whose guards timing_entries counts. */ +inline constexpr std::string_view timing_library = "codecs"; + +/** Whether `character` separates a path's components, on any system webcpp builds on. */ +constexpr bool path_separator(char character) noexcept { + return character == '/' || character == '\\'; +} + +/** + * Whether `path` holds `name` at `position`, every index checked against the path's size (no + * call that may throw, unlike `substr`). + * + * @param path A `file_name()`. + * @param position Where `name` would start. + * @param name The characters to find there. + * @return Whether the characters of `path` from `position` are those of `name`. + */ +constexpr bool path_holds_at(std::string_view path, std::size_t position, + std::string_view name) noexcept { + if (position > path.size() || name.size() > path.size() - position) { + return false; + } + for (std::size_t index = 0; index < name.size(); ++index) { + if (path[position + index] != name[index]) { + return false; + } + } + return true; +} + +/** + * Whether a path names a file under a library's include directory: the components `include`, + * `webcpp` and `library`, in that order, each followed by a separator, `/` or `\` in any mix, and + * `include` the path's first component or after a separator. + * + * @param path A `file_name()`. + * @param library The library's directory name. + * @return Whether the path is under `include/webcpp//`. + */ +constexpr bool path_in_library(std::string_view path, std::string_view library) noexcept { + constexpr std::string_view include_root = "include"; + constexpr std::string_view root = "webcpp"; + for (std::size_t at = path.find(include_root); at != std::string_view::npos; + at = path.find(include_root, at + 1)) { + std::size_t const root_at = at + include_root.size() + 1; + std::size_t const library_at = root_at + root.size() + 1; + std::size_t const after = library_at + library.size(); + if ((at == 0 || path_separator(path[at - 1])) && after < path.size() && + path_separator(path[root_at - 1]) && path_holds_at(path, root_at, root) && + path_separator(path[library_at - 1]) && path_holds_at(path, library_at, library) && + path_separator(path[after])) { + return true; + } + } + return false; +} + +/** + * Records the entry into a webcpp::secure::timing_guard: counts it, as the library's when + * its file is under the library's include directory, and keeps its function as the first since + * timing_first_entry was reset and as the last. + * + * @param where Where the guard is declared. + */ +inline void timing_entered(std::source_location const& where) noexcept { + ++timing_all_entries; + if (path_in_library(where.file_name(), timing_library)) { + ++timing_entries; + } + if (timing_first_entry == nullptr) { + timing_first_entry = where.function_name(); + } + timing_last_entry = where.function_name(); +} + +} // namespace webcpp::codecs::test + +/** Records the entry into a webcpp::secure::timing_guard declared at `where`. */ +#define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::codecs::test::timing_entered(where)) + +#endif // WEBCPP_TEST_CODECS_SUPPORT_TIMING_SEAM_HPP diff --git a/test/timing_test.cpp b/test/timing_test.cpp new file mode 100644 index 0000000..318da2b --- /dev/null +++ b/test/timing_test.cpp @@ -0,0 +1,225 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The timing guard of a secret operation (D10, D12, B11): secure's seam, recorded by +// support/timing_seam.hpp, counts one engaged guard of codecs' for each secret operation, held by +// the core's public function that runs it, and none for a public operation (the spec's scenario "A +// secret operation sets DIT through secure", here on the format letters; Task 13 adds hex's). +// Where the guard acts (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, a value codec of the +// test's own reads DIT set while it encodes a secret, and clear after. + +#include "support/timing_seam.hpp" + +#include "support/timing_dit.hpp" + +#include "support/letters.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +namespace timing { + +/** A secret type of the test's own: 32 bytes of a constant size, a byte input. */ +class key32 { +public: + /** The size. */ + static constexpr std::size_t size() noexcept { return 32; } + + /** The bytes. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + operator std::span() const& noexcept { return held_bytes; } + + /** The bytes. */ + std::array held_bytes{}; +}; + +/** A secret value whose value codec reads DIT while it encodes. */ +struct dit_probe { + /** The byte written. */ + std::uint8_t value = 0; +}; + +/** The format of dit_probe. */ +struct probe_format_t { + /** The format's name. */ + static constexpr std::string_view name = "probe"; +}; + +/** The format of dit_probe. */ +inline constexpr probe_format_t probe_format{}; + +/** Whether DIT read set in the last encode of a dit_probe. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +inline bool dit_while_encoding = false; + +} // namespace timing + +namespace webcpp::codecs { + +/** key32 is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** dit_probe's value codec: secret, one byte, which records DIT as it writes it. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + /** One byte. */ + static constexpr std::size_t max_encoded_size = 1; + + /** One byte. */ + static std::size_t encoded_size(timing::probe_format_t const& /*format*/, + timing::dit_probe const& /*held_value*/) noexcept { + return 1; + } + + /** Records whether DIT is set, then writes the byte. */ + static result encode(timing::probe_format_t const& /*format*/, + timing::dit_probe const& held_value, + std::span output_bytes) noexcept { + timing::dit_while_encoding = secure::dit_is_set(); + output_bytes[0] = held_value.value; + return std::size_t{1}; + } +}; + +} // namespace webcpp::codecs + +namespace timing { +namespace { + +/** Whether the first guard since the last reset is held by `function`, as the compiler names it. */ +bool first_guard_in(std::string_view function) { + return test::timing_first_entry != nullptr && + std::string_view{test::timing_first_entry}.find(function) != std::string_view::npos; +} + +/** Forgets the guards entered so far. */ +void reset_guards() { + test::timing_entries = 0; + test::timing_all_entries = 0; + test::timing_first_entry = nullptr; +} + +/** Checks that `operation` entered exactly one guard, codecs', held by `function`. */ +template +void expect_one_guard(char const* function, Operation operation) { + reset_guards(); + operation(); + BOOST_TEST_EQ(test::timing_entries, 1U); + BOOST_TEST_EQ(test::timing_all_entries, 1U); + BOOST_TEST(first_guard_in(function)); +} + +/** Checks that `operation` entered no guard. */ +template +void expect_no_guard(Operation operation) { + reset_guards(); + operation(); + BOOST_TEST_EQ(test::timing_all_entries, 0U); + BOOST_TEST(test::timing_first_entry == nullptr); +} + +void a_secret_operation_enters_one_guard() { + key32 const key{}; + std::array const public_bytes{}; + // The spec's scenario: a secret type, then public bytes. + expect_one_guard("webcpp::codecs::encode", + [&] { BOOST_TEST(codecs::encode(test::letters, key).has_value()); }); + expect_no_guard([&] { BOOST_TEST(codecs::encode(test::letters, public_bytes).has_value()); }); + // Every form of a secret operation, each through one guard of the function that runs it. + std::string const text_value(64, 'a'); + secure::secret<32> const secret_key; + expect_one_guard("webcpp::codecs::encode", + [&] { BOOST_TEST(codecs::encode(test::letters, secret_key).has_value()); }); + expect_one_guard("webcpp::codecs::encode", [&] { + BOOST_TEST(codecs::encode(test::letters, key, tokens::return_string).has_value()); + }); + expect_one_guard("webcpp::codecs::encode", [&] { + BOOST_TEST(codecs::encode(test::letters, std::vector(3), tokens::secret) + .has_value()); + }); + expect_one_guard("webcpp::codecs::encode", [&] { + BOOST_TEST(codecs::encode(test::letters, public_bytes, tokens::secret).has_value()); + }); + expect_one_guard("webcpp::codecs::encode", [&] { + BOOST_TEST(codecs::encode(test::letters, key, tokens::automatic{}).has_value()); + }); + expect_one_guard("webcpp::codecs::encode", [&] { + std::array buffer{}; + BOOST_TEST(codecs::encode(test::letters, key, std::span{buffer}).has_value()); + }); + expect_one_guard("webcpp::codecs::encode", [&] { + std::array buffer{}; + BOOST_TEST(codecs::encode(probe_format, dit_probe{}, std::span{buffer}).has_value()); + }); + expect_one_guard("encoded_size", + [&] { BOOST_TEST_EQ(codecs::encoded_size(test::letters, key), 64U); }); + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST(codecs::decode>(test::letters, text_value).has_value()); + }); + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST(codecs::decode(test::letters, text_value, tokens::secret).has_value()); + }); + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST(codecs::decode( + test::letters, text_value, std::pmr::polymorphic_allocator{}) + .has_value()); + }); + // The public forms hold none. + expect_no_guard([&] { + BOOST_TEST(codecs::decode(test::letters, text_value).has_value()); + BOOST_TEST( + (codecs::decode>(test::letters, text_value).has_value())); + BOOST_TEST(codecs::encode(test::letters, public_bytes, tokens::return_string).has_value()); + BOOST_TEST_EQ(codecs::encoded_size(test::letters, public_bytes), 64U); + }); +} + +void dit_is_set_while_a_secret_encodes() { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!secure::cpu_has_dit()) { + return; + } + test::force_dit(false); + BOOST_TEST(!secure::dit_is_set()); + dit_while_encoding = false; + auto const encoded = codecs::encode(probe_format, dit_probe{.value = 7}); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(dit_while_encoding); + BOOST_TEST(!secure::dit_is_set()); +#endif +} + +} // namespace +} // namespace timing + +int main() { + timing::a_secret_operation_enters_one_guard(); + timing::dit_is_set_while_a_secret_encodes(); + return boost::report_errors(); +} From 7b05d8a9caa62dda052339254577dc6d5e5d81ac Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:31:50 -0300 Subject: [PATCH 026/157] codecs: assign_to leaves its string or vector as it was when the operation fails, a scratch in place or of its allocator assigned on success alone and wiped of what the target does not get --- .../webcpp/codecs/detail/core/operations.hpp | 76 +++++++-- include/webcpp/codecs/detail/core/tokens.hpp | 153 ++++++++++++++++-- test/allocator_throw_test.cpp | 28 ++++ test/secret_operation_test.cpp | 82 ++++++++++ test/support/be16.hpp | 32 ++++ test/tokens_test.cpp | 40 +++++ 6 files changed, 382 insertions(+), 29 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index b741e4b..faf04e9 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -447,10 +447,10 @@ template Encodes into `token_object`, a concrete token (B6): the checks of the input, then the token's `capacity` against the exact size, then one `prepare` with that size, the format's `encode` into what it returned (its secret arithmetic when `Secret` and it has one, R7), and one `result`. A - token is untouched when a check fails. When the conversion itself fails after `prepare` (a value - codec's own error), a token of codecs' that appends is put back as it was; an assigning token has - lost its old content and a token of a program's own is left as `prepare` made it. A token of - codecs' is cut to the count the format wrote. + token is untouched when a check fails. When the conversion itself fails after `prepare` (a value + codec's own error), a token of codecs' that appends is put back as it was and one that assigns + has written into its scratch alone; a token of a program's own is left as `prepare` made it. A + token of codecs' is cut to the count the format wrote. */ template [[nodiscard]] result encode_to( @@ -548,14 +548,59 @@ template return token_object.result(); } +/** + Converts by `convert`, which runs `encode_to` or `decode_to` into the token it is given, into + `token_object`, the token of `assign_to`, through a scratch in place of `Bound` elements, wiped + when `Secret`; the container gets the result only on success, by one copy. +*/ +template +[[nodiscard]] result assign_in_place(assigning_token& token_object, + Convert convert) { + in_place_scratch scratch; + auto const written = convert(scratch); + if (!written) { + return written.error(); + } + // Read unchecked: the error was returned above. + return token_object.assign(written.unsafe_value()); +} + /** Encodes into `token`, as it was passed, a token or a tag of `codecs::tokens` the core turns into - one (B6), under the guard of the public function that calls it. + one (B6), under the guard of the public function that calls it; `assign_to` of a static bound + through a scratch in place. */ template [[nodiscard]] auto encode_into(F const& format_value, Input const& input_value, Token& token) { auto&& concrete_token = detail::concrete_token()>(token); - return encode_to(format_value, input_value, concrete_token); + constexpr std::size_t bound = static_encoded_bound(); + if constexpr (is_assigning_token> && + bound != std::dynamic_extent) { + return assign_in_place(concrete_token, [&](auto& scratch) { + return encode_to(format_value, input_value, scratch); + }); + } else { + return encode_to(format_value, input_value, concrete_token); + } +} + +/** + Decodes into `token`, as it was passed, a byte token or a tag of `codecs::tokens` the core turns + into one (B6), under the guard of the public function that calls it; `assign_to` of a text of a + static size through a scratch in place. +*/ +template +[[nodiscard]] auto decode_into(F const& format_value, Text const& text_value, Token& token) { + auto&& concrete_token = detail::concrete_token(token); + constexpr std::size_t bound = static_decoded_bound(); + if constexpr (is_assigning_token> && + bound != std::dynamic_extent) { + return assign_in_place(concrete_token, [&](auto& scratch) { + return decode_to(format_value, text_value, scratch); + }); + } else { + return decode_to(format_value, text_value, concrete_token); + } } /** @@ -742,9 +787,12 @@ template input (an input whose encoding does not fit in `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one - `result`. A token is untouched when a check fails (an error of a value codec's own, found after - `prepare`, puts an `append_to` token back as it was; an `assign_to` token and a token of a - program's own are left as `prepare` made them). A token of codecs' holds what the format wrote. The + `result`. A token is untouched when a check fails, and a token of codecs' also when the + conversion fails after `prepare` (an error of a value codec's own): `append_to` is put back as it + was, and `assign_to` converts into a scratch (in place when the bound is known at compile time, + else of the container's allocator, wiped of what the container does not get) and assigns only on + success; a token of a program's own is left as `prepare` made it. A token of codecs' holds what + the format wrote. The forms that allocate are not `noexcept` (an allocator's exception propagates, owner decision 24); `fixed` is, and `secret` when its result is in place. The operation is secret (D10) when the input's `is_secret_v`, the value codec's `secret` or the token's `secret` says so: it then holds @@ -811,8 +859,8 @@ template `std::size_t` is @ref error::input_too_long, the whole text is checked and its data error with the lowest value of @ref error returned, then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A - token is untouched when a check fails (a conversion that fails after `prepare` puts an `append_to` - token back; see `encode`). The forms that allocate are not `noexcept`; `fixed` is, and `secret` + token is untouched when a check fails, and a token of codecs' also when the conversion fails after + `prepare` (see `encode`). The forms that allocate are not `noexcept`; `fixed` is, and `secret` when its result is in place. A decode is secret (D10) through its token alone (`secret`, or a token whose `secret` is true): it then holds secure's timing guard and runs the format's secret arithmetic where it has one. A format with no `codec` specialization stops the build with a message @@ -852,11 +900,9 @@ template return result>{std::vector{}}; } else if constexpr (detail::secret_operation_v) { secure::timing_guard const timing_scope{true}; - auto&& concrete_token = detail::concrete_token(token); - return detail::decode_to(format_value, text_value, concrete_token); + return detail::decode_into(format_value, text_value, token); } else { - auto&& concrete_token = detail::concrete_token(token); - return detail::decode_to(format_value, text_value, concrete_token); + return detail::decode_into(format_value, text_value, token); } } diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 793f70f..d447dd5 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -17,11 +17,14 @@ #include #include #include +#include +#include #include #include #include #include +#include #include #include #include @@ -199,32 +202,148 @@ class appending_token { std::size_t old_size_ = 0; }; -/** A token that replaces the content of a string or a vector with the result. */ +/** + A token that replaces the content of a string or a vector with the result, and leaves it as it + was when the operation fails (the owner's ruling): the conversion writes into a scratch, and the + container gets the result only on success. + + Through the token contract, the scratch is a container of the target's own type and allocator, + which `prepare` allocates (an allocation that throws leaves the target untouched) and `result` + swaps with the target, so that its buffer becomes the target's and nothing is copied. When the + bound is known at compile time the core converts into a scratch in place instead and gives the + result to `assign`, one copy. The scratch's elements that are not given to the target (all of + them on a failure, those past the written count on success) are wiped by + `secure::erase_secret` before they go: the token cannot tell a secret operation from a public one. +*/ template class assigning_token { public: /** The container, by reference, as Boost.URL's `assign_to` gives it. */ using result_type = Container&; + /** The element of the container: `char` or `std::uint8_t`. */ + using element_type = Container::value_type; + /** Constructs a token that assigns to `target`, which outlives it. */ explicit assigning_token(Container& target) noexcept : target_(&target) {} - /** Resizes the container to `size` elements and returns a pointer to them. */ - [[nodiscard]] auto* prepare(std::size_t size) { - target_->resize(size); - return target_->data(); + /** + Makes a scratch of `size` elements, of the target's allocator, and returns them; the target is + untouched. + */ + [[nodiscard]] element_type* prepare(std::size_t size) { + scratch_.emplace(target_->get_allocator()); + scratch_->resize(size); + return scratch_->data(); } - /** Cuts the container to the `written` elements. */ - void shrink_to(std::size_t written) { target_->resize(written); } + /** Cuts the scratch to the `written` elements, the others wiped. */ + void shrink_to(std::size_t written) { + secure::erase_secret( + std::span{scratch_->data() + written, scratch_->size() - written}); + scratch_->resize(written); + } - /** The container. */ - [[nodiscard]] result_type result() noexcept { return *target_; } + /** Wipes the scratch and gives it back: the target keeps its content. */ + void abandon() noexcept { + secure::erase_secret(*scratch_); + scratch_.reset(); + } + + /** Gives the scratch's buffer to the target, whose old one goes with the scratch. */ + [[nodiscard]] result_type result() { + target_->swap(*scratch_); + return *target_; + } + + /** + Replaces the content of the target with `written`, a scratch the core held in place, or + leaves it as it was when the allocation this needs throws: in the target's own buffer when it + holds them, else in a new container of its allocator, swapped in. + + @param written The elements of the result. + @return The target. + */ + result_type assign(std::span written) { + if (written.size() <= target_->capacity()) { + target_->assign(written.begin(), written.end()); + } else { + Container fresh(target_->get_allocator()); + fresh.assign(written.begin(), written.end()); + target_->swap(fresh); + } + return *target_; + } private: Container* target_; + std::optional scratch_; +}; + +/** + The scratch in place of an operation into `assign_to` whose bound, `N`, is known at compile + time: a token of `N` elements whose result is the elements written, wiped when it goes when + `Wiped`, a secret operation's. + + @tparam Element `char` or `std::uint8_t`. + @tparam N The most elements. + @tparam Wiped Whether the operation is secret. +*/ +template +class in_place_scratch { +public: + /** The elements written. */ + using result_type = std::span; + + /** The most elements. */ + static constexpr std::size_t capacity = N; + + /** An empty scratch. */ + in_place_scratch() noexcept = default; + + /** Not copyable: the elements are the operation's. */ + in_place_scratch(in_place_scratch const&) = delete; + /** Not copyable: the elements are the operation's. */ + in_place_scratch& operator=(in_place_scratch const&) = delete; + /** Not movable: the elements are the operation's. */ + in_place_scratch(in_place_scratch&&) = delete; + /** Not movable: the elements are the operation's. */ + in_place_scratch& operator=(in_place_scratch&&) = delete; + + /** Wipes the elements prepared, when `Wiped`. */ + ~in_place_scratch() { + if constexpr (Wiped) { + secure::erase_secret(std::span{elements_}.first(prepared_)); + } + } + + /** Returns `size` elements, which the core made sure fit. */ + [[nodiscard]] Element* prepare(std::size_t size) noexcept { + prepared_ = size; + written_ = size; + return elements_.data(); + } + + /** Keeps the `written` elements. */ + void shrink_to(std::size_t written) noexcept { written_ = written; } + + /** The elements written. */ + [[nodiscard]] result_type result() const noexcept { return {elements_.data(), written_}; } + +private: + std::array elements_{}; + std::size_t prepared_ = 0; + std::size_t written_ = 0; }; +/** Whether `T` is the token of `assign_to`. */ +template +inline constexpr bool is_assigning_token = false; + +/** The token of `assign_to`. */ +template +inline constexpr bool is_assigning_token> = true; + /** A token that gives a string of its own, made with the allocator it was constructed with. */ template class returning_token { @@ -373,7 +492,8 @@ template } /** - The tag that appends the bytes of a decode to `target`, a vector of any allocator; decode only. + The tag that appends the bytes of a decode (or of a value codec of bytes) to `target`, a vector of + any allocator. The vector's own allocator is used. The operation returns `target` by reference. @@ -390,8 +510,12 @@ template The tag that replaces the content of `target`, a string of any traits and allocator, with the result. - The string's own allocator is used. The operation returns `target` by reference. The input must - not be a part of `target`. + The string's own allocator is used. The operation returns `target` by reference, and leaves it as + it was when it fails, also after the conversion began (a value codec's own error) and when an + allocation throws: the conversion writes into a scratch, in place when the bound is known at + compile time and of the string's allocator otherwise, and the string gets the result only on + success, so that the input may be a part of `target`. The scratch's bytes that the string does + not get are wiped. @tparam Traits The string's character traits. @tparam Allocator The string's allocator. @@ -405,9 +529,10 @@ template /** The tag that replaces the content of `target`, a vector of any allocator, with the bytes of a - decode; decode only. + decode (or of a value codec of bytes). - The vector's own allocator is used. The operation returns `target` by reference. + The vector's own allocator is used. The operation returns `target` by reference, and leaves it as + it was when it fails, as `assign_to` of a string does. @tparam Allocator The vector's allocator. @param target The vector to assign to. diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index b49b89b..8b86b4f 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -186,6 +186,33 @@ void decode_into_a_vector_keeps_it() { BOOST_TEST(attempts >= 1U); } +void assign_to_a_vector_keeps_it() { + // A text of a size known at run time: assign_to's scratch comes from the vector's allocator, + // and when that allocation throws the vector holds what it held. + std::string const expected = expected_text(); + auto const held_bytes = input_bytes(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_bytes target{{9, 9}, allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::decode(test::letters, expected, tokens::assign_to(target)).has_value()); + BOOST_TEST(std::ranges::equal(target, held_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST((target == throwing_bytes{{9, 9}, allocator})); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + void a_typed_decode_throws_through() { std::string const expected = expected_text(); auto const held_bytes = input_bytes(); @@ -341,6 +368,7 @@ int main() { append_to_keeps_the_string(); assign_to_keeps_the_string(); decode_into_a_vector_keeps_it(); + assign_to_a_vector_keeps_it(); a_typed_decode_throws_through(); a_secret_growth_keeps_its_bytes(); a_secret_move_between_unequal_allocators_keeps_both(); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index 1c0b421..1c73c7e 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -88,6 +88,18 @@ struct secret_number { bool operator==(secret_number const&) const = default; }; +/** A secret value whose value codec writes its bytes and then fails, with no stated bound. */ +struct secret_failing_number { + /** The bits. */ + std::uint16_t value; +}; + +/** A secret_failing_number whose value codec states its bound: its scratch is in place. */ +struct bounded_secret_failing_number { + /** The bits. */ + std::uint16_t value; +}; + /** A value of a secret value codec of text with no stated bound. */ struct secret_word { /** The characters. */ @@ -170,6 +182,44 @@ struct value_codec +struct failing_value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + + /** Two bytes. */ + static std::size_t encoded_size(secret_operation::secret_values_t const& /*format*/, + Failing const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes, then reports checksum_mismatch. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + Failing const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return error::checksum_mismatch; + } +}; + +/** The failing secret value codec with no stated bound. */ +template <> +struct value_codec + : failing_value_codec {}; + +/** The failing secret value codec with a stated bound. */ +template <> +struct value_codec + : failing_value_codec { + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; +}; + /** The secret value codec of text: the characters as they are. */ template <> struct value_codec { @@ -429,6 +479,37 @@ void a_secret_value_codec() { BOOST_TEST(run_text.value().view() == "abpp"); } +/** Whether a wipe of `size` bytes, all zero, was recorded. */ +bool wiped_of_size(std::size_t size) { + return wiped_elsewhere(nullptr, size); +} + +void a_failed_secret_operation_into_assign_to() { + // The value codec writes its two secret bytes and then fails: assign_to's target keeps what it + // held, and the scratch that held the bytes was wiped, from the target's allocator and in + // place. + std::vector kept{9, 8, 7}; + test::clear_wipes(); + auto const failed = + codecs::encode(secret_values, secret_failing_number{0x1234}, tokens::assign_to(kept)); + BOOST_TEST(failed.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + BOOST_TEST(wiped_of_size(2)); + test::clear_wipes(); + auto const bounded = codecs::encode(secret_values, bounded_secret_failing_number{0x1234}, + tokens::assign_to(kept)); + BOOST_TEST(bounded.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + BOOST_TEST(wiped_of_size(2)); + // On success the scratch in place is wiped too, once its bytes are in the target. + std::string text_target = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::letters, make_key32(), tokens::assign_to(text_target)).has_value()); + BOOST_TEST(text_target == key_text()); + BOOST_TEST(wiped_of_size(64)); +} + void the_secret_arithmetic_runs_in_a_secret_operation_alone() { // A public operation runs the format's public arithmetic. test::tagged_calls.reset(); @@ -521,6 +602,7 @@ int main() { secret_operation::a_secret_result_type_is_secret(); secret_operation::the_secret_token_both_ways(); secret_operation::a_secret_value_codec(); + secret_operation::a_failed_secret_operation_into_assign_to(); secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); secret_operation::the_fixed_secret_forms_allocate_nothing(); return boost::report_errors(); diff --git a/test/support/be16.hpp b/test/support/be16.hpp index 7e5a6c7..57a077f 100644 --- a/test/support/be16.hpp +++ b/test/support/be16.hpp @@ -8,6 +8,8 @@ // endian, by a value codec of bytes that states its bound, so that the default result is a fixed // one. Decoding any other length is invalid_length. A `hex_number` is written as four hexadecimal // digits by a value codec of text that states no bound, so that the default result is a string. +// A `failing_number` and a `bounded_failing_number` write their two bytes and then fail, the +// second with a stated bound. #ifndef WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP #define WEBCPP_CODECS_TEST_SUPPORT_BE16_HPP @@ -54,6 +56,12 @@ struct failing_number { std::uint16_t value; }; +/** A failing_number whose value codec states its bound, so that its result is a fixed one. */ +struct bounded_failing_number { + /** The bits. */ + std::uint16_t value; +}; + } // namespace webcpp::codecs::test namespace webcpp::codecs { @@ -117,6 +125,30 @@ struct value_codec { } }; +/** The value codec of be16 for a `bounded_failing_number`: as failing_number's, with a bound. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size(test::be16_t const& /*format*/, + test::bounded_failing_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes of its own, then reports checksum_mismatch. */ + static result encode(test::be16_t const& /*format*/, + test::bounded_failing_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return error::checksum_mismatch; + } +}; + /** The value codec of be16 for a `hex_number`: text with no stated bound. */ template <> struct value_codec { diff --git a/test/tokens_test.cpp b/test/tokens_test.cpp index cf89c0c..3038587 100644 --- a/test/tokens_test.cpp +++ b/test/tokens_test.cpp @@ -415,6 +415,45 @@ void a_failure_after_prepare_puts_an_appending_token_back() { BOOST_TEST_EQ(bytes_kept.size(), 3U); } +void a_failure_after_prepare_leaves_an_assigning_token_untouched() { + // The value codec writes its bytes and then fails: assign_to converts into a scratch and + // assigns only on success (the owner's ruling), so its target keeps what it held, whether the + // bound is known at run time (a scratch of the target's allocator) or at compile time (a + // scratch in place). + std::vector kept{9, 8, 7}; + auto const failed = + codecs::encode(test::be16, test::failing_number{0x1234}, tokens::assign_to(kept)); + BOOST_TEST(failed.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + auto const bounded_failed = + codecs::encode(test::be16, test::bounded_failing_number{0x1234}, tokens::assign_to(kept)); + BOOST_TEST(bounded_failed.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + std::string text_kept = "kept"; + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::assign_to(text_kept)) + .has_value()); + BOOST_TEST(text_kept == "kept"); + // On success the target holds the result, by each path. + BOOST_TEST( + codecs::encode(test::be16, test::number{0x1234}, tokens::assign_to(kept)).has_value()); + BOOST_TEST((kept == std::vector{0x12, 0x34})); + BOOST_TEST(codecs::encode(test::be16, test::hex_number{0xbeef}, tokens::assign_to(text_kept)) + .has_value()); + BOOST_TEST(text_kept == "beef"); + // A static bound larger than what the target holds, and smaller. + std::string short_target = "k"; + BOOST_TEST( + codecs::encode(test::letters, two_bytes, tokens::assign_to(short_target)).has_value()); + BOOST_TEST(short_target == "abpp"); + std::string long_target(100, 'k'); + BOOST_TEST( + codecs::encode(test::letters, two_bytes, tokens::assign_to(long_target)).has_value()); + BOOST_TEST(long_target == "abpp"); + BOOST_TEST( + codecs::decode(test::letters, codecs::text<4>{}, tokens::assign_to(kept)).has_value()); + BOOST_TEST(kept.empty()); +} + void a_result_holds_what_the_format_wrote() { // shrinking asks for one element more than it writes: the tokens of codecs' hold the written // count, as the heap results do. @@ -456,6 +495,7 @@ int main() { a_value_codec_goes_through_a_token(); a_typed_decode_uses_the_default_resource(); a_failure_after_prepare_puts_an_appending_token_back(); + a_failure_after_prepare_leaves_an_assigning_token_untouched(); a_result_holds_what_the_format_wrote(); return boost::report_errors(); } From c4a1fec9d851b07808420516e8b3395915627515 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:35:46 -0300 Subject: [PATCH 027/157] codecs: the reference builds: a @tparam for each is_secret specialization the check reads, one-sentence briefs of swap --- include/webcpp/codecs/detail/core/secrecy.hpp | 26 +++++++++++++++---- .../codecs/detail/core/secret_types.hpp | 18 +++++++------ 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 5d8abc1..489bebc 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -60,23 +60,39 @@ struct is_secret : std::false_type {}; template inline constexpr bool is_secret_v = is_secret>::value; -/** secure's secret is secret. */ +/** + secure's secret is secret. + + @tparam N The size of the secret. +*/ template struct is_secret> : std::true_type {}; -/** The text of a secret encoding is secret. */ +/** + The text of a secret encoding is secret. + + @tparam N The most characters it holds. +*/ template struct is_secret> : std::true_type {}; -/** The bytes of a secret decoding are secret. */ +/** + The bytes of a secret decoding are secret. + + @tparam N The most bytes they hold. +*/ template struct is_secret> : std::true_type {}; -/** A secret string on the heap is secret. */ +// The reference's check (tools/doc/doc_comments.py) keys the partial specializations of one +// template by its name, so that every @tparam of them must name a parameter of the first: these +// two state their allocator in their text. + +/** A secret string on the heap is secret, whatever its allocator. */ template struct is_secret> : std::true_type {}; -/** Secret bytes on the heap are secret. */ +/** Secret bytes on the heap are secret, whatever their allocator. */ template struct is_secret> : std::true_type {}; diff --git a/include/webcpp/codecs/detail/core/secret_types.hpp b/include/webcpp/codecs/detail/core/secret_types.hpp index 6696a5e..2856fb3 100644 --- a/include/webcpp/codecs/detail/core/secret_types.hpp +++ b/include/webcpp/codecs/detail/core/secret_types.hpp @@ -683,10 +683,11 @@ class basic_secret_string { void shrink_to_fit() { buffer_.shrink_to_fit(); } /** - Exchanges the characters and the buffers of this string and `other_string`, and their - allocators when the allocator propagates on swap (`propagate_on_container_swap`); between - allocators that do not, they must be equal, as the standard containers require. Nothing is - copied, allocated or wiped. + Exchanges the characters and the buffers of this string and `other_string`. + + The allocators are exchanged too when they propagate on swap + (`propagate_on_container_swap`); allocators that do not must be equal, as the standard + containers require. Nothing is copied, allocated or wiped. @param other_string The string to exchange with. */ @@ -886,10 +887,11 @@ class basic_secret_byte_vector { void shrink_to_fit() { buffer_.shrink_to_fit(); } /** - Exchanges the bytes and the buffers of these bytes and `other_bytes`, and their allocators - when the allocator propagates on swap (`propagate_on_container_swap`); between allocators that - do not, they must be equal, as the standard containers require. Nothing is copied, allocated - or wiped. + Exchanges the bytes and the buffers of these bytes and `other_bytes`. + + The allocators are exchanged too when they propagate on swap + (`propagate_on_container_swap`); allocators that do not must be equal, as the standard + containers require. Nothing is copied, allocated or wiped. @param other_bytes The bytes to exchange with. */ From 4840798a52db3fb55dac761fc2896adb8d3f0f6c Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:41:41 -0300 Subject: [PATCH 028/157] codecs: secret operations lint fix, the test types of internal linkage, the allocators' moves suppressed by the check's name, a guard made by parentheses --- .../webcpp/codecs/detail/core/operations.hpp | 4 +- test/secret_operation_test.cpp | 54 ++++++++++--------- test/support/allocators.hpp | 4 +- test/timing_test.cpp | 11 +++- 4 files changed, 41 insertions(+), 32 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index faf04e9..7b34fda 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -379,13 +379,13 @@ template auto target_value = make_target(allocator_values...); // A heap secret result wipes its own buffers; a public operation wipes nothing. constexpr bool wipes_temporary = Secret && decode_is_fixed; - [[maybe_unused]] temporary_wipe const target_wipe{[&] { + [[maybe_unused]] temporary_wipe const target_wipe([&] { if constexpr (wipes_temporary) { return fixed_storage(target_value); } else { return std::span{}; } - }()}; + }()); std::span output_span; if constexpr (is_fixed_result) { if (byte_count > Target::capacity()) { diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index 1c73c7e..a2c4ba9 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -44,6 +44,7 @@ namespace test = webcpp::codecs::test; namespace tokens = webcpp::codecs::tokens; namespace secret_operation { +namespace { /** A secret type of the test's own: 32 bytes of a constant size, a byte input. */ class key32 { @@ -115,6 +116,31 @@ struct secret_values_t { /** The format of the secret value codecs. */ inline constexpr secret_values_t secret_values{}; +/** The secret value codec that fails after writing: two bytes, then checksum_mismatch. */ +template +struct failing_value_codec { + /** Bytes. */ + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + + /** Two bytes. */ + static std::size_t encoded_size(secret_values_t const& /*format*/, + Failing const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes, then reports checksum_mismatch. */ + static codecs::result encode(secret_values_t const& /*format*/, + Failing const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return codecs::error::checksum_mismatch; + } +}; + +} // namespace } // namespace secret_operation namespace webcpp::codecs { @@ -182,40 +208,16 @@ struct value_codec -struct failing_value_codec { - /** Bytes. */ - static constexpr output_kind output = output_kind::bytes; - /** The value is secret. */ - static constexpr bool secret = true; - - /** Two bytes. */ - static std::size_t encoded_size(secret_operation::secret_values_t const& /*format*/, - Failing const& /*held_value*/) noexcept { - return 2; - } - - /** Writes the two bytes, then reports checksum_mismatch. */ - static result encode(secret_operation::secret_values_t const& /*format*/, - Failing const& held_value, - std::span output_bytes) noexcept { - output_bytes[0] = static_cast(held_value.value >> 8U); - output_bytes[1] = static_cast(held_value.value & 0xffU); - return error::checksum_mismatch; - } -}; - /** The failing secret value codec with no stated bound. */ template <> struct value_codec - : failing_value_codec {}; + : secret_operation::failing_value_codec {}; /** The failing secret value codec with a stated bound. */ template <> struct value_codec - : failing_value_codec { + : secret_operation::failing_value_codec { /** Two bytes, always. */ static constexpr std::size_t max_encoded_size = 2; }; diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 1f94f2b..499a6ff 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -76,7 +76,7 @@ class throwing_allocator { A move is a copy: the source keeps the shared count and stays equal to what it was, as the allocator requirements ask; the implicit move would leave it with none. */ - // NOLINTNEXTLINE(performance-move-constructor-init): the copy is the intent, as above + // NOLINTNEXTLINE(cert-oop11-cpp,performance-move-constructor-init): the copy is the intent throwing_allocator(throwing_allocator&& other) noexcept : state_(other.state_) {} /** A copy shares the count. */ @@ -219,7 +219,7 @@ class wipe_checking_allocator { A move is a copy: the source keeps the shared count and stays equal to what it was, as the allocator requirements ask; the implicit move would leave it with none. */ - // NOLINTNEXTLINE(performance-move-constructor-init): the copy is the intent, as above + // NOLINTNEXTLINE(cert-oop11-cpp,performance-move-constructor-init): the copy is the intent wipe_checking_allocator(wipe_checking_allocator&& other) noexcept : state_(other.state_) {} /** A copy shares the count. */ diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 318da2b..e708f85 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -39,6 +39,7 @@ namespace test = webcpp::codecs::test; namespace tokens = webcpp::codecs::tokens; namespace timing { +namespace { /** A secret type of the test's own: 32 bytes of a constant size, a byte input. */ class key32 { @@ -71,8 +72,9 @@ inline constexpr probe_format_t probe_format{}; /** Whether DIT read set in the last encode of a dit_probe. */ // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record -inline bool dit_while_encoding = false; +bool dit_while_encoding = false; +} // namespace } // namespace timing namespace webcpp::codecs { @@ -152,7 +154,6 @@ void a_secret_operation_enters_one_guard() { [&] { BOOST_TEST(codecs::encode(test::letters, key).has_value()); }); expect_no_guard([&] { BOOST_TEST(codecs::encode(test::letters, public_bytes).has_value()); }); // Every form of a secret operation, each through one guard of the function that runs it. - std::string const text_value(64, 'a'); secure::secret<32> const secret_key; expect_one_guard("webcpp::codecs::encode", [&] { BOOST_TEST(codecs::encode(test::letters, secret_key).has_value()); }); @@ -179,6 +180,11 @@ void a_secret_operation_enters_one_guard() { }); expect_one_guard("encoded_size", [&] { BOOST_TEST_EQ(codecs::encoded_size(test::letters, key), 64U); }); +} + +void a_secret_decode_enters_one_guard() { + std::string const text_value(64, 'a'); + std::array const public_bytes{}; expect_one_guard("webcpp::codecs::decode", [&] { BOOST_TEST(codecs::decode>(test::letters, text_value).has_value()); }); @@ -220,6 +226,7 @@ void dit_is_set_while_a_secret_encodes() { int main() { timing::a_secret_operation_enters_one_guard(); + timing::a_secret_decode_enters_one_guard(); timing::dit_is_set_while_a_secret_encodes(); return boost::report_errors(); } From a715dba23b50ec85941e889517744731c32307ac Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 12:54:05 -0300 Subject: [PATCH 029/157] codecs: secret operations lint fix, no fluent chains, the DIT check run on every target --- test/allocator_test.cpp | 3 ++- test/secret_operation_test.cpp | 5 +++-- test/timing_test.cpp | 21 ++++++++++++++------- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 5dbc63b..3af56da 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -257,7 +257,8 @@ void the_secret_token_over_an_arena() { std::is_same_v const>); BOOST_TEST(encoded.value().view() == text_value); BOOST_TEST(arena.owns(encoded.value().data())); - BOOST_TEST(encoded.value().get_allocator().resource() == &arena); + auto const& encoded_secret = encoded.value(); + BOOST_TEST(encoded_secret.get_allocator().resource() == &arena); }); BOOST_TEST_EQ(arena.allocation_count(), 1U); BOOST_TEST_EQ(arena.deallocation_count(), 1U); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index a2c4ba9..fa89c99 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -395,8 +395,9 @@ void secures_secret_is_secret() { test::clear_wipes(); auto const decoded = codecs::decode>(test::letters, encoded.value().view()); BOOST_TEST(decoded.has_value()); - BOOST_TEST(std::ranges::equal(decoded.value().bytes(), key_bytes())); - BOOST_TEST(wiped_elsewhere(decoded.value().bytes().data(), 32)); + auto const& decoded_secret = decoded.value(); + BOOST_TEST(std::ranges::equal(decoded_secret.bytes(), key_bytes())); + BOOST_TEST(wiped_elsewhere(decoded_secret.bytes().data(), 32)); // The errors reach the caller. BOOST_TEST(codecs::decode>(test::letters, "abq").error() == codecs::error::invalid_character); diff --git a/test/timing_test.cpp b/test/timing_test.cpp index e708f85..371969e 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -206,19 +206,26 @@ void a_secret_decode_enters_one_guard() { }); } -void dit_is_set_while_a_secret_encodes() { +/** Whether the guard acts here (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT. */ +bool dit_applies() { #ifdef WEBCPP_SECURE_TIMING_COVERED - if (!secure::cpu_has_dit()) { - return; - } + return secure::cpu_has_dit(); +#else + return false; +#endif +} + +void dit_is_set_while_a_secret_encodes() { + // DIT reads set inside a secret encode where the guard acts and the CPU has DIT, and clear + // after it; elsewhere it never reads set. + bool const applies = dit_applies(); test::force_dit(false); BOOST_TEST(!secure::dit_is_set()); - dit_while_encoding = false; + dit_while_encoding = !applies; auto const encoded = codecs::encode(probe_format, dit_probe{.value = 7}); BOOST_TEST(encoded.has_value()); - BOOST_TEST(dit_while_encoding); + BOOST_TEST_EQ(dit_while_encoding, applies); BOOST_TEST(!secure::dit_is_set()); -#endif } } // namespace From 3881bb358032a00f685f0b930ea99c2953113a6e Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 13:21:22 -0300 Subject: [PATCH 030/157] codecs: a codec's overload that takes secret_tag first and returns another type stops the build instead of passing to the public arithmetic, a message case; secret_operation_v's Token is void for none --- include/webcpp/codecs/detail/core/secrecy.hpp | 72 +++++++++++++++-- test/messages/Jamfile | 1 + test/messages/refused_secret_overload/Jamfile | 16 ++++ .../refused_secret_overload.cpp | 80 +++++++++++++++++++ 4 files changed, 163 insertions(+), 6 deletions(-) create mode 100644 test/messages/refused_secret_overload/Jamfile create mode 100644 test/messages/refused_secret_overload/refused_secret_overload.cpp diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 489bebc..38613db 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -175,7 +175,8 @@ constexpr bool token_is_secret() noexcept { @tparam Format The format's type. @tparam Value The value's type. - @tparam Token The token's type, as it was passed; `tokens::automatic` for none. + @tparam Token The token's type, as it was passed; `void` for none (the forms without a token, + and `automatic`, which gives their result). */ template inline constexpr bool secret_operation_v = @@ -185,14 +186,43 @@ inline constexpr bool secret_operation_v = The tag a format's codec takes first in the overloads of its functions whose arithmetic differs when the operation is secret (ruling R7): base58's, whose public arithmetic exits early. The core calls such an overload of `encoded_size`, `decoded_size`, `encode` or `decode` in a secret - operation when it exists, and the format's function of D3 otherwise. + operation when it exists, and the format's function of D3 otherwise; an overload that returns + another type than the function without the tag stops the build. */ struct secret_tag { /** Constructed by name only, so that `{}` never stands for it. */ explicit secret_tag() = default; }; -/** Whether `codec` has an `encoded_size` that takes `secret_tag` first. */ +/** Whether `codec` has an `encoded_size` that takes `secret_tag` first, of any result. */ +template +concept takes_secret_encoded_size = + requires(F const& format_value, std::span input_view) { + codec::encoded_size(secret_tag{}, format_value, input_view); + }; + +/** Whether `codec` has a `decoded_size` that takes `secret_tag` first, of any result. */ +template +concept takes_secret_decoded_size = + requires(F const& format_value, std::string_view text_characters) { + codec::decoded_size(secret_tag{}, format_value, text_characters); + }; + +/** Whether `codec` has an `encode` that takes `secret_tag` first, of any result. */ +template +concept takes_secret_encode = requires( + F const& format_value, std::span input_view, std::span output_span) { + codec::encode(secret_tag{}, format_value, input_view, output_span); +}; + +/** Whether `codec` has a `decode` that takes `secret_tag` first, of any result. */ +template +concept takes_secret_decode = requires(F const& format_value, std::string_view text_characters, + std::span output_span) { + codec::decode(secret_tag{}, format_value, text_characters, output_span); +}; + +/** Whether `codec` has an `encoded_size` that takes `secret_tag` first and gives a size. */ template concept has_secret_encoded_size = requires(F const& format_value, std::span input_view) { @@ -201,7 +231,7 @@ concept has_secret_encoded_size = } -> std::same_as; }; -/** Whether `codec` has a `decoded_size` that takes `secret_tag` first. */ +/** Whether `codec` has a `decoded_size` that takes `secret_tag` first and gives a result. */ template concept has_secret_decoded_size = requires(F const& format_value, std::string_view text_characters) { @@ -210,7 +240,7 @@ concept has_secret_decoded_size = } -> std::same_as>; }; -/** Whether `codec` has an `encode` that takes `secret_tag` first. */ +/** Whether `codec` has an `encode` that takes `secret_tag` first and gives a result. */ template concept has_secret_encode = requires( F const& format_value, std::span input_view, std::span output_span) { @@ -219,7 +249,7 @@ concept has_secret_encode = requires( } -> std::same_as>; }; -/** Whether `codec` has a `decode` that takes `secret_tag` first. */ +/** Whether `codec` has a `decode` that takes `secret_tag` first and gives a result. */ template concept has_secret_decode = requires(F const& format_value, std::string_view text_characters, std::span output_span) { @@ -228,6 +258,32 @@ concept has_secret_decode = requires(F const& format_value, std::string_view tex } -> std::same_as>; }; +/** + Whether every overload of `codec` that takes `secret_tag` first returns what the function of + its name without the tag returns (D3): the requirement of the check below. +*/ +template +inline constexpr bool secret_overloads_match = + (!takes_secret_encoded_size || has_secret_encoded_size) && + (!takes_secret_decoded_size || has_secret_decoded_size) && + (!takes_secret_encode || has_secret_encode) && + (!takes_secret_decode || has_secret_decode); + +/** + Stops the build when an overload of `codec` that takes `secret_tag` first returns another type + than the function without the tag: such an overload would otherwise be passed over, and a secret + operation would run the public arithmetic in silence (R7). +*/ +template +constexpr void check_secret_overloads() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::secret_overloads_match, + "webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or " + "decode that takes detail::secret_tag first returns what the function without it " + "returns: std::size_t for encoded_size, webcpp::codecs::result for " + "the others"); +} + /** The exact size of the text of `input_view`: the format's secret arithmetic in a secret operation when it has one (R7), its `encoded_size` otherwise. @@ -235,6 +291,7 @@ concept has_secret_decode = requires(F const& format_value, std::string_view tex template [[nodiscard]] constexpr std::size_t codec_encoded_size( F const& format_value, std::span input_view) noexcept { + check_secret_overloads(); if constexpr (Secret && has_secret_encoded_size) { return codec::encoded_size(secret_tag{}, format_value, input_view); } else { @@ -249,6 +306,7 @@ template template [[nodiscard]] constexpr result codec_decoded_size( F const& format_value, std::string_view text_characters) noexcept { + check_secret_overloads(); if constexpr (Secret && has_secret_decoded_size) { return codec::decoded_size(secret_tag{}, format_value, text_characters); } else { @@ -264,6 +322,7 @@ template [[nodiscard]] constexpr result codec_encode(F const& format_value, std::span input_view, std::span output_span) noexcept { + check_secret_overloads(); if constexpr (Secret && has_secret_encode) { return codec::encode(secret_tag{}, format_value, input_view, output_span); } else { @@ -279,6 +338,7 @@ template [[nodiscard]] constexpr result codec_decode( F const& format_value, std::string_view text_characters, std::span output_span) noexcept { + check_secret_overloads(); if constexpr (Secret && has_secret_decode) { return codec::decode(secret_tag{}, format_value, text_characters, output_span); } else { diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 06334dc..0914a33 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -20,3 +20,4 @@ build-project refused_encode_only ; build-project refused_input ; build-project refused_token ; build-project refused_allocator ; +build-project refused_secret_overload ; diff --git a/test/messages/refused_secret_overload/Jamfile b/test/messages/refused_secret_overload/Jamfile new file mode 100644 index 0000000..53c0f9e --- /dev/null +++ b/test/messages/refused_secret_overload/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_secret_overload : refused_secret_overload.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_secret_overload_refused : refused_secret_overload.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_secret_overload/refused_secret_overload.cpp b/test/messages/refused_secret_overload/refused_secret_overload.cpp new file mode 100644 index 0000000..1728b2e --- /dev/null +++ b/test/messages/refused_secret_overload/refused_secret_overload.cpp @@ -0,0 +1,80 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A format whose codec offers an overload that takes detail::secret_tag first (ruling R7) but +// returns another type than the function without the tag (here encode's, a std::size_t for a +// result) stops the build in the core's check, whose requirement names the format's +// type: a secret operation never falls back to the public arithmetic in silence. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::secret_overloads_match': webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or decode that takes detail::secret_tag first returns what the function without it returns: std::size_t for encoded_size, webcpp::codecs::result for the others}} +// clang-format on + +#include "../../support/letters.hpp" + +#include +#include + +#include +#include +#include +#include + +/** A format of letters whose secret encode returns a std::size_t. */ +struct mismatched_t { + /** The format's name. */ + static constexpr std::string_view name = "mismatched"; +}; + +namespace webcpp::codecs { + +/** letters' codec, with a secret encode of the wrong return type. */ +template <> +struct codec : codec { + /** letters' size of the text. */ + static std::size_t encoded_size(mismatched_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::letters, input_bytes); + } + + /** letters' size of the bytes. */ + static result decoded_size(mismatched_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::letters, text_characters); + } + + /** letters' encode. */ + static result encode(mismatched_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::letters, input_bytes, output_characters); + } + + /** letters' decode. */ + static result decode(mismatched_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::letters, text_characters, output_bytes); + } + + /** The secret encode, of the wrong return type. */ + static std::size_t encode(detail::secret_tag /*secret*/, mismatched_t const& /*format*/, + std::span /*input_bytes*/, + std::span /*output_characters*/) noexcept { + return 0; + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + webcpp::secure::secret<2> const key; + auto const encoded = codecs::encode(mismatched_t{}, key); + return encoded.has_value() ? 0 : 1; +} From 0ff7376dfd14d29d428c06ffcffd6a56db6a74a0 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 13:21:22 -0300 Subject: [PATCH 031/157] codecs: every token the core makes wipes what the caller does not get in a secret operation; assign_to's scratch in place up to 4096 elements, copied into the target, which keeps its buffer, and given back at once; a program's own secret token tested both ways; guards named exactly --- .../webcpp/codecs/detail/core/operations.hpp | 76 +++-- include/webcpp/codecs/detail/core/tokens.hpp | 310 ++++++++++++++---- test/allocation_test.cpp | 67 ++++ test/allocator_test.cpp | 10 +- test/allocator_throw_test.cpp | 58 +++- test/secret_operation_test.cpp | 175 +++++++++- test/support/secret_tokens.hpp | 69 ++++ test/timing_test.cpp | 42 ++- 8 files changed, 700 insertions(+), 107 deletions(-) create mode 100644 test/support/secret_tokens.hpp diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 7b34fda..abf9f04 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -447,10 +447,11 @@ template Encodes into `token_object`, a concrete token (B6): the checks of the input, then the token's `capacity` against the exact size, then one `prepare` with that size, the format's `encode` into what it returned (its secret arithmetic when `Secret` and it has one, R7), and one `result`. A - token is untouched when a check fails. When the conversion itself fails after `prepare` (a value + token is untouched when a check fails. When the conversion itself fails after `prepare` (a value codec's own error), a token of codecs' that appends is put back as it was and one that assigns has written into its scratch alone; a token of a program's own is left as `prepare` made it. A - token of codecs' is cut to the count the format wrote. + token of codecs' is cut to the count the format wrote, and in a secret operation wipes what it + takes back. */ template [[nodiscard]] result encode_to( @@ -553,8 +554,8 @@ template `token_object`, the token of `assign_to`, through a scratch in place of `Bound` elements, wiped when `Secret`; the container gets the result only on success, by one copy. */ -template -[[nodiscard]] result assign_in_place(assigning_token& token_object, +template +[[nodiscard]] result assign_in_place(assigning_token& token_object, Convert convert) { in_place_scratch scratch; auto const written = convert(scratch); @@ -565,17 +566,25 @@ template return token_object.assign(written.unsafe_value()); } +/** + Whether an operation into `assign_to` whose bound is `Bound` converts into a scratch in place: a + bound known at compile time and at most `in_place_scratch_limit`. +*/ +template +inline constexpr bool assigns_in_place = + Bound != std::dynamic_extent && Bound <= in_place_scratch_limit; + /** Encodes into `token`, as it was passed, a token or a tag of `codecs::tokens` the core turns into - one (B6), under the guard of the public function that calls it; `assign_to` of a static bound - through a scratch in place. + one (B6), under the guard of the public function that calls it; `assign_to` of a static bound of + at most `in_place_scratch_limit` through a scratch in place. */ template [[nodiscard]] auto encode_into(F const& format_value, Input const& input_value, Token& token) { - auto&& concrete_token = detail::concrete_token()>(token); + auto&& concrete_token = detail::concrete_token(), Secret>(token); constexpr std::size_t bound = static_encoded_bound(); if constexpr (is_assigning_token> && - bound != std::dynamic_extent) { + assigns_in_place) { return assign_in_place(concrete_token, [&](auto& scratch) { return encode_to(format_value, input_value, scratch); }); @@ -587,14 +596,14 @@ template /** Decodes into `token`, as it was passed, a byte token or a tag of `codecs::tokens` the core turns into one (B6), under the guard of the public function that calls it; `assign_to` of a text of a - static size through a scratch in place. + static size whose bound is at most `in_place_scratch_limit` through a scratch in place. */ template [[nodiscard]] auto decode_into(F const& format_value, Text const& text_value, Token& token) { - auto&& concrete_token = detail::concrete_token(token); + auto&& concrete_token = detail::concrete_token(token); constexpr std::size_t bound = static_decoded_bound(); if constexpr (is_assigning_token> && - bound != std::dynamic_extent) { + assigns_in_place) { return assign_in_place(concrete_token, [&](auto& scratch) { return decode_to(format_value, text_value, scratch); }); @@ -627,7 +636,8 @@ constexpr bool encode_token_is_noexcept() noexcept { } else if constexpr (is_secret_tag) { return is_fixed_result>; } else { - return token_is_noexcept(), Token>>; + return token_is_noexcept(), + secret_operation_v, Token>>; } } @@ -640,7 +650,8 @@ constexpr bool decode_token_is_noexcept() noexcept { } else if constexpr (is_secret_tag) { return is_fixed_result>; } else { - return token_is_noexcept>; + return token_is_noexcept< + concrete_token_t, Token>>; } } @@ -787,20 +798,22 @@ template input (an input whose encoding does not fit in `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one - `result`. A token is untouched when a check fails, and a token of codecs' also when the + `result`. A token is untouched when a check fails, and a token of codecs' also when the conversion fails after `prepare` (an error of a value codec's own): `append_to` is put back as it - was, and `assign_to` converts into a scratch (in place when the bound is known at compile time, - else of the container's allocator, wiped of what the container does not get) and assigns only on - success; a token of a program's own is left as `prepare` made it. A token of codecs' holds what - the format wrote. The - forms that allocate are not `noexcept` (an allocator's exception propagates, owner decision 24); - `fixed` is, and `secret` when its result is in place. The operation is secret (D10) when the - input's `is_secret_v`, the value codec's `secret` or the token's `secret` says so: it then holds - secure's timing guard and runs the format's secret arithmetic where it has one, and the result is - the token's (a secret input into `return_string` gives a `std::string`, as the caller asked). A - pair that is not @ref encodable stops the build with a message that the format does not convert - this type, and a token that does not take the pair's encoding (`append_to` of a vector, which is - for decode) with one that names the token's type. + was, and `assign_to` converts into a scratch (in place when the bound is known at compile time + and at most 4096 elements, else of the container's allocator) and copies it into the container + only on success; a token of a program's own is left as `prepare` made it. A token of codecs' + holds what the format wrote. The forms that allocate are not `noexcept` (an allocator's exception + propagates, owner decision 24); `fixed` is, and `secret` when its result is in place. The + operation is secret (D10) when the input's `is_secret_v`, the value codec's `secret` or the + token's `secret` says so: it then holds secure's timing guard and runs the format's secret + arithmetic where it has one, and the result is the token's (a secret input into `return_string` + gives a `std::string`, as the caller asked); a token of codecs' then wipes, by + `secure::erase_secret`, what the caller does not get (what it wrote when the conversion fails, + the tail it cuts, its own copy, `assign_to`'s scratch). A pair that is not @ref encodable stops + the build with a message that the format does not convert this type, and a token that does not + take the pair's encoding (`append_to` of a vector, which is for decode) with one that names the + token's type. @tparam F The format's type. @tparam Input The input's type: a byte input, or a value of a value codec. @@ -831,12 +844,13 @@ template } } else { constexpr bool to_bytes = detail::encodes_to_bytes(); - using concrete_type = detail::concrete_token_t; + constexpr bool secret = detail::secret_operation_v; + using concrete_type = detail::concrete_token_t; if constexpr (!(detail::value_encodable ? detail::byte_token : detail::text_token)) { detail::refuse_token(); return result{std::string{}}; - } else if constexpr (detail::secret_operation_v) { + } else if constexpr (secret) { secure::timing_guard const timing_scope{true}; return detail::encode_into(format_value, input_value, token); } else { @@ -859,7 +873,7 @@ template `std::size_t` is @ref error::input_too_long, the whole text is checked and its data error with the lowest value of @ref error returned, then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A - token is untouched when a check fails, and a token of codecs' also when the conversion fails after + token is untouched when a check fails, and a token of codecs' also when the conversion fails after `prepare` (see `encode`). The forms that allocate are not `noexcept`; `fixed` is, and `secret` when its result is in place. A decode is secret (D10) through its token alone (`secret`, or a token whose `secret` is true): it then holds secure's timing guard and runs the format's secret @@ -895,7 +909,9 @@ template return detail::decode_as( format_value, text_value, typename result_type::allocator_type(token.allocator)); } - } else if constexpr (!detail::byte_token>) { + } else if constexpr (!detail::byte_token, + Token>>) { detail::refuse_token(); return result>{std::vector{}}; } else if constexpr (detail::secret_operation_v) { diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index d447dd5..d6a2e1a 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -171,8 +172,18 @@ struct fixed { namespace detail { -/** A token that appends the result to a string or a vector; its result is the container. */ -template +/** + A token that appends the result to a string or a vector; its result is the container. + + `append_to` gives the token of a public operation; in a secret one the core converts through + `wiping()`, whose token wipes, by `secure::erase_secret`, the elements it takes back from the + container: all those appended when the conversion fails, the tail past the written count on + success. + + @tparam Container The string or the vector. + @tparam Wiped Whether the operation is secret. +*/ +template class appending_token { public: /** The container, by reference, as Boost.URL's `append_to` gives it. */ @@ -181,6 +192,11 @@ class appending_token { /** Constructs a token that appends to `target`, which outlives it. */ explicit appending_token(Container& target) noexcept : target_(&target) {} + /** The token of a secret operation that appends to the same container. */ + [[nodiscard]] appending_token wiping() const noexcept { + return appending_token{*target_}; + } + /** Grows the container by `size` elements and returns a pointer to the new ones. */ [[nodiscard]] auto* prepare(std::size_t size) { old_size_ = target_->size(); @@ -188,34 +204,56 @@ class appending_token { return target_->data() + old_size_; } - /** Cuts the container to the `written` elements appended. */ - void shrink_to(std::size_t written) { target_->resize(old_size_ + written); } + /** Cuts the container to the `written` elements appended, the cut ones wiped when `Wiped`. */ + void shrink_to(std::size_t written) { cut_to(old_size_ + written); } - /** Puts the container back as it was before `prepare`. */ - void abandon() { target_->resize(old_size_); } + /** + Puts the container back as it was before `prepare`, the elements appended wiped when + `Wiped`. + */ + void abandon() { cut_to(old_size_); } /** The container. */ [[nodiscard]] result_type result() noexcept { return *target_; } private: + /** Cuts the container to `kept` elements, wiping the others first when `Wiped`. */ + void cut_to(std::size_t kept) { + if constexpr (Wiped) { + secure::erase_secret(std::span{*target_}.subspan(kept)); + } + target_->resize(kept); + } + Container* target_; std::size_t old_size_ = 0; }; +/** + The most elements of a scratch in place of an operation into `assign_to`: past it, or when the + bound is not known at compile time, the scratch is a container of the target's allocator (the + owner's ruling). +*/ +inline constexpr std::size_t in_place_scratch_limit = 4096; + /** A token that replaces the content of a string or a vector with the result, and leaves it as it was when the operation fails (the owner's ruling): the conversion writes into a scratch, and the - container gets the result only on success. + container gets the result only on success, by one copy. Through the token contract, the scratch is a container of the target's own type and allocator, - which `prepare` allocates (an allocation that throws leaves the target untouched) and `result` - swaps with the target, so that its buffer becomes the target's and nothing is copied. When the - bound is known at compile time the core converts into a scratch in place instead and gives the - result to `assign`, one copy. The scratch's elements that are not given to the target (all of - them on a failure, those past the written count on success) are wiped by - `secure::erase_secret` before they go: the token cannot tell a secret operation from a public one. + which `prepare` allocates (an allocation that throws leaves the target untouched); `result` + copies it into the target, which keeps its buffer when it holds the result, and gives the + scratch back at once. When the bound is known at compile time and at most + `in_place_scratch_limit` elements, the core converts into a scratch in place instead and gives + the result to `assign`. `assign_to` gives the token of a public operation; in a secret one the + core converts through `wiping()`, whose token wipes the scratch, by `secure::erase_secret`, + before it gives it back, also when an allocation throws. + + @tparam Container The string or the vector. + @tparam Wiped Whether the operation is secret. */ -template +template class assigning_token { public: /** The container, by reference, as Boost.URL's `assign_to` gives it. */ @@ -227,6 +265,23 @@ class assigning_token { /** Constructs a token that assigns to `target`, which outlives it. */ explicit assigning_token(Container& target) noexcept : target_(&target) {} + /** A copy of a token: of one not prepared yet, the use the core makes of it. */ + assigning_token(assigning_token const&) = default; + /** A copy of a token: of one not prepared yet, the use the core makes of it. */ + assigning_token& operator=(assigning_token const&) = default; + /** A move of a token. */ + assigning_token(assigning_token&&) noexcept = default; + /** A move of a token. */ + assigning_token& operator=(assigning_token&&) noexcept = default; + + /** Gives the scratch back, wiped when `Wiped`, if the operation did not. */ + ~assigning_token() { release_scratch(); } + + /** The token of a secret operation that assigns to the same container. */ + [[nodiscard]] assigning_token wiping() const noexcept { + return assigning_token{*target_}; + } + /** Makes a scratch of `size` elements, of the target's allocator, and returns them; the target is untouched. @@ -237,53 +292,73 @@ class assigning_token { return scratch_->data(); } - /** Cuts the scratch to the `written` elements, the others wiped. */ + /** Cuts the scratch to the `written` elements, the others wiped when `Wiped`. */ void shrink_to(std::size_t written) { - secure::erase_secret( - std::span{scratch_->data() + written, scratch_->size() - written}); + if constexpr (Wiped) { + secure::erase_secret(std::span{*scratch_}.subspan(written)); + } scratch_->resize(written); } - /** Wipes the scratch and gives it back: the target keeps its content. */ - void abandon() noexcept { - secure::erase_secret(*scratch_); - scratch_.reset(); - } + /** Gives the scratch back, wiped when `Wiped`: the target keeps its content. */ + void abandon() noexcept { release_scratch(); } - /** Gives the scratch's buffer to the target, whose old one goes with the scratch. */ + /** + Copies the scratch into the target and gives it back, wiped when `Wiped`; when the copy's + allocation throws, the target is as it was. + */ [[nodiscard]] result_type result() { - target_->swap(*scratch_); + assign(std::span{*scratch_}); + release_scratch(); return *target_; } /** - Replaces the content of the target with `written`, a scratch the core held in place, or - leaves it as it was when the allocation this needs throws: in the target's own buffer when it - holds them, else in a new container of its allocator, swapped in. + Replaces the content of the target with `written`, or leaves it as it was when the allocation + this needs throws: in the target's own buffer when it holds them, else in a new container of + its allocator, swapped in. @param written The elements of the result. @return The target. */ result_type assign(std::span written) { + // Through pointers, which every standard library copies directly: an iterator of another + // type may be copied through a temporary container first (libc++ does so for a checked + // iterator), an unwiped copy of a secret. + element_type const* const first = written.data(); + element_type const* const last = first + written.size(); if (written.size() <= target_->capacity()) { - target_->assign(written.begin(), written.end()); + target_->assign(first, last); } else { Container fresh(target_->get_allocator()); - fresh.assign(written.begin(), written.end()); + fresh.assign(first, last); target_->swap(fresh); } return *target_; } private: + /** Wipes the scratch's whole buffer when `Wiped` and gives it back, if there is one. */ + void release_scratch() noexcept { + if constexpr (Wiped) { + if (scratch_) { + // Within the capacity: no allocation, and every element a part of the container. + scratch_->resize(scratch_->capacity()); + secure::erase_secret(*scratch_); + } + } + scratch_.reset(); + } + Container* target_; std::optional scratch_; }; /** The scratch in place of an operation into `assign_to` whose bound, `N`, is known at compile - time: a token of `N` elements whose result is the elements written, wiped when it goes when - `Wiped`, a secret operation's. + time and at most `in_place_scratch_limit`: a token of `N` elements whose result is the elements + written, wiped when it goes when `Wiped`, a secret operation's. Its elements are not zeroed when + it is made: the conversion writes those it prepares before they are read. @tparam Element `char` or `std::uint8_t`. @tparam N The most elements. @@ -331,7 +406,8 @@ class in_place_scratch { [[nodiscard]] result_type result() const noexcept { return {elements_.data(), written_}; } private: - std::array elements_{}; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read + std::array elements_; std::size_t prepared_ = 0; std::size_t written_ = 0; }; @@ -341,11 +417,32 @@ template inline constexpr bool is_assigning_token = false; /** The token of `assign_to`. */ +template +inline constexpr bool is_assigning_token> = true; + +/** Whether `T` is the token of `append_to` or `assign_to` of a public operation. */ +template +inline constexpr bool is_public_container_token = false; + +/** The token of `append_to` of a public operation. */ +template +inline constexpr bool is_public_container_token> = true; + +/** The token of `assign_to` of a public operation. */ template -inline constexpr bool is_assigning_token> = true; +inline constexpr bool is_public_container_token> = true; -/** A token that gives a string of its own, made with the allocator it was constructed with. */ -template +/** + A token that gives a string of its own, made with the allocator it was constructed with. + + In a secret operation (`Wiped`) it wipes, by `secure::erase_secret`, what the caller does not get: + the characters written when the conversion fails, the tail past the written count, and what its + string still holds when it goes (a short string's characters stay in a moved-from one). + + @tparam String The string. + @tparam Wiped Whether the operation is secret. +*/ +template class returning_token { public: /** The string. */ @@ -355,14 +452,44 @@ class returning_token { explicit returning_token(String::allocator_type const& allocator_value) noexcept : value_(allocator_value) {} + /** Not copyable: the string is the operation's. */ + returning_token(returning_token const&) = delete; + /** Not copyable: the string is the operation's. */ + returning_token& operator=(returning_token const&) = delete; + /** Not movable: the token is the operation's. */ + returning_token(returning_token&&) = delete; + /** Not movable: the token is the operation's. */ + returning_token& operator=(returning_token&&) = delete; + + /** Wipes the whole buffer of the string, when `Wiped`. */ + ~returning_token() { + if constexpr (Wiped) { + // Within the capacity: no allocation, and every character a part of the string. + value_.resize(value_.capacity()); + secure::erase_secret(value_); + } + } + /** Resizes the string to `size` characters and returns a pointer to them. */ [[nodiscard]] char* prepare(std::size_t size) { value_.resize(size); return value_.data(); } - /** Cuts the string to the `written` characters. */ - void shrink_to(std::size_t written) { value_.resize(written); } + /** Cuts the string to the `written` characters, the others wiped when `Wiped`. */ + void shrink_to(std::size_t written) { + if constexpr (Wiped) { + secure::erase_secret(std::span{value_}.subspan(written)); + } + value_.resize(written); + } + + /** Wipes the characters written, when `Wiped`: the caller gets none of them. */ + void abandon() noexcept { + if constexpr (Wiped) { + secure::erase_secret(value_); + } + } /** The string, moved out. */ [[nodiscard]] result_type result() noexcept { return std::move(value_); } @@ -371,8 +498,17 @@ class returning_token { String value_; }; -/** A token that gives `text` or `bytes`: the elements in place, nothing allocated. */ -template +/** + A token that gives `text` or `bytes`: the elements in place, nothing allocated. + + The elements past the written count are zero, as the result's own are. In a secret operation + (`Wiped`) it wipes, by `secure::erase_secret`, the elements written when the conversion fails, the + tail past the written count, and its own copy of the result when it goes. + + @tparam Fixed `text` or `bytes`. + @tparam Wiped Whether the operation is secret. +*/ +template class fixed_token { public: /** The fixed result. */ @@ -381,20 +517,59 @@ class fixed_token { /** The most elements. */ static constexpr std::size_t capacity = Fixed::capacity(); + /** A token of no elements. */ + fixed_token() noexcept = default; + + /** Not copyable: the elements are the operation's. */ + fixed_token(fixed_token const&) = delete; + /** Not copyable: the elements are the operation's. */ + fixed_token& operator=(fixed_token const&) = delete; + /** Not movable: the token is the operation's. */ + fixed_token(fixed_token&&) = delete; + /** Not movable: the token is the operation's. */ + fixed_token& operator=(fixed_token&&) = delete; + + /** Wipes the elements it holds, when `Wiped`. */ + ~fixed_token() { + if constexpr (Wiped) { + secure::erase_secret(fixed_access::writable(value_).first(held_)); + } + } + /** Sets the size and returns a pointer to the elements, which the core made sure fit. */ [[nodiscard]] auto* prepare(std::size_t size) noexcept { + held_ = size; fixed_access::resize(value_, size); return fixed_access::writable(value_).data(); } - /** Sets the size to the `written` elements. */ - void shrink_to(std::size_t written) noexcept { fixed_access::resize(value_, written); } + /** Sets the size to the `written` elements, the others zeroed (wiped when `Wiped`). */ + void shrink_to(std::size_t written) noexcept { + auto const cut = fixed_access::writable(value_).subspan(written, held_ - written); + if constexpr (Wiped) { + secure::erase_secret(cut); + } else { + std::ranges::fill(cut, 0); + } + held_ = written; + fixed_access::resize(value_, written); + } + + /** Wipes the elements written, when `Wiped`: the caller gets none of them. */ + void abandon() noexcept { + if constexpr (Wiped) { + secure::erase_secret(fixed_access::writable(value_).first(held_)); + } + held_ = 0; + fixed_access::resize(value_, 0); + } /** The fixed result. */ [[nodiscard]] result_type result() noexcept { return value_; } private: Fixed value_{}; + std::size_t held_ = 0; }; /** Whether `T` is a `return_string_t`. */ @@ -433,35 +608,52 @@ concept token_argument = /** The concrete token of a `return_string`: the string made with the tag's allocator, rebound to - `char`. + `char`, which wipes what the caller does not get when `Secret`. */ -template +template [[nodiscard]] auto concrete_token(tokens::return_string_t const& tag_value) { using string_allocator = std::allocator_traits::template rebind_alloc; using string_type = std::basic_string, string_allocator>; - return returning_token{string_allocator{tag_value.allocator}}; + return returning_token{string_allocator{tag_value.allocator}}; } -/** The concrete token of `fixed`: `text` for text, `bytes` for bytes. */ -template -[[nodiscard]] constexpr auto concrete_token(tokens::fixed const& /*tag_value*/) noexcept { +/** + The concrete token of `fixed`: `text` for text, `bytes` for bytes, which wipes what the + caller does not get when `Secret`. +*/ +template +[[nodiscard]] auto concrete_token(tokens::fixed const& /*tag_value*/) noexcept { if constexpr (Bytes) { - return fixed_token>{}; + return fixed_token, Secret>{}; } else { - return fixed_token>{}; + return fixed_token, Secret>{}; } } +/** + The token of `append_to` or `assign_to` in a secret operation: the one of the same container that + wipes what the container does not get. +*/ +template + requires(Secret && is_public_container_token) +[[nodiscard]] auto concrete_token(Token& token_object) noexcept { + return token_object.wiping(); +} + /** A token that is one already: used as given. */ -template - requires(byte_token && !token_tag) +template + requires(byte_token && !token_tag && + !(Secret && is_public_container_token)) [[nodiscard]] constexpr Token& concrete_token(Token& token_object) noexcept { return token_object; } -/** The type of the concrete token of `Token`, the argument of the operation as it was passed. */ -template -using concrete_token_t = std::remove_cvref_t( +/** + The type of the concrete token of `Token`, the argument of the operation as it was passed, in an + operation that is secret when `Secret`. +*/ +template +using concrete_token_t = std::remove_cvref_t( std::declval&>()))>; /** Whether using `Token`, a concrete token, cannot throw: its `prepare` and `result` do not. */ @@ -479,7 +671,8 @@ namespace tokens { The string's own allocator is used. The operation returns `target` by reference, as Boost.URL's does; the bytes of a decode are appended as characters. The input must not be a part of - `target`. + `target`. In a secret operation the characters the string does not keep (all those appended when + the operation fails) are wiped before it is cut. @tparam Traits The string's character traits. @tparam Allocator The string's allocator. @@ -513,9 +706,10 @@ template The string's own allocator is used. The operation returns `target` by reference, and leaves it as it was when it fails, also after the conversion began (a value codec's own error) and when an allocation throws: the conversion writes into a scratch, in place when the bound is known at - compile time and of the string's allocator otherwise, and the string gets the result only on - success, so that the input may be a part of `target`. The scratch's bytes that the string does - not get are wiped. + compile time and at most 4096 characters, else of the string's allocator (one allocation), and the + string gets the result only on success, by one copy, so that the input may be a part of + `target`. The string keeps its buffer when it holds the result. In a secret operation the scratch + is wiped before it is given back. @tparam Traits The string's character traits. @tparam Allocator The string's allocator. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index a7cce85..82b2b87 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -390,6 +390,72 @@ void check_secret_operations() { BOOST_TEST(verdict); } +/** Runs `body` and returns how many times operator new was called in it. */ +template +std::size_t allocations_of(Body body) { + std::size_t const before = test::counted_new.load(); + body(); + return test::counted_new.load() - before; +} + +/** assign_to (the owner's ruling): a scratch in place when the bound is known at compile time and + at most 4096 elements, else a scratch of the target's allocator, one allocation; the result is + copied into the target, which keeps its buffer when it holds the result. */ +void check_assign_to_scratch() { + std::array const at_the_limit{}; // 4096 letters + std::array const past_the_limit{}; // 4098 letters + std::vector const heap_input(100); // a size known at run time + std::array at_the_limit_text{}; // 4096 bytes + std::array past_the_limit_text{}; // 4097 bytes + at_the_limit_text.fill('a'); + past_the_limit_text.fill('a'); + std::string text_target; + text_target.reserve(8192); + char const* const text_buffer = text_target.data(); + std::vector byte_target; + byte_target.reserve(8192); + std::uint8_t const* const byte_buffer = byte_target.data(); + bool volatile verdict = false; + expect_no_allocation("assign_to of a static bound of 4096, in place", [&] { + verdict = + codecs::encode(test::letters, at_the_limit, codecs::tokens::assign_to(text_target)) + .has_value() && + codecs::decode(test::letters, at_the_limit_text, codecs::tokens::assign_to(byte_target)) + .has_value(); + }); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 4096U); + BOOST_TEST_EQ(byte_target.size(), 4096U); + // Past it, and of a size known at run time: one allocation each, the heap scratch. + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::encode(test::letters, past_the_limit, + codecs::tokens::assign_to(text_target)) + .has_value(); + }), + 1U); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 4098U); + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::decode(test::letters, past_the_limit_text, + codecs::tokens::assign_to(byte_target)) + .has_value(); + }), + 1U); + BOOST_TEST(verdict); + BOOST_TEST_EQ(byte_target.size(), 4097U); + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::encode(test::letters, heap_input, + codecs::tokens::assign_to(text_target)) + .has_value(); + }), + 1U); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 200U); + // Each time the target kept its buffer. + BOOST_TEST(text_target.data() == text_buffer); + BOOST_TEST(byte_target.data() == byte_buffer); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -437,6 +503,7 @@ int main() { check_fixed_tokens(); check_secret_results(); check_secret_operations(); + check_assign_to_scratch(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 3af56da..8b452e7 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -132,8 +132,16 @@ void assign_to_a_pmr_vector() { }); BOOST_TEST_EQ(target.size(), input.size()); BOOST_TEST(std::equal(input.begin(), input.end(), target.begin())); - BOOST_TEST_EQ(arena.allocation_count(), 1U); + // The scratch (a text of a size known at run time), then the vector's own buffer, which it + // lacked: the scratch is copied into the vector and given back. + BOOST_TEST_EQ(arena.allocation_count(), 2U); BOOST_TEST(arena.owns(target.data())); + // A vector that holds the result keeps its buffer: the scratch alone is allocated. + std::uint8_t const* const kept_buffer = target.data(); + std::size_t const before_kept = arena.allocation_count(); + BOOST_TEST(codecs::decode(test::letters, text_value, tokens::assign_to(target)).has_value()); + BOOST_TEST_EQ(arena.allocation_count(), before_kept + 1); + BOOST_TEST(target.data() == kept_buffer); // The same for append_to. std::pmr::vector appended{&arena}; std::size_t const before = arena.allocation_count(); diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index 8b86b4f..c69a9db 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -11,13 +11,14 @@ // (the MSVC STL's debug proxy, allocated in noexcept constructors) is neither counted nor failed by // throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). A secret heap // type whose allocation throws keeps its value, and every buffer it gives back reads zero; so does -// every buffer of a secret operation through tokens::secret(allocator). Later tasks add their -// rows. +// every buffer of a secret operation through tokens::secret(allocator), and assign_to's scratch +// of a secret operation. Later tasks add their rows. #include "support/allocators.hpp" #include "support/letters.hpp" #include +#include #include @@ -316,8 +317,10 @@ void a_secret_move_between_unequal_allocators_keeps_both() { } void the_secret_token_throws_through() { - // A secret encode through tokens::secret(allocator): the allocator's exception reaches the - // caller, and every buffer the operation had allocated was given back zero. + // A secret encode through tokens::secret(allocator), then a clone of its result: two + // allocations, so that the second fails after the first gave a buffer that held the secret + // text. The allocator's exception reaches the caller, and every buffer allocated before it was + // given back zero. std::vector const held_bytes(input_size, 0x5a); // the heap: not a static size std::string const expected = codecs::encode(test::letters, held_bytes, tokens::return_string).value(); @@ -329,6 +332,8 @@ void the_secret_token_throws_through() { auto const encoded = codecs::encode(test::letters, held_bytes, tokens::secret(allocator)); BOOST_TEST(encoded.value().view() == expected); + auto const copy = encoded.value().clone(); + BOOST_TEST(copy.view() == expected); } catch (std::bad_alloc const&) { thrown = true; } @@ -338,10 +343,14 @@ void the_secret_token_throws_through() { BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); break; } + // From the second on, a buffer of the secret text was allocated before the throw. + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at - 1); ++attempts; } - BOOST_TEST_EQ(attempts, 1U); - // The same for a decode, and a typed decode into a secret vector of the allocator. + BOOST_TEST_EQ(attempts, 2U); + // The same for a decode, and a typed decode into a secret vector of the allocator: the second + // allocation fails after the decode's buffer held the secret bytes. + attempts = 0; for (std::size_t fail_at = 1;; ++fail_at) { test::throwing_allocator const allocator{fail_at}; bool thrown = false; @@ -354,11 +363,47 @@ void the_secret_token_throws_through() { thrown = true; } BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); if (!thrown) { BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); break; } + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at - 1); + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); +} + +void a_secret_assign_to_wipes_its_scratch_when_the_target_throws() { + // A secret input whose encoding (4200 letters) is past the bound of a scratch in place: + // assign_to's scratch comes from the string's allocator (the first allocation), and the copy + // into a string too short for it allocates the second. When the second throws, the string holds + // what it held and the scratch, which held the secret text, was given back zero. + webcpp::secure::secret<2100> key; + std::ranges::fill(key.writable(), std::uint8_t{0x5a}); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST(codecs::encode(test::letters, key, tokens::assign_to(target)).has_value()); + BOOST_TEST_EQ(target.size(), 4200U); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, "kept")); + } + // Read before the string, which holds the text when the operation succeeded, goes. + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at == 1 ? 0U : 1U); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; } + BOOST_TEST_EQ(attempts, 2U); } } // namespace @@ -373,5 +418,6 @@ int main() { a_secret_growth_keeps_its_bytes(); a_secret_move_between_unequal_allocators_keeps_both(); the_secret_token_throws_through(); + a_secret_assign_to_wipes_its_scratch_when_the_target_throws(); return boost::report_errors(); } diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index fa89c99..f90a0fe 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -10,13 +10,19 @@ // temporary of the core, as secure's wipe seam (support/wipe_recorder.hpp) records it. The fixed // secret forms allocate nothing, as support/counting.hpp's operator new sees. The spec's scenarios // "A secret type encodes to a wiped text", "secure's secret is secret" and "A secret result type -// is secret", here on the format letters (Task 13 adds hex's). +// is secret", here on the format letters (Task 13 adds hex's). A token of the program's own whose +// secret is true makes the operation secret and keeps its result type; every token the core makes +// (return_string's, fixed's, and append_to's and assign_to's in a secret operation) wipes what +// it wrote and does not give, on a failure and in the tail a shrink cuts. #include "support/wipe_recorder.hpp" #include "support/counting.hpp" +#include "support/be16.hpp" #include "support/letters.hpp" +#include "support/secret_tokens.hpp" +#include "support/shrinking.hpp" #include "support/tagged_letters.hpp" #include @@ -101,6 +107,12 @@ struct bounded_secret_failing_number { std::uint16_t value; }; +/** A secret value whose value codec of text writes its characters and then fails. */ +struct secret_failing_word { + /** The characters. */ + std::string characters; +}; + /** A value of a secret value codec of text with no stated bound. */ struct secret_word { /** The characters. */ @@ -245,6 +257,31 @@ struct value_codec +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + /** The value is secret. */ + static constexpr bool secret = true; + + /** The characters. */ + static std::size_t encoded_size( + secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_failing_word const& held_value) noexcept { + return held_value.characters.size(); + } + + /** Writes the characters, then reports checksum_mismatch. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_failing_word const& held_value, + std::span output_characters) noexcept { + std::ranges::copy(held_value.characters, output_characters.begin()); + return error::checksum_mismatch; + } +}; + } // namespace webcpp::codecs namespace secret_operation { @@ -276,6 +313,20 @@ static_assert(secret_operation_v, toke static_assert( !secret_operation_v, tokens::return_string_t<>>); +// A token of the program's own whose secret is true makes the operation secret, its result the +// token's own. +static_assert(secret_operation_v, + test::secret_text_token&>); +static_assert(secret_operation_v); +static_assert(std::is_same_v>(), + std::declval())), + codecs::result>); +static_assert(std::is_same_v())), + codecs::result>>); + // tokens::secret: a tag of both directions, also callable with an allocator, that it keeps. static_assert(tokens::secret_t<>::secret); static_assert(std::is_same_v const>); @@ -373,6 +424,11 @@ bool wiped_elsewhere(void const* kept, std::size_t size) { return false; } +/** Whether a wipe of `size` bytes, all zero, was recorded. */ +bool wiped_of_size(std::size_t size) { + return wiped_elsewhere(nullptr, size); +} + void a_secret_type_encodes_to_a_wiped_text() { key32 const key = make_key32(); void const* storage = nullptr; @@ -418,6 +474,7 @@ void a_libraries_secret_type_has_its_temporary_wiped() { test::clear_wipes(); BOOST_TEST(codecs::decode(test::letters, "abab").error() == codecs::error::invalid_length); + BOOST_TEST(wiped_of_size(32)); } void a_secret_result_type_is_secret() { @@ -482,11 +539,6 @@ void a_secret_value_codec() { BOOST_TEST(run_text.value().view() == "abpp"); } -/** Whether a wipe of `size` bytes, all zero, was recorded. */ -bool wiped_of_size(std::size_t size) { - return wiped_elsewhere(nullptr, size); -} - void a_failed_secret_operation_into_assign_to() { // The value codec writes its two secret bytes and then fails: assign_to's target keeps what it // held, and the scratch that held the bytes was wiped, from the target's allocator and in @@ -513,6 +565,115 @@ void a_failed_secret_operation_into_assign_to() { BOOST_TEST(wiped_of_size(64)); } +void a_programs_own_secret_token_makes_the_operation_secret() { + // The spec's tokens requirement: a token's static constexpr bool secret makes the operation + // secret. Each direction runs tagged_letters' secret overloads and gives the token's result. + std::array const public_bytes = key_bytes(); + std::string const text_value = key_text(); + test::tagged_calls.reset(); + test::secret_text_token text_token; + auto const encoded = codecs::encode(test::tagged_letters, public_bytes, text_token); + BOOST_TEST(encoded.value() == text_value); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + test::tagged_calls.reset(); + test::secret_byte_token byte_token; + auto const decoded = + codecs::decode(test::tagged_letters, std::string_view{text_value}, byte_token); + BOOST_TEST(std::ranges::equal(decoded.value(), public_bytes)); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + // Passed as rvalues, the same; a text of a static size too. + test::tagged_calls.reset(); + BOOST_TEST( + codecs::encode(test::tagged_letters, public_bytes, test::secret_text_token{}).has_value()); + auto const fixed_text = codecs::encode(test::letters, public_bytes); + BOOST_TEST(codecs::decode(test::tagged_letters, fixed_text.value(), test::secret_byte_token{}) + .has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 4U); +} + +/** A secure::secret<2> of 0x01 and 0xff, whose letters are "abpp". */ +secure::secret<2> make_short_secret() { + secure::secret<2> made; + made.writable()[0] = 0x01; + made.writable()[1] = 0xff; + return made; +} + +void the_core_tokens_wipe_what_they_do_not_give() { + // A secret value codec of text writes its characters and then fails: the token of + // return_string, of fixed and of append_to wipes what it wrote. + secret_failing_word const failing{.characters = "xy"}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::return_string).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(wiped_of_size(2)); + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::fixed<8>{}).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(wiped_of_size(2)); + std::string appended = "kept"; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::append_to(appended)).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(appended == "kept"); + BOOST_TEST(wiped_of_size(2)); + std::vector appended_bytes{9}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, secret_failing_number{0x1234}, + tokens::append_to(appended_bytes)) + .error() == codecs::error::checksum_mismatch); + BOOST_TEST((appended_bytes == std::vector{9})); + BOOST_TEST(wiped_of_size(2)); + // shrinking asks for one character more than it writes: a secret operation's shrink wipes the + // tail it cuts. + secure::secret<2> const secret_input = make_short_secret(); + test::clear_wipes(); + auto const returned = codecs::encode(test::shrinking, secret_input, tokens::return_string); + BOOST_TEST(returned.value() == "abpp"); + BOOST_TEST(wiped_of_size(1)); + test::clear_wipes(); + auto const fixed_text = codecs::encode(test::shrinking, secret_input, tokens::fixed<8>{}); + BOOST_TEST(fixed_text.value().view() == "abpp"); + BOOST_TEST(wiped_of_size(1)); + // The fixed token's own copy of the text is wiped once the result has it. + BOOST_TEST(wiped_of_size(4)); + appended = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::shrinking, secret_input, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "keptabpp"); + BOOST_TEST(wiped_of_size(1)); + std::string assigned = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::shrinking, secret_input, tokens::assign_to(assigned)).has_value()); + BOOST_TEST(assigned == "abpp"); + BOOST_TEST(wiped_of_size(5)); + // A public operation wipes nothing, through each token, whether it fails or shrinks. + std::array const public_input{0x01, 0xff}; + std::vector public_bytes{9}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(test::shrinking, public_input, tokens::return_string).has_value()); + BOOST_TEST(codecs::encode(test::shrinking, public_input, tokens::fixed<8>{}).has_value()); + BOOST_TEST( + codecs::encode(test::shrinking, public_input, tokens::append_to(appended)).has_value()); + BOOST_TEST( + codecs::encode(test::shrinking, public_input, tokens::assign_to(assigned)).has_value()); + BOOST_TEST( + !codecs::encode(test::be16, test::failing_number{1}, tokens::return_string).has_value()); + BOOST_TEST( + !codecs::encode(test::be16, test::failing_number{1}, tokens::fixed<8>{}).has_value()); + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::append_to(public_bytes)) + .has_value()); + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::assign_to(public_bytes)) + .has_value()); + BOOST_TEST_EQ(test::wipes.count, 0U); +} + void the_secret_arithmetic_runs_in_a_secret_operation_alone() { // A public operation runs the format's public arithmetic. test::tagged_calls.reset(); @@ -606,6 +767,8 @@ int main() { secret_operation::the_secret_token_both_ways(); secret_operation::a_secret_value_codec(); secret_operation::a_failed_secret_operation_into_assign_to(); + secret_operation::a_programs_own_secret_token_makes_the_operation_secret(); + secret_operation::the_core_tokens_wipe_what_they_do_not_give(); secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); secret_operation::the_fixed_secret_forms_allocate_nothing(); return boost::report_errors(); diff --git a/test/support/secret_tokens.hpp b/test/support/secret_tokens.hpp new file mode 100644 index 0000000..08c8a51 --- /dev/null +++ b/test/support/secret_tokens.hpp @@ -0,0 +1,69 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Tokens of a program's own whose static constexpr bool secret is true: the spec's tokens +// requirement says that such a token makes the operation secret (D10), and its result stays the +// token's own. secret_text_token takes the text of an encode as a std::string, secret_byte_token +// the bytes of a decode as a std::vector. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_SECRET_TOKENS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_SECRET_TOKENS_HPP + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A text token of a program's own that makes the operation secret. */ +class secret_text_token { +public: + /** The text, as a string. */ + using result_type = std::string; + + /** The operation is secret. */ + static constexpr bool secret = true; + + /** Makes room for `size` characters. */ + [[nodiscard]] char* prepare(std::size_t size) { + held_.resize(size); + return held_.data(); + } + + /** The text. */ + [[nodiscard]] result_type result() { return std::move(held_); } + +private: + std::string held_; +}; + +/** A byte token of a program's own that makes the operation secret. */ +class secret_byte_token { +public: + /** The bytes, as a vector. */ + using result_type = std::vector; + + /** The operation is secret. */ + static constexpr bool secret = true; + + /** Makes room for `size` bytes. */ + [[nodiscard]] std::uint8_t* prepare(std::size_t size) { + held_.resize(size); + return held_.data(); + } + + /** The bytes. */ + [[nodiscard]] result_type result() { return std::move(held_); } + +private: + std::vector held_; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_SECRET_TOKENS_HPP diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 371969e..37d1905 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -6,8 +6,9 @@ // The timing guard of a secret operation (D10, D12, B11): secure's seam, recorded by // support/timing_seam.hpp, counts one engaged guard of codecs' for each secret operation, held by -// the core's public function that runs it, and none for a public operation (the spec's scenario "A -// secret operation sets DIT through secure", here on the format letters; Task 13 adds hex's). +// the core's function that runs it, named exactly, and none for a public operation (the spec's +// scenario "A secret operation sets DIT through secure", here on the format letters; Task 13 adds +// hex's). A token of the program's own whose secret is true makes its operation secret. // Where the guard acts (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, a value codec of the // test's own reads DIT set while it encodes a secret, and clear after. @@ -16,6 +17,7 @@ #include "support/timing_dit.hpp" #include "support/letters.hpp" +#include "support/secret_tokens.hpp" #include #include @@ -114,10 +116,27 @@ struct value_codec { namespace timing { namespace { -/** Whether the first guard since the last reset is held by `function`, as the compiler names it. */ +/** + Whether the first guard since the last reset is held by `function`, a qualified name, as the + compiler spells it: the name whole, after a space or at the start, and before its parameters or + template arguments (so that `webcpp::codecs::encode` is not `webcpp::codecs::encoded_size`). +*/ bool first_guard_in(std::string_view function) { - return test::timing_first_entry != nullptr && - std::string_view{test::timing_first_entry}.find(function) != std::string_view::npos; + if (test::timing_first_entry == nullptr) { + return false; + } + std::string_view const spelled{test::timing_first_entry}; + for (std::size_t at = spelled.find(function); at != std::string_view::npos; + at = spelled.find(function, at + 1)) { + std::size_t const after = at + function.size(); + bool const starts = at == 0 || spelled[at - 1] == ' '; + bool const ends = + after < spelled.size() && (spelled[after] == '(' || spelled[after] == '<'); + if (starts && ends) { + return true; + } + } + return false; } /** Forgets the guards entered so far. */ @@ -178,8 +197,14 @@ void a_secret_operation_enters_one_guard() { std::array buffer{}; BOOST_TEST(codecs::encode(probe_format, dit_probe{}, std::span{buffer}).has_value()); }); - expect_one_guard("encoded_size", + // encoded_size is constexpr, which a guard cannot be: its guard is in the helper it calls. + expect_one_guard("webcpp::codecs::detail::secret_encoded_size", [&] { BOOST_TEST_EQ(codecs::encoded_size(test::letters, key), 64U); }); + // A text token of the program's own whose secret is true. + expect_one_guard("webcpp::codecs::encode", [&] { + BOOST_TEST( + codecs::encode(test::letters, public_bytes, test::secret_text_token{}).has_value()); + }); } void a_secret_decode_enters_one_guard() { @@ -191,6 +216,11 @@ void a_secret_decode_enters_one_guard() { expect_one_guard("webcpp::codecs::decode", [&] { BOOST_TEST(codecs::decode(test::letters, text_value, tokens::secret).has_value()); }); + // A byte token of the program's own whose secret is true. + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST( + codecs::decode(test::letters, text_value, test::secret_byte_token{}).has_value()); + }); expect_one_guard("webcpp::codecs::decode", [&] { BOOST_TEST(codecs::decode( test::letters, text_value, std::pmr::polymorphic_allocator{}) From 518e8d3ff3291aaa49124e286dc941a14f138e91 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 13:25:55 -0300 Subject: [PATCH 032/157] codecs: secret operations fix round lint fix, the in-place bound by one comparison, the no-throw resizes and the unzeroed scratch stated, the wipe test in three --- include/webcpp/codecs/detail/core/operations.hpp | 6 +++--- include/webcpp/codecs/detail/core/tokens.hpp | 6 ++++-- test/secret_operation_test.cpp | 14 ++++++++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index abf9f04..0b7c474 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -568,11 +568,11 @@ template -inline constexpr bool assigns_in_place = - Bound != std::dynamic_extent && Bound <= in_place_scratch_limit; +inline constexpr bool assigns_in_place = Bound <= in_place_scratch_limit; /** Encodes into `token`, as it was passed, a token or a tag of `codecs::tokens` the core turns into diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index d6a2e1a..9c1bdab 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -339,6 +339,7 @@ class assigning_token { private: /** Wipes the scratch's whole buffer when `Wiped` and gives it back, if there is one. */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize within the capacity cannot throw void release_scratch() noexcept { if constexpr (Wiped) { if (scratch_) { @@ -373,7 +374,8 @@ class in_place_scratch { /** The most elements. */ static constexpr std::size_t capacity = N; - /** An empty scratch. */ + /** An empty scratch, its elements not zeroed. */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read in_place_scratch() noexcept = default; /** Not copyable: the elements are the operation's. */ @@ -406,7 +408,6 @@ class in_place_scratch { [[nodiscard]] result_type result() const noexcept { return {elements_.data(), written_}; } private: - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read std::array elements_; std::size_t prepared_ = 0; std::size_t written_ = 0; @@ -462,6 +463,7 @@ class returning_token { returning_token& operator=(returning_token&&) = delete; /** Wipes the whole buffer of the string, when `Wiped`. */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize within the capacity cannot throw ~returning_token() { if constexpr (Wiped) { // Within the capacity: no allocation, and every character a part of the string. diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index f90a0fe..a1bc5c1 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -628,6 +628,9 @@ void the_core_tokens_wipe_what_they_do_not_give() { .error() == codecs::error::checksum_mismatch); BOOST_TEST((appended_bytes == std::vector{9})); BOOST_TEST(wiped_of_size(2)); +} + +void a_secret_shrink_wipes_the_tail() { // shrinking asks for one character more than it writes: a secret operation's shrink wipes the // tail it cuts. secure::secret<2> const secret_input = make_short_secret(); @@ -641,7 +644,7 @@ void the_core_tokens_wipe_what_they_do_not_give() { BOOST_TEST(wiped_of_size(1)); // The fixed token's own copy of the text is wiped once the result has it. BOOST_TEST(wiped_of_size(4)); - appended = "kept"; + std::string appended = "kept"; test::clear_wipes(); BOOST_TEST( codecs::encode(test::shrinking, secret_input, tokens::append_to(appended)).has_value()); @@ -653,8 +656,13 @@ void the_core_tokens_wipe_what_they_do_not_give() { codecs::encode(test::shrinking, secret_input, tokens::assign_to(assigned)).has_value()); BOOST_TEST(assigned == "abpp"); BOOST_TEST(wiped_of_size(5)); - // A public operation wipes nothing, through each token, whether it fails or shrinks. +} + +void a_public_operation_wipes_nothing() { + // Through each token of codecs', whether the conversion fails or shrinks. std::array const public_input{0x01, 0xff}; + std::string appended = "kept"; + std::string assigned = "kept"; std::vector public_bytes{9}; test::clear_wipes(); BOOST_TEST(codecs::encode(test::shrinking, public_input, tokens::return_string).has_value()); @@ -769,6 +777,8 @@ int main() { secret_operation::a_failed_secret_operation_into_assign_to(); secret_operation::a_programs_own_secret_token_makes_the_operation_secret(); secret_operation::the_core_tokens_wipe_what_they_do_not_give(); + secret_operation::a_secret_shrink_wipes_the_tail(); + secret_operation::a_public_operation_wipes_nothing(); secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); secret_operation::the_fixed_secret_forms_allocate_nothing(); return boost::report_errors(); From 4731eb4f801e1dbac99f9604736f980fa5626068 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 13:49:31 -0300 Subject: [PATCH 033/157] codecs: Task 6's review minors: a secret_tag overload whose parameters the core's arguments do not convert to stops the build too, and an assigning token's copy and move take its target alone, never an engaged scratch --- include/webcpp/codecs/detail/core/secrecy.hpp | 64 +++++++++------ include/webcpp/codecs/detail/core/tokens.hpp | 37 +++++++-- test/messages/Jamfile | 1 + .../refused_secret_overload.cpp | 2 +- .../refused_secret_parameters/Jamfile | 16 ++++ .../refused_secret_parameters.cpp | 81 +++++++++++++++++++ test/secret_operation_test.cpp | 32 ++++++++ 7 files changed, 199 insertions(+), 34 deletions(-) create mode 100644 test/messages/refused_secret_parameters/Jamfile create mode 100644 test/messages/refused_secret_parameters/refused_secret_parameters.cpp diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 38613db..c4368bb 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -194,32 +194,44 @@ struct secret_tag { explicit secret_tag() = default; }; -/** Whether `codec` has an `encoded_size` that takes `secret_tag` first, of any result. */ +/** + An argument that converts to any type, which a probe passes where the core's own argument might + not convert to a parameter: unevaluated, never defined. +*/ +struct any_argument { + /** Converts to any type, a reference to `const` included. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // the probe's argument converts to anything + operator T() const noexcept; +}; + +/** + Whether `codec` has an `encoded_size` of the arity of the core's call that takes `secret_tag` + first, of any parameters after it and any result: an overload the core's arguments do not + convert to (a `std::span` input) is found too, so that it cannot be passed over. +*/ template -concept takes_secret_encoded_size = - requires(F const& format_value, std::span input_view) { - codec::encoded_size(secret_tag{}, format_value, input_view); - }; +concept takes_secret_encoded_size = requires(F const& format_value) { + codec::encoded_size(secret_tag{}, format_value, any_argument{}); +}; -/** Whether `codec` has a `decoded_size` that takes `secret_tag` first, of any result. */ +/** Whether `codec` has a `decoded_size` of that arity that takes `secret_tag` first. */ template -concept takes_secret_decoded_size = - requires(F const& format_value, std::string_view text_characters) { - codec::decoded_size(secret_tag{}, format_value, text_characters); - }; +concept takes_secret_decoded_size = requires(F const& format_value) { + codec::decoded_size(secret_tag{}, format_value, any_argument{}); +}; -/** Whether `codec` has an `encode` that takes `secret_tag` first, of any result. */ +/** Whether `codec` has an `encode` of that arity that takes `secret_tag` first. */ template -concept takes_secret_encode = requires( - F const& format_value, std::span input_view, std::span output_span) { - codec::encode(secret_tag{}, format_value, input_view, output_span); +concept takes_secret_encode = requires(F const& format_value) { + codec::encode(secret_tag{}, format_value, any_argument{}, any_argument{}); }; -/** Whether `codec` has a `decode` that takes `secret_tag` first, of any result. */ +/** Whether `codec` has a `decode` of that arity that takes `secret_tag` first. */ template -concept takes_secret_decode = requires(F const& format_value, std::string_view text_characters, - std::span output_span) { - codec::decode(secret_tag{}, format_value, text_characters, output_span); +concept takes_secret_decode = requires(F const& format_value) { + codec::decode(secret_tag{}, format_value, any_argument{}, any_argument{}); }; /** Whether `codec` has an `encoded_size` that takes `secret_tag` first and gives a size. */ @@ -259,8 +271,9 @@ concept has_secret_decode = requires(F const& format_value, std::string_view tex }; /** - Whether every overload of `codec` that takes `secret_tag` first returns what the function of - its name without the tag returns (D3): the requirement of the check below. + Whether every overload of `codec` that takes `secret_tag` first, whatever its parameters, is + one the core calls and returns what the function of its name without the tag returns (D3): the + requirement of the check below. */ template inline constexpr bool secret_overloads_match = @@ -271,17 +284,18 @@ inline constexpr bool secret_overloads_match = /** Stops the build when an overload of `codec` that takes `secret_tag` first returns another type - than the function without the tag: such an overload would otherwise be passed over, and a secret - operation would run the public arithmetic in silence (R7). + than the function without the tag, or takes parameters the core's arguments do not convert to: + such an overload would otherwise be passed over, and a secret operation would run the public + arithmetic in silence (R7). */ template constexpr void check_secret_overloads() noexcept { // Qualified, so that the compiler's message names the requirement as the core's. static_assert(webcpp::codecs::detail::secret_overloads_match, "webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or " - "decode that takes detail::secret_tag first returns what the function without it " - "returns: std::size_t for encoded_size, webcpp::codecs::result for " - "the others"); + "decode that takes detail::secret_tag first takes the parameters of the function " + "without it and returns what it returns: std::size_t for encoded_size, " + "webcpp::codecs::result for the others"); } /** diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 9c1bdab..290e712 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -265,14 +265,35 @@ class assigning_token { /** Constructs a token that assigns to `target`, which outlives it. */ explicit assigning_token(Container& target) noexcept : target_(&target) {} - /** A copy of a token: of one not prepared yet, the use the core makes of it. */ - assigning_token(assigning_token const&) = default; - /** A copy of a token: of one not prepared yet, the use the core makes of it. */ - assigning_token& operator=(assigning_token const&) = default; - /** A move of a token. */ - assigning_token(assigning_token&&) noexcept = default; - /** A move of a token. */ - assigning_token& operator=(assigning_token&&) noexcept = default; + /** + A copy of a token takes its target alone and has no scratch: the scratch belongs to the + operation that prepared it, and a copy would duplicate an engaged secret one. The core copies + tokens that are not prepared yet. + */ + assigning_token(assigning_token const& other) noexcept : target_(other.target_) {} + + /** + A copy assignment takes the target of `other` and gives this token's own scratch back, + wiped when `Wiped`: it belonged to the old target's operation; `other` keeps its own. + */ + assigning_token& operator=(assigning_token const& other) noexcept { + target_ = other.target_; + release_scratch(); + return *this; + } + + /** + A move takes the target alone, as a copy does: an engaged scratch stays with `other`, which + gives it back when it goes, so that none is dropped or duplicated. + */ + assigning_token(assigning_token&& other) noexcept : target_(other.target_) {} + + /** A move assignment takes the target alone, as the copy assignment does. */ + assigning_token& operator=(assigning_token&& other) noexcept { + target_ = other.target_; + release_scratch(); + return *this; + } /** Gives the scratch back, wiped when `Wiped`, if the operation did not. */ ~assigning_token() { release_scratch(); } diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 0914a33..8827489 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -21,3 +21,4 @@ build-project refused_input ; build-project refused_token ; build-project refused_allocator ; build-project refused_secret_overload ; +build-project refused_secret_parameters ; diff --git a/test/messages/refused_secret_overload/refused_secret_overload.cpp b/test/messages/refused_secret_overload/refused_secret_overload.cpp index 1728b2e..4f5dad7 100644 --- a/test/messages/refused_secret_overload/refused_secret_overload.cpp +++ b/test/messages/refused_secret_overload/refused_secret_overload.cpp @@ -12,7 +12,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::secret_overloads_match': webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or decode that takes detail::secret_tag first returns what the function without it returns: std::size_t for encoded_size, webcpp::codecs::result for the others}} +// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::secret_overloads_match': webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or decode that takes detail::secret_tag first takes the parameters of the function without it and returns what it returns: std::size_t for encoded_size, webcpp::codecs::result for the others}} // clang-format on #include "../../support/letters.hpp" diff --git a/test/messages/refused_secret_parameters/Jamfile b/test/messages/refused_secret_parameters/Jamfile new file mode 100644 index 0000000..6d085e0 --- /dev/null +++ b/test/messages/refused_secret_parameters/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_secret_parameters : refused_secret_parameters.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_secret_parameters_refused : refused_secret_parameters.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_secret_parameters/refused_secret_parameters.cpp b/test/messages/refused_secret_parameters/refused_secret_parameters.cpp new file mode 100644 index 0000000..cd127e9 --- /dev/null +++ b/test/messages/refused_secret_parameters/refused_secret_parameters.cpp @@ -0,0 +1,81 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A format whose codec offers an overload that takes detail::secret_tag first (ruling R7) but +// takes other parameters than the function without the tag (here encode's input, a +// std::span where the core passes a std::span) stops the build +// in the core's check, whose requirement names the format's type: a secret operation never falls +// back to the public arithmetic in silence. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::secret_overloads_match': webcpp::codecs: an overload of a codec's encoded_size, decoded_size, encode or decode that takes detail::secret_tag first takes the parameters of the function without it and returns what it returns: std::size_t for encoded_size, webcpp::codecs::result for the others}} +// clang-format on + +#include "../../support/letters.hpp" + +#include +#include + +#include +#include +#include +#include + +/** A format of letters whose secret encode takes a span of mutable bytes. */ +struct parameters_t { + /** The format's name. */ + static constexpr std::string_view name = "parameters"; +}; + +namespace webcpp::codecs { + +/** letters' codec, with a secret encode of parameters the core's arguments do not convert to. */ +template <> +struct codec : codec { + /** letters' size of the text. */ + static std::size_t encoded_size(parameters_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::letters, input_bytes); + } + + /** letters' size of the bytes. */ + static result decoded_size(parameters_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::letters, text_characters); + } + + /** letters' encode. */ + static result encode(parameters_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::letters, input_bytes, output_characters); + } + + /** letters' decode. */ + static result decode(parameters_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::letters, text_characters, output_bytes); + } + + /** The secret encode, whose input is a span of mutable bytes. */ + static result encode(detail::secret_tag /*secret*/, parameters_t const& /*format*/, + std::span /*input_bytes*/, + std::span /*output_characters*/) noexcept { + return std::size_t{0}; + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + webcpp::secure::secret<2> const key; + auto const encoded = codecs::encode(parameters_t{}, key); + return encoded.has_value() ? 0 : 1; +} diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index a1bc5c1..a405985 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -630,6 +630,37 @@ void the_core_tokens_wipe_what_they_do_not_give() { BOOST_TEST(wiped_of_size(2)); } +void an_assigning_tokens_copy_and_move_take_the_target_alone() { + // A copy or a move of a token whose scratch is engaged takes the target and no scratch: the + // scratch is not duplicated (two wipes of one buffer) nor dropped (none), but given back, + // wiped, once, by the token that prepared it. + using wiping_token = codecs::detail::assigning_token; + static_assert(std::is_nothrow_copy_constructible_v); + static_assert(std::is_nothrow_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + std::string target = "kept"; + wiping_token prepared{target}; + std::fill_n(prepared.prepare(40), 40, 'x'); // past a small string: the heap + test::clear_wipes(); + { + wiping_token const copied{prepared}; + wiping_token copy_assigned{target}; + copy_assigned = prepared; + // NOLINTNEXTLINE(bugprone-use-after-move): the source of a move keeps its scratch, which + // is what the test pins + wiping_token const moved{std::move(prepared)}; + wiping_token move_assigned{target}; + move_assigned = std::move(prepared); + } + BOOST_TEST_EQ(test::wipes.count, 0U); + // The scratch is still the original's: its result is the text it holds, once. + // NOLINTNEXTLINE(bugprone-use-after-move): see above + BOOST_TEST_EQ(prepared.result().size(), 40U); + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(target == std::string(40, 'x')); +} + void a_secret_shrink_wipes_the_tail() { // shrinking asks for one character more than it writes: a secret operation's shrink wipes the // tail it cuts. @@ -777,6 +808,7 @@ int main() { secret_operation::a_failed_secret_operation_into_assign_to(); secret_operation::a_programs_own_secret_token_makes_the_operation_secret(); secret_operation::the_core_tokens_wipe_what_they_do_not_give(); + secret_operation::an_assigning_tokens_copy_and_move_take_the_target_alone(); secret_operation::a_secret_shrink_wipes_the_tail(); secret_operation::a_public_operation_wipes_nothing(); secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); From 69ebea4920913ce8f898719cd23cdc522258e398 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:11:28 -0300 Subject: [PATCH 034/157] codecs: over, a format of two links, its intermediate in place or from its allocator and wiped when secret --- include/webcpp/codecs.hpp | 1 + .../webcpp/codecs/detail/core/contract.hpp | 122 +++ .../webcpp/codecs/detail/core/operations.hpp | 97 +- include/webcpp/codecs/detail/core/over.hpp | 937 ++++++++++++++++++ include/webcpp/codecs/detail/core/secrecy.hpp | 82 +- include/webcpp/codecs/detail/core/sizes.hpp | 90 +- test/Jamfile | 4 + test/allocation_test.cpp | 79 ++ test/allocator_test.cpp | 93 ++ test/allocator_throw_test.cpp | 84 ++ test/noexcept_test.cpp | 67 ++ test/over_test.cpp | 559 +++++++++++ 12 files changed, 2151 insertions(+), 64 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/over.hpp create mode 100644 test/over_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 96701d6..3826305 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index a72ff43..8ff677e 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -419,6 +419,102 @@ constexpr void refuse_allocator() noexcept { "allocator must construct it"); } +/** + The bytes of an input whose size is known at compile time to be at most `Bound` + (@ref static_input_size_v): a view that converts to the `std::span` every codec takes, and a type + a codec that holds an intermediate of that size in place (`over`) reads the bound from. The core + gives a codec this type when the input's type states a bound, and a plain `std::span` otherwise. + It is no range, so that the conversion to a `std::span` is its own, `noexcept`, and not the + span's range constructor, which is not. + + @tparam Bound The most bytes. +*/ +template +class bounded_bytes { +public: + /** The most bytes, known at compile time. */ + static constexpr std::size_t bound = Bound; + + /** Views `input_bytes`, which the caller knows to hold at most `Bound` bytes. */ + explicit constexpr bounded_bytes(std::span input_bytes) noexcept + : view_(input_bytes) {} + + /** The bytes, as the `std::span` a codec takes. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // it is a view of a span + constexpr operator std::span() const noexcept { return view_; } + + /** The number of bytes. */ + [[nodiscard]] constexpr std::size_t size() const noexcept { return view_.size(); } + +private: + std::span view_; +}; + +/** + The characters of a text whose size is known at compile time to be at most `Bound`, as + @ref bounded_bytes is for bytes: a view that converts to the `std::string_view` every codec takes. + + @tparam Bound The most characters. +*/ +template +class bounded_text { +public: + /** The most characters, known at compile time. */ + static constexpr std::size_t bound = Bound; + + /** Views `text_characters`, which the caller knows to hold at most `Bound` characters. */ + explicit constexpr bounded_text(std::string_view text_characters) noexcept + : view_(text_characters) {} + + /** The characters, as the `std::string_view` a codec takes. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): + // it is a view of a string view + constexpr operator std::string_view() const noexcept { return view_; } + + /** The number of characters. */ + [[nodiscard]] constexpr std::size_t size() const noexcept { return view_.size(); } + +private: + std::string_view view_; +}; + +/** The bound a view of bytes or characters states at compile time, else `std::dynamic_extent`. */ +template +inline constexpr std::size_t view_bound_v = std::dynamic_extent; + +/** A @ref bounded_bytes: its bound. */ +template +inline constexpr std::size_t view_bound_v> = Bound; + +/** A @ref bounded_text: its bound. */ +template +inline constexpr std::size_t view_bound_v> = Bound; + +/** Whether `T` is a @ref bounded_bytes. */ +template +inline constexpr bool is_bounded_bytes = false; + +/** A @ref bounded_bytes. */ +template +inline constexpr bool is_bounded_bytes> = true; + +/** Whether `T` is a @ref bounded_text. */ +template +inline constexpr bool is_bounded_text = false; + +/** A @ref bounded_text. */ +template +inline constexpr bool is_bounded_text> = true; + +/** A view of bytes that is a `std::span` or a `bounded_bytes`. */ +template +concept byte_view = std::same_as> || is_bounded_bytes; + +/** A view of characters that is a `std::string_view` or a `bounded_text`. */ +template +concept character_view = std::same_as || is_bounded_text; + /** The characters of a text input; an array of `char` is read up to its first zero and never past its end, as a string literal is read as a `std::string_view` (B5), and another range of `char` @@ -465,6 +561,32 @@ template } } +/** + The view of the bytes of an input a codec is given: a @ref bounded_bytes of the input's bound when + its type states one (@ref static_input_size_v), else a `std::span`. +*/ +template +using input_view_t = + std::conditional_t == std::dynamic_extent, + std::span, bounded_bytes>>; + +/** The view of the characters of a text a codec is given, as @ref input_view_t gives it. */ +template +using text_view_t = std::conditional_t == std::dynamic_extent, + std::string_view, bounded_text>>; + +/** The bytes of a byte input, as the view a codec is given (@ref input_view_t). */ +template +[[nodiscard]] constexpr input_view_t bounded_input_bytes(Input const& input_value) noexcept { + return input_view_t{input_bytes(input_value)}; +} + +/** The characters of a text input, as the view a codec is given (@ref text_view_t). */ +template +[[nodiscard]] constexpr text_view_t bounded_text_view(Text const& text_value) noexcept { + return text_view_t{text_view(text_value)}; +} + } // namespace detail } // namespace webcpp::codecs diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 0b7c474..6d09d8a 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -261,12 +261,13 @@ template template [[nodiscard]] result encode_as( F const& format_value, Input const& input_value, - Allocators const&... allocator_values) noexcept(is_fixed_result) { - std::span const input_view = [&] { + Allocators const&... allocator_values) noexcept(is_fixed_result && + encode_calls_are_noexcept()) { + auto const input_view = [&] { if constexpr (value_encodable) { return std::span{}; } else { - return input_bytes(input_value); + return bounded_input_bytes(input_value); } }(); std::size_t output_size = 0; @@ -323,17 +324,28 @@ inline constexpr bool decode_is_fixed = is_fixed_result || fixed_target || is_byte_array; /** - Whether a typed decode into `Value` in `F` cannot throw: a value codec's decode is `noexcept` as - the value codec declares it, so that an allocating value codec's exception propagates (owner - decision 24); a byte result is when it holds its bytes in place. + Whether a typed decode of `Input` into `Value` in `F` cannot throw: a value codec's decode is + `noexcept` as the value codec declares it for the view it is given, so that an allocating value + codec's exception propagates (owner decision 24); a byte result is when it holds its bytes in + place and the codec's functions are (ruling R3). */ -template +template constexpr bool typed_decode_is_noexcept() noexcept { if constexpr (value_decodable) { - return noexcept(value_codec::decode(std::declval(), - std::declval>())); + using value_type = value_codec; + if constexpr (value_type::output == output_kind::bytes && byte_input) { + return noexcept( + value_type::decode(std::declval(), std::declval>())); + } else if constexpr (value_type::output == output_kind::text && text_input) { + return noexcept( + value_type::decode(std::declval(), std::declval>())); + } else { + return noexcept(value_type::decode(std::declval(), + std::declval>())); + } } else { - return has_codec && decode_is_fixed; + return has_codec && decode_is_fixed && + decode_calls_are_noexcept>(); } } @@ -364,8 +376,9 @@ template template [[nodiscard]] result decode_as( F const& format_value, Text const& text_value, - Allocators const&... allocator_values) noexcept(decode_is_fixed) { - std::string_view const text_characters = text_view(text_value); + Allocators const&... allocator_values) noexcept(decode_is_fixed && + decode_calls_are_noexcept()) { + auto const text_characters = bounded_text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; } @@ -456,13 +469,14 @@ template template [[nodiscard]] result encode_to( F const& format_value, Input const& input_value, - Token& token_object) noexcept(token_is_noexcept) { + Token& token_object) noexcept(token_is_noexcept && + encode_calls_are_noexcept()) { constexpr bool from_value = value_encodable; - std::span const input_view = [&] { + auto const input_view = [&] { if constexpr (from_value) { return std::span{}; } else { - return input_bytes(input_value); + return bounded_input_bytes(input_value); } }(); std::size_t output_size = 0; @@ -516,8 +530,9 @@ template template [[nodiscard]] result decode_to( F const& format_value, Text const& text_value, - Token& token_object) noexcept(token_is_noexcept) { - std::string_view const text_characters = text_view(text_value); + Token& token_object) noexcept(token_is_noexcept && + decode_calls_are_noexcept()) { + auto const text_characters = bounded_text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; } @@ -618,7 +633,8 @@ template */ template [[nodiscard]] result encode_value_into_buffer( - F const& format_value, Input const& input_value, std::span output_buffer) noexcept { + F const& format_value, Input const& input_value, + std::span output_buffer) noexcept(encode_calls_are_noexcept()) { std::size_t const output_size = value_codec::encoded_size(format_value, input_value); if (output_buffer.size() < output_size) { return error::output_too_small; @@ -632,12 +648,15 @@ template constexpr bool encode_token_is_noexcept() noexcept { using tag_type = std::remove_cvref_t; if constexpr (std::same_as) { - return is_fixed_result>; + return is_fixed_result> && + encode_calls_are_noexcept>(); } else if constexpr (is_secret_tag) { - return is_fixed_result>; + return is_fixed_result> && + encode_calls_are_noexcept(); } else { return token_is_noexcept(), - secret_operation_v, Token>>; + secret_operation_v, Token>> && + encode_calls_are_noexcept>(); } } @@ -646,12 +665,15 @@ template constexpr bool decode_token_is_noexcept() noexcept { using tag_type = std::remove_cvref_t; if constexpr (std::same_as) { - return is_fixed_result>; + return is_fixed_result> && + decode_calls_are_noexcept(); } else if constexpr (is_secret_tag) { - return is_fixed_result>; + return is_fixed_result> && + decode_calls_are_noexcept(); } else { return token_is_noexcept< - concrete_token_t, Token>>; + concrete_token_t, Token>> && + decode_calls_are_noexcept>(); } } @@ -681,7 +703,8 @@ constexpr bool decode_token_is_noexcept() noexcept { */ template [[nodiscard]] auto encode(F const& format_value, Input const& input_value) noexcept( - detail::is_fixed_result>) { + detail::is_fixed_result> && + detail::encode_calls_are_noexcept>()) { using result_type = detail::default_encode_result; if constexpr (!encodable) { detail::refuse(); @@ -714,8 +737,10 @@ template template requires(detail::value_encodable && value_codec::output == output_kind::bytes) -[[nodiscard]] result encode(F const& format_value, Input const& input_value, - std::span output_buffer) noexcept { +[[nodiscard]] result encode( + F const& format_value, Input const& input_value, + std::span + output_buffer) noexcept(detail::encode_calls_are_noexcept()) { if constexpr (detail::secret_operation_v) { secure::timing_guard const timing_scope{true}; return detail::encode_value_into_buffer(format_value, input_value, output_buffer); @@ -744,8 +769,9 @@ template template requires(detail::value_encodable && value_codec::output == output_kind::text) -[[nodiscard]] result encode(F const& format_value, Input const& input_value, - std::span output_buffer) noexcept { +[[nodiscard]] result encode( + F const& format_value, Input const& input_value, + std::span output_buffer) noexcept(detail::encode_calls_are_noexcept()) { if constexpr (detail::secret_operation_v) { secure::timing_guard const timing_scope{true}; return detail::encode_value_into_buffer(format_value, input_value, output_buffer); @@ -774,7 +800,8 @@ template */ template [[nodiscard]] auto decode(F const& format_value, Text const& text_value) noexcept( - detail::is_fixed_result>) { + detail::is_fixed_result> && + detail::decode_calls_are_noexcept()) { if constexpr (detail::has_codec) { return detail::decode_as, false>(format_value, text_value); @@ -950,23 +977,23 @@ template */ template [[nodiscard]] result decode(F const& format_value, Input const& input_value) noexcept( - detail::typed_decode_is_noexcept()) { + detail::typed_decode_is_noexcept()) { constexpr bool secret = detail::secret_operation_v; if constexpr (detail::value_decodable) { using value_type = value_codec; if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { if constexpr (secret) { secure::timing_guard const timing_scope{true}; - return value_type::decode(format_value, detail::input_bytes(input_value)); + return value_type::decode(format_value, detail::bounded_input_bytes(input_value)); } else { - return value_type::decode(format_value, detail::input_bytes(input_value)); + return value_type::decode(format_value, detail::bounded_input_bytes(input_value)); } } else if constexpr (value_type::output == output_kind::text && detail::text_input) { if constexpr (secret) { secure::timing_guard const timing_scope{true}; - return value_type::decode(format_value, detail::text_view(input_value)); + return value_type::decode(format_value, detail::bounded_text_view(input_value)); } else { - return value_type::decode(format_value, detail::text_view(input_value)); + return value_type::decode(format_value, detail::bounded_text_view(input_value)); } } else { // The pair converts; this input is not what the value codec reads. diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp new file mode 100644 index 0000000..d7a7dd1 --- /dev/null +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -0,0 +1,937 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The composition of webcpp::codecs (D11): `over`, a format that encodes with its inner link and + then with its outer one, and decodes with the outer link and then the inner one, holding the + bytes between them in an intermediate of its own. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_OVER_HPP +#define WEBCPP_CODECS_DETAIL_CORE_OVER_HPP + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** + The name of the chain of `Outer` over `Inner`, joined in a static array that lives as long as + the program. +*/ +template +struct over_name { + /** The separator between the two names. */ + static constexpr std::string_view separator = " over "; + + /** The characters of the joined name. */ + static constexpr std::size_t size = std::string_view{Outer::name}.size() + separator.size() + + std::string_view{Inner::name}.size(); + + /** The joined name's characters. */ + static constexpr std::array characters = [] { + std::array joined{}; + std::size_t position = 0; + for (std::string_view const part : + {std::string_view{Outer::name}, separator, std::string_view{Inner::name}}) { + for (char const character : part) { + joined[position++] = character; + } + } + return joined; + }(); + + /** The name, which views `characters`. */ + static constexpr std::string_view value{characters.data(), size}; +}; + +} // namespace detail + +/** + The composition of two formats: encoding encodes with `inner` and then encodes that output with + `outer`, decoding decodes with `outer` and then decodes that output with `inner`. + + `Outer` is a format with a `codec` (text feeds it as bytes); `Inner` is a format with a `codec`, + or one a `value_codec` converts a value in. `over` is a format whose `name` is the name of the + outer link, then the characters " over ", then the name of the inner link, and class template + argument deduction builds it from the two links, with or without the allocator as a third + argument. A chain is constant time when both links are, and secret when any link's operation is: + the core runs the links' secret overloads (ruling R7) and the intermediate is wiped by + `secure::erase_secret`, in place or before its allocator gets it back. + + The intermediate, the bytes between the links, is held in place when its bound is known at + compile time, which is when the input's type states its size (`std::array`, `std::span` of a + static extent, `secure::secret`, `text`, `bytes`) or the value codec states + `max_encoded_size`; it is otherwise made with `allocator`, which is used for nothing else, so + that `over` allocates through `std::allocator`. The exact `encoded_size` and + `decoded_size` run the inner link into the intermediate (ruling R3): with a heap intermediate they + allocate, so those, `encode` and `decode` are not `noexcept` and an exception of the allocator + reaches the caller, the buffer forms of the core among them (the one allocating buffer form), + and with a bound known at compile time they are `noexcept` and allocate nothing. `over` stays + one-shot: its stream counterpart is `pipe`. + + @tparam Outer The format that writes the final text and reads it first. + @tparam Inner The format whose bytes the outer link encodes and decodes. + @tparam Allocator The allocator of the heap intermediate. +*/ +template > +struct over { + /** The outer link. */ + Outer outer; + /** The inner link. */ + Inner inner; + /** The allocator of the heap intermediate, used for nothing else. */ + Allocator allocator; + + /** The name: the outer link's, " over ", and the inner link's. */ + static constexpr std::string_view name = detail::over_name::value; + + /** + Makes a chain of the two links and the allocator of its heap intermediate. + + @param outer_link The outer link. + @param inner_link The inner link. + @param allocator_value The allocator of the heap intermediate. + */ + constexpr over(Outer outer_link, Inner inner_link, Allocator allocator_value = Allocator{}) + : outer(std::move(outer_link)), + inner(std::move(inner_link)), + allocator(std::move(allocator_value)) {} + + /** A copy of a chain: the links and the allocator. */ + constexpr over(over const&) = default; + + /** A move of a chain: the links and the allocator. */ + constexpr over(over&&) = default; + + /** + Takes the links and the allocator of `other`. + + An allocator that cannot be assigned, as `std::pmr::polymorphic_allocator`, is made again + from `other`'s: a chain is a value, whatever its allocator, and a format is copyable. + + @param other The chain to copy. + @return This chain. + */ + constexpr over& operator=(over const& other) { + if (this != &other) { + outer = other.outer; + inner = other.inner; + take_allocator(other.allocator); + } + return *this; + } + + /** + Takes the links and the allocator of `other`, as the copy assignment does. + + @param other The chain to take. + @return This chain. + */ + constexpr over& operator=(over&& other) { + if (this != &other) { + outer = std::move(other.outer); + inner = std::move(other.inner); + take_allocator(std::move(other.allocator)); + } + return *this; + } + + /** Destroys the chain. */ + constexpr ~over() = default; + +private: + /** Assigns `source` to the allocator, or makes it again where it has no assignment. */ + template + constexpr void take_allocator(Source&& source) { + if constexpr (std::is_assignable_v) { + allocator = std::forward(source); + } else { + // An allocator's copy and move cannot throw: the chain is never left with none. + std::destroy_at(&allocator); + std::construct_at(&allocator, std::forward(source)); + } + } +}; + +/** + Deduces `over` from the two links. + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. +*/ +template +over(Outer, Inner) -> over; + +/** + Deduces `over` from the two links and the allocator of the heap + intermediate. + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. + @tparam Allocator The allocator's type. +*/ +template +over(Outer, Inner, Allocator) -> over; + +namespace detail { + +/** The most bytes the intermediate of a link's encode holds when its input holds `Bound`. */ +template +[[nodiscard]] constexpr std::size_t encoded_bound() noexcept { + if constexpr (Bound == std::dynamic_extent) { + return std::dynamic_extent; + } else { + // A bound that saturates is SIZE_MAX, which is std::dynamic_extent: no size to hold in + // place. + return codec::max_encoded_size(Bound); + } +} + +/** The most bytes the intermediate of a link's decode holds when its text holds `Bound`. */ +template +[[nodiscard]] constexpr std::size_t decoded_bound() noexcept { + if constexpr (Bound == std::dynamic_extent) { + return std::dynamic_extent; + } else { + return codec::max_decoded_size(Bound); + } +} + +/** + Whether `size` is no size to hold an intermediate of: past `Bound`, a bound known at compile + time, or `SIZE_MAX`, which a link's size says when it does not fit. +*/ +template +[[nodiscard]] constexpr bool past_bound(std::size_t size) noexcept { + if constexpr (Bound == std::dynamic_extent) { + return size == std::numeric_limits::max(); + } else { + return size > Bound; + } +} + +/** The bytes of an intermediate of at most `Bound` bytes, as the view the next link is given. */ +template +using intermediate_bytes = std::conditional_t, bounded_bytes>; + +/** The characters of an intermediate of at most `Bound` characters, as the next link is given. */ +template +using intermediate_text = + std::conditional_t>; + +/** + The intermediate of a chain whose bound is known at compile time: `Bound` bytes in place, wiped + when it goes if `Secret`. Its bytes are not zeroed when it is made: the first link writes those + it asks for before the second reads them. + + @tparam Bound The most bytes. + @tparam Secret Whether the chain is secret. +*/ +template +class in_place_intermediate { +public: + /** + Makes an intermediate of `byte_count` bytes, at most `Bound`; the allocator is not used. + + @param byte_count The bytes the first link writes. + */ + template + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read + in_place_intermediate(std::size_t byte_count, Allocator const& /*allocator*/) noexcept + : size_(byte_count) {} + + /** Not copyable: the bytes are the operation's. */ + in_place_intermediate(in_place_intermediate const&) = delete; + /** Not copyable: the bytes are the operation's. */ + in_place_intermediate& operator=(in_place_intermediate const&) = delete; + /** Not movable: the bytes are the operation's. */ + in_place_intermediate(in_place_intermediate&&) = delete; + /** Not movable: the bytes are the operation's. */ + in_place_intermediate& operator=(in_place_intermediate&&) = delete; + + /** Wipes the bytes, when `Secret`. */ + ~in_place_intermediate() { + if constexpr (Secret) { + secure::erase_secret(bytes()); + } + } + + /** The bytes, which the first link writes. */ + [[nodiscard]] std::span bytes() noexcept { return {elements_.data(), size_}; } + +private: + std::array elements_; + std::size_t size_; +}; + +/** + The intermediate of a chain whose bound is not known at compile time: bytes from the chain's + allocator, wiped before it gets them back if `Secret`, also when an allocation throws. + + @tparam Secret Whether the chain is secret. + @tparam Allocator The chain's allocator. +*/ +template +class heap_intermediate { + using byte_allocator = std::allocator_traits::template rebind_alloc; + using storage_type = std::conditional_t, + std::vector>; + +public: + /** + Makes an intermediate of `byte_count` bytes with `allocator_value`, which may throw what the + allocator throws. + + @param byte_count The bytes the first link writes. + @param allocator_value The allocator. + */ + heap_intermediate(std::size_t byte_count, Allocator const& allocator_value) + : storage_(byte_allocator(allocator_value)), size_(byte_count) { + if constexpr (Secret) { + storage_.resize_for_overwrite(byte_count); + } else { + storage_.resize(byte_count); + } + } + + /** The bytes, which the first link writes. */ + [[nodiscard]] std::span bytes() noexcept { return {storage_.data(), size_}; } + +private: + storage_type storage_; + std::size_t size_; +}; + +/** + The intermediate of a chain: in place when `Bound` is known, else from `Allocator`. + + @tparam Bound The most bytes, or `std::dynamic_extent` when not known at compile time. + @tparam Secret Whether the chain is secret. + @tparam Allocator The chain's allocator. +*/ +template +using over_intermediate = + std::conditional_t, + heap_intermediate>; + +/** + The first `count` bytes of `intermediate`, given to the next link as bytes: a `bounded_bytes` of + `Bound` when it is known. +*/ +template +[[nodiscard]] intermediate_bytes next_bytes(Intermediate& intermediate, + std::size_t count) noexcept { + std::span const written = + intermediate.bytes().first(std::min(count, intermediate.bytes().size())); + return intermediate_bytes{written}; +} + +/** + The first `count` bytes of `intermediate`, given to the next link as characters: a + `bounded_text` of `Bound` when it is known. +*/ +template +[[nodiscard]] intermediate_text next_text(Intermediate& intermediate, + std::size_t count) noexcept { + std::span const written = intermediate.bytes(); + // A byte is read through a char, which may alias any object. + return intermediate_text{std::string_view{reinterpret_cast(written.data()), + std::min(count, written.size())}}; +} + +/** The intermediate's bytes as the characters the first link of an encode writes. */ +template +[[nodiscard]] std::span intermediate_characters(Intermediate& intermediate) noexcept { + std::span const written = intermediate.bytes(); + // A byte is written through a char, which may alias any object. + return {reinterpret_cast(written.data()), written.size()}; +} + +/** + Whether the functions of the links an encode of `View` through `Outer` over `Inner` calls cannot + throw, and the intermediate is in place: `over`'s exact sizes, `encode` and `decode` are `noexcept` + exactly then (ruling R3). +*/ +template +[[nodiscard]] constexpr bool over_encode_is_noexcept() noexcept { + constexpr std::size_t middle_bound = encoded_bound>(); + using middle_view = intermediate_bytes; + return middle_bound != std::dynamic_extent && + codec_encoded_size_is_noexcept() && + codec_encode_is_noexcept() && + codec_encoded_size_is_noexcept() && + codec_encode_is_noexcept(); +} + +/** Whether a decode of `View` through `Outer` over `Inner` cannot throw, as for an encode. */ +template +[[nodiscard]] constexpr bool over_decode_is_noexcept() noexcept { + constexpr std::size_t middle_bound = decoded_bound>(); + using middle_view = intermediate_text; + return middle_bound != std::dynamic_extent && + codec_decoded_size_is_noexcept() && + codec_decode_is_noexcept() && + codec_decoded_size_is_noexcept() && + codec_decode_is_noexcept(); +} + +/** + The exact size of the text `chain` encodes `input_view` to: the inner link runs into the + intermediate (ruling R3), then the outer link sizes what it holds. When the inner link fails, the + outer link's bound on the intermediate's size is returned, so that `encode` finds the error. +*/ +template +[[nodiscard]] std::size_t over_encoded_size( + over const& chain, + View input_view) noexcept(over_encode_is_noexcept()) { + constexpr std::size_t middle_bound = encoded_bound>(); + std::size_t const middle_size = codec_encoded_size(chain.inner, input_view); + if (past_bound(middle_size)) { + // The input is past the bound its type stated, or its encoding does not fit: no size. + return std::numeric_limits::max(); + } + over_intermediate middle{middle_size, chain.allocator}; + result const written = + codec_encode(chain.inner, input_view, intermediate_characters(middle)); + if (!written) { + return codec::max_encoded_size(middle_size); + } + // Read unchecked: the error was returned above. + return codec_encoded_size(chain.outer, + next_bytes(middle, written.unsafe_value())); +} + +/** Writes the text `chain` encodes `input_view` to into `output_span`. */ +template +[[nodiscard]] result over_encode( + over const& chain, View input_view, + std::span output_span) noexcept(over_encode_is_noexcept()) { + constexpr std::size_t middle_bound = encoded_bound>(); + std::size_t const middle_size = codec_encoded_size(chain.inner, input_view); + if (past_bound(middle_size)) { + return error::input_too_long; + } + over_intermediate middle{middle_size, chain.allocator}; + result const written = + codec_encode(chain.inner, input_view, intermediate_characters(middle)); + if (!written) { + return written; + } + // Read unchecked: the error was returned above. + return codec_encode( + chain.outer, next_bytes(middle, written.unsafe_value()), output_span); +} + +/** + The exact size of the bytes `chain` decodes `text_characters` to: the outer link decodes into the + intermediate (ruling R3), then the inner link sizes what it holds; the outer link's error is + reported before the inner link's. +*/ +template +[[nodiscard]] result over_decoded_size( + over const& chain, + View text_characters) noexcept(over_decode_is_noexcept()) { + constexpr std::size_t middle_bound = decoded_bound>(); + result const middle_size = + codec_decoded_size(chain.outer, text_characters); + if (!middle_size) { + return middle_size; + } + // Read unchecked: the error was returned above. + if (past_bound(middle_size.unsafe_value())) { + return error::input_too_long; + } + over_intermediate middle{middle_size.unsafe_value(), + chain.allocator}; + result const written = + codec_decode(chain.outer, text_characters, middle.bytes()); + if (!written) { + return written; + } + return codec_decoded_size(chain.inner, + next_text(middle, written.unsafe_value())); +} + +/** Writes the bytes `chain` decodes `text_characters` to into `output_span`. */ +template +[[nodiscard]] result over_decode( + over const& chain, View text_characters, + std::span + output_span) noexcept(over_decode_is_noexcept()) { + constexpr std::size_t middle_bound = decoded_bound>(); + result const middle_size = + codec_decoded_size(chain.outer, text_characters); + if (!middle_size) { + return middle_size; + } + // Read unchecked: the error was returned above. + if (past_bound(middle_size.unsafe_value())) { + return error::input_too_long; + } + over_intermediate middle{middle_size.unsafe_value(), + chain.allocator}; + result const written = + codec_decode(chain.outer, text_characters, middle.bytes()); + if (!written) { + return written; + } + return codec_decode( + chain.inner, next_text(middle, written.unsafe_value()), output_span); +} + +} // namespace detail + +/** + The codec of `over` when both links have a codec. + + Its bounds compose the links', its functions run the links through the core's dispatchers, and + its overloads that take `detail::secret_tag` first run their secret arithmetic and wipe the + intermediate (ruling R7). They are `noexcept` exactly when the intermediate is in place (ruling + R3), which is when the view of the input or of the text is a `detail::bounded_bytes` or a + `detail::bounded_text`, the core's way to give a codec the bound its input's type states. + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. + @tparam Allocator The allocator's type. +*/ +template + requires(detail::has_codec && detail::has_codec) +struct codec> { + /** The chain's format. */ + using format_type = over; + + /** A chain is constant time when both links are. */ + static constexpr bool constant_time = + codec::constant_time && codec::constant_time; + + /** + The outer link's bound on the inner link's, saturated at `SIZE_MAX`. + + @param input_size The bytes of the input. + @return The bound on the text, `SIZE_MAX` when it does not fit. + */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + std::size_t const middle_size = codec::max_encoded_size(input_size); + return middle_size == std::numeric_limits::max() + ? middle_size + : codec::max_encoded_size(middle_size); + } + + /** + The inner link's bound on the outer link's, saturated at `SIZE_MAX`. + + @param text_size The characters of the text. + @return The bound on the bytes, `SIZE_MAX` when it does not fit. + */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + std::size_t const middle_size = codec::max_decoded_size(text_size); + return middle_size == std::numeric_limits::max() + ? middle_size + : codec::max_decoded_size(middle_size); + } + + /** + The exact size of the text of `input_view`, the inner link run into the intermediate. + + @tparam View A `std::span` of the bytes, or a `detail::bounded_bytes` of them. + @param chain The chain. + @param input_view The bytes. + @return The size, a bound when the inner link fails, so that `encode` finds the error. + */ + template + [[nodiscard]] static std::size_t encoded_size( + format_type const& chain, + View input_view) noexcept(detail::over_encode_is_noexcept()) { + return detail::over_encoded_size(chain, input_view); + } + + /** + The exact size of the text of `input_view`, in a secret operation. + + @tparam View A `std::span` of the bytes, or a `detail::bounded_bytes` of them. + @param chain The chain. + @param input_view The bytes. + @return The size, as the overload without the tag gives it. + */ + template + [[nodiscard]] static std::size_t encoded_size( + detail::secret_tag /*secret*/, format_type const& chain, + View input_view) noexcept(detail::over_encode_is_noexcept()) { + return detail::over_encoded_size(chain, input_view); + } + + /** + The exact size of the bytes of `text_characters`, the whole text checked. + + @tparam View A `std::string_view` of the text, or a `detail::bounded_text` of it. + @param chain The chain. + @param text_characters The text. + @return The size, or the outer link's error, else the inner link's. + */ + template + [[nodiscard]] static result + decoded_size(format_type const& chain, View text_characters) noexcept( + detail::over_decode_is_noexcept()) { + return detail::over_decoded_size(chain, text_characters); + } + + /** + The exact size of the bytes of `text_characters`, in a secret operation. + + @tparam View A `std::string_view` of the text, or a `detail::bounded_text` of it. + @param chain The chain. + @param text_characters The text. + @return The size, or the error, as the overload without the tag gives it. + */ + template + [[nodiscard]] static result decoded_size( + detail::secret_tag /*secret*/, format_type const& chain, + View + text_characters) noexcept(detail::over_decode_is_noexcept()) { + return detail::over_decoded_size(chain, text_characters); + } + + /** + Writes the text of `input_view` into `output_characters`. + + @tparam View A `std::span` of the bytes, or a `detail::bounded_bytes` of them. + @param chain The chain. + @param input_view The bytes. + @param output_characters The buffer the text is written to. + @return The number of characters written, or the error. + */ + template + [[nodiscard]] static result + encode(format_type const& chain, View input_view, std::span output_characters) noexcept( + detail::over_encode_is_noexcept()) { + return detail::over_encode(chain, input_view, output_characters); + } + + /** + Writes the text of `input_view` into `output_characters`, in a secret operation. + + @tparam View A `std::span` of the bytes, or a `detail::bounded_bytes` of them. + @param chain The chain. + @param input_view The bytes. + @param output_characters The buffer the text is written to. + @return The number of characters written, or the error. + */ + template + [[nodiscard]] static result encode( + detail::secret_tag /*secret*/, format_type const& chain, View input_view, + std::span + output_characters) noexcept(detail::over_encode_is_noexcept()) { + return detail::over_encode(chain, input_view, output_characters); + } + + /** + Writes the bytes of `text_characters` into `output_bytes`. + + @tparam View A `std::string_view` of the text, or a `detail::bounded_text` of it. + @param chain The chain. + @param text_characters The text. + @param output_bytes The buffer the bytes are written to. + @return The number of bytes written, or the error. + */ + template + [[nodiscard]] static result decode( + format_type const& chain, View text_characters, + std::span + output_bytes) noexcept(detail::over_decode_is_noexcept()) { + return detail::over_decode(chain, text_characters, output_bytes); + } + + /** + Writes the bytes of `text_characters` into `output_bytes`, in a secret operation. + + @tparam View A `std::string_view` of the text, or a `detail::bounded_text` of it. + @param chain The chain. + @param text_characters The text. + @param output_bytes The buffer the bytes are written to. + @return The number of bytes written, or the error. + */ + template + [[nodiscard]] static result decode( + detail::secret_tag /*secret*/, format_type const& chain, View text_characters, + std::span + output_bytes) noexcept(detail::over_decode_is_noexcept()) { + return detail::over_decode(chain, text_characters, output_bytes); + } +}; + +namespace detail { + +/** Whether `value_codec` is specialized. */ +template +concept inner_value_codec = requires { sizeof(value_codec); }; + +/** The bound `value_codec` states on its encoding, else `std::dynamic_extent`. */ +template +[[nodiscard]] constexpr std::size_t inner_value_bound() noexcept { + if constexpr (requires { + { + value_codec::max_encoded_size + } -> std::convertible_to; + }) { + return value_codec::max_encoded_size; + } else { + return std::dynamic_extent; + } +} + +/** + Whether a chain of values of `Value` over `Inner` is secret: the value is, or its link says so. +*/ +template +inline constexpr bool over_value_is_secret = + is_secret_v || value_codec_is_secret(); + +/** + Whether the functions an encode of a `Value` through `Outer` over the value codec of `Inner` + calls cannot throw and the intermediate is in place. +*/ +template +[[nodiscard]] constexpr bool over_value_encode_is_noexcept() noexcept { + using inner_codec = value_codec; + constexpr std::size_t middle_bound = inner_value_bound(); + using middle_view = intermediate_bytes; + using inner_output = value_output_span; + return middle_bound != std::dynamic_extent && + noexcept(inner_codec::encoded_size(std::declval(), + std::declval())) && + noexcept(inner_codec::encode(std::declval(), std::declval(), + std::declval())) && + codec_encoded_size_is_noexcept() && + codec_encode_is_noexcept(); +} + +/** Whether a decode of `View` into a `Value` through `Outer` over `Inner` cannot throw. */ +template +[[nodiscard]] constexpr bool over_value_decode_is_noexcept() noexcept { + using inner_codec = value_codec; + constexpr std::size_t middle_bound = decoded_bound>(); + using middle_view = + std::conditional_t, intermediate_text>; + return middle_bound != std::dynamic_extent && + codec_decoded_size_is_noexcept() && + codec_decode_is_noexcept() && + noexcept(inner_codec::decode(std::declval(), std::declval())); +} + +/** Runs the value codec of `Inner` into `middle`, as the span its output kind writes. */ +template +[[nodiscard]] result encode_value_into( + Inner const& inner_format, Value const& held_value, + Intermediate& + middle) noexcept(noexcept(value_codec:: + encode(inner_format, held_value, + std::declval>()))) { + if constexpr (value_codec::output == output_kind::bytes) { + return value_codec::encode(inner_format, held_value, middle.bytes()); + } else { + return value_codec::encode(inner_format, held_value, + intermediate_characters(middle)); + } +} + +/** The exact size of the text of `held_value`: its value codec runs into the intermediate (R3). */ +template +[[nodiscard]] std::size_t over_value_encoded_size( + over const& chain, + Value const& + held_value) noexcept(over_value_encode_is_noexcept()) { + constexpr std::size_t middle_bound = inner_value_bound(); + std::size_t const middle_size = + value_codec::encoded_size(chain.inner, held_value); + if (past_bound(middle_size)) { + return std::numeric_limits::max(); + } + over_intermediate middle{middle_size, chain.allocator}; + result const written = encode_value_into(chain.inner, held_value, middle); + if (!written) { + return codec::max_encoded_size(middle_size); + } + // Read unchecked: the error was returned above. + return codec_encoded_size(chain.outer, + next_bytes(middle, written.unsafe_value())); +} + +/** Writes the text of `held_value` into `output_characters`. */ +template +[[nodiscard]] result over_value_encode( + over const& chain, Value const& held_value, + std::span + output_characters) noexcept(over_value_encode_is_noexcept()) { + constexpr std::size_t middle_bound = inner_value_bound(); + std::size_t const middle_size = + value_codec::encoded_size(chain.inner, held_value); + if (past_bound(middle_size)) { + return error::input_too_long; + } + over_intermediate middle{middle_size, chain.allocator}; + result const written = encode_value_into(chain.inner, held_value, middle); + if (!written) { + return written; + } + // Read unchecked: the error was returned above. + return codec_encode( + chain.outer, next_bytes(middle, written.unsafe_value()), output_characters); +} + +/** + The value `chain` decodes `text_characters` to: the outer link into the intermediate, then the + value codec of the inner link. +*/ +template +[[nodiscard]] result +over_value_decode(over const& chain, View text_characters) noexcept( + over_value_decode_is_noexcept()) { + using inner_codec = value_codec; + constexpr std::size_t middle_bound = decoded_bound>(); + result const middle_size = + codec_decoded_size(chain.outer, text_characters); + if (!middle_size) { + return middle_size.error(); + } + // Read unchecked: the error was returned above. + if (past_bound(middle_size.unsafe_value())) { + return error::input_too_long; + } + over_intermediate middle{middle_size.unsafe_value(), + chain.allocator}; + result const written = + codec_decode(chain.outer, text_characters, middle.bytes()); + if (!written) { + return written.error(); + } + if constexpr (inner_codec::output == output_kind::bytes) { + return inner_codec::decode(chain.inner, + next_bytes(middle, written.unsafe_value())); + } else { + return inner_codec::decode(chain.inner, + next_text(middle, written.unsafe_value())); + } +} + +/** The bound a chain of `Value` over `Inner` states on its text, when the inner link states one. */ +template +struct over_value_bound {}; + +/** The chain's bound is the outer link's on the inner link's, when that fits in place. */ +template + requires(inner_value_bound() != std::dynamic_extent && + codec::max_encoded_size(inner_value_bound()) != + std::numeric_limits::max()) +struct over_value_bound { + /** The most characters the text has. */ + static constexpr std::size_t max_encoded_size = + codec::max_encoded_size(inner_value_bound()); +}; + +/** The encoding half of a chain's value codec, which exists when the inner value codec encodes. */ +template +struct over_value_encoding {}; + +/** The inner value codec encodes: the chain's `encoded_size` and `encode`. */ +template + requires value_encodable +struct over_value_encoding { + /** The exact size of the text of `held_value`. */ + [[nodiscard]] static std::size_t + encoded_size(over const& chain, Value const& held_value) noexcept( + over_value_encode_is_noexcept, Outer, Inner, Value>()) { + return over_value_encoded_size>(chain, held_value); + } + + /** Writes the text of `held_value` into `output_characters`. */ + [[nodiscard]] static result encode( + over const& chain, Value const& held_value, + std::span + output_characters) noexcept(over_value_encode_is_noexcept, + Outer, Inner, Value>()) { + return over_value_encode>(chain, held_value, + output_characters); + } +}; + +/** The decoding half of a chain's value codec, which exists when the inner value codec decodes. */ +template +struct over_value_decoding {}; + +/** The inner value codec decodes: the chain's `decode`. */ +template + requires value_decodable +struct over_value_decoding { + /** The value `text_characters` decodes to. */ + template + [[nodiscard]] static result + decode(over const& chain, View text_characters) noexcept( + over_value_decode_is_noexcept, Outer, Inner, Value, + View>()) { + return over_value_decode, Outer, Inner, Allocator, + Value>(chain, text_characters); + } +}; + +} // namespace detail + +/** + The value codec of `over` for a `Value` the value codec of `Inner` + converts. + + It exists when `Outer` has a codec: the value codec of `Inner` runs into the intermediate and + `Outer` encodes that, or `Outer` decodes into the intermediate and the value codec of `Inner` + reads that. Its encoding is text. It states `max_encoded_size` when the inner value codec does + and the outer link's bound on it fits, so that the default result is in place, and it is secret + when the value is (`is_secret_v`) or the inner value codec says so, which wipes the intermediate + and runs the outer link's secret arithmetic. Its functions are `noexcept` exactly when the + intermediate is in place (ruling R3), as `codec>`'s are. + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. + @tparam Allocator The allocator's type. + @tparam Value The value's type. +*/ +template + requires(detail::has_codec && detail::inner_value_codec) +struct value_codec, Value> + : detail::over_value_bound, + detail::over_value_encoding, + detail::over_value_decoding { + /** Text: the outer link writes characters. */ + static constexpr output_kind output = output_kind::text; + /** Secret when the value is or the inner value codec says so. */ + static constexpr bool secret = detail::over_value_is_secret; +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_OVER_HPP diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index c4368bb..57f5aba 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -25,6 +25,7 @@ #include #include #include +#include namespace webcpp::codecs { @@ -298,13 +299,67 @@ constexpr void check_secret_overloads() noexcept { "webcpp::codecs::result for the others"); } +/** + Whether the call of `codec::encoded_size` that @ref codec_encoded_size makes cannot throw: the + contract says every function of a codec is `noexcept`, and `over` with a heap intermediate is + the one that is not (ruling R3). +*/ +template +[[nodiscard]] constexpr bool codec_encoded_size_is_noexcept() noexcept { + if constexpr (Secret && has_secret_encoded_size) { + return noexcept( + codec::encoded_size(secret_tag{}, std::declval(), std::declval())); + } else { + return noexcept(codec::encoded_size(std::declval(), std::declval())); + } +} + +/** Whether the call @ref codec_decoded_size makes cannot throw, as for @ref codec_encoded_size. */ +template +[[nodiscard]] constexpr bool codec_decoded_size_is_noexcept() noexcept { + if constexpr (Secret && has_secret_decoded_size) { + return noexcept( + codec::decoded_size(secret_tag{}, std::declval(), std::declval())); + } else { + return noexcept(codec::decoded_size(std::declval(), std::declval())); + } +} + +/** Whether the call @ref codec_encode makes cannot throw, as for @ref codec_encoded_size. */ +template +[[nodiscard]] constexpr bool codec_encode_is_noexcept() noexcept { + if constexpr (Secret && has_secret_encode) { + return noexcept(codec::encode(secret_tag{}, std::declval(), + std::declval(), std::declval>())); + } else { + return noexcept(codec::encode(std::declval(), std::declval(), + std::declval>())); + } +} + +/** Whether the call @ref codec_decode makes cannot throw, as for @ref codec_encoded_size. */ +template +[[nodiscard]] constexpr bool codec_decode_is_noexcept() noexcept { + if constexpr (Secret && has_secret_decode) { + return noexcept(codec::decode(secret_tag{}, std::declval(), + std::declval(), + std::declval>())); + } else { + return noexcept(codec::decode(std::declval(), std::declval(), + std::declval>())); + } +} + /** The exact size of the text of `input_view`: the format's secret arithmetic in a secret operation - when it has one (R7), its `encoded_size` otherwise. + when it has one (R7), its `encoded_size` otherwise. `input_view` is the bytes as a `std::span`, + or as a @ref bounded_bytes when their type states a bound, which a codec that holds an + intermediate in place reads. */ -template +template [[nodiscard]] constexpr std::size_t codec_encoded_size( - F const& format_value, std::span input_view) noexcept { + F const& format_value, + View input_view) noexcept(codec_encoded_size_is_noexcept()) { check_secret_overloads(); if constexpr (Secret && has_secret_encoded_size) { return codec::encoded_size(secret_tag{}, format_value, input_view); @@ -316,10 +371,13 @@ template /** The exact size of the bytes of `text_characters`, the whole text checked: the format's secret arithmetic in a secret operation when it has one (R7), its `decoded_size` otherwise. + `text_characters` is a `std::string_view`, or a @ref bounded_text when the text's type states a + bound. */ -template +template [[nodiscard]] constexpr result codec_decoded_size( - F const& format_value, std::string_view text_characters) noexcept { + F const& format_value, + View text_characters) noexcept(codec_decoded_size_is_noexcept()) { check_secret_overloads(); if constexpr (Secret && has_secret_decoded_size) { return codec::decoded_size(secret_tag{}, format_value, text_characters); @@ -332,10 +390,10 @@ template Writes the text of `input_view` into `output_span`: the format's secret arithmetic in a secret operation when it has one (R7), its `encode` otherwise. */ -template -[[nodiscard]] constexpr result codec_encode(F const& format_value, - std::span input_view, - std::span output_span) noexcept { +template +[[nodiscard]] constexpr result codec_encode( + F const& format_value, View input_view, + std::span output_span) noexcept(codec_encode_is_noexcept()) { check_secret_overloads(); if constexpr (Secret && has_secret_encode) { return codec::encode(secret_tag{}, format_value, input_view, output_span); @@ -348,10 +406,10 @@ template Writes the bytes of `text_characters` into `output_span`: the format's secret arithmetic in a secret operation when it has one (R7), its `decode` otherwise. */ -template +template [[nodiscard]] constexpr result codec_decode( - F const& format_value, std::string_view text_characters, - std::span output_span) noexcept { + F const& format_value, View text_characters, + std::span output_span) noexcept(codec_decode_is_noexcept()) { check_secret_overloads(); if constexpr (Secret && has_secret_decode) { return codec::decode(secret_tag{}, format_value, text_characters, output_span); diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index cedc801..2a88ae7 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -25,6 +25,8 @@ #include #include #include +#include +#include namespace webcpp::codecs { @@ -74,18 +76,67 @@ template return std::nullopt; } +/** + Whether the calls of a format's functions that an encode of `Input` in `F` makes cannot throw: + the value codec's `encoded_size` and `encode` as it declares them, or the codec's through the + core's dispatchers, which are `noexcept` for every codec but `over` with a heap intermediate + (ruling R3). A pair that is not encodable is refused elsewhere. + + @tparam F The format's type. + @tparam Input The input's type. + @tparam Secret Whether the operation is secret. +*/ +template +[[nodiscard]] constexpr bool encode_calls_are_noexcept() noexcept { + using input_type = std::remove_cvref_t; + if constexpr (value_encodable) { + using value_type = value_codec; + return noexcept(value_type::encoded_size(std::declval(), + std::declval())) && + noexcept(value_type::encode(std::declval(), + std::declval(), + std::declval>())); + } else if constexpr (byte_input && has_codec) { + using view_type = input_view_t; + return codec_encoded_size_is_noexcept() && + codec_encode_is_noexcept(); + } else { + return true; + } +} + +/** + Whether the calls of a codec's functions that a decode of `Text` in `F` makes cannot throw, as + for @ref encode_calls_are_noexcept. + + @tparam F The format's type. + @tparam Text The text's type. + @tparam Secret Whether the operation is secret. +*/ +template +[[nodiscard]] constexpr bool decode_calls_are_noexcept() noexcept { + if constexpr (has_codec) { + using view_type = text_view_t>; + return codec_decoded_size_is_noexcept() && + codec_decode_is_noexcept(); + } else { + return true; + } +} + /** The exact size of what `encode` writes for the secret `input_value`: the format's secret arithmetic (R7), under secure's timing guard, which a constant expression cannot hold. */ template -[[nodiscard]] std::size_t secret_encoded_size(F const& format_value, - Input const& input_value) noexcept { +[[nodiscard]] std::size_t secret_encoded_size( + F const& format_value, + Input const& input_value) noexcept(encode_calls_are_noexcept()) { secure::timing_guard const timing_scope{true}; if constexpr (value_encodable) { return value_codec::encoded_size(format_value, input_value); } else { - return codec_encoded_size(format_value, input_bytes(input_value)); + return codec_encoded_size(format_value, bounded_input_bytes(input_value)); } } @@ -94,10 +145,10 @@ template where `Secret` and the format has one (R7): the buffer form's checks, then the conversion. */ template -[[nodiscard]] result encode_into_buffer(F const& format_value, - Input const& input_value, - std::span output_buffer) noexcept { - std::span const input_view = input_bytes(input_value); +[[nodiscard]] result encode_into_buffer( + F const& format_value, Input const& input_value, + std::span output_buffer) noexcept(encode_calls_are_noexcept()) { + auto const input_view = bounded_input_bytes(input_value); if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; } @@ -130,8 +181,9 @@ template @return The size, `SIZE_MAX` when it does not fit in `std::size_t`. */ template -[[nodiscard]] constexpr std::size_t encoded_size(F const& format_value, - Input const& input_value) noexcept { +[[nodiscard]] constexpr std::size_t +encoded_size(F const& format_value, Input const& input_value) noexcept( + detail::encode_calls_are_noexcept>()) { if constexpr (!encodable) { detail::refuse(); return 0; @@ -140,7 +192,7 @@ template } else if constexpr (detail::value_encodable) { return value_codec::encoded_size(format_value, input_value); } else { - return codec::encoded_size(format_value, detail::input_bytes(input_value)); + return codec::encoded_size(format_value, detail::bounded_input_bytes(input_value)); } } @@ -195,8 +247,9 @@ template */ template requires(!detail::value_encodable) -[[nodiscard]] result encode(F const& format_value, Input const& input_value, - std::span output_buffer) noexcept { +[[nodiscard]] result +encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept( + detail::encode_calls_are_noexcept>()) { if constexpr (!detail::has_codec) { detail::refuse(); return std::size_t{0}; @@ -230,15 +283,17 @@ template @return The number of bytes written, or the error. */ template -[[nodiscard]] result decode(F const& format_value, Text const& text_value, - std::span output_buffer) noexcept { +[[nodiscard]] result decode( + F const& format_value, Text const& text_value, + std::span + output_buffer) noexcept(detail::decode_calls_are_noexcept()) { if constexpr (detail::has_codec) { - std::string_view const text_characters = detail::text_view(text_value); + auto const text_characters = detail::bounded_text_view(text_value); if (auto const size_fault = detail::text_size_fault(format_value, text_characters.size())) { return *size_fault; } result const byte_count = - codec::decoded_size(format_value, text_characters); + detail::codec_decoded_size(format_value, text_characters); if (!byte_count) { return byte_count; } @@ -247,7 +302,8 @@ template if (output_buffer.size() < bytes_size) { return error::output_too_small; } - return codec::decode(format_value, text_characters, output_buffer.first(bytes_size)); + return detail::codec_decode(format_value, text_characters, + output_buffer.first(bytes_size)); } else { detail::refuse(); return std::size_t{0}; diff --git a/test/Jamfile b/test/Jamfile index 369e740..b2247d1 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -69,6 +69,10 @@ codecs-run secret_operation : secret_operation_test.cpp # for a public one, as secure's timing seam records it; DIT set inside where the # CPU has it. codecs-run timing : timing_test.cpp ; +# over (D11): a format of two links; its intermediate in place or from its +# allocator, wiped when the chain is secret, as secure's wipe seam records it; +# the links' secret overloads (R7) run in a secret chain. +codecs-run over : over_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 82b2b87..00e6ae6 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -21,6 +21,7 @@ #include +#include #include #include #include @@ -456,6 +457,83 @@ void check_assign_to_scratch() { BOOST_TEST(byte_target.data() == byte_buffer); } +/** over with a bound known at compile time (Task 7, spec "Allocation"): its intermediate is in + place, so every form allocates nothing, a secret chain and a value codec's included; with a heap + intermediate the exact sizes, encode and decode allocate (ruling R3, finding F17), the buffer forms + among them, which the control below counts. */ +void check_over() { + constexpr codecs::over chain{test::letters, test::letters}; + constexpr codecs::over value_chain{test::letters, test::be16}; + std::array const input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + std::vector const heap_input(input.begin(), input.end()); + webcpp::secure::secret<32> key; + std::array output{}; + std::array decoded{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + expect_no_allocation("over, the default results", [&] { + auto const encoded = codecs::encode(chain, input); + auto const bytes_back = codecs::decode(chain, encoded.value()); + verdict = encoded.has_value() && bytes_back.has_value() && + std::ranges::equal(bytes_back.value().view(), input); + }); + BOOST_TEST(verdict); + expect_no_allocation("over, the sizes", [&] { + sink = codecs::encoded_size(chain, input); + sink = codecs::encoded_size(chain, key); + }); + expect_no_allocation("over, the buffer forms", [&] { + verdict = codecs::encode(chain, input, output).has_value() && + codecs::decode(chain, codecs::text<64>{}, decoded).has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("over, a typed decode and the tokens", [&] { + auto const text_value = codecs::encode(chain, input); + auto const as_array = + codecs::decode>(chain, text_value.value()); + auto const fixed = codecs::encode(chain, input, codecs::tokens::fixed<64>{}); + verdict = as_array.has_value() && fixed.has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("over, a secret chain", [&] { + auto const secret_text = codecs::encode(chain, key); + // The text's size is known at compile time: a text of 128 characters in an array. + std::array text_array{}; + std::ranges::copy(secret_text.value().view(), text_array.begin()); + auto const secret_back = codecs::decode>(chain, text_array); + verdict = secret_text.has_value() && secret_back.has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("over, a value codec", [&] { + auto const encoded = codecs::encode(value_chain, test::number{0x1234}); + auto const number_back = codecs::decode(value_chain, encoded.value()); + verdict = encoded.has_value() && number_back.has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("over, an input whose bound saturates and the empty input", [&] { + constexpr codecs::over saturating_chain{test::letters, test::saturating}; + std::array const long_input{}; + verdict = codecs::encode(saturating_chain, long_input).has_value() || + codecs::encode(chain, std::array{}).value().size() != 0; + }); + BOOST_TEST(!verdict); + // The heap intermediate allocates, in the sizes and in the buffer forms: the form that counts. + BOOST_TEST_GE(allocations_of([&] { sink = codecs::encoded_size(chain, heap_input); }), 1U); + BOOST_TEST_GE( + allocations_of([&] { verdict = codecs::encode(chain, heap_input, output).has_value(); }), + 2U); + BOOST_TEST(verdict); + std::string const heap_text = + codecs::encode(chain, heap_input, codecs::tokens::return_string).value(); + std::array wide_decoded{}; + BOOST_TEST_GE(allocations_of([&] { + verdict = codecs::decode(chain, heap_text, wide_decoded).has_value(); + }), + 2U); + BOOST_TEST(verdict); + static_cast(sink); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -504,6 +582,7 @@ int main() { check_secret_results(); check_secret_operations(); check_assign_to_scratch(); + check_over(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 8b452e7..a47b107 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -18,6 +18,7 @@ #include "support/allocators.hpp" #include "support/arena.hpp" +#include "support/be16.hpp" #include "support/letters.hpp" #include @@ -290,6 +291,96 @@ void the_secret_token_over_an_arena() { expect_every_block_zero(arena); } +/** over with its own allocator (Task 7, owner decision 23): the heap intermediate of a chain on a + vector input comes from the arena, one block for each time a link runs into it (the exact size, + then the encode), and the global operator new sees none; in place, with a size known at compile + time, the allocator is not asked at all. A secret chain gives its intermediates back wiped. */ +void over_takes_its_intermediate_from_its_allocator() { + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + static_assert(std::is_same_v, + codecs::over>>); + std::vector const input(40, 0x5a); + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const expected = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + // The result goes to the arena too, so that the global operator new sees nothing. + std::pmr::polymorphic_allocator const char_allocator{&arena}; + expect_no_global_allocation("over over an arena, encode", [&] { + auto const encoded = codecs::encode(chain, input, tokens::return_string(char_allocator)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + BOOST_TEST(arena.owns(encoded.value().data())); + }); + // The exact size's intermediate, the encode's, and the string. + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_GE(arena.allocation(0).size, inner_text.size()); + BOOST_TEST_GE(arena.allocation(1).size, inner_text.size()); + for (std::size_t index = 0; index < 2; ++index) { + BOOST_TEST(arena.owns(arena.allocation(index).pointer)); + } + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("over over an arena, decode", [&] { + auto const decoded = codecs::decode(chain, expected, tokens::return_string(char_allocator)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + }); + // The exact size's intermediate, the decode's, and the string. + BOOST_TEST_EQ(arena.allocation_count() - before, 3U); + // With a size known at compile time, the allocator is not asked. + std::array const known{}; + std::size_t const before_known = arena.allocation_count(); + BOOST_TEST(codecs::encode(chain, known).has_value()); + BOOST_TEST_EQ(arena.allocation_count(), before_known); + // A value codec of text with no stated bound takes the arena too. + test::recording_resource value_arena; + auto const value_chain = codecs::over{ + test::letters, test::be16, std::pmr::polymorphic_allocator{&value_arena}}; + BOOST_TEST( + codecs::encode(value_chain, test::hex_number{0x1234}, + tokens::return_string(std::pmr::polymorphic_allocator{&value_arena})) + .has_value()); + // The exact size's intermediate and the encode's; the eight characters stay in the string. + BOOST_TEST_GE(value_arena.allocation_count(), 2U); +} + +/** A secret chain over an arena (Task 7): each intermediate comes from the arena and goes back to + it wiped, with the secret result on the arena too. */ +void a_secret_over_gives_its_intermediates_back_wiped() { + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + std::vector const input(40, 0x5a); + std::pmr::polymorphic_allocator const char_allocator{&arena}; + expect_no_global_allocation("a secret over over an arena, encode", [&] { + auto const encoded = codecs::encode(chain, input, tokens::secret(char_allocator)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(encoded.value().view().size(), 160U); + }); + // The exact size's intermediate, the encode's, and the secret text. + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + expect_every_block_zero(arena); + // The decode: the outer link's intermediates, and the secret bytes, wiped likewise. + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const text_value = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("a secret over over an arena, decode", [&] { + auto const decoded = codecs::decode(chain, text_value, tokens::secret(char_allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + }); + BOOST_TEST_EQ(arena.allocation_count() - before, 3U); + BOOST_TEST_EQ(arena.deallocation_count(), arena.allocation_count()); + expect_every_block_zero(arena); +} + void the_allocators_of_the_tests_own() { // non_propagating_allocator: equal only to a copy. test::non_propagating_allocator const first_allocator{1}; @@ -332,6 +423,8 @@ int main() { a_typed_decode_with_an_allocator(); secret_types_over_an_arena(); the_secret_token_over_an_arena(); + over_takes_its_intermediate_from_its_allocator(); + a_secret_over_gives_its_intermediates_back_wiped(); the_allocators_of_the_tests_own(); return boost::report_errors(); } diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index c69a9db..c470ea1 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -406,6 +406,89 @@ void a_secret_assign_to_wipes_its_scratch_when_the_target_throws() { BOOST_TEST_EQ(attempts, 2U); } +void an_over_throws_through_and_wipes_when_secret() { + // over's heap intermediate (Task 7): the exact size's intermediate is the first allocation and + // the encode's the second; an exception of either reaches the caller, and on a secret chain + // every buffer the allocator was given back reads zero. + std::vector const input(input_size, 0x5a); + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const expected = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + for (bool const secret : {false, true}) { + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + bool thrown = false; + try { + if (secret) { + auto const encoded = codecs::encode(chain, input, tokens::secret); + BOOST_TEST(encoded.value().view() == expected); + } else { + auto const encoded = codecs::encode(chain, input); + BOOST_TEST(encoded.value() == expected); + } + } catch (std::bad_alloc const&) { + thrown = true; + } + if (secret) { + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + } + BOOST_TEST_EQ(allocator.state()->deallocations, + allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); + } + // The decode: the outer link's intermediate, for the size and for the decode. + for (bool const secret : {false, true}) { + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + bool thrown = false; + try { + if (secret) { + auto const decoded = codecs::decode(chain, expected, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + } else { + auto const decoded = codecs::decode(chain, expected); + BOOST_TEST((decoded.value() == input)); + } + } catch (std::bad_alloc const&) { + thrown = true; + } + if (secret) { + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + } + BOOST_TEST_EQ(allocator.state()->deallocations, + allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); + } + // The buffer form allocates, too (finding F17), and the exception reaches the caller. + test::throwing_allocator const allocator{1}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + std::array buffer{}; + bool thrown = false; + try { + BOOST_TEST(codecs::encode(chain, input, std::span{buffer}).has_value()); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST(thrown); +} + } // namespace int main() { @@ -419,5 +502,6 @@ int main() { a_secret_move_between_unequal_allocators_keeps_both(); the_secret_token_throws_through(); a_secret_assign_to_wipes_its_scratch_when_the_target_throws(); + an_over_throws_through_and_wipes_when_secret(); return boost::report_errors(); } diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 96ba2d5..5677b1d 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -160,6 +160,73 @@ static_assert( static_assert(!noexcept(std::declval().swap( std::declval()))); +// over (Task 7, ruling R3): with a bound known at compile time its intermediate is in place and +// every form is noexcept; with a heap intermediate the exact sizes, encode and decode allocate and +// are not, the buffer forms of the core among them (the one allocating buffer form). +constexpr codecs::over letters_over_letters{test::letters, test::letters}; +constexpr codecs::over be16_over_letters{test::letters, test::be16}; +using letters_over_letters_t = std::remove_cv_t; +namespace over_detail = codecs::detail; +// In place: the input's type states its size. +static_assert(noexcept(codecs::encode(letters_over_letters, std::array{}))); +static_assert(noexcept(codecs::encoded_size(letters_over_letters, std::array{}))); +static_assert(noexcept(codecs::encode(letters_over_letters, std::array{}, + std::span{}))); +static_assert(noexcept(codecs::decode(letters_over_letters, codecs::text<64>{}))); +static_assert(noexcept(codecs::decode(letters_over_letters, codecs::text<64>{}, + std::span{}))); +static_assert(noexcept(codecs::decode>(letters_over_letters, + codecs::text<64>{}))); +static_assert(noexcept(codecs::encode(letters_over_letters, std::array{}, + tokens::fixed<64>{}))); +static_assert(noexcept(codecs::encode(letters_over_letters, + std::declval>()))); +static_assert(noexcept(codecs::encode(letters_over_letters, + std::declval>()))); +// On the heap: a size known at run time. +static_assert(!noexcept(codecs::encode(letters_over_letters, std::vector{}))); +static_assert(!noexcept(codecs::encoded_size(letters_over_letters, std::vector{}))); +static_assert(!noexcept(codecs::encode(letters_over_letters, std::vector{}, + std::span{}))); +static_assert(!noexcept(codecs::decode(letters_over_letters, std::string_view{}))); +static_assert(!noexcept(codecs::decode(letters_over_letters, std::string_view{}, + std::span{}))); +static_assert(!noexcept(codecs::encode(letters_over_letters, std::vector{}, + tokens::fixed<64>{}))); +static_assert(!noexcept(codecs::encode(letters_over_letters, std::vector{}, + tokens::return_string))); +// A result in place does not make a heap intermediate noexcept: the text is of a size known at +// run time. +static_assert(!noexcept(codecs::decode>(letters_over_letters, + std::string_view{}))); +static_assert(!noexcept(codecs::decode(letters_over_letters, std::string_view{}, + tokens::fixed<16>{}))); +// The codec's own functions follow the view they are given. +static_assert(noexcept(codecs::codec::encoded_size( + letters_over_letters, std::declval>()))); +static_assert(noexcept(codecs::codec::decode( + letters_over_letters, std::declval>(), + std::declval>()))); +static_assert(!noexcept(codecs::codec::encode( + letters_over_letters, std::declval>(), + std::declval>()))); +static_assert(!noexcept(codecs::codec::decoded_size( + letters_over_letters, std::declval()))); +static_assert(!noexcept(codecs::codec::decoded_size( + over_detail::secret_tag{}, letters_over_letters, std::declval()))); +// A value codec: in place when it states its bound (be16's number), else on the heap (hex_number). +static_assert(noexcept(codecs::encode(be16_over_letters, test::number{}))); +static_assert(noexcept(codecs::encode(be16_over_letters, test::number{}, std::span{}))); +static_assert(noexcept(codecs::encoded_size(be16_over_letters, test::number{}))); +static_assert(noexcept(codecs::decode(be16_over_letters, codecs::text<4>{}))); +static_assert(!noexcept(codecs::decode(be16_over_letters, std::string_view{}))); +static_assert(!noexcept(codecs::encode(be16_over_letters, test::hex_number{}))); +static_assert(!noexcept(codecs::encode(be16_over_letters, test::hex_number{}, std::span{}))); +// A chain of a chain is in place when every link is. +constexpr codecs::over three_links{test::letters, letters_over_letters}; +static_assert(noexcept(codecs::encode(three_links, std::array{}))); +static_assert(!noexcept(codecs::encode(three_links, std::vector{}))); + // append_to of a vector is for decode, and a vector token is no text token. static_assert(!codecs::detail::text_token< decltype(tokens::append_to(std::declval&>()))>); diff --git a/test/over_test.cpp b/test/over_test.cpp new file mode 100644 index 0000000..510b3af --- /dev/null +++ b/test/over_test.cpp @@ -0,0 +1,559 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// over (D11): a format of two links, on the tests' own formats (Task 16 adds hex over base64). +// Its name, its deduction with and without an allocator, a chain of codecs and a chain of a value +// codec, the default results it gives (in place when the input's type states its size), its bounds +// and the refusals that follow from them, the order of the errors, nesting, constant time, and the +// secret chain: the links' secret overloads run (ruling R7) and the intermediate, in place and on +// the heap, is wiped, as secure's wipe seam records it. + +#include "support/wipe_recorder.hpp" + +#include "support/be16.hpp" +#include "support/letters.hpp" +#include "support/saturating.hpp" +#include "support/tagged_letters.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace over_test { +namespace { + +namespace codecs = webcpp::codecs; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +/** A format of letters that says it is constant time. */ +struct steady_t { + /** The format's name. */ + static constexpr std::string_view name = "steady"; +}; + +/** A value of a value codec of bytes that is secret: sixteen bits. */ +struct sealed_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(sealed_number const&) const = default; +}; + +/** The format of `sealed_number`: two bytes, big endian, by a value codec that is secret. */ +struct seal_t { + /** The format's name. */ + static constexpr std::string_view name = "seal"; +}; + +} // namespace +} // namespace over_test + +namespace webcpp::codecs { + +/** steady is letters, and constant time. */ +template <> +struct codec : codec { + /** The format is constant time. */ + static constexpr bool constant_time = true; +}; + +/** A sealed number is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** The value codec of seal: two bytes, a bound, and secret. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + /** The value is secret. */ + static constexpr bool secret = true; + + /** Two bytes. */ + static std::size_t encoded_size(over_test::seal_t const& /*format*/, + over_test::sealed_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static result encode(over_test::seal_t const& /*format*/, + over_test::sealed_number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } + + /** Reads two bytes. */ + static result decode( + over_test::seal_t const& /*format*/, std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return error::invalid_length; + } + unsigned const bits = (static_cast(input_bytes[0]) << 8U) | input_bytes[1]; + return over_test::sealed_number{static_cast(bits)}; + } +}; + +} // namespace webcpp::codecs + +namespace over_test { +namespace { + +/** 16 bytes, the spec's scenario's input. */ +std::array bytes_16() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast((index * 17U) + 3U); + } + return held_bytes; +} + +/** The letters of `bytes_value`. */ +std::string letters_of(std::span bytes_value) { + return codecs::encode(test::letters, bytes_value, tokens::return_string).value(); +} + +/** The letters of the characters of `text_value`, read as bytes. */ +std::string letters_of(std::string_view text_value) { + return codecs::encode(test::letters, text_value, tokens::return_string).value(); +} + +/** The letters of the letters of `bytes_value`, made link by link. */ +std::string letters_of_letters(std::span bytes_value) { + return letters_of(std::string_view{letters_of(bytes_value)}); +} + +// The name, joined in a static array, and the format's own requirements. +constexpr auto letters_over_letters = codecs::over{test::letters, test::letters}; +static_assert(codecs::format>); +static_assert(letters_over_letters.name == "letters over letters"); +static_assert(codecs::over::name == "letters over be16"); +static_assert(codecs::over>::name == + "letters over letters over be16"); + +// Deduction from values, with and without an allocator; the default allocator is std::allocator's. +static_assert( + std::is_same_v, + codecs::over>>); +static_assert( + std::is_same_v{}}), + codecs::over>>); +static_assert(std::is_same_v>); + +// What `over` converts: a chain of two codecs converts bytes, and a chain with a value codec its +// values; an outer link with no codec converts nothing. +static_assert( + codecs::encodable, std::remove_cv_t>); +static_assert( + codecs::decodable, std::remove_cv_t>); +static_assert(codecs::encodable>); +static_assert(codecs::decodable>); +static_assert( + !codecs::encodable, codecs::over>); +static_assert(!codecs::encodable>); +static_assert( + !codecs::encodable, codecs::over>); + +void a_chain_of_codecs() { + auto const input = bytes_16(); + // The spec's scenario on the tests' formats: 16 bytes, 64 characters, in place. + auto const encoded = codecs::encode(letters_over_letters, input); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(encoded.value().view() == letters_of_letters(input)); + BOOST_TEST_EQ(encoded.value().size(), 64U); + auto const decoded = codecs::decode(letters_over_letters, encoded.value()); + static_assert(std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + // The exact sizes. + BOOST_TEST_EQ(codecs::encoded_size(letters_over_letters, input), 64U); + BOOST_TEST_EQ(codecs::max_decoded_size(letters_over_letters, encoded.value()), 16U); + // A size known at run time gives the heap results. + std::vector const bytes_vector(input.begin(), input.end()); + auto const heap_encoded = codecs::encode(letters_over_letters, bytes_vector); + static_assert(std::is_same_v const>); + BOOST_TEST(heap_encoded.value() == letters_of_letters(input)); + auto const heap_decoded = codecs::decode(letters_over_letters, heap_encoded.value()); + static_assert( + std::is_same_v> const>); + BOOST_TEST((heap_decoded.value() == bytes_vector)); + // The typed decodes and the tokens. + auto const as_array = + codecs::decode>(letters_over_letters, encoded.value()); + BOOST_TEST(as_array.value() == input); + BOOST_TEST(codecs::decode(letters_over_letters, heap_encoded.value()).value() == + std::string(input.begin(), input.end())); + BOOST_TEST(codecs::encode(letters_over_letters, bytes_vector, tokens::return_string).value() == + letters_of_letters(input)); + BOOST_TEST_EQ(codecs::encode(letters_over_letters, input, tokens::fixed<64>{}).value().size(), + 64U); + // Empty, in every form. + BOOST_TEST(codecs::encode(letters_over_letters, std::vector{}).value().empty()); + BOOST_TEST(codecs::decode(letters_over_letters, std::string_view{}).value().empty()); + BOOST_TEST_EQ( + codecs::encode(letters_over_letters, std::array{}).value().size(), 0U); +} + +void the_buffer_forms() { + auto const input = bytes_16(); + std::array text_buffer{}; + auto const written = codecs::encode(letters_over_letters, input, std::span{text_buffer}); + BOOST_TEST(written.has_value()); + BOOST_TEST_EQ(written.value(), 64U); + BOOST_TEST((std::string_view{text_buffer.data(), 64} == letters_of_letters(input))); + // A buffer too short is refused, nothing is written. + std::array short_buffer{}; + BOOST_TEST(codecs::encode(letters_over_letters, input, std::span{short_buffer}).error() == + codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(short_buffer, [](char byte_value) { return byte_value == 0; })); + // The decode, into the text's own storage: the bytes come out right. + std::array in_place{}; + std::ranges::copy(std::string_view{text_buffer.data(), 64}, in_place.begin()); + auto const text_in_buffer = + std::string_view{reinterpret_cast(in_place.data()), 64}; + auto const decoded = + codecs::decode(letters_over_letters, text_in_buffer, std::span{in_place}); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value(), 16U); + BOOST_TEST(std::equal(input.begin(), input.end(), in_place.begin())); + std::array short_bytes{}; + BOOST_TEST(codecs::decode(letters_over_letters, letters_of_letters(input), + std::span{short_bytes}) + .error() == codecs::error::output_too_small); +} + +void the_errors_and_their_order() { + // The outer link reads the text first: its error is the chain's. + BOOST_TEST(codecs::decode(letters_over_letters, "abcz").error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(letters_over_letters, "abc").error() == + codecs::error::invalid_length); + // The inner link reads what the outer link gave: here "ab" is 0x01 and "cd" is 0x23. + constexpr auto be16_over_letters = codecs::over{test::letters, test::be16}; + BOOST_TEST(codecs::decode(be16_over_letters, "bcde").value() == + test::number{0x1234}); + BOOST_TEST(codecs::decode(be16_over_letters, "bcdebf").error() == + codecs::error::invalid_length); + // The outer link's character error first. + BOOST_TEST(codecs::decode(be16_over_letters, "bcdebz").error() == + codecs::error::invalid_character); + // The inner link's data error of a decode through the sizes: letters of letters, whose inner + // text is invalid ("qq" is "b" 'q' as the inner letters, outside a to p). + // An odd count of letters in the inner text: the outer link decodes "abc" and the inner link + // finds it odd. + BOOST_TEST(codecs::decode(letters_over_letters, letters_of(std::string_view{"abc"})).error() == + codecs::error::invalid_length); + std::string const invalid_inner = + codecs::encode(test::letters, std::string_view{"aq"}, tokens::return_string).value(); + BOOST_TEST(codecs::decode(letters_over_letters, invalid_inner).error() == + codecs::error::invalid_character); + // An inner link whose encode fails after its size is known: its error reaches the caller, from + // the buffer form and the default one, and the exact size is a bound that finds it. + constexpr auto failing_over = codecs::over{test::letters, test::be16}; + BOOST_TEST(codecs::encode(failing_over, test::failing_number{1}).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(codecs::encode(failing_over, test::bounded_failing_number{1}).error() == + codecs::error::checksum_mismatch); + std::array buffer{}; + BOOST_TEST( + codecs::encode(failing_over, test::failing_number{1}, std::span{buffer}).error() == + codecs::error::checksum_mismatch); +} + +void a_chain_with_a_value_codec() { + constexpr auto be16_over_letters = codecs::over{test::letters, test::be16}; + // The spec's value: number{0x1234} is the bytes 0x12 0x34, the letters "bcde". + auto const encoded = codecs::encode(be16_over_letters, test::number{0x1234}); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == "bcde"); + auto const decoded = codecs::decode(be16_over_letters, encoded.value()); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(decoded.value() == test::number{0x1234}); + BOOST_TEST(codecs::decode(be16_over_letters, std::string{"bcde"}).value() == + test::number{0x1234}); + // The value codec's buffer form. + std::array buffer{}; + BOOST_TEST_EQ( + codecs::encode(be16_over_letters, test::number{0x1234}, std::span{buffer}).value(), + 4U); + BOOST_TEST((std::string_view{buffer.data(), 4} == "bcde")); + BOOST_TEST( + codecs::encode(be16_over_letters, test::number{0x1234}, std::span{buffer.data(), 3}) + .error() == codecs::error::output_too_small); + BOOST_TEST_EQ(codecs::encoded_size(be16_over_letters, test::number{0x1234}), 4U); + // A value codec of text with no stated bound: the intermediate is on the heap, the result a + // string, which is what encoding the digits through letters gives. + auto const heap_encoded = codecs::encode(be16_over_letters, test::hex_number{0x1234}); + static_assert(std::is_same_v const>); + BOOST_TEST( + heap_encoded.value() == + codecs::encode(test::letters, std::string_view{"1234"}, tokens::return_string).value()); + BOOST_TEST(codecs::decode(be16_over_letters, heap_encoded.value()).value() == + test::hex_number{0x1234}); + // A chain of three links: the value codec under two codecs. + constexpr auto twice = codecs::over{test::letters, be16_over_letters}; + auto const nested = codecs::encode(twice, test::number{0x1234}); + static_assert(std::is_same_v> const>); + BOOST_TEST( + nested.value().view() == + codecs::encode(test::letters, std::string_view{"bcde"}, tokens::return_string).value()); + BOOST_TEST(codecs::decode(twice, nested.value()).value() == test::number{0x1234}); +} + +void the_bounds_and_the_refusals() { + using chain_codec = codecs::codec>; + static_assert(chain_codec::max_encoded_size(16) == 64); + static_assert(chain_codec::max_decoded_size(64) == 16); + static_assert(chain_codec::max_encoded_size(0) == 0); + // The bound saturates when the inner link's does, and when the outer link's does. + constexpr std::size_t most = std::numeric_limits::max(); + static_assert(chain_codec::max_encoded_size((most / 4) + 1) == most); + static_assert(chain_codec::max_encoded_size(most) == most); + using inner_saturating = codecs::codec>; + static_assert(inner_saturating::max_encoded_size(test::saturating_t::most_bytes) == 16); + static_assert(inner_saturating::max_encoded_size(test::saturating_t::most_bytes + 1) == most); + using outer_saturating = codecs::codec>; + static_assert(outer_saturating::max_encoded_size(2) == 8); + static_assert(outer_saturating::max_encoded_size(3) == most); + static_assert(outer_saturating::max_decoded_size(test::saturating_t::most_characters) == 2); + static_assert(outer_saturating::max_decoded_size(test::saturating_t::most_characters + 1) == + most); + // An input whose bound saturates is refused before any link reads it, in every form: the + // saturating format's functions report checksum_mismatch if they ever run. + constexpr auto inner_chain = codecs::over{test::letters, test::saturating}; + constexpr auto outer_chain = codecs::over{test::saturating, test::letters}; + std::vector const long_bytes(test::saturating_t::most_bytes + 1); + std::array const long_array{}; + BOOST_TEST(codecs::encode(inner_chain, long_bytes).error() == codecs::error::input_too_long); + BOOST_TEST(codecs::encode(inner_chain, long_array).error() == codecs::error::input_too_long); + std::array buffer{}; + BOOST_TEST(codecs::encode(inner_chain, long_array, std::span{buffer}).error() == + codecs::error::input_too_long); + std::vector const three_bytes(3); + BOOST_TEST(codecs::encode(outer_chain, three_bytes).error() == codecs::error::input_too_long); + std::string const long_text(test::saturating_t::most_characters + 1, 'a'); + BOOST_TEST(codecs::decode(outer_chain, long_text).error() == codecs::error::input_too_long); + BOOST_TEST_EQ(codecs::encoded_size(inner_chain, long_bytes), most); +} + +void a_chain_of_chains() { + constexpr auto three = codecs::over{test::letters, codecs::over{test::letters, test::letters}}; + static_assert(three.name == "letters over letters over letters"); + auto const input = bytes_16(); + auto const encoded = codecs::encode(three, input); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == letters_of(std::string_view{letters_of_letters(input)})); + auto const decoded = codecs::decode(three, encoded.value()); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + // The heap, through three links. + std::vector const bytes_vector(input.begin(), input.end()); + auto const heap_encoded = codecs::encode(three, bytes_vector); + BOOST_TEST(heap_encoded.value() == std::string{encoded.value().view()}); + BOOST_TEST((codecs::decode>(three, heap_encoded.value()).value() == + bytes_vector)); +} + +void constant_time_follows_the_links() { + using plain_chain = codecs::codec>; + using mixed_chain = codecs::codec>; + using steady_chain = codecs::codec>; + static_assert(!plain_chain::constant_time); + static_assert(!mixed_chain::constant_time); + static_assert(!codecs::codec>::constant_time); + static_assert(steady_chain::constant_time); +} + +/** Whether a wipe of `size` bytes, all zero, was recorded. */ +bool wiped_of_size(std::size_t size) { + for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); + ++index) { + test::wipe_entry const& entry = test::wipes.entries[index]; + if (entry.size == size && entry.zero) { + return true; + } + } + return false; +} + +/** 32 secret bytes. */ +secure::secret<32> make_key() { + secure::secret<32> made; + for (std::size_t index = 0; index < 32; ++index) { + made.writable()[index] = static_cast(index * 8U); + } + return made; +} + +void a_secret_chain_wipes_its_intermediate() { + constexpr auto chain = codecs::over{test::letters, test::letters}; + auto const key = make_key(); + auto const public_input = bytes_16(); + std::string const expected = letters_of_letters(key.bytes()); + // A secret input: a secret result of the bound, in place, and the intermediate (the 64 letters + // of the inner link) wiped. + test::clear_wipes(); + auto const encoded = codecs::encode(chain, key); + static_assert( + std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == expected); + BOOST_TEST(wiped_of_size(64)); + // A public input wipes nothing. + test::clear_wipes(); + BOOST_TEST(codecs::encode(chain, public_input).has_value()); + BOOST_TEST_EQ(test::wipes.count, 0U); + // The decode into a secret type: the intermediate of the outer link (the inner letters, 64 + // bytes) is wiped. + test::clear_wipes(); + auto const decoded = codecs::decode>(chain, expected); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::equal(decoded.value().view(), key.bytes())); + BOOST_TEST(wiped_of_size(64)); + // And through a secret token, with the text of a size known at compile time. + test::clear_wipes(); + auto const public_text = codecs::encode(chain, public_input); + BOOST_TEST(public_text.has_value()); + auto const through_token = codecs::decode(chain, public_text.value(), tokens::secret); + static_assert( + std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(through_token.value().view(), public_input)); + // The 64 letters decode to 32 bytes between the links. + BOOST_TEST(wiped_of_size(32)); + // The buffer form of a secret input. + std::array buffer{}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(chain, key, std::span{buffer}).has_value()); + BOOST_TEST((std::string_view{buffer.data(), 128} == expected)); + BOOST_TEST(wiped_of_size(64)); +} + +void a_secret_chain_on_the_heap_wipes_too() { + constexpr auto chain = codecs::over{test::letters, test::letters}; + std::vector const input(40, 0x5a); + std::string const expected = letters_of_letters(input); + test::clear_wipes(); + auto const encoded = codecs::encode(chain, input, tokens::secret); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.value().view() == expected); + // The intermediate, 80 letters on the heap, was wiped before the allocator got it back. + BOOST_TEST(wiped_of_size(80)); + test::clear_wipes(); + auto const decoded = codecs::decode(chain, expected); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), 40U); + BOOST_TEST(wiped_of_size(80)); + // A public operation on the heap wipes nothing. + test::clear_wipes(); + BOOST_TEST(codecs::encode(chain, input).has_value()); + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +void a_secret_value_makes_the_chain_secret() { + constexpr auto chain = codecs::over{test::letters, seal_t{}}; + static_assert(codecs::value_codec, sealed_number>::secret); + test::clear_wipes(); + auto const encoded = codecs::encode(chain, sealed_number{0x1234}); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == "bcde"); + // The two bytes of the value codec, between the links, wiped. + BOOST_TEST(wiped_of_size(2)); + test::clear_wipes(); + auto const decoded = codecs::decode(chain, std::string_view{"bcde"}); + BOOST_TEST(decoded.value() == sealed_number{0x1234}); + BOOST_TEST(wiped_of_size(2)); +} + +void the_links_secret_overloads_run_in_a_secret_chain() { + // R7 through the chain: a public operation runs no secret overload of either link, a secret + // one runs the secret overloads of both, in the order the chain calls them. + constexpr auto chain = codecs::over{test::tagged_letters, test::tagged_letters}; + auto const public_input = bytes_16(); + test::tagged_calls.reset(); + auto const public_text = codecs::encode(chain, public_input); + BOOST_TEST(public_text.has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + test::tagged_calls.reset(); + BOOST_TEST(codecs::decode(chain, public_text.value()).has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + // The encode: the exact size runs the inner link's size and encode and the outer link's size; + // the encode runs the inner link's size and encode and the outer link's encode. + auto const key = make_key(); + test::tagged_calls.reset(); + auto const secret_text = codecs::encode(chain, key); + BOOST_TEST(secret_text.has_value()); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 3U); + BOOST_TEST_EQ(test::tagged_calls.encode, 3U); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 0U); + BOOST_TEST_EQ(test::tagged_calls.decode, 0U); + BOOST_TEST(secret_text.value().view() == letters_of_letters(key.bytes())); + // The decode into a secret type: the exact size runs the outer link's size and decode and the + // inner link's size; the decode runs the outer link's size and decode and the inner link's + // decode. + test::tagged_calls.reset(); + auto const secret_bytes = + codecs::decode>(chain, secret_text.value().view()); + BOOST_TEST(secret_bytes.has_value()); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 3U); + BOOST_TEST_EQ(test::tagged_calls.decode, 3U); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 0U); + BOOST_TEST_EQ(test::tagged_calls.encode, 0U); + // A link of one kind and a link of the other: only the one with the overloads counts. + constexpr auto mixed = codecs::over{test::letters, test::tagged_letters}; + test::tagged_calls.reset(); + BOOST_TEST(codecs::encode(mixed, key).has_value()); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 2U); + BOOST_TEST_EQ(test::tagged_calls.encode, 2U); + // The buffer forms and the tokens are secret as the default form is. + std::array buffer{}; + test::tagged_calls.reset(); + BOOST_TEST(codecs::encode(chain, key, std::span{buffer}).has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 6U); + test::tagged_calls.reset(); + BOOST_TEST(codecs::encode(chain, public_input, tokens::secret).has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 6U); +} + +} // namespace +} // namespace over_test + +int main() { + over_test::a_chain_of_codecs(); + over_test::the_buffer_forms(); + over_test::the_errors_and_their_order(); + over_test::a_chain_with_a_value_codec(); + over_test::the_bounds_and_the_refusals(); + over_test::a_chain_of_chains(); + over_test::constant_time_follows_the_links(); + over_test::a_secret_chain_wipes_its_intermediate(); + over_test::a_secret_chain_on_the_heap_wipes_too(); + over_test::a_secret_value_makes_the_chain_secret(); + over_test::the_links_secret_overloads_run_in_a_secret_chain(); + return boost::report_errors(); +} From f8ba6e7490e19a9435994c734ed5a2c15ecac781 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:16:45 -0300 Subject: [PATCH 035/157] codecs: over lint fix, the trait helpers not noexcept, the move and self-assignment of the chain and the token, the notes of the conversions on their own line --- .../webcpp/codecs/detail/core/contract.hpp | 8 +- .../webcpp/codecs/detail/core/operations.hpp | 2 +- include/webcpp/codecs/detail/core/over.hpp | 28 ++--- include/webcpp/codecs/detail/core/secrecy.hpp | 12 +- include/webcpp/codecs/detail/core/sizes.hpp | 4 +- include/webcpp/codecs/detail/core/tokens.hpp | 12 +- test/allocator_throw_test.cpp | 108 ++++++++---------- test/over_test.cpp | 4 +- test/secret_operation_test.cpp | 7 +- 9 files changed, 87 insertions(+), 98 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 8ff677e..5513843 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -440,8 +440,8 @@ class bounded_bytes { : view_(input_bytes) {} /** The bytes, as the `std::span` a codec takes. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // it is a view of a span + // A view converts to the span it holds, which is its purpose. + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::span() const noexcept { return view_; } /** The number of bytes. */ @@ -468,8 +468,8 @@ class bounded_text { : view_(text_characters) {} /** The characters, as the `std::string_view` a codec takes. */ - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // it is a view of a string view + // A view converts to the string view it holds, which is its purpose. + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) constexpr operator std::string_view() const noexcept { return view_; } /** The number of characters. */ diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 6d09d8a..58512dd 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -330,7 +330,7 @@ inline constexpr bool decode_is_fixed = place and the codec's functions are (ruling R3). */ template -constexpr bool typed_decode_is_noexcept() noexcept { +constexpr bool typed_decode_is_noexcept() { if constexpr (value_decodable) { using value_type = value_codec; if constexpr (value_type::output == output_kind::bytes && byte_input) { diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index d7a7dd1..62b8046 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -151,7 +151,8 @@ struct over { @param other The chain to take. @return This chain. */ - constexpr over& operator=(over&& other) { + constexpr over& operator=(over&& other) noexcept(std::is_nothrow_move_assignable_v && + std::is_nothrow_move_assignable_v) { if (this != &other) { outer = std::move(other.outer); inner = std::move(other.inner); @@ -360,8 +361,9 @@ template std::size_t count) noexcept { std::span const written = intermediate.bytes(); // A byte is read through a char, which may alias any object. - return intermediate_text{std::string_view{reinterpret_cast(written.data()), - std::min(count, written.size())}}; + auto const* const first_character = reinterpret_cast(written.data()); + return intermediate_text{ + std::string_view{first_character, std::min(count, written.size())}}; } /** The intermediate's bytes as the characters the first link of an encode writes. */ @@ -378,7 +380,7 @@ template exactly then (ruling R3). */ template -[[nodiscard]] constexpr bool over_encode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool over_encode_is_noexcept() { constexpr std::size_t middle_bound = encoded_bound>(); using middle_view = intermediate_bytes; return middle_bound != std::dynamic_extent && @@ -390,7 +392,7 @@ template /** Whether a decode of `View` through `Outer` over `Inner` cannot throw, as for an encode. */ template -[[nodiscard]] constexpr bool over_decode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool over_decode_is_noexcept() { constexpr std::size_t middle_bound = decoded_bound>(); using middle_view = intermediate_text; return middle_bound != std::dynamic_extent && @@ -466,8 +468,8 @@ template (middle_size.unsafe_value())) { return error::input_too_long; } - over_intermediate middle{middle_size.unsafe_value(), - chain.allocator}; + std::size_t const middle_count = middle_size.unsafe_value(); + over_intermediate middle{middle_count, chain.allocator}; result const written = codec_decode(chain.outer, text_characters, middle.bytes()); if (!written) { @@ -493,8 +495,8 @@ template (middle_size.unsafe_value())) { return error::input_too_long; } - over_intermediate middle{middle_size.unsafe_value(), - chain.allocator}; + std::size_t const middle_count = middle_size.unsafe_value(); + over_intermediate middle{middle_count, chain.allocator}; result const written = codec_decode(chain.outer, text_characters, middle.bytes()); if (!written) { @@ -717,7 +719,7 @@ inline constexpr bool over_value_is_secret = calls cannot throw and the intermediate is in place. */ template -[[nodiscard]] constexpr bool over_value_encode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool over_value_encode_is_noexcept() { using inner_codec = value_codec; constexpr std::size_t middle_bound = inner_value_bound(); using middle_view = intermediate_bytes; @@ -733,7 +735,7 @@ template /** Whether a decode of `View` into a `Value` through `Outer` over `Inner` cannot throw. */ template -[[nodiscard]] constexpr bool over_value_decode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool over_value_decode_is_noexcept() { using inner_codec = value_codec; constexpr std::size_t middle_bound = decoded_bound>(); using middle_view = @@ -824,8 +826,8 @@ over_value_decode(over const& chain, View text_characte if (past_bound(middle_size.unsafe_value())) { return error::input_too_long; } - over_intermediate middle{middle_size.unsafe_value(), - chain.allocator}; + std::size_t const middle_count = middle_size.unsafe_value(); + over_intermediate middle{middle_count, chain.allocator}; result const written = codec_decode(chain.outer, text_characters, middle.bytes()); if (!written) { diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 57f5aba..7e2353b 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -202,8 +202,8 @@ struct secret_tag { struct any_argument { /** Converts to any type, a reference to `const` included. */ template - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor): - // the probe's argument converts to anything + // The probe's argument converts to anything, which is its purpose. + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) operator T() const noexcept; }; @@ -305,7 +305,7 @@ constexpr void check_secret_overloads() noexcept { the one that is not (ruling R3). */ template -[[nodiscard]] constexpr bool codec_encoded_size_is_noexcept() noexcept { +[[nodiscard]] constexpr bool codec_encoded_size_is_noexcept() { if constexpr (Secret && has_secret_encoded_size) { return noexcept( codec::encoded_size(secret_tag{}, std::declval(), std::declval())); @@ -316,7 +316,7 @@ template /** Whether the call @ref codec_decoded_size makes cannot throw, as for @ref codec_encoded_size. */ template -[[nodiscard]] constexpr bool codec_decoded_size_is_noexcept() noexcept { +[[nodiscard]] constexpr bool codec_decoded_size_is_noexcept() { if constexpr (Secret && has_secret_decoded_size) { return noexcept( codec::decoded_size(secret_tag{}, std::declval(), std::declval())); @@ -327,7 +327,7 @@ template /** Whether the call @ref codec_encode makes cannot throw, as for @ref codec_encoded_size. */ template -[[nodiscard]] constexpr bool codec_encode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool codec_encode_is_noexcept() { if constexpr (Secret && has_secret_encode) { return noexcept(codec::encode(secret_tag{}, std::declval(), std::declval(), std::declval>())); @@ -339,7 +339,7 @@ template /** Whether the call @ref codec_decode makes cannot throw, as for @ref codec_encoded_size. */ template -[[nodiscard]] constexpr bool codec_decode_is_noexcept() noexcept { +[[nodiscard]] constexpr bool codec_decode_is_noexcept() { if constexpr (Secret && has_secret_decode) { return noexcept(codec::decode(secret_tag{}, std::declval(), std::declval(), diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index 2a88ae7..55bcb04 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -87,7 +87,7 @@ template @tparam Secret Whether the operation is secret. */ template -[[nodiscard]] constexpr bool encode_calls_are_noexcept() noexcept { +[[nodiscard]] constexpr bool encode_calls_are_noexcept() { using input_type = std::remove_cvref_t; if constexpr (value_encodable) { using value_type = value_codec; @@ -114,7 +114,7 @@ template @tparam Secret Whether the operation is secret. */ template -[[nodiscard]] constexpr bool decode_calls_are_noexcept() noexcept { +[[nodiscard]] constexpr bool decode_calls_are_noexcept() { if constexpr (has_codec) { using view_type = text_view_t>; return codec_decoded_size_is_noexcept() && diff --git a/include/webcpp/codecs/detail/core/tokens.hpp b/include/webcpp/codecs/detail/core/tokens.hpp index 290e712..c36ca38 100644 --- a/include/webcpp/codecs/detail/core/tokens.hpp +++ b/include/webcpp/codecs/detail/core/tokens.hpp @@ -277,8 +277,10 @@ class assigning_token { wiped when `Wiped`: it belonged to the old target's operation; `other` keeps its own. */ assigning_token& operator=(assigning_token const& other) noexcept { - target_ = other.target_; - release_scratch(); + if (this != &other) { + target_ = other.target_; + release_scratch(); + } return *this; } @@ -290,8 +292,10 @@ class assigning_token { /** A move assignment takes the target alone, as the copy assignment does. */ assigning_token& operator=(assigning_token&& other) noexcept { - target_ = other.target_; - release_scratch(); + if (this != &other) { + target_ = other.target_; + release_scratch(); + } return *this; } diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index c470ea1..fcee4a6 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -406,76 +406,58 @@ void a_secret_assign_to_wipes_its_scratch_when_the_target_throws() { BOOST_TEST_EQ(attempts, 2U); } +/** Runs `operation`, which is given a chain of letters over letters whose allocator throws on its + `fail_at`th allocation, for every `fail_at` until it does not: an exception reaches the caller + from the first and the second allocation (the exact size's intermediate and the operation's), + every buffer is given back, and on a secret chain every one reads zero. */ +template +void for_each_failing_allocation(bool secret, Operation operation) { + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + bool thrown = false; + try { + operation(chain); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (secret) { + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); +} + void an_over_throws_through_and_wipes_when_secret() { // over's heap intermediate (Task 7): the exact size's intermediate is the first allocation and - // the encode's the second; an exception of either reaches the caller, and on a secret chain - // every buffer the allocator was given back reads zero. + // the operation's the second; on a secret chain every buffer the allocator was given back + // reads zero. std::vector const input(input_size, 0x5a); std::string const inner_text = codecs::encode(test::letters, input, tokens::return_string).value(); std::string const expected = codecs::encode(test::letters, inner_text, tokens::return_string).value(); - for (bool const secret : {false, true}) { - std::size_t attempts = 0; - for (std::size_t fail_at = 1;; ++fail_at) { - test::throwing_allocator const allocator{fail_at}; - auto const chain = codecs::over{test::letters, test::letters, allocator}; - bool thrown = false; - try { - if (secret) { - auto const encoded = codecs::encode(chain, input, tokens::secret); - BOOST_TEST(encoded.value().view() == expected); - } else { - auto const encoded = codecs::encode(chain, input); - BOOST_TEST(encoded.value() == expected); - } - } catch (std::bad_alloc const&) { - thrown = true; - } - if (secret) { - BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); - } - BOOST_TEST_EQ(allocator.state()->deallocations, - allocator.allocations() - (thrown ? 1 : 0)); - if (!thrown) { - BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); - break; - } - ++attempts; - } - BOOST_TEST_EQ(attempts, 2U); - } - // The decode: the outer link's intermediate, for the size and for the decode. - for (bool const secret : {false, true}) { - std::size_t attempts = 0; - for (std::size_t fail_at = 1;; ++fail_at) { - test::throwing_allocator const allocator{fail_at}; - auto const chain = codecs::over{test::letters, test::letters, allocator}; - bool thrown = false; - try { - if (secret) { - auto const decoded = codecs::decode(chain, expected, tokens::secret); - BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); - } else { - auto const decoded = codecs::decode(chain, expected); - BOOST_TEST((decoded.value() == input)); - } - } catch (std::bad_alloc const&) { - thrown = true; - } - if (secret) { - BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); - } - BOOST_TEST_EQ(allocator.state()->deallocations, - allocator.allocations() - (thrown ? 1 : 0)); - if (!thrown) { - BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); - break; - } - ++attempts; - } - BOOST_TEST_EQ(attempts, 2U); - } + for_each_failing_allocation(false, [&](auto const& chain) { + BOOST_TEST(codecs::encode(chain, input).value() == expected); + }); + for_each_failing_allocation(true, [&](auto const& chain) { + auto const encoded = codecs::encode(chain, input, tokens::secret); + BOOST_TEST(encoded.value().view() == expected); + }); + for_each_failing_allocation(false, [&](auto const& chain) { + BOOST_TEST((codecs::decode(chain, expected).value() == input)); + }); + for_each_failing_allocation(true, [&](auto const& chain) { + auto const decoded = codecs::decode(chain, expected, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + }); // The buffer form allocates, too (finding F17), and the exception reaches the caller. test::throwing_allocator const allocator{1}; auto const chain = codecs::over{test::letters, test::letters, allocator}; diff --git a/test/over_test.cpp b/test/over_test.cpp index 510b3af..e5f65db 100644 --- a/test/over_test.cpp +++ b/test/over_test.cpp @@ -150,7 +150,7 @@ std::string letters_of_letters(std::span bytes_value) { // The name, joined in a static array, and the format's own requirements. constexpr auto letters_over_letters = codecs::over{test::letters, test::letters}; static_assert(codecs::format>); -static_assert(letters_over_letters.name == "letters over letters"); +static_assert(std::remove_cv_t::name == "letters over letters"); static_assert(codecs::over::name == "letters over be16"); static_assert(codecs::over>::name == "letters over letters over be16"); @@ -366,7 +366,7 @@ void the_bounds_and_the_refusals() { void a_chain_of_chains() { constexpr auto three = codecs::over{test::letters, codecs::over{test::letters, test::letters}}; - static_assert(three.name == "letters over letters over letters"); + static_assert(std::remove_cv_t::name == "letters over letters over letters"); auto const input = bytes_16(); auto const encoded = codecs::encode(three, input); static_assert(std::is_same_v> const>); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index a405985..a9c102c 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -647,15 +647,16 @@ void an_assigning_tokens_copy_and_move_take_the_target_alone() { wiping_token const copied{prepared}; wiping_token copy_assigned{target}; copy_assigned = prepared; - // NOLINTNEXTLINE(bugprone-use-after-move): the source of a move keeps its scratch, which - // is what the test pins + // The source of a move keeps its scratch, which is what the test pins. + // NOLINTBEGIN(bugprone-use-after-move) wiping_token const moved{std::move(prepared)}; wiping_token move_assigned{target}; move_assigned = std::move(prepared); + // NOLINTEND(bugprone-use-after-move) } BOOST_TEST_EQ(test::wipes.count, 0U); // The scratch is still the original's: its result is the text it holds, once. - // NOLINTNEXTLINE(bugprone-use-after-move): see above + // NOLINTNEXTLINE(bugprone-use-after-move) BOOST_TEST_EQ(prepared.result().size(), 40U); BOOST_TEST_EQ(test::wipes.count, 1U); BOOST_TEST(target == std::string(40, 'x')); From 34e334c4bb80ccb90293d3cf412cef8832b1858c Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:19:03 -0300 Subject: [PATCH 036/157] codecs: MSVC checkpoint 1 fixes: parameters that hid a program's globals (C4459), the debug proxy of the assign_to scratch counted --- include/webcpp/codecs/detail/core/contract.hpp | 12 ++++++------ include/webcpp/codecs/detail/core/over.hpp | 12 ++++++------ test/allocation_test.cpp | 10 +++++++--- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 5513843..58fc5e2 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -435,9 +435,9 @@ class bounded_bytes { /** The most bytes, known at compile time. */ static constexpr std::size_t bound = Bound; - /** Views `input_bytes`, which the caller knows to hold at most `Bound` bytes. */ - explicit constexpr bounded_bytes(std::span input_bytes) noexcept - : view_(input_bytes) {} + /** Views `viewed_bytes`, which the caller knows to hold at most `Bound` bytes. */ + explicit constexpr bounded_bytes(std::span viewed_bytes) noexcept + : view_(viewed_bytes) {} /** The bytes, as the `std::span` a codec takes. */ // A view converts to the span it holds, which is its purpose. @@ -463,9 +463,9 @@ class bounded_text { /** The most characters, known at compile time. */ static constexpr std::size_t bound = Bound; - /** Views `text_characters`, which the caller knows to hold at most `Bound` characters. */ - explicit constexpr bounded_text(std::string_view text_characters) noexcept - : view_(text_characters) {} + /** Views `viewed_characters`, which the caller knows to hold at most `Bound` characters. */ + explicit constexpr bounded_text(std::string_view viewed_characters) noexcept + : view_(viewed_characters) {} /** The characters, as the `std::string_view` a codec takes. */ // A view converts to the string view it holds, which is its purpose. diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 62b8046..a48d445 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -534,11 +534,11 @@ struct codec> { /** The outer link's bound on the inner link's, saturated at `SIZE_MAX`. - @param input_size The bytes of the input. + @param input_byte_count The bytes of the input. @return The bound on the text, `SIZE_MAX` when it does not fit. */ - static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { - std::size_t const middle_size = codec::max_encoded_size(input_size); + static constexpr std::size_t max_encoded_size(std::size_t input_byte_count) noexcept { + std::size_t const middle_size = codec::max_encoded_size(input_byte_count); return middle_size == std::numeric_limits::max() ? middle_size : codec::max_encoded_size(middle_size); @@ -547,11 +547,11 @@ struct codec> { /** The inner link's bound on the outer link's, saturated at `SIZE_MAX`. - @param text_size The characters of the text. + @param text_character_count The characters of the text. @return The bound on the bytes, `SIZE_MAX` when it does not fit. */ - static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { - std::size_t const middle_size = codec::max_decoded_size(text_size); + static constexpr std::size_t max_decoded_size(std::size_t text_character_count) noexcept { + std::size_t const middle_size = codec::max_decoded_size(text_character_count); return middle_size == std::numeric_limits::max() ? middle_size : codec::max_decoded_size(middle_size); diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 00e6ae6..b08c18f 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -13,6 +13,7 @@ #include "support/counting.hpp" #include "support/be16.hpp" +#include "support/bookkeeping.hpp" #include "support/letters.hpp" #include "support/saturating.hpp" @@ -416,6 +417,9 @@ void check_assign_to_scratch() { std::vector byte_target; byte_target.reserve(8192); std::uint8_t const* const byte_buffer = byte_target.data(); + // The scratch container's own bookkeeping block (support/bookkeeping.hpp) is one more where + // the standard library allocates one: the MSVC STL's debug proxy. + std::size_t const one_scratch = test::bookkeeping().bytes != 0 ? 2U : 1U; bool volatile verdict = false; expect_no_allocation("assign_to of a static bound of 4096, in place", [&] { verdict = @@ -433,7 +437,7 @@ void check_assign_to_scratch() { codecs::tokens::assign_to(text_target)) .has_value(); }), - 1U); + one_scratch); BOOST_TEST(verdict); BOOST_TEST_EQ(text_target.size(), 4098U); BOOST_TEST_EQ(allocations_of([&] { @@ -441,7 +445,7 @@ void check_assign_to_scratch() { codecs::tokens::assign_to(byte_target)) .has_value(); }), - 1U); + one_scratch); BOOST_TEST(verdict); BOOST_TEST_EQ(byte_target.size(), 4097U); BOOST_TEST_EQ(allocations_of([&] { @@ -449,7 +453,7 @@ void check_assign_to_scratch() { codecs::tokens::assign_to(text_target)) .has_value(); }), - 1U); + one_scratch); BOOST_TEST(verdict); BOOST_TEST_EQ(text_target.size(), 200U); // Each time the target kept its buffer. From 36575c5ede2775679a1cfc27fc39adbbc417908e Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:22:17 -0300 Subject: [PATCH 037/157] codecs: over lint fix --- include/webcpp/codecs/detail/core/operations.hpp | 4 ++-- include/webcpp/codecs/detail/core/over.hpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 58512dd..90eb42b 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -645,7 +645,7 @@ template /** Whether an encode of `Input` in `F` into `Token`, as it was passed, cannot throw. */ template -constexpr bool encode_token_is_noexcept() noexcept { +constexpr bool encode_token_is_noexcept() { using tag_type = std::remove_cvref_t; if constexpr (std::same_as) { return is_fixed_result> && @@ -662,7 +662,7 @@ constexpr bool encode_token_is_noexcept() noexcept { /** Whether a decode in `F` into `Token`, as it was passed, cannot throw. */ template -constexpr bool decode_token_is_noexcept() noexcept { +constexpr bool decode_token_is_noexcept() { using tag_type = std::remove_cvref_t; if constexpr (std::same_as) { return is_fixed_result> && diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index a48d445..660c436 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -362,8 +362,8 @@ template std::span const written = intermediate.bytes(); // A byte is read through a char, which may alias any object. auto const* const first_character = reinterpret_cast(written.data()); - return intermediate_text{ - std::string_view{first_character, std::min(count, written.size())}}; + std::string_view const characters{first_character, std::min(count, written.size())}; + return intermediate_text{characters}; } /** The intermediate's bytes as the characters the first link of an encode writes. */ From c51bd5b19e4f8b7b0f693ee27841a13046ed170b Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:35:34 -0300 Subject: [PATCH 038/157] codecs: over lint fix --- include/webcpp/codecs/detail/core/contract.hpp | 6 +++--- include/webcpp/codecs/detail/core/over.hpp | 7 +++---- test/allocator_test.cpp | 3 ++- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 58fc5e2..4467557 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -421,7 +421,7 @@ constexpr void refuse_allocator() noexcept { /** The bytes of an input whose size is known at compile time to be at most `Bound` - (@ref static_input_size_v): a view that converts to the `std::span` every codec takes, and a type + (see `static_input_size_v`), a view that converts to the `std::span` every codec takes, and a type a codec that holds an intermediate of that size in place (`over`) reads the bound from. The core gives a codec this type when the input's type states a bound, and a plain `std::span` otherwise. It is no range, so that the conversion to a `std::span` is its own, `noexcept`, and not the @@ -483,11 +483,11 @@ class bounded_text { template inline constexpr std::size_t view_bound_v = std::dynamic_extent; -/** A @ref bounded_bytes: its bound. */ +/** The bound of a `bounded_bytes`. */ template inline constexpr std::size_t view_bound_v> = Bound; -/** A @ref bounded_text: its bound. */ +/** The bound of a `bounded_text`. */ template inline constexpr std::size_t view_bound_v> = Bound; diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 660c436..cd22ca6 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -116,10 +116,9 @@ struct over { @param inner_link The inner link. @param allocator_value The allocator of the heap intermediate. */ - constexpr over(Outer outer_link, Inner inner_link, Allocator allocator_value = Allocator{}) - : outer(std::move(outer_link)), - inner(std::move(inner_link)), - allocator(std::move(allocator_value)) {} + constexpr over(Outer outer_link, Inner inner_link, + Allocator const& allocator_value = Allocator{}) + : outer(std::move(outer_link)), inner(std::move(inner_link)), allocator(allocator_value) {} /** A copy of a chain: the links and the allocator. */ constexpr over(over const&) = default; diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index a47b107..20828f0 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -358,7 +358,8 @@ void a_secret_over_gives_its_intermediates_back_wiped() { expect_no_global_allocation("a secret over over an arena, encode", [&] { auto const encoded = codecs::encode(chain, input, tokens::secret(char_allocator)); BOOST_TEST(encoded.has_value()); - BOOST_TEST_EQ(encoded.value().view().size(), 160U); + auto const& secret_text = encoded.value(); + BOOST_TEST_EQ(secret_text.view().size(), 160U); }); // The exact size's intermediate, the encode's, and the secret text. BOOST_TEST_EQ(arena.allocation_count(), 3U); From bf761b3ebc82cf203cd191845523d48825663eed Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 14:36:14 -0300 Subject: [PATCH 039/157] codecs: over lint fix --- include/webcpp/codecs/detail/core/over.hpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index cd22ca6..9c75b9a 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -116,10 +116,15 @@ struct over { @param inner_link The inner link. @param allocator_value The allocator of the heap intermediate. */ + // The allocator is taken by reference to const and copied, as the standard containers take + // it: an allocator's copy cannot throw, and is cheap. + // NOLINTBEGIN(modernize-pass-by-value) constexpr over(Outer outer_link, Inner inner_link, Allocator const& allocator_value = Allocator{}) : outer(std::move(outer_link)), inner(std::move(inner_link)), allocator(allocator_value) {} + // NOLINTEND(modernize-pass-by-value) + /** A copy of a chain: the links and the allocator. */ constexpr over(over const&) = default; From e0d39b59b5e465a18c7deaf0df86790f88cb7b5d Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:00:10 -0300 Subject: [PATCH 040/157] codecs: a value codec's secret_tag overloads run in every secret operation (R7), so that over's value codec made secret by its token wipes its intermediate and runs both links' secret arithmetic; over's stack cost and its format constraint stated, the garbled comment of its test fixed --- .../webcpp/codecs/detail/core/operations.hpp | 77 +++--- include/webcpp/codecs/detail/core/over.hpp | 98 +++++--- include/webcpp/codecs/detail/core/secrecy.hpp | 175 +++++++++++++- include/webcpp/codecs/detail/core/sizes.hpp | 19 +- test/Jamfile | 6 +- test/messages/Jamfile | 1 + .../refused_secret_value_overload/Jamfile | 16 ++ .../refused_secret_value_overload.cpp | 74 ++++++ test/noexcept_test.cpp | 11 + test/over_test.cpp | 79 +++++- test/secret_operation_test.cpp | 228 +++++++++++++++++- 11 files changed, 694 insertions(+), 90 deletions(-) create mode 100644 test/messages/refused_secret_value_overload/Jamfile create mode 100644 test/messages/refused_secret_value_overload/refused_secret_value_overload.cpp diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 90eb42b..32f7c21 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -272,7 +272,7 @@ template }(); std::size_t output_size = 0; if constexpr (value_encodable) { - output_size = value_codec::encoded_size(format_value, input_value); + output_size = value_encoded_size(format_value, input_value); } else { if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; @@ -294,7 +294,7 @@ template }; result written_size = std::size_t{0}; if constexpr (value_encodable) { - written_size = value_codec::encode(format_value, input_value, output_span()); + written_size = value_encode(format_value, input_value, output_span()); } else { written_size = codec_encode(format_value, input_view, output_span()); } @@ -331,21 +331,19 @@ inline constexpr bool decode_is_fixed = */ template constexpr bool typed_decode_is_noexcept() { + constexpr bool secret = secret_operation_v; if constexpr (value_decodable) { using value_type = value_codec; if constexpr (value_type::output == output_kind::bytes && byte_input) { - return noexcept( - value_type::decode(std::declval(), std::declval>())); + return value_decode_is_noexcept>(); } else if constexpr (value_type::output == output_kind::text && text_input) { - return noexcept( - value_type::decode(std::declval(), std::declval>())); + return value_decode_is_noexcept>(); } else { - return noexcept(value_type::decode(std::declval(), - std::declval>())); + return value_decode_is_noexcept>(); } } else { return has_codec && decode_is_fixed && - decode_calls_are_noexcept>(); + decode_calls_are_noexcept(); } } @@ -481,7 +479,7 @@ template }(); std::size_t output_size = 0; if constexpr (from_value) { - output_size = value_codec::encoded_size(format_value, input_value); + output_size = value_encoded_size(format_value, input_value); } else { if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; @@ -496,13 +494,12 @@ template auto* const prepared = token_object.prepare(output_size); result written_size = std::size_t{0}; if constexpr (from_value) { - using value_type = value_codec; - if constexpr (value_type::output == output_kind::bytes) { - written_size = - value_type::encode(format_value, input_value, - std::span{as_byte_pointer(prepared), output_size}); + if constexpr (value_codec::output == output_kind::bytes) { + written_size = value_encode( + format_value, input_value, + std::span{as_byte_pointer(prepared), output_size}); } else { - written_size = value_type::encode( + written_size = value_encode( format_value, input_value, std::span{as_char_pointer(prepared), output_size}); } } else { @@ -629,18 +626,18 @@ template /** Encodes `input_value`, a value of a value codec, into the caller's buffer: the exact size checked - against the buffer's, then the value codec's `encode` into the first elements. + against the buffer's, then the value codec's `encode` into the first elements; its secret + overloads when `Secret` and it has them (R7). */ -template +template [[nodiscard]] result encode_value_into_buffer( F const& format_value, Input const& input_value, - std::span output_buffer) noexcept(encode_calls_are_noexcept()) { - std::size_t const output_size = value_codec::encoded_size(format_value, input_value); + std::span output_buffer) noexcept(encode_calls_are_noexcept()) { + std::size_t const output_size = value_encoded_size(format_value, input_value); if (output_buffer.size() < output_size) { return error::output_too_small; } - return value_codec::encode(format_value, input_value, - output_buffer.first(output_size)); + return value_encode(format_value, input_value, output_buffer.first(output_size)); } /** Whether an encode of `Input` in `F` into `Token`, as it was passed, cannot throw. */ @@ -725,7 +722,8 @@ template the exact size is @ref error::output_too_small. The bytes are then written at the start of `output_buffer`, whose other bytes are unchanged. The errors the value codec returns reach the caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds secure's - timing guard while the value codec runs. + timing guard while the value codec runs, which runs its overloads that take `detail::secret_tag` + first where it has them (R7). @tparam F The format's type. @tparam Input The value's type, one `value_codec` encodes into bytes. @@ -740,12 +738,14 @@ template [[nodiscard]] result encode( F const& format_value, Input const& input_value, std::span - output_buffer) noexcept(detail::encode_calls_are_noexcept()) { + output_buffer) noexcept(detail::encode_calls_are_noexcept>()) { if constexpr (detail::secret_operation_v) { secure::timing_guard const timing_scope{true}; - return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } else { - return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } } @@ -757,7 +757,8 @@ template the exact size is @ref error::output_too_small. The text is then written at the start of `output_buffer`, whose other characters are unchanged. The errors the value codec returns reach the caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds - secure's timing guard while the value codec runs. + secure's timing guard while the value codec runs, which runs its overloads that take + `detail::secret_tag` first where it has them (R7). @tparam F The format's type. @tparam Input The value's type, one `value_codec` encodes into text. @@ -769,14 +770,14 @@ template template requires(detail::value_encodable && value_codec::output == output_kind::text) -[[nodiscard]] result encode( - F const& format_value, Input const& input_value, - std::span output_buffer) noexcept(detail::encode_calls_are_noexcept()) { +[[nodiscard]] result +encode(F const& format_value, Input const& input_value, std::span output_buffer) noexcept( + detail::encode_calls_are_noexcept>()) { if constexpr (detail::secret_operation_v) { secure::timing_guard const timing_scope{true}; - return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } else { - return detail::encode_value_into_buffer(format_value, input_value, output_buffer); + return detail::encode_value_into_buffer(format_value, input_value, output_buffer); } } @@ -984,16 +985,20 @@ template if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { if constexpr (secret) { secure::timing_guard const timing_scope{true}; - return value_type::decode(format_value, detail::bounded_input_bytes(input_value)); + return detail::value_decode(format_value, + detail::bounded_input_bytes(input_value)); } else { - return value_type::decode(format_value, detail::bounded_input_bytes(input_value)); + return detail::value_decode(format_value, + detail::bounded_input_bytes(input_value)); } } else if constexpr (value_type::output == output_kind::text && detail::text_input) { if constexpr (secret) { secure::timing_guard const timing_scope{true}; - return value_type::decode(format_value, detail::bounded_text_view(input_value)); + return detail::value_decode(format_value, + detail::bounded_text_view(input_value)); } else { - return value_type::decode(format_value, detail::bounded_text_view(input_value)); + return detail::value_decode(format_value, + detail::bounded_text_view(input_value)); } } else { // The pair converts; this input is not what the value codec reads. diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 9c75b9a..9f34ab1 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -75,7 +75,9 @@ struct over_name { `outer`, decoding decodes with `outer` and then decodes that output with `inner`. `Outer` is a format with a `codec` (text feeds it as bytes); `Inner` is a format with a `codec`, - or one a `value_codec` converts a value in. `over` is a format whose `name` is the name of the + or one a `value_codec` converts a value in. Both are constrained by the concept `format`: a value + codec's format is copyable and has a `name` as every format has. `over` is a format whose `name` + is the name of the outer link, then the characters " over ", then the name of the inner link, and class template argument deduction builds it from the two links, with or without the allocator as a third argument. A chain is constant time when both links are, and secret when any link's operation is: @@ -93,6 +95,15 @@ struct over_name { and with a bound known at compile time they are `noexcept` and allocate nothing. `over` stays one-shot: its stream counterpart is `pipe`. + An intermediate in place is held for every bound known at compile time, with no cap, so that + `over` with a static bound allocates nothing, as the spec's Allocation requirement says. Its cost + is the stack: an array of the middle bound (the inner link's bound on the input's size for an + encode, the outer link's bound on the text's size for a decode) in the frame of each of `over`'s + functions, one for each level of a chain of chains. A caller with a large input of a static size + who wants the intermediate on the heap passes it as a view of a dynamic extent + (`std::span`, `std::string_view`), whose intermediate comes from `allocator`; + the allocator of a result or a token is not the intermediate's. + @tparam Outer The format that writes the final text and reads it first. @tparam Inner The format whose bytes the outer link encodes and decodes. @tparam Allocator The allocator of the heap intermediate. @@ -712,7 +723,8 @@ template } /** - Whether a chain of values of `Value` over `Inner` is secret: the value is, or its link says so. + Whether a chain of values of `Value` over `Inner` is secret of its own: the value is, or its link + says so. An operation made secret by its token calls the overloads that take `secret_tag` instead. */ template inline constexpr bool over_value_is_secret = @@ -724,15 +736,11 @@ inline constexpr bool over_value_is_secret = */ template [[nodiscard]] constexpr bool over_value_encode_is_noexcept() { - using inner_codec = value_codec; constexpr std::size_t middle_bound = inner_value_bound(); using middle_view = intermediate_bytes; - using inner_output = value_output_span; return middle_bound != std::dynamic_extent && - noexcept(inner_codec::encoded_size(std::declval(), - std::declval())) && - noexcept(inner_codec::encode(std::declval(), std::declval(), - std::declval())) && + value_encoded_size_is_noexcept() && + value_encode_is_noexcept() && codec_encoded_size_is_noexcept() && codec_encode_is_noexcept(); } @@ -748,22 +756,21 @@ template return middle_bound != std::dynamic_extent && codec_decoded_size_is_noexcept() && codec_decode_is_noexcept() && - noexcept(inner_codec::decode(std::declval(), std::declval())); + value_decode_is_noexcept(); } -/** Runs the value codec of `Inner` into `middle`, as the span its output kind writes. */ -template +/** + Runs the value codec of `Inner` into `middle`, as the span its output kind writes: its secret + overload when `Secret` and it has one (R7). +*/ +template [[nodiscard]] result encode_value_into( Inner const& inner_format, Value const& held_value, - Intermediate& - middle) noexcept(noexcept(value_codec:: - encode(inner_format, held_value, - std::declval>()))) { + Intermediate& middle) noexcept(value_encode_is_noexcept()) { if constexpr (value_codec::output == output_kind::bytes) { - return value_codec::encode(inner_format, held_value, middle.bytes()); + return value_encode(inner_format, held_value, middle.bytes()); } else { - return value_codec::encode(inner_format, held_value, - intermediate_characters(middle)); + return value_encode(inner_format, held_value, intermediate_characters(middle)); } } @@ -774,13 +781,12 @@ template Value const& held_value) noexcept(over_value_encode_is_noexcept()) { constexpr std::size_t middle_bound = inner_value_bound(); - std::size_t const middle_size = - value_codec::encoded_size(chain.inner, held_value); + std::size_t const middle_size = value_encoded_size(chain.inner, held_value); if (past_bound(middle_size)) { return std::numeric_limits::max(); } over_intermediate middle{middle_size, chain.allocator}; - result const written = encode_value_into(chain.inner, held_value, middle); + result const written = encode_value_into(chain.inner, held_value, middle); if (!written) { return codec::max_encoded_size(middle_size); } @@ -796,13 +802,12 @@ template std::span output_characters) noexcept(over_value_encode_is_noexcept()) { constexpr std::size_t middle_bound = inner_value_bound(); - std::size_t const middle_size = - value_codec::encoded_size(chain.inner, held_value); + std::size_t const middle_size = value_encoded_size(chain.inner, held_value); if (past_bound(middle_size)) { return error::input_too_long; } over_intermediate middle{middle_size, chain.allocator}; - result const written = encode_value_into(chain.inner, held_value, middle); + result const written = encode_value_into(chain.inner, held_value, middle); if (!written) { return written; } @@ -819,7 +824,6 @@ template over_value_decode(over const& chain, View text_characters) noexcept( over_value_decode_is_noexcept()) { - using inner_codec = value_codec; constexpr std::size_t middle_bound = decoded_bound>(); result const middle_size = codec_decoded_size(chain.outer, text_characters); @@ -837,12 +841,12 @@ over_value_decode(over const& chain, View text_characte if (!written) { return written.error(); } - if constexpr (inner_codec::output == output_kind::bytes) { - return inner_codec::decode(chain.inner, - next_bytes(middle, written.unsafe_value())); + if constexpr (value_codec::output == output_kind::bytes) { + return value_decode( + chain.inner, next_bytes(middle, written.unsafe_value())); } else { - return inner_codec::decode(chain.inner, - next_text(middle, written.unsafe_value())); + return value_decode(chain.inner, + next_text(middle, written.unsafe_value())); } } @@ -886,6 +890,25 @@ struct over_value_encoding { return over_value_encode>(chain, held_value, output_characters); } + + /** + The exact size of the text of `held_value` in a secret operation, also one made secret by its + token alone: the intermediate wiped, both links' secret overloads run (R7). + */ + [[nodiscard]] static std::size_t encoded_size( + secret_tag /*secret*/, over const& chain, + Value const& + held_value) noexcept(over_value_encode_is_noexcept()) { + return over_value_encoded_size(chain, held_value); + } + + /** Writes the text of `held_value` into `output_characters` in a secret operation. */ + [[nodiscard]] static result encode( + secret_tag /*secret*/, over const& chain, Value const& held_value, + std::span output_characters) noexcept(over_value_encode_is_noexcept()) { + return over_value_encode(chain, held_value, output_characters); + } }; /** The decoding half of a chain's value codec, which exists when the inner value codec decodes. */ @@ -905,6 +928,15 @@ struct over_value_decoding { return over_value_decode, Outer, Inner, Allocator, Value>(chain, text_characters); } + + /** The value `text_characters` decodes to, in a secret operation: the intermediate wiped. */ + template + [[nodiscard]] static result decode( + secret_tag /*secret*/, over const& chain, + View text_characters) noexcept(over_value_decode_is_noexcept()) { + return over_value_decode(chain, text_characters); + } }; } // namespace detail @@ -918,8 +950,10 @@ struct over_value_decoding { reads that. Its encoding is text. It states `max_encoded_size` when the inner value codec does and the outer link's bound on it fits, so that the default result is in place, and it is secret when the value is (`is_secret_v`) or the inner value codec says so, which wipes the intermediate - and runs the outer link's secret arithmetic. Its functions are `noexcept` exactly when the - intermediate is in place (ruling R3), as `codec>`'s are. + and runs both links' secret arithmetic. Its overloads that take `detail::secret_tag` first do the + same, and the core calls them in every secret operation (ruling R7), one made secret by its token + alone (`tokens::secret`, a token whose `secret` is true) included. Its functions are `noexcept` + exactly when the intermediate is in place (ruling R3), as `codec>`'s are. @tparam Outer The outer link's type. @tparam Inner The inner link's type. diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 7e2353b..0ca13ab 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -7,7 +7,8 @@ /** The secrecy of webcpp::codecs (D10): the trait `is_secret`, its specializations for secure's `secret` and codecs' secret results, `secure::secret` as the target of a typed decode, when - an operation is secret, and the core's call of a format's secret arithmetic (ruling R7). + an operation is secret, and the core's call of the secret arithmetic of a format's codec or value + codec (ruling R7). */ #ifndef WEBCPP_CODECS_DETAIL_CORE_SECRECY_HPP #define WEBCPP_CODECS_DETAIL_CORE_SECRECY_HPP @@ -188,7 +189,11 @@ inline constexpr bool secret_operation_v = when the operation is secret (ruling R7): base58's, whose public arithmetic exits early. The core calls such an overload of `encoded_size`, `decoded_size`, `encode` or `decode` in a secret operation when it exists, and the format's function of D3 otherwise; an overload that returns - another type than the function without the tag stops the build. + another type than the function without the tag, or takes parameters the core's arguments do not + convert to, stops the build. A value codec's `encoded_size`, `encode` and `decode` take it alike: + its overloads run in an operation made secret by its token too (`tokens::secret`, a token whose + `secret` is true), where the value codec's own `secret` does not say so (`over`'s, which then + wipes its intermediate and runs its outer link's secret arithmetic). */ struct secret_tag { /** Constructed by name only, so that `{}` never stands for it. */ @@ -418,6 +423,172 @@ template } } +/** + Whether `value_codec` has an `encoded_size` of the arity of the core's call that takes + `secret_tag` first, of any parameters after it and any result, as for a codec's. +*/ +template +concept takes_secret_value_encoded_size = requires(F const& format_value) { + value_codec::encoded_size(secret_tag{}, format_value, any_argument{}); +}; + +/** Whether `value_codec` has an `encode` of that arity that takes `secret_tag` first. */ +template +concept takes_secret_value_encode = requires(F const& format_value) { + value_codec::encode(secret_tag{}, format_value, any_argument{}, any_argument{}); +}; + +/** Whether `value_codec` has a `decode` of that arity that takes `secret_tag` first. */ +template +concept takes_secret_value_decode = requires(F const& format_value) { + value_codec::decode(secret_tag{}, format_value, any_argument{}); +}; + +/** Whether `value_codec` has an `encoded_size` that takes `secret_tag` first, a size. */ +template +concept has_secret_value_encoded_size = requires(F const& format_value, V const& held_value) { + { + value_codec::encoded_size(secret_tag{}, format_value, held_value) + } -> std::same_as; +}; + +/** Whether `value_codec` has an `encode` that takes `secret_tag` first and gives a result. */ +template +concept has_secret_value_encode = + requires(F const& format_value, V const& held_value, value_output_span output_span) { + { + value_codec::encode(secret_tag{}, format_value, held_value, output_span) + } -> std::same_as>; + }; + +/** Whether `value_codec` has a `decode` that takes `secret_tag` first and gives a value. */ +template +concept has_secret_value_decode = + requires(F const& format_value, value_input_view input_view) { + { + value_codec::decode(secret_tag{}, format_value, input_view) + } -> std::same_as>; + }; + +/** + Whether every overload of `value_codec` that takes `secret_tag` first, whatever its + parameters, is one the core calls and returns what the function of its name without the tag + returns: the requirement of the check below. +*/ +template +inline constexpr bool secret_value_overloads_match = + (!takes_secret_value_encoded_size || has_secret_value_encoded_size) && + (!takes_secret_value_encode || has_secret_value_encode) && + (!takes_secret_value_decode || has_secret_value_decode); + +/** + Stops the build when an overload of `value_codec` that takes `secret_tag` first returns + another type than the function without the tag, or takes parameters the core's arguments do not + convert to, as @ref check_secret_overloads does for a codec (R7). +*/ +template +constexpr void check_secret_value_overloads() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::secret_value_overloads_match, + "webcpp::codecs: an overload of a value codec's encoded_size, encode or decode " + "that takes detail::secret_tag first takes the parameters of the function " + "without it and returns what it returns: std::size_t for encoded_size, " + "webcpp::codecs::result for encode, webcpp::codecs::result " + "for decode"); +} + +/** + Whether the call of `value_codec::encoded_size` that @ref value_encoded_size makes cannot + throw, as the value codec declares it. +*/ +template +[[nodiscard]] constexpr bool value_encoded_size_is_noexcept() { + if constexpr (Secret && has_secret_value_encoded_size) { + return noexcept(value_codec::encoded_size(secret_tag{}, std::declval(), + std::declval())); + } else { + return noexcept( + value_codec::encoded_size(std::declval(), std::declval())); + } +} + +/** Whether the call @ref value_encode makes cannot throw, as the value codec declares it. */ +template +[[nodiscard]] constexpr bool value_encode_is_noexcept() { + if constexpr (Secret && has_secret_value_encode) { + return noexcept(value_codec::encode(secret_tag{}, std::declval(), + std::declval(), + std::declval>())); + } else { + return noexcept(value_codec::encode(std::declval(), + std::declval(), + std::declval>())); + } +} + +/** + Whether the call @ref value_decode makes with a `View` cannot throw, as the value codec declares + it for that view. +*/ +template +[[nodiscard]] constexpr bool value_decode_is_noexcept() { + if constexpr (Secret && has_secret_value_decode) { + return noexcept(value_codec::decode(secret_tag{}, std::declval(), + std::declval())); + } else { + return noexcept(value_codec::decode(std::declval(), std::declval())); + } +} + +/** + The exact size of the encoding of `held_value`: the value codec's overload that takes + `secret_tag` first in a secret operation when it has one (R7, which value codecs share with + codecs), its `encoded_size` otherwise. +*/ +template +[[nodiscard]] constexpr std::size_t value_encoded_size( + F const& format_value, + V const& held_value) noexcept(value_encoded_size_is_noexcept()) { + check_secret_value_overloads(); + if constexpr (Secret && has_secret_value_encoded_size) { + return value_codec::encoded_size(secret_tag{}, format_value, held_value); + } else { + return value_codec::encoded_size(format_value, held_value); + } +} + +/** + Writes the encoding of `held_value` into `output_span`, the span of the value codec's `output`: + its secret overload in a secret operation when it has one (R7), its `encode` otherwise. +*/ +template +[[nodiscard]] constexpr result value_encode( + F const& format_value, V const& held_value, + value_output_span output_span) noexcept(value_encode_is_noexcept()) { + check_secret_value_overloads(); + if constexpr (Secret && has_secret_value_encode) { + return value_codec::encode(secret_tag{}, format_value, held_value, output_span); + } else { + return value_codec::encode(format_value, held_value, output_span); + } +} + +/** + The value `input_view` decodes to: the value codec's secret overload in a secret operation when it + has one (R7), its `decode` otherwise. `input_view` is the bytes or the characters as the core + gives them, a @ref bounded_bytes or a @ref bounded_text when their type states a bound. +*/ +template +[[nodiscard]] constexpr result value_decode(F const& format_value, View input_view) noexcept( + value_decode_is_noexcept()) { + check_secret_value_overloads(); + if constexpr (Secret && has_secret_value_decode) { + return value_codec::decode(secret_tag{}, format_value, input_view); + } else { + return value_codec::decode(format_value, input_view); + } +} + /** Wipes `wiped` by `secure::erase_secret` when it goes, when `Engaged`: the scope guard of a secret operation's temporary, which wipes it also when the operation returns early or an allocation diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index 55bcb04..e88d24d 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -78,9 +78,10 @@ template /** Whether the calls of a format's functions that an encode of `Input` in `F` makes cannot throw: - the value codec's `encoded_size` and `encode` as it declares them, or the codec's through the - core's dispatchers, which are `noexcept` for every codec but `over` with a heap intermediate - (ruling R3). A pair that is not encodable is refused elsewhere. + the value codec's `encoded_size` and `encode` as it declares them (its secret overloads when + `Secret` and it has them), or the codec's through the core's dispatchers, which are `noexcept` + for every codec but `over` with a heap intermediate (ruling R3). A pair that is not encodable is + refused elsewhere. @tparam F The format's type. @tparam Input The input's type. @@ -90,12 +91,8 @@ template [[nodiscard]] constexpr bool encode_calls_are_noexcept() { using input_type = std::remove_cvref_t; if constexpr (value_encodable) { - using value_type = value_codec; - return noexcept(value_type::encoded_size(std::declval(), - std::declval())) && - noexcept(value_type::encode(std::declval(), - std::declval(), - std::declval>())); + return value_encoded_size_is_noexcept() && + value_encode_is_noexcept(); } else if constexpr (byte_input && has_codec) { using view_type = input_view_t; return codec_encoded_size_is_noexcept() && @@ -134,7 +131,7 @@ template Input const& input_value) noexcept(encode_calls_are_noexcept()) { secure::timing_guard const timing_scope{true}; if constexpr (value_encodable) { - return value_codec::encoded_size(format_value, input_value); + return value_encoded_size(format_value, input_value); } else { return codec_encoded_size(format_value, bounded_input_bytes(input_value)); } @@ -190,7 +187,7 @@ encoded_size(F const& format_value, Input const& input_value) noexcept( } else if constexpr (detail::secret_operation_v) { return detail::secret_encoded_size(format_value, input_value); } else if constexpr (detail::value_encodable) { - return value_codec::encoded_size(format_value, input_value); + return detail::value_encoded_size(format_value, input_value); } else { return codec::encoded_size(format_value, detail::bounded_input_bytes(input_value)); } diff --git a/test/Jamfile b/test/Jamfile index b2247d1..6227246 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -60,9 +60,9 @@ codecs-run secret_fixed : secret_fixed_test.cpp codecs-run secret_heap : secret_heap_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # Secret operations (D10): by the value, the value codec, the token or the -# requested type; D9's secret column; a format's secret_tag overloads (R7); -# every temporary of the core wiped, as secure's wipe seam records it; the fixed -# secret forms allocate nothing. +# requested type; D9's secret column; the secret_tag overloads of a codec and +# of a value codec (R7); every temporary of the core wiped, as secure's wipe +# seam records it; the fixed secret forms allocate nothing. codecs-run secret_operation : secret_operation_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The timing guard of a secret operation: one guard of codecs' for each, none diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 8827489..a3c492b 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -22,3 +22,4 @@ build-project refused_token ; build-project refused_allocator ; build-project refused_secret_overload ; build-project refused_secret_parameters ; +build-project refused_secret_value_overload ; diff --git a/test/messages/refused_secret_value_overload/Jamfile b/test/messages/refused_secret_value_overload/Jamfile new file mode 100644 index 0000000..71f457c --- /dev/null +++ b/test/messages/refused_secret_value_overload/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_secret_value_overload : refused_secret_value_overload.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_secret_value_overload_refused : refused_secret_value_overload.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_secret_value_overload/refused_secret_value_overload.cpp b/test/messages/refused_secret_value_overload/refused_secret_value_overload.cpp new file mode 100644 index 0000000..3ea24cb --- /dev/null +++ b/test/messages/refused_secret_value_overload/refused_secret_value_overload.cpp @@ -0,0 +1,74 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec that offers an overload that takes detail::secret_tag first (ruling R7) but +// returns another type than the function without the tag (here encode's, a std::size_t for a +// result) stops the build in the core's check, whose requirement names the format's +// type and the value's: an operation made secret by its token never runs the public arithmetic in +// silence. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/secrecy.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::secret_value_overloads_match': webcpp::codecs: an overload of a value codec's encoded_size, encode or decode that takes detail::secret_tag first takes the parameters of the function without it and returns what it returns: std::size_t for encoded_size, webcpp::codecs::result for encode, webcpp::codecs::result for decode}} +// clang-format on + +#include + +#include +#include +#include +#include + +/** A format of a value codec whose secret encode returns a std::size_t. */ +struct mismatched_t { + /** The format's name. */ + static constexpr std::string_view name = "mismatched"; +}; + +/** The value: sixteen bits. */ +struct number { + /** The bits. */ + std::uint16_t value; +}; + +namespace webcpp::codecs { + +/** Two bytes, big endian, with a secret encode of the wrong return type. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Two bytes. */ + static std::size_t encoded_size(mismatched_t const& /*format*/, + number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static result encode(mismatched_t const& /*format*/, number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } + + /** The secret encode, of the wrong return type. */ + static std::size_t encode(detail::secret_tag /*secret*/, mismatched_t const& /*format*/, + number const& /*held_value*/, + std::span /*output_bytes*/) noexcept { + return 0; + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + auto const encoded = codecs::encode(mismatched_t{}, number{0x1234}, codecs::tokens::secret); + return encoded.has_value() ? 0 : 1; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 5677b1d..cbf2126 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -222,6 +222,17 @@ static_assert(noexcept(codecs::decode(be16_over_letters, codecs::t static_assert(!noexcept(codecs::decode(be16_over_letters, std::string_view{}))); static_assert(!noexcept(codecs::encode(be16_over_letters, test::hex_number{}))); static_assert(!noexcept(codecs::encode(be16_over_letters, test::hex_number{}, std::span{}))); +// Made secret by a token, a value chain runs the overloads that take secret_tag (R7), in place as +// the public one is when the value codec states its bound. +static_assert(noexcept(codecs::encode(be16_over_letters, test::number{}, tokens::secret))); +static_assert(!noexcept(codecs::encode(be16_over_letters, test::hex_number{}, tokens::secret))); +static_assert(noexcept( + codecs::value_codec, test::number>::encode( + over_detail::secret_tag{}, be16_over_letters, test::number{}, std::span{}))); +static_assert(!noexcept( + codecs::value_codec, + test::hex_number>::encoded_size(over_detail::secret_tag{}, + be16_over_letters, test::hex_number{}))); // A chain of a chain is in place when every link is. constexpr codecs::over three_links{test::letters, letters_over_letters}; static_assert(noexcept(codecs::encode(three_links, std::array{}))); diff --git a/test/over_test.cpp b/test/over_test.cpp index e5f65db..182d509 100644 --- a/test/over_test.cpp +++ b/test/over_test.cpp @@ -9,13 +9,15 @@ // codec, the default results it gives (in place when the input's type states its size), its bounds // and the refusals that follow from them, the order of the errors, nesting, constant time, and the // secret chain: the links' secret overloads run (ruling R7) and the intermediate, in place and on -// the heap, is wiped, as secure's wipe seam records it. +// the heap, is wiped, as secure's wipe seam records it, also for a chain of a value codec made +// secret by its token alone. #include "support/wipe_recorder.hpp" #include "support/be16.hpp" #include "support/letters.hpp" #include "support/saturating.hpp" +#include "support/secret_tokens.hpp" #include "support/tagged_letters.hpp" #include @@ -265,12 +267,12 @@ void the_errors_and_their_order() { // The outer link's character error first. BOOST_TEST(codecs::decode(be16_over_letters, "bcdebz").error() == codecs::error::invalid_character); - // The inner link's data error of a decode through the sizes: letters of letters, whose inner - // text is invalid ("qq" is "b" 'q' as the inner letters, outside a to p). // An odd count of letters in the inner text: the outer link decodes "abc" and the inner link // finds it odd. BOOST_TEST(codecs::decode(letters_over_letters, letters_of(std::string_view{"abc"})).error() == codecs::error::invalid_length); + // A character outside the inner link's alphabet: the outer link decodes the text to "aq", and + // the inner link finds 'q', past 'p'. std::string const invalid_inner = codecs::encode(test::letters, std::string_view{"aq"}, tokens::return_string).value(); BOOST_TEST(codecs::decode(letters_over_letters, invalid_inner).error() == @@ -540,6 +542,75 @@ void the_links_secret_overloads_run_in_a_secret_chain() { BOOST_TEST_EQ(test::tagged_calls.total(), 6U); } +void a_secret_token_makes_a_value_chain_secret() { + // A public value through a secret token: the core calls the chain's value codec's overloads + // that take secret_tag, which wipe the intermediate and run the outer link's secret arithmetic. + constexpr auto chain = codecs::over{test::letters, test::be16}; + test::clear_wipes(); + auto const encoded = codecs::encode(chain, test::number{0x1234}, tokens::secret); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == "bcde"); + // The two bytes of be16, in place between the links, wiped. + BOOST_TEST(wiped_of_size(2)); + // The same value in a public operation wipes nothing. + test::clear_wipes(); + BOOST_TEST(codecs::encode(chain, test::number{0x1234}).has_value()); + BOOST_TEST_EQ(test::wipes.count, 0U); + // A value codec of text with no stated bound: the four digits on the heap, wiped before the + // allocator gets them back. + test::clear_wipes(); + auto const heap_encoded = codecs::encode(chain, test::hex_number{0x1234}, tokens::secret); + static_assert( + std::is_same_v const>); + BOOST_TEST(heap_encoded.value().view() == letters_of(std::string_view{"1234"})); + BOOST_TEST(wiped_of_size(4)); + // tagged_letters as the outer link: a public operation runs none of its secret overloads, the + // secret token its encoded_size once (the exact size) and its encode once. + constexpr auto tagged_chain = codecs::over{test::tagged_letters, test::be16}; + test::tagged_calls.reset(); + BOOST_TEST(codecs::encode(tagged_chain, test::number{0x1234}).has_value()); + BOOST_TEST( + codecs::encode(tagged_chain, test::number{0x1234}, tokens::return_string).has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + auto const tagged = codecs::encode(tagged_chain, test::number{0x1234}, tokens::secret); + BOOST_TEST(tagged.value().view() == "bcde"); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + // A token of a program's own whose secret is true does the same, its result its own. + test::clear_wipes(); + test::tagged_calls.reset(); + auto const own = codecs::encode(tagged_chain, test::number{0x1234}, test::secret_text_token{}); + static_assert(std::is_same_v const>); + BOOST_TEST(own.value() == "bcde"); + BOOST_TEST(wiped_of_size(2)); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + // And on the heap, through the program's token. + test::clear_wipes(); + test::tagged_calls.reset(); + test::secret_text_token text_token; + BOOST_TEST(codecs::encode(tagged_chain, test::hex_number{0x1234}, text_token).value() == + letters_of(std::string_view{"1234"})); + BOOST_TEST(wiped_of_size(4)); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); +} + +void a_secret_value_chain_runs_the_outer_links_secret_decode() { + // A typed decode is secret by its value: the outer link's secret decoded_size and decode run, + // once for the chain's own decode. + constexpr auto chain = codecs::over{test::tagged_letters, seal_t{}}; + test::tagged_calls.reset(); + test::clear_wipes(); + auto const decoded = codecs::decode(chain, std::string_view{"bcde"}); + BOOST_TEST(decoded.value() == sealed_number{0x1234}); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + BOOST_TEST(wiped_of_size(2)); +} + } // namespace } // namespace over_test @@ -555,5 +626,7 @@ int main() { over_test::a_secret_chain_on_the_heap_wipes_too(); over_test::a_secret_value_makes_the_chain_secret(); over_test::the_links_secret_overloads_run_in_a_secret_chain(); + over_test::a_secret_token_makes_a_value_chain_secret(); + over_test::a_secret_value_chain_runs_the_outer_links_secret_decode(); return boost::report_errors(); } diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index a9c102c..13c4af2 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -6,9 +6,10 @@ // Secret operations (D10): an operation is secret by the value's is_secret, the value codec's // secret, the token's secret or the requested type of a typed decode, and then returns D9's secret -// column, runs a format's secret_tag overloads where it has them (ruling R7), and wipes every -// temporary of the core, as secure's wipe seam (support/wipe_recorder.hpp) records it. The fixed -// secret forms allocate nothing, as support/counting.hpp's operator new sees. The spec's scenarios +// column, runs the secret_tag overloads of a format's codec or value codec where it has them +// (ruling R7), and wipes every temporary of the core, as secure's wipe seam +// (support/wipe_recorder.hpp) records it. The fixed secret forms allocate nothing, as +// support/counting.hpp's operator new sees. The spec's scenarios // "A secret type encodes to a wiped text", "secure's secret is secret" and "A secret result type // is secret", here on the format letters (Task 13 adds hex's). A token of the program's own whose // secret is true makes the operation secret and keeps its result type; every token the core makes @@ -152,11 +153,160 @@ struct failing_value_codec { } }; +/** The calls of the tagged value codec's overloads that take `detail::secret_tag` first. */ +struct tagged_value_counts { + /** The calls of `encoded_size`. */ + std::size_t encoded_size = 0; + /** The calls of `encode`. */ + std::size_t encode = 0; + /** The calls of `decode`. */ + std::size_t decode = 0; + + /** Every call. */ + [[nodiscard]] std::size_t total() const noexcept { return encoded_size + encode + decode; } +}; + +/** The calls of the tagged value codec's secret overloads. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +tagged_value_counts tagged_value_calls; + +/** A public value of the tagged value codec: sixteen bits. */ +struct tagged_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(tagged_number const&) const = default; +}; + +/** A value of the tagged value codec that is secret (`is_secret`): sixteen bits. */ +struct tagged_secret_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(tagged_secret_number const&) const = default; +}; + +/** A value whose value codec's secret decode takes parameters the core does not give. */ +struct misread_number { + /** The bits. */ + std::uint16_t value; +}; + +/** The format of the tagged value codec. */ +struct tagged_values_t { + /** The format's name. */ + static constexpr std::string_view name = "tagged values"; +}; + +/** The format of the tagged value codec. */ +inline constexpr tagged_values_t tagged_values{}; + +/** + A value codec of bytes whose arithmetic differs when the operation is secret (ruling R7): two + bytes, big endian, and the overloads that take `detail::secret_tag` first, which count their calls + and then convert as the others do. +*/ +template +struct tagged_value_codec { + /** Bytes. */ + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size(tagged_values_t const& /*format*/, + Number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static codecs::result encode(tagged_values_t const& /*format*/, + Number const& held_value, + std::span output_bytes) noexcept { + output_bytes[0] = static_cast(held_value.value >> 8U); + output_bytes[1] = static_cast(held_value.value & 0xffU); + return std::size_t{2}; + } + + /** Reads two bytes, big endian. */ + static codecs::result decode(tagged_values_t const& /*format*/, + std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return codecs::error::invalid_length; + } + unsigned const bits = (static_cast(input_bytes[0]) << 8U) | input_bytes[1]; + return Number{static_cast(bits)}; + } + + /** The secret operation's `encoded_size`: counted, then the public one. */ + static std::size_t encoded_size(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + Number const& held_value) noexcept { + ++tagged_value_calls.encoded_size; + return encoded_size(format_value, held_value); + } + + /** The secret operation's `encode`: counted, then the public one. */ + static codecs::result encode(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + Number const& held_value, + std::span output_bytes) noexcept { + ++tagged_value_calls.encode; + return encode(format_value, held_value, output_bytes); + } + + /** The secret operation's `decode`: counted, then the public one. */ + static codecs::result decode(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + std::span input_bytes) noexcept { + ++tagged_value_calls.decode; + return decode(format_value, input_bytes); + } +}; + } // namespace } // namespace secret_operation namespace webcpp::codecs { +/** The tagged value codec of a public number. */ +template <> +struct value_codec + : secret_operation::tagged_value_codec {}; + +/** The tagged value codec of a secret number. */ +template <> +struct value_codec + : secret_operation::tagged_value_codec {}; + +/** A value codec whose secret decode reads mutable bytes, which the core's view does not convert + to. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Reads nothing. */ + static result decode( + secret_operation::tagged_values_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return error::invalid_length; + } + + /** The secret decode, of mutable bytes. */ + static result decode( + detail::secret_tag /*secret*/, secret_operation::tagged_values_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return error::invalid_length; + } +}; + +/** tagged_secret_number is secret. */ +template <> +struct is_secret : std::true_type {}; + /** key32 is secret. */ template <> struct is_secret : std::true_type {}; @@ -714,6 +864,77 @@ void a_public_operation_wipes_nothing() { BOOST_TEST_EQ(test::wipes.count, 0U); } +void a_value_codecs_secret_arithmetic_runs_in_a_secret_operation() { + // R7 for a value codec: the core calls its overloads that take secret_tag first in a secret + // operation, whether the value, the value codec or the token makes it secret, and never in a + // public one. + tagged_value_calls = {}; + auto const public_bytes = codecs::encode(tagged_values, tagged_number{0x1234}); + BOOST_TEST(public_bytes.has_value()); + std::array buffer{}; + BOOST_TEST(codecs::encode(tagged_values, tagged_number{0x1234}, std::span{buffer}).has_value()); + BOOST_TEST_EQ(codecs::encoded_size(tagged_values, tagged_number{0x1234}), 2U); + BOOST_TEST(codecs::decode(tagged_values, buffer).value() == + tagged_number{0x1234}); + BOOST_TEST_EQ(tagged_value_calls.total(), 0U); + // The secret token: a public value, the secret column, the secret encoded_size and encode. + auto const through_token = codecs::encode(tagged_values, tagged_number{0x1234}, tokens::secret); + static_assert( + std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(through_token.value().view(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 2U); + // A token of a program's own whose secret is true, its result its own. + tagged_value_calls = {}; + auto const own = + codecs::encode(tagged_values, tagged_number{0x1234}, test::secret_byte_token{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(own.value(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 2U); + // A secret value, in each form: the default result, the buffer form, the size, the typed + // decode. + tagged_value_calls = {}; + auto const secret_encoded = codecs::encode(tagged_values, tagged_secret_number{0x1234}); + static_assert( + std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(secret_encoded.value().view(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + tagged_value_calls = {}; + std::array secret_buffer{}; + BOOST_TEST_EQ( + codecs::encode(tagged_values, tagged_secret_number{0x1234}, std::span{secret_buffer}) + .value(), + 2U); + BOOST_TEST_EQ(codecs::encoded_size(tagged_values, tagged_secret_number{0x1234}), 2U); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 2U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + tagged_value_calls = {}; + BOOST_TEST(codecs::decode(tagged_values, secret_buffer).value() == + tagged_secret_number{0x1234}); + BOOST_TEST_EQ(tagged_value_calls.decode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 1U); +} + +// The core's check of a value codec's secret overloads (R7): those that take the core's arguments +// and return what the functions without the tag return pass; one of other parameters is found +// (refused_secret_value_overload is the message case of another return type). +static_assert(codecs::detail::secret_value_overloads_match); +static_assert(codecs::detail::takes_secret_value_decode); +static_assert(!codecs::detail::has_secret_value_decode); +static_assert(!codecs::detail::secret_value_overloads_match); + +// The secret overloads are noexcept, as the forms that call them are when nothing allocates. +static_assert(noexcept(codecs::encode(tagged_values, tagged_number{}, tokens::secret))); +static_assert(noexcept(codecs::encode(tagged_values, tagged_secret_number{}))); +static_assert(noexcept(codecs::encode(tagged_values, tagged_secret_number{}, + std::declval>()))); +static_assert(noexcept(codecs::decode(tagged_values, + std::array{}))); + void the_secret_arithmetic_runs_in_a_secret_operation_alone() { // A public operation runs the format's public arithmetic. test::tagged_calls.reset(); @@ -813,6 +1034,7 @@ int main() { secret_operation::a_secret_shrink_wipes_the_tail(); secret_operation::a_public_operation_wipes_nothing(); secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); + secret_operation::a_value_codecs_secret_arithmetic_runs_in_a_secret_operation(); secret_operation::the_fixed_secret_forms_allocate_nothing(); return boost::report_errors(); } From ea07828659cc60b6c9e7bde1b53619b5a2e41514 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:00:10 -0300 Subject: [PATCH 041/157] codecs: a codec's functions take D3's span types, which the bounded views convert to, stated and tested through every form; over's buffer decode row reads its real text --- .../webcpp/codecs/detail/core/contract.hpp | 16 +- test/allocation_test.cpp | 12 +- test/contract_test.cpp | 171 +++++++++++++++++- 3 files changed, 194 insertions(+), 5 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 4467557..06a0349 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -66,6 +66,15 @@ namespace webcpp::codecs { refused with @ref error::input_too_long before it is read. When a data error is found, the one with the lowest value of @ref error is reported. + Each function takes the parameter types written above, which D3 names: `std::span` for the bytes read, `std::string_view` for the text read, `std::span` and + `std::span` for the output, never a deduced template parameter. The core gives the + bytes or the text of an input whose type states its size (`std::array`, `text`) as a + `detail::bounded_bytes` or a `detail::bounded_text`, a view that converts to those types + implicitly and `noexcept`, so that a codec's `noexcept` reaches the operation; the view is no + range, and a function template that deduced its parameter would get the view and could not read + it. `over` is the one codec that takes the views, to read the bound they state. + @tparam Format The format's type. */ template @@ -96,7 +105,12 @@ struct codec; @endcode A value codec whose `output` is @ref output_kind::text writes a `std::span` and reads a - `std::string_view`. The errors it returns, of any category, reach the caller unchanged. + `std::string_view`. The errors it returns, of any category, reach the caller unchanged. Its + `decode` takes `std::span` or `std::string_view`, not a deduced parameter, as + a codec's functions do: the core may give it a `detail::bounded_bytes` or a + `detail::bounded_text`, which converts to them. Its `encoded_size`, `encode` and `decode` may + also have overloads that take `detail::secret_tag` first, which the core calls in a secret + operation (ruling R7), as for a codec. @tparam Format The format's type. @tparam Value The value's type. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index b08c18f..3e35b91 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -487,8 +487,11 @@ void check_over() { sink = codecs::encoded_size(chain, key); }); expect_no_allocation("over, the buffer forms", [&] { - verdict = codecs::encode(chain, input, output).has_value() && - codecs::decode(chain, codecs::text<64>{}, decoded).has_value(); + // The decode reads the 64 letters of the input, a text<64>: its intermediate is in place. + auto const written = codecs::decode(chain, codecs::encode(chain, input).value(), decoded); + verdict = codecs::encode(chain, input, output).has_value() && written.has_value() && + written.value() == input.size() && + std::ranges::equal(std::span{decoded}.first(input.size()), input); }); BOOST_TEST(verdict); expect_no_allocation("over, a typed decode and the tokens", [&] { @@ -511,7 +514,10 @@ void check_over() { expect_no_allocation("over, a value codec", [&] { auto const encoded = codecs::encode(value_chain, test::number{0x1234}); auto const number_back = codecs::decode(value_chain, encoded.value()); - verdict = encoded.has_value() && number_back.has_value(); + // Made secret by its token: the intermediate in place, wiped, the result a secret_text<4>. + auto const secret_text = + codecs::encode(value_chain, test::number{0x1234}, codecs::tokens::secret); + verdict = encoded.has_value() && number_back.has_value() && secret_text.has_value(); }); BOOST_TEST(verdict); expect_no_allocation("over, an input whose bound saturates and the empty input", [&] { diff --git a/test/contract_test.cpp b/test/contract_test.cpp index 8a1e64a..e496f16 100644 --- a/test/contract_test.cpp +++ b/test/contract_test.cpp @@ -6,8 +6,11 @@ // The format contract's concepts: what a format is, which inputs are bytes and which texts, the // sizes known at compile time (D7, B5), and which pairs encode and decode (D5); then the bytes -// and the text the core reads from each kind of input. +// and the text the core reads from each kind of input; then a program's own format whose codec is +// written with D3's exact parameter types, which gets an input whose type states its size as a +// view that converts to them, in every form, its noexcept carried to the operation. +#include "support/be16.hpp" #include "support/letters.hpp" #include @@ -20,11 +23,102 @@ #include #include #include +#include #include #include #include +#include +#include #include +/** A program's own format, whose codec's functions take D3's exact parameter types. */ +struct exact_t { + /** The format's name. */ + static constexpr std::string_view name = "exact"; +}; + +/** The same format, whose encode is not declared noexcept: the operations follow it. */ +struct loose_t { + /** The format's name. */ + static constexpr std::string_view name = "loose"; +}; + +namespace webcpp::codecs { + +/** letters' arithmetic, behind functions of D3's exact parameter types, none a template. */ +template <> +struct codec { + /** letters branches on its data. */ + static constexpr bool constant_time = false; + + /** Two letters a byte. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return codec::max_encoded_size(input_size); + } + + /** A byte for two letters. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return codec::max_decoded_size(text_size); + } + + /** The letters of `input_bytes`. */ + static std::size_t encoded_size(exact_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::letters, input_bytes); + } + + /** The bytes of `text_characters`. */ + static result decoded_size(exact_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::letters, text_characters); + } + + /** Writes the letters of `input_bytes`. */ + static result encode(exact_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::letters, input_bytes, output_characters); + } + + /** Writes the bytes of `text_characters`. */ + static result decode(exact_t const& /*format*/, std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::letters, text_characters, output_bytes); + } +}; + +/** exact's codec, with an encode that is not declared noexcept. */ +template <> +struct codec : codec { + /** The letters of `input_bytes`. */ + static std::size_t encoded_size(loose_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(exact_t{}, input_bytes); + } + + /** The bytes of `text_characters`. */ + static result decoded_size(loose_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(exact_t{}, text_characters); + } + + /** Writes the letters of `input_bytes`, declared as one that may throw. */ + // NOLINTNEXTLINE(bugprone-exception-escape): the missing noexcept is the case under test + static result encode(loose_t const& /*format*/, + std::span input_bytes, + std::span output_characters) { + return codec::encode(exact_t{}, input_bytes, output_characters); + } + + /** Writes the bytes of `text_characters`. */ + static result decode(loose_t const& /*format*/, std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(exact_t{}, text_characters, output_bytes); + } +}; + +} // namespace webcpp::codecs + namespace { namespace codecs = webcpp::codecs; @@ -149,10 +243,85 @@ void text_view_of_each_input() { BOOST_TEST_EQ(codecs::detail::text_view(std::span{array_text}), "cd"); } +// The views the core gives a codec for an input whose type states its size: no ranges, and +// converted to D3's types implicitly and noexcept. +static_assert( + std::is_nothrow_convertible_v, std::span>); +static_assert(std::is_nothrow_convertible_v, std::string_view>); +static_assert(!std::ranges::range>); +static_assert(!std::ranges::range>); + +// The forms that allocate nothing are noexcept for a format of D3's exact types, with an input of +// a static size, as for one of a dynamic size. +static_assert(noexcept(codecs::encode(exact_t{}, std::array{}))); +static_assert(noexcept(codecs::encode(exact_t{}, std::array{}, + std::span{}))); +static_assert(noexcept(codecs::encoded_size(exact_t{}, std::array{}))); +static_assert(noexcept(codecs::encode(exact_t{}, std::array{}, + codecs::tokens::fixed<4>{}))); +static_assert(noexcept(codecs::encode(exact_t{}, std::array{}, + codecs::tokens::secret))); +static_assert(noexcept(codecs::decode(exact_t{}, codecs::text<4>{}))); +static_assert(noexcept(codecs::decode(exact_t{}, codecs::text<4>{}, std::span{}))); +static_assert(noexcept(codecs::decode(exact_t{}, codecs::text<4>{}, codecs::tokens::fixed<2>{}))); +static_assert(noexcept(codecs::decode(exact_t{}, codecs::text<4>{}, codecs::tokens::secret))); +static_assert(noexcept(codecs::decode>(exact_t{}, codecs::text<4>{}))); +static_assert(noexcept(codecs::encode(exact_t{}, std::span{}, + std::span{}))); +// A value codec of D3's exact types, be16's, read from an input of a static size. +static_assert(noexcept(codecs::decode(test::be16, std::array{}))); +// A codec whose encode may throw makes the forms that call it not noexcept, with either view. +static_assert(!noexcept(codecs::encode(loose_t{}, std::array{}))); +static_assert(!noexcept(codecs::encode(loose_t{}, std::array{}, + std::span{}))); +static_assert(!noexcept(codecs::encode(loose_t{}, std::span{}, + std::span{}))); +static_assert(noexcept(codecs::decode(loose_t{}, codecs::text<4>{}))); + +/** A format of D3's exact types converts an input whose type states its size in every form. */ +void a_codec_of_exact_types_takes_the_bounded_views() { + std::array const input{0x12, 0x34}; + // The buffer form. + std::array text_buffer{}; + BOOST_TEST_EQ(codecs::encode(exact_t{}, input, std::span{text_buffer}).value(), 4U); + BOOST_TEST((std::string_view{text_buffer.data(), text_buffer.size()} == "bcde")); + // The default form, a text<4>, and the size. + auto const encoded = codecs::encode(exact_t{}, input); + static_assert(std::is_same_v> const>); + BOOST_TEST(encoded.value().view() == "bcde"); + BOOST_TEST_EQ(codecs::encoded_size(exact_t{}, input), 4U); + // The tokens. + auto const fixed_text = codecs::encode(exact_t{}, input, codecs::tokens::fixed<4>{}); + BOOST_TEST(fixed_text.value().view() == "bcde"); + auto const secret_text = codecs::encode(exact_t{}, input, codecs::tokens::secret); + BOOST_TEST(secret_text.value().view() == "bcde"); + BOOST_TEST(codecs::encode(exact_t{}, input, codecs::tokens::return_string).value() == "bcde"); + // The decodes of the text<4>: the default form, the buffer form, a token, the typed form. + codecs::text<4> const text_value = encoded.value(); + auto const decoded = codecs::decode(exact_t{}, text_value); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + std::array byte_buffer{}; + BOOST_TEST_EQ( + codecs::decode(exact_t{}, text_value, std::span{byte_buffer}).value(), 2U); + BOOST_TEST(byte_buffer == input); + auto const fixed_bytes = codecs::decode(exact_t{}, text_value, codecs::tokens::fixed<2>{}); + BOOST_TEST(std::ranges::equal(fixed_bytes.value().view(), input)); + auto const secret_bytes = codecs::decode(exact_t{}, text_value, codecs::tokens::secret); + BOOST_TEST(std::ranges::equal(secret_bytes.value().view(), input)); + BOOST_TEST( + (codecs::decode>(exact_t{}, text_value).value() == input)); + // A value codec of D3's exact types, from an array of a static size. + BOOST_TEST(codecs::decode(test::be16, input).value() == test::number{0x1234}); + // The codec whose encode may throw converts as well. + auto const loose_text = codecs::encode(loose_t{}, input); + BOOST_TEST(loose_text.value().view() == "bcde"); +} + } // namespace int main() { input_bytes_of_each_input(); text_view_of_each_input(); + a_codec_of_exact_types_takes_the_bounded_views(); return boost::report_errors(); } From 10cdbef58b24bec5b1cd1f371676803eef166cc5 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:03:15 -0300 Subject: [PATCH 042/157] codecs: the codec's parameter types each in one inline span, as the rendered reference reads them --- include/webcpp/codecs/detail/core/contract.hpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 06a0349..ca4859b 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -66,14 +66,15 @@ namespace webcpp::codecs { refused with @ref error::input_too_long before it is read. When a data error is found, the one with the lowest value of @ref error is reported. - Each function takes the parameter types written above, which D3 names: `std::span` for the bytes read, `std::string_view` for the text read, `std::span` and - `std::span` for the output, never a deduced template parameter. The core gives the - bytes or the text of an input whose type states its size (`std::array`, `text`) as a - `detail::bounded_bytes` or a `detail::bounded_text`, a view that converts to those types - implicitly and `noexcept`, so that a codec's `noexcept` reaches the operation; the view is no - range, and a function template that deduced its parameter would get the view and could not read - it. `over` is the one codec that takes the views, to read the bound they state. + Each function takes the parameter types written above, which D3 names: + `std::span` for the bytes read, `std::string_view` for the text read, + `std::span` and `std::span` for the output, never a deduced template + parameter. The core gives the bytes or the text of an input whose type states its size + (`std::array`, `text`) as a `detail::bounded_bytes` or a `detail::bounded_text`, a view + that converts to those types implicitly and `noexcept`, so that a codec's `noexcept` reaches the + operation; the view is no range, and a function template that deduced its parameter would get the + view and could not read it. `over` is the one codec that takes the views, to read the bound they + state. @tparam Format The format's type. */ From dc334a8bb9b8e280ba37c2737c47535de4e0c457 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:08:17 -0300 Subject: [PATCH 043/157] codecs: fix round lint fix, the contract test's formats of internal linkage --- test/contract_test.cpp | 46 +++++++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/test/contract_test.cpp b/test/contract_test.cpp index e496f16..5e90d7a 100644 --- a/test/contract_test.cpp +++ b/test/contract_test.cpp @@ -31,6 +31,9 @@ #include #include +namespace contract_formats { +namespace { + /** A program's own format, whose codec's functions take D3's exact parameter types. */ struct exact_t { /** The format's name. */ @@ -43,11 +46,14 @@ struct loose_t { static constexpr std::string_view name = "loose"; }; +} // namespace +} // namespace contract_formats + namespace webcpp::codecs { /** letters' arithmetic, behind functions of D3's exact parameter types, none a template. */ template <> -struct codec { +struct codec { /** letters branches on its data. */ static constexpr bool constant_time = false; @@ -62,26 +68,27 @@ struct codec { } /** The letters of `input_bytes`. */ - static std::size_t encoded_size(exact_t const& /*format*/, + static std::size_t encoded_size(contract_formats::exact_t const& /*format*/, std::span input_bytes) noexcept { return codec::encoded_size(test::letters, input_bytes); } /** The bytes of `text_characters`. */ - static result decoded_size(exact_t const& /*format*/, + static result decoded_size(contract_formats::exact_t const& /*format*/, std::string_view text_characters) noexcept { return codec::decoded_size(test::letters, text_characters); } /** Writes the letters of `input_bytes`. */ - static result encode(exact_t const& /*format*/, + static result encode(contract_formats::exact_t const& /*format*/, std::span input_bytes, std::span output_characters) noexcept { return codec::encode(test::letters, input_bytes, output_characters); } /** Writes the bytes of `text_characters`. */ - static result decode(exact_t const& /*format*/, std::string_view text_characters, + static result decode(contract_formats::exact_t const& /*format*/, + std::string_view text_characters, std::span output_bytes) noexcept { return codec::decode(test::letters, text_characters, output_bytes); } @@ -89,31 +96,36 @@ struct codec { /** exact's codec, with an encode that is not declared noexcept. */ template <> -struct codec : codec { +struct codec : codec { /** The letters of `input_bytes`. */ - static std::size_t encoded_size(loose_t const& /*format*/, + static std::size_t encoded_size(contract_formats::loose_t const& /*format*/, std::span input_bytes) noexcept { - return codec::encoded_size(exact_t{}, input_bytes); + return codec::encoded_size(contract_formats::exact_t{}, + input_bytes); } /** The bytes of `text_characters`. */ - static result decoded_size(loose_t const& /*format*/, + static result decoded_size(contract_formats::loose_t const& /*format*/, std::string_view text_characters) noexcept { - return codec::decoded_size(exact_t{}, text_characters); + return codec::decoded_size(contract_formats::exact_t{}, + text_characters); } /** Writes the letters of `input_bytes`, declared as one that may throw. */ // NOLINTNEXTLINE(bugprone-exception-escape): the missing noexcept is the case under test - static result encode(loose_t const& /*format*/, + static result encode(contract_formats::loose_t const& /*format*/, std::span input_bytes, std::span output_characters) { - return codec::encode(exact_t{}, input_bytes, output_characters); + return codec::encode(contract_formats::exact_t{}, input_bytes, + output_characters); } /** Writes the bytes of `text_characters`. */ - static result decode(loose_t const& /*format*/, std::string_view text_characters, + static result decode(contract_formats::loose_t const& /*format*/, + std::string_view text_characters, std::span output_bytes) noexcept { - return codec::decode(exact_t{}, text_characters, output_bytes); + return codec::decode(contract_formats::exact_t{}, + text_characters, output_bytes); } }; @@ -123,6 +135,8 @@ namespace { namespace codecs = webcpp::codecs; namespace test = webcpp::codecs::test; +using contract_formats::exact_t; +using contract_formats::loose_t; // A format: copyable, with a name that converts to std::string_view. static_assert(codecs::format); @@ -251,6 +265,10 @@ static_assert(std::is_nothrow_convertible_v, std static_assert(!std::ranges::range>); static_assert(!std::ranges::range>); +// The codec states its constant time as D3's does, and the loose one inherits it. +static_assert(!codecs::codec::constant_time); +static_assert(!codecs::codec::constant_time); + // The forms that allocate nothing are noexcept for a format of D3's exact types, with an input of // a static size, as for one of a dynamic size. static_assert(noexcept(codecs::encode(exact_t{}, std::array{}))); From 70bafb71cb44f9d4143185cf9eb7d08c6a1ebf27 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:27:29 -0300 Subject: [PATCH 044/157] codecs: over's Doc Comment rewrapped, its ragged line joined --- include/webcpp/codecs/detail/core/over.hpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 9f34ab1..6dedffc 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -74,14 +74,13 @@ struct over_name { The composition of two formats: encoding encodes with `inner` and then encodes that output with `outer`, decoding decodes with `outer` and then decodes that output with `inner`. - `Outer` is a format with a `codec` (text feeds it as bytes); `Inner` is a format with a `codec`, - or one a `value_codec` converts a value in. Both are constrained by the concept `format`: a value - codec's format is copyable and has a `name` as every format has. `over` is a format whose `name` - is the name of the - outer link, then the characters " over ", then the name of the inner link, and class template - argument deduction builds it from the two links, with or without the allocator as a third - argument. A chain is constant time when both links are, and secret when any link's operation is: - the core runs the links' secret overloads (ruling R7) and the intermediate is wiped by + `Outer` is a format with a `codec` (text feeds it as bytes); `Inner` is a format with a `codec`, or + one a `value_codec` converts a value in. Both are constrained by the concept `format`: a value + codec's format is copyable and has a `name` as every format has. `over` is a format whose `name` is + the name of the outer link, then the characters " over ", then the name of the inner link, and + class template argument deduction builds it from the two links, with or without the allocator as a + third argument. A chain is constant time when both links are, and secret when any link's operation + is: the core runs the links' secret overloads (ruling R7) and the intermediate is wiped by `secure::erase_secret`, in place or before its allocator gets it back. The intermediate, the bytes between the links, is held in place when its bound is known at From c7621fad81d1852e35ee8babbcd6ed374819af8f Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:37:25 -0300 Subject: [PATCH 045/157] codecs: the conversion contract, one-shot and stream transformers of any data, the flow and the toy media types that prove it --- include/webcpp/codecs.hpp | 1 + .../webcpp/codecs/detail/core/transformer.hpp | 225 ++++++++++ test/Jamfile | 7 + test/allocation_test.cpp | 55 +++ test/support/doubler.hpp | 139 +++++++ test/support/toy_media.hpp | 258 ++++++++++++ test/toy_media_test.cpp | 243 +++++++++++ test/transformer_test.cpp | 387 ++++++++++++++++++ 8 files changed, 1315 insertions(+) create mode 100644 include/webcpp/codecs/detail/core/transformer.hpp create mode 100644 test/support/doubler.hpp create mode 100644 test/support/toy_media.hpp create mode 100644 test/toy_media_test.cpp create mode 100644 test/transformer_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 3826305..8846c74 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -23,5 +23,6 @@ #include #include #include +#include #endif // WEBCPP_CODECS_HPP diff --git a/include/webcpp/codecs/detail/core/transformer.hpp b/include/webcpp/codecs/detail/core/transformer.hpp new file mode 100644 index 0000000..cc28afe --- /dev/null +++ b/include/webcpp/codecs/detail/core/transformer.hpp @@ -0,0 +1,225 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The conversion contract of webcpp::codecs (D17, D18): the two transformer concepts, one-shot and + stream, over elements of any type; the flow state and the step of the stream protocol; the tags + of a capacity in place and of a secret operation; and the traits the compositions read. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP +#define WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP + +#include + +#include +#include + +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The state of a stream transformer after a call, beside its result and never an error (D18). + + "Receive again" and "send more" are the normal course of a stream, so they are not error codes: + a result's error is a real fault alone. +*/ +enum class flow : unsigned char { + /** Everything accepted is processed: send more, or flush. */ + needs_input = 1, + /** Output is waiting: receive it. */ + output_pending = 2, + /** Flushed and every output received: reset to start again. */ + finished = 3, +}; + +/** What a stream transformer's `send` or `receive` did: a count of elements and the state after. */ +struct step { + /** The elements `send` accepted, or the elements `receive` wrote. */ + std::size_t count; + /** The state after the call. */ + codecs::flow flow; +}; + +namespace detail { + +/** An element type of a transformer: a cv-unqualified object type of any kind. */ +template +concept transformer_element = std::is_object_v && std::same_as>; + +/** + The types both transformer concepts require: `T` is movable, and its `input_type` and + `output_type` are cv-unqualified object types (D17). +*/ +template +concept transformer_types = std::movable && requires { + typename T::input_type; + typename T::output_type; +} && transformer_element && transformer_element; + +} // namespace detail + +/** + A transformer that converts a whole input at once: `transform(input, output)` writes all of its + output and returns the count, or writes nothing and returns an error (D17). + + Its `input_type` and `output_type` are any cv-unqualified object types (a byte, a character, a + compressed packet, a decoded frame) and every transfer is a contiguous span of elements, read + from the caller's input and written into the caller's output. A short output is + @ref error::output_too_small, with nothing written. `transform` takes the transformer by + non-const reference, so that it may keep state between calls (a media encoder's context). A type + may add overloads of its own; the concept requires the span form alone, and assumes no bytes, + characters, constant time or secrecy. + + Optional members, read when present and never required: `max_output_size(std::size_t)`, a bound + on the output of that many input elements, constexpr where it can be, and `output_size(input)`, + the exact size; `static constexpr bool constant_time`, read through @ref is_constant_time_v. + + @tparam T The type to check. +*/ +template +concept one_shot_transformer = + detail::transformer_types && + requires(T& transformer, std::span input, + std::span output) { + { transformer.transform(input, output) } -> std::same_as>; + }; + +/** + A transformer that converts a stream: `send` gives it input, `receive` takes its output, `flush` + ends the input and `reset` starts again, with the protocol of D18. + + It starts in @ref flow::needs_input. `send(input)` in that state accepts a prefix of `input` and + returns how many elements it accepted with the state after; in any other state it accepts + nothing and returns `{0, state}`. The elements accepted stay the caller's, alive and unchanged, + until the transformer next reports @ref flow::needs_input or @ref flow::finished, or is reset or + destroyed: it reads them during `receive`, from the caller's input straight into the caller's + output. `receive(output)` writes up to `output.size()` elements and returns how many with the + state after; an empty span returns `{0, state}`. `flush()` ends the input and returns + @ref flow::output_pending while output remains and @ref flow::finished when none does; after it + nothing is accepted until `reset`. A fault of the data is reported once, after `flush`, by the + first call that has processed the whole input, and every call returns it until `reset`. + `reset()` returns the transformer to @ref flow::needs_input with nothing borrowed, nothing pending + and no error, and a moved-from transformer is in the state `reset` leaves, so that it converts a + new input from the start; the concept cannot check either, and every transformer of codecs keeps + both. + + The concept assumes no bytes, characters, constant time or secrecy; a type may satisfy it and + @ref one_shot_transformer both. + + @tparam T The type to check. +*/ +template +concept stream_transformer = detail::transformer_types && + requires(T& transformer, std::span input, + std::span output) { + { transformer.send(input) } -> std::same_as>; + { transformer.receive(output) } -> std::same_as>; + { transformer.flush() } -> std::same_as>; + { transformer.reset() } noexcept -> std::same_as; + }; + +/** + The tag of a capacity in place of `N` elements, which a composition takes instead of its default + (`pipe`'s intermediate, `drain`'s buffer) or of an allocator (`buffered`, `each`). + + @tparam N The capacity, in elements. +*/ +template +struct capacity_t { + /** The capacity, in elements. */ + static constexpr std::size_t value = N; +}; + +/** + A capacity in place of `N` elements: `codecs::pipe(first, second, codecs::capacity<64>)`. + + @tparam N The capacity, in elements. +*/ +template +inline constexpr capacity_t capacity{}; + +/** The tag that makes a transformer of a format secret: `encoder(format, secret_operation)`. */ +struct secret_operation_t { + /** Constructed by name only, so that `{}` never stands for it. */ + explicit secret_operation_t() = default; +}; + +/** The tag that makes a transformer of a format secret, wiped and under secure's timing guard. */ +inline constexpr secret_operation_t secret_operation{}; + +namespace detail { + +/** Whether `T` states `constant_time`, a constant. */ +template +concept states_constant_time = requires { + { std::bool_constant(T::constant_time)>{} }; +}; + +/** `T::constant_time` when `T` states it, else false. */ +template +constexpr bool constant_time_of() noexcept { + if constexpr (states_constant_time) { + return static_cast(T::constant_time); + } else { + return false; + } +} + +} // namespace detail + +/** + Whether a transformer of type `T` runs in a time that does not depend on its data: its + `static constexpr bool constant_time` when it states one, and false otherwise. + + @tparam T The transformer's type; a reference and `const` are ignored. +*/ +template +inline constexpr bool is_constant_time_v = detail::constant_time_of>(); + +/** + The default capacity in place of a composition's buffer of elements of type `Element`: 512 bytes, + at least one element (B32). + + @tparam Element The buffer's element type. +*/ +template +inline constexpr std::size_t default_capacity_v = + sizeof(Element) >= 512 ? 1 : 512 / sizeof(Element); + +namespace detail { + +/** + Whether elements of `From` are read as elements of `To` with no copy: the same type, or both + one-byte character or byte types (`char`, `unsigned char`, which is `std::uint8_t`, and + `std::byte`), as `over` reads text as bytes (D19). +*/ +template +concept compatible_elements = std::same_as || (byte_element && byte_element); + +/** Whether `T` states a bound on its output, `T::max_output_size(std::size_t)`. */ +template +concept has_max_output_size = requires(std::size_t input_size) { + { T::max_output_size(input_size) } -> std::convertible_to; +}; + +/** + Whether `T` states its bound as a constant expression, which an in-place storage sizes itself by + (checked at one element). +*/ +template +concept has_constant_max_output_size = has_max_output_size && requires { + typename std::integral_constant; +}; + +} // namespace detail + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP diff --git a/test/Jamfile b/test/Jamfile index 6227246..8c3a5bb 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -73,6 +73,13 @@ codecs-run timing : timing_test.cpp ; # allocator, wiped when the chain is secret, as secure's wipe seam records it; # the links' secret overloads (R7) run in a secret chain. codecs-run over : over_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The conversion contract (D17, D18): the transformer concepts, the stream +# protocol's states over a stream transformer of the tests' own, the tags and +# the traits the compositions read. +codecs-run transformer : transformer_test.cpp ; +# The toy media types: transformers of packets, frames and images, no byte or +# character among their elements, satisfy the contract. +codecs-run toy_media : toy_media_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 3e35b91..9f73888 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -14,8 +14,10 @@ #include "support/be16.hpp" #include "support/bookkeeping.hpp" +#include "support/doubler.hpp" #include "support/letters.hpp" #include "support/saturating.hpp" +#include "support/toy_media.hpp" #include #include @@ -544,6 +546,58 @@ void check_over() { static_cast(sink); } +/** The transformers of the tests' own, a stream and the one-shots of the toy media, convert in the + caller's spans and allocate nothing (D17, D18). */ +void check_transformers() { + std::array const packets{{{0, 1}, {1, 2}, {2, 0}}}; + std::array frames{}; + std::array frame_bytes{}; + std::array images{}; + std::array doubled{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + expect_no_allocation("doubler, a stream", [&] { + test::doubler transformer; + bool streamed = transformer.send(std::string_view{"abc"}).has_value(); + auto const received = transformer.receive(doubled); + streamed = streamed && received.has_value() && received->count == 6 && + transformer.flush().has_value(); + test::doubler moved{std::move(transformer)}; + moved.reset(); + verdict = streamed && std::string_view{doubled.data(), 6} == "aabbcc"; + }); + BOOST_TEST(verdict); + expect_no_allocation("packets_to_frames, a stream", [&] { + test::packets_to_frames decoder; + std::size_t received_count = 0; + for (test::packet const& input_packet : packets) { + auto const sent = decoder.send(std::span{&input_packet, 1}); + auto const received = decoder.receive(std::span{frames}.subspan(received_count)); + received_count += sent.has_value() && received.has_value() ? received->count : 0; + } + auto const flushed = decoder.flush(); + auto const tail = decoder.receive(std::span{frames}.subspan(received_count)); + received_count += flushed.has_value() && tail.has_value() ? tail->count : 0; + test::packets_to_frames moved{std::move(decoder)}; + moved.reset(); + verdict = received_count == 3 && frames[0].index == 0 && frames[1].index == 2 && + frames[2].index == 3; + }); + BOOST_TEST(verdict); + expect_no_allocation("frame_to_bytes and frame_to_image, one-shot", [&] { + auto const written = + test::frame_to_bytes::transform(std::span{frames}.first(3), frame_bytes); + auto const bounded = + test::frame_to_bytes_bounded::transform(std::span{frames}.first(3), frame_bytes); + auto const imaged = test::frame_to_image::transform(std::span{frames}.first(3), images); + sink = written.has_value() ? written.value() : 0; + verdict = + written.has_value() && bounded.has_value() && imaged.has_value() && imaged.value() == 3; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -593,6 +647,7 @@ int main() { check_secret_operations(); check_assign_to_scratch(); check_over(); + check_transformers(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/support/doubler.hpp b/test/support/doubler.hpp new file mode 100644 index 0000000..dec5f85 --- /dev/null +++ b/test/support/doubler.hpp @@ -0,0 +1,139 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// doubler, a stream transformer of the tests' own: `char` to `char`, every character written +// twice, so that the stream protocol (D18) is proven before any format streams. It borrows what +// `send` accepts and reads it during `receive`, straight into the caller's span; when the span has +// room for the first copy of a character alone, it holds the second, its whole pending state one +// character. It never fails, is not constant time and is not secret. A moved-from doubler is in +// the state `reset` leaves (Review Focus 5). + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_DOUBLER_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_DOUBLER_HPP + +#include + +#include +#include + +namespace webcpp::codecs::test { + +/** Writes every character twice, as a stream transformer. */ +class doubler { +public: + /** The characters read. */ + using input_type = char; + /** The characters written. */ + using output_type = char; + + /** A doubler in `needs_input`. */ + doubler() noexcept = default; + + /** A copy borrows what `other` borrows. */ + doubler(doubler const& other) noexcept = default; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + doubler(doubler&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + held_(other.held_), + holding_(other.holding_), + flushed_(other.flushed_) { + other.reset(); + } + + /** A copy borrows what `other` borrows. */ + doubler& operator=(doubler const& other) noexcept = default; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + doubler& operator=(doubler&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + held_ = other.held_; + holding_ = other.holding_; + flushed_ = other.flushed_; + other.reset(); + } + return *this; + } + + ~doubler() = default; + + /** Borrows all of `input` in `needs_input`; accepts nothing in another state. */ + result send(std::span input) noexcept { + if (state() != flow::needs_input) { + return step{0, state()}; + } + borrowed_ = input; + position_ = 0; + return step{input.size(), state()}; + } + + /** Writes the held character, then each borrowed one twice, as far as `output` has room. */ + result receive(std::span output) noexcept { + std::size_t written = 0; + if (holding_ && written < output.size()) { + output[written++] = held_; + holding_ = false; + } + while (position_ < borrowed_.size() && written < output.size()) { + char const character = borrowed_[position_++]; + output[written++] = character; + if (written < output.size()) { + output[written++] = character; + } else { + held_ = character; + holding_ = true; + } + } + if (!holding_ && position_ == borrowed_.size()) { + // Everything borrowed is processed: the caller's input is free again. + borrowed_ = {}; + position_ = 0; + } + return step{written, state()}; + } + + /** Ends the input: `output_pending` while output remains, else `finished`. */ + result flush() noexcept { + flushed_ = true; + return state(); + } + + /** Back to `needs_input`, nothing borrowed or held. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + held_ = '\0'; + holding_ = false; + flushed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (holding_ || position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The input `send` accepted, the caller's until the doubler reports `needs_input`. */ + std::span borrowed_; + /** The next borrowed character to read. */ + std::size_t position_ = 0; + /** The second copy of a character that found no room. */ + char held_ = '\0'; + /** Whether `held_` waits. */ + bool holding_ = false; + /** Whether `flush` ended the input. */ + bool flushed_ = false; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_DOUBLER_HPP diff --git a/test/support/toy_media.hpp b/test/support/toy_media.hpp new file mode 100644 index 0000000..e8620fa --- /dev/null +++ b/test/support/toy_media.hpp @@ -0,0 +1,258 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The toy media types (D17, the spec's "A toy media transformer satisfies the contract"): a +// compressed `packet`, a decoded `frame` of four pixels and an encoded `image`, none of whose +// elements is a byte or a character, and the transformers between them that prove the contract +// is about any data: +// +// - packets_to_frames, a stateful stream transformer of packets to frames, as a video decoder: +// each packet yields `frames` frames, the last of which it holds back until the next packet or +// flush (a B-frame's reordering), so that frames come out in index order. Like FFmpeg's +// avcodec_send_packet, `send` accepts one packet and copies what it needs, so that the caller's +// input is free at once (D18 allows it); +// - frame_to_bytes, a one-shot transformer of frames to bytes of a variable size and no bound; +// - frame_to_bytes_bounded, the same with a bound stated as a constant expression; +// - frame_to_image, a one-shot transformer of one image a frame. +// +// None of them allocates, fails on valid data, is constant time or is secret. A moved-from +// packets_to_frames is in the state `reset` leaves (Review Focus 5). + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_TOY_MEDIA_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_TOY_MEDIA_HPP + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A compressed packet: its index and how many frames it decodes to (0, 1 or 2). */ +struct packet { + /** The packet's place in the stream. */ + std::uint32_t index; + /** The frames it decodes to: 0, 1 or 2. */ + std::uint8_t frames; +}; + +/** A decoded frame: its index and four pixels. */ +struct frame { + /** The frame's place in the stream. */ + std::uint32_t index; + /** The pixels: `index`, `index + 1`, `index + 2` and `index + 3`, truncated to 16 bits. */ + std::array pixels; +}; + +/** An encoded image: its frame's index and a checksum of the frame's pixels. */ +struct image { + /** The frame's index. */ + std::uint32_t index; + /** The four pixels packed, the first in the low 16 bits. */ + std::uint64_t checksum; +}; + +/** The frame of index `frame_index`, whose pixels are `frame_index` and the three that follow. */ +constexpr frame make_frame(std::uint32_t frame_index) noexcept { + return frame{ + frame_index, + {static_cast(frame_index), static_cast(frame_index + 1), + static_cast(frame_index + 2), static_cast(frame_index + 3)}}; +} + +/** Decodes packets into frames, as a stream, holding the last frame back. */ +class packets_to_frames { +public: + /** The packets read. */ + using input_type = packet; + /** The frames written. */ + using output_type = frame; + + /** A decoder in `needs_input`. */ + packets_to_frames() noexcept = default; + + /** A copy holds the frames `other` holds. */ + packets_to_frames(packets_to_frames const& other) noexcept = default; + + /** Takes `other`'s frames and leaves `other` as `reset` does. */ + packets_to_frames(packets_to_frames&& other) noexcept + : queued_(other.queued_), + queued_count_(other.queued_count_), + ready_count_(other.ready_count_), + flushed_(other.flushed_) { + other.reset(); + } + + /** A copy holds the frames `other` holds. */ + packets_to_frames& operator=(packets_to_frames const& other) noexcept = default; + + /** Takes `other`'s frames and leaves `other` as `reset` does. */ + packets_to_frames& operator=(packets_to_frames&& other) noexcept { + if (this != &other) { + queued_ = other.queued_; + queued_count_ = other.queued_count_; + ready_count_ = other.ready_count_; + flushed_ = other.flushed_; + other.reset(); + } + return *this; + } + + ~packets_to_frames() = default; + + /** + Accepts the first packet of `input` in `needs_input`, which releases the frame held back and + holds back the last frame of this packet; accepts nothing in another state. A count of frames + above two is read as two. + */ + result send(std::span input) noexcept { + if (state() != flow::needs_input || input.empty()) { + return step{0, state()}; + } + packet const accepted = input.front(); + auto const frame_count = std::min(accepted.frames, most_frames); + for (std::size_t rank = 0; rank < frame_count; ++rank) { + queued_[queued_count_++] = + make_frame(static_cast((accepted.index * 2U) + rank)); + } + // The next packet releases the frame held back, even a packet of no frame; this packet's + // last frame is held back in its turn. + ready_count_ = frame_count == 0 ? queued_count_ : queued_count_ - 1; + return step{1, state()}; + } + + /** Writes the frames that are not held back, as far as `output` has room. */ + result receive(std::span output) noexcept { + std::size_t const written = std::min(ready_count_, output.size()); + if (written == 0) { + return step{0, state()}; + } + std::copy_n(queued_.begin(), written, output.begin()); + // The frames left move to the front: a copy to the left, which std::copy allows. + std::copy(queued_.begin() + static_cast(written), + queued_.begin() + static_cast(queued_count_), queued_.begin()); + queued_count_ -= written; + ready_count_ -= written; + return step{written, state()}; + } + + /** Ends the input, which releases the frame held back. */ + result flush() noexcept { + flushed_ = true; + ready_count_ = queued_count_; + return state(); + } + + /** Back to `needs_input`, no frame held. */ + void reset() noexcept { + queued_ = {}; + queued_count_ = 0; + ready_count_ = 0; + flushed_ = false; + } + +private: + /** The most frames a packet decodes to. */ + static constexpr std::size_t most_frames = 2; + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (ready_count_ != 0) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The frames decoded and not yet received: the one held back and a packet's. */ + std::array queued_{}; + /** How many of `queued_` are decoded. */ + std::size_t queued_count_ = 0; + /** How many of `queued_`, from the first, are not held back. */ + std::size_t ready_count_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; +}; + +/** + Encodes frames into bytes, a variable number a frame: `2 + index % 3` bytes, the index's low byte + and then the pixels' low bytes, with no bound stated. +*/ +struct frame_to_bytes { + /** The frames read. */ + using input_type = frame; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** The bytes of one frame. */ + static constexpr std::size_t bytes_of(frame const& input_frame) noexcept { + return 2 + (input_frame.index % 3); + } + + /** Writes every frame's bytes, or nothing and `output_too_small` when `output` is short. */ + static result transform(std::span input, + std::span output) noexcept { + std::size_t total = 0; + for (frame const& input_frame : input) { + total += bytes_of(input_frame); + } + if (output.size() < total) { + return error::output_too_small; + } + std::size_t written = 0; + for (frame const& input_frame : input) { + output[written++] = static_cast(input_frame.index & 0xFFU); + for (std::size_t pixel = 0; pixel + 1 < bytes_of(input_frame); ++pixel) { + output[written++] = static_cast(input_frame.pixels[pixel] & 0xFFU); + } + } + return written; + } +}; + +/** frame_to_bytes with its bound stated as a constant expression: four bytes a frame. */ +struct frame_to_bytes_bounded : frame_to_bytes { + /** Four bytes a frame, saturated at `SIZE_MAX`. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return detail::saturating_multiply(input_size, 4); + } +}; + +/** Encodes each frame into one image. */ +struct frame_to_image { + /** The frames read. */ + using input_type = frame; + /** The images written. */ + using output_type = image; + + /** One image a frame. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Writes one image a frame, or nothing and `output_too_small` when `output` is short. */ + static result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size()) { + return error::output_too_small; + } + std::size_t written = 0; + for (frame const& input_frame : input) { + std::uint64_t checksum = 0; + for (std::size_t pixel = 0; pixel < input_frame.pixels.size(); ++pixel) { + checksum |= std::uint64_t{input_frame.pixels[pixel]} << (16U * pixel); + } + output[written++] = image{input_frame.index, checksum}; + } + return written; + } +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_TOY_MEDIA_HPP diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp new file mode 100644 index 0000000..d505d5f --- /dev/null +++ b/test/toy_media_test.cpp @@ -0,0 +1,243 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The toy media types (support/toy_media.hpp) satisfy the contract with no byte or character as +// their elements (D17, the spec's "A toy media transformer satisfies the contract"): the packet +// decoder is a stream transformer whose frames come out in index order, the frame held back +// until the next packet or flush; the frame encoders are one-shot transformers whose outputs are +// checked for frame 4, and which write nothing into a short output. + +#include "support/toy_media.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +static_assert(codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); + +// The bounds: frame_to_bytes states none, the other two a constant expression. +static_assert(!codecs::detail::has_max_output_size); +static_assert(codecs::detail::has_constant_max_output_size); +static_assert(test::frame_to_bytes_bounded::max_output_size(3) == 12); +static_assert(codecs::detail::has_constant_max_output_size); +static_assert(test::frame_to_image::max_output_size(3) == 3); + +// None is constant time. +static_assert(!codecs::is_constant_time_v); +static_assert(!codecs::is_constant_time_v); +static_assert(!codecs::is_constant_time_v); + +/** Five packets of 1, 0, 2, 1 and 2 frames. */ +constexpr std::array packets{{{0, 1}, {1, 0}, {2, 2}, {3, 1}, {4, 2}}}; + +/** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ +bool is_step(codecs::result const& actual, std::size_t expected_count, + codecs::flow expected_flow) { + return actual.has_value() && actual->count == expected_count && actual->flow == expected_flow; +} + +/** Whether `actual` is frame `expected_index`, its pixels the index and the three that follow. */ +bool is_frame(test::frame const& actual, std::uint32_t expected_index) { + return actual.index == expected_index && + actual.pixels == + std::array{static_cast(expected_index), + static_cast(expected_index + 1), + static_cast(expected_index + 2), + static_cast(expected_index + 3)}; +} + +/** Sends one packet a send and receives one frame a receive, until each send's needs_input. */ +std::vector decode_one_by_one(test::packets_to_frames& decoder) { + std::vector frames; + test::frame received{}; + for (test::packet const& input_packet : packets) { + auto const sent = decoder.send(std::span{&input_packet, 1}); + BOOST_TEST(sent.has_value() && sent->count == 1); + while (true) { + auto const got = decoder.receive(std::span{&received, 1}); + BOOST_TEST(got.has_value()); + if (!got.has_value() || got->count == 0) { + break; + } + frames.push_back(received); + } + } + return frames; +} + +/** Five packets streamed one a send give frames 0, 4, 5, 6 and 8 before flush, 9 after. */ +void check_packets_to_frames() { + test::packets_to_frames decoder; + std::vector const before_flush = decode_one_by_one(decoder); + BOOST_TEST_EQ(before_flush.size(), 5U); + std::array const expected_before{0, 4, 5, 6, 8}; + for (std::size_t index = 0; index < std::min(before_flush.size(), expected_before.size()); + ++index) { + BOOST_TEST(is_frame(before_flush[index], expected_before[index])); + } + + // The hold-back delays frame 9 until flush. + test::frame received{}; + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::output_pending); + BOOST_TEST(is_step(decoder.receive(std::span{&received, 1}), 1, codecs::flow::finished)); + BOOST_TEST(is_frame(received, 9)); + BOOST_TEST(is_step(decoder.receive(std::span{&received, 1}), 0, codecs::flow::finished)); + BOOST_TEST(is_step(decoder.send(std::span{packets}.first(1)), 0, codecs::flow::finished)); +} + +/** The steps one by one: a packet of one frame gives nothing until the next packet. */ +void check_packets_to_frames_steps() { + test::packets_to_frames decoder; + std::array output{}; + std::span const all{packets}; + + // Packet 0's frame 0 is held: absorbed, nothing to receive. + BOOST_TEST(is_step(decoder.send(all), 1, codecs::flow::needs_input)); + BOOST_TEST(is_step(decoder.receive(output), 0, codecs::flow::needs_input)); + // Packet 1, of no frame, releases frame 0. + BOOST_TEST(is_step(decoder.send(all.subspan(1)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.send(all.subspan(2)), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::needs_input)); + BOOST_TEST(is_frame(output[0], 0)); + // Packet 2: frame 4 at once, frame 5 held; packet 3 releases 5 and holds 6. + BOOST_TEST(is_step(decoder.send(all.subspan(2)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.send(all.subspan(3)), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.receive(std::span{}), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::needs_input)); + BOOST_TEST(is_frame(output[0], 4)); + BOOST_TEST(is_step(decoder.send(all.subspan(3)), 1, codecs::flow::output_pending)); + // Packet 4 before frame 5 is received is refused; then it releases 6 and gives 8, holding 9. + BOOST_TEST(is_step(decoder.send(all.subspan(4)), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::needs_input)); + BOOST_TEST(is_frame(output[0], 5)); + BOOST_TEST(is_step(decoder.send(all.subspan(4)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST(is_frame(output[0], 6)); + BOOST_TEST(is_frame(output[1], 8)); + // flush releases 9; a second flush returns the state. + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::output_pending); + auto const flushed_again = decoder.flush(); + BOOST_TEST(flushed_again.has_value() && *flushed_again == codecs::flow::output_pending); + BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::finished)); + BOOST_TEST(is_frame(output[0], 9)); + + // reset: the stream starts again. + decoder.reset(); + BOOST_TEST(is_step(decoder.receive(output), 0, codecs::flow::needs_input)); + std::vector const again = decode_one_by_one(decoder); + BOOST_TEST_EQ(again.size(), 5U); +} + +/** A flush with nothing sent finishes at once; a moved-from decoder starts from the beginning. */ +void check_packets_to_frames_empty_and_moved() { + test::packets_to_frames decoder; + std::array output{}; + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::finished); + BOOST_TEST(is_step(decoder.receive(output), 0, codecs::flow::finished)); + + test::packets_to_frames source; + BOOST_TEST( + is_step(source.send(std::span{packets}.subspan(2)), 1, codecs::flow::output_pending)); + test::packets_to_frames target{std::move(source)}; + BOOST_TEST(is_step(target.receive(output), 1, codecs::flow::needs_input)); + BOOST_TEST(is_frame(output[0], 4)); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from transformer is reused (Review Focus 5) + BOOST_TEST(is_step(source.receive(output), 0, codecs::flow::needs_input)); + std::vector const frames = decode_one_by_one(source); + BOOST_TEST_EQ(frames.size(), 5U); + if (!frames.empty()) { + BOOST_TEST(is_frame(frames.front(), 0)); + } +} + +/** The one-shot transformers' outputs for frame 4, and frames 5 and 6 for each byte count. */ +void check_one_shot_outputs() { + std::array const frames{test::make_frame(4), test::make_frame(5), + test::make_frame(6)}; + + // frame_to_bytes: frame 4 writes 2 + 4 % 3 = 3 bytes, its index's low byte, then two pixels. + std::array bytes{}; + auto const written = test::frame_to_bytes::transform(std::span{frames}.first(1), bytes); + BOOST_TEST(written.has_value() && *written == 3); + BOOST_TEST((std::array{bytes[0], bytes[1], bytes[2]} == + std::array{4, 4, 5})); + + // Three frames at once: 3, 4 and 2 bytes. + auto const all_written = test::frame_to_bytes::transform(frames, bytes); + BOOST_TEST(all_written.has_value() && *all_written == 9); + std::array const expected_bytes{4, 4, 5, 5, 5, 6, 7, 6, 6}; + BOOST_TEST(std::equal(expected_bytes.begin(), expected_bytes.end(), bytes.begin())); + + // A short output: output_too_small, nothing written. + std::array short_bytes{}; + short_bytes.fill(0xAA); + auto const refused = test::frame_to_bytes::transform(frames, short_bytes); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::output_too_small); + BOOST_TEST(std::all_of(short_bytes.begin(), short_bytes.end(), + [](std::uint8_t value) { return value == 0xAA; })); + + // The bounded one writes the same. + std::array bounded{}; + auto const bounded_written = + test::frame_to_bytes_bounded::transform(std::span{frames}.first(1), bounded); + BOOST_TEST(bounded_written.has_value() && *bounded_written == 3); + BOOST_TEST((std::array{bounded[0], bounded[1], bounded[2]} == + std::array{4, 4, 5})); + + // frame_to_image: frame 4 is image 4, its four pixels packed. + std::array images{}; + auto const imaged = + test::frame_to_image::transform(std::span{frames}.first(1), std::span{images}.first(1)); + BOOST_TEST(imaged.has_value() && *imaged == 1); + BOOST_TEST_EQ(images[0].index, 4U); + BOOST_TEST_EQ(images[0].checksum, 0x0007'0006'0005'0004ULL); + auto const too_few = test::frame_to_image::transform(frames, std::span{images}.first(2)); + BOOST_TEST(!too_few.has_value() && too_few.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(images[1].index, 0U); + auto const all_images = test::frame_to_image::transform(frames, images); + BOOST_TEST(all_images.has_value() && *all_images == 3); + BOOST_TEST_EQ(images[2].index, 6U); + BOOST_TEST_EQ(images[2].checksum, 0x0009'0008'0007'0006ULL); + + // Empty spans: nothing written, a count of zero (Review Focus 3). + auto const none = + test::frame_to_bytes::transform(std::span{}, std::span{}); + BOOST_TEST(none.has_value() && *none == 0); + auto const no_image = + test::frame_to_image::transform(std::span{}, std::span{}); + BOOST_TEST(no_image.has_value() && *no_image == 0); +} + +} // namespace + +int main() { + check_packets_to_frames(); + check_packets_to_frames_steps(); + check_packets_to_frames_empty_and_moved(); + check_one_shot_outputs(); + return boost::report_errors(); +} diff --git a/test/transformer_test.cpp b/test/transformer_test.cpp new file mode 100644 index 0000000..fb07f0b --- /dev/null +++ b/test/transformer_test.cpp @@ -0,0 +1,387 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The conversion contract (D17, D18): which types the two transformer concepts admit and refuse; +// the stream protocol's states over test::doubler, a stream transformer of the tests' own; a +// moved-from doubler in reset's state; flow, step, the capacity and secret tags, and the traits +// the compositions read (is_constant_time_v, default_capacity_v, compatible_elements and the +// bounds of a transformer's output). + +#include "support/doubler.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace transformer_types { +namespace { + +/** A one-shot transformer of ints to doubles and nothing else. */ +struct one_shot_only { + /** The ints read. */ + using input_type = int; + /** The doubles written. */ + using output_type = double; + + /** Writes each int as a double. */ + static webcpp::codecs::result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size()) { + return webcpp::codecs::error::output_too_small; + } + for (std::size_t index = 0; index < input.size(); ++index) { + output[index] = input[index]; + } + return input.size(); + } +}; + +/** One-shot and stream both, constant time. */ +struct both_kinds { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** The transformer runs in a time that does not depend on its data. */ + static constexpr bool constant_time = true; + + /** Copies nothing. */ + static webcpp::codecs::result transform( + std::span /*input*/, std::span /*output*/) noexcept { + return std::size_t{0}; + } + + /** Accepts nothing. */ + static webcpp::codecs::result send( + std::span /*input*/) noexcept { + return webcpp::codecs::step{0, webcpp::codecs::flow::needs_input}; + } + + /** Writes nothing. */ + static webcpp::codecs::result receive( + std::span /*output*/) noexcept { + return webcpp::codecs::step{0, webcpp::codecs::flow::needs_input}; + } + + /** Ends at once. */ + static webcpp::codecs::result flush() noexcept { + return webcpp::codecs::flow::finished; + } + + /** Nothing to reset. */ + static void reset() noexcept {} +}; + +/** both_kinds whose reset may throw: no stream transformer. */ +struct throwing_reset : both_kinds { + /** Not noexcept. */ + static void reset() {} +}; + +/** both_kinds whose flush returns a step: no stream transformer. */ +struct wrong_flush : both_kinds { + /** The wrong type. */ + static webcpp::codecs::result flush() noexcept { + return webcpp::codecs::step{0, webcpp::codecs::flow::finished}; + } +}; + +/** both_kinds whose transform returns a bare count: no one-shot transformer. */ +struct bare_count : both_kinds { + /** The wrong type. */ + static std::size_t transform(std::span /*input*/, + std::span /*output*/) noexcept { + return 0; + } +}; + +/** both_kinds with a const input type: neither. */ +struct const_input : both_kinds { + /** cv-qualified. */ + using input_type = std::uint8_t const; +}; + +/** both_kinds with a reference output type: neither. */ +struct reference_output : both_kinds { + /** Not an object type. */ + using output_type = std::uint8_t&; +}; + +/** both_kinds with no output type: neither. */ +struct no_types { + /** The bytes read. */ + using input_type = std::uint8_t; +}; + +/** both_kinds that cannot be moved: neither. */ +struct unmovable : both_kinds { + unmovable() = default; + unmovable(unmovable const&) = delete; + unmovable(unmovable&&) = delete; + unmovable& operator=(unmovable const&) = delete; + unmovable& operator=(unmovable&&) = delete; + ~unmovable() = default; +}; + +/** both_kinds whose constant_time is false. */ +struct not_constant : both_kinds { + /** Its time depends on its data. */ + static constexpr bool constant_time = false; +}; + +/** A bound that is no constant expression. */ +struct runtime_bound : one_shot_only { + /** Not constexpr. */ + static std::size_t max_output_size(std::size_t input_size) noexcept { return input_size; } +}; + +/** A bound that is a constant expression. */ +struct constant_bound : one_shot_only { + /** One double an int. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } +}; + +/** A bound that needs an object: not the static bound the core reads. */ +struct member_bound : one_shot_only { + /** A member function. */ + [[nodiscard]] std::size_t max_output_size(std::size_t input_size) const noexcept { + return input_size + offset; + } + + /** What the bound adds. */ + std::size_t offset = 0; +}; + +} // namespace +} // namespace transformer_types + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace types = transformer_types; + +/** Whether an argument `{}` makes a `Tag`, copy-list-initialized. */ +template +concept made_from_empty_braces = requires(void (*taker)(Tag)) { taker({}); }; + +// The concepts admit any element type, and the two are independent. +static_assert(codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::detail::transformer_types); + +// What they refuse: a reset that may throw, a wrong return type, cv-qualified or reference +// element types, a missing type, an unmovable type. +static_assert(!codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!codecs::detail::transformer_types); +static_assert(!codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); + +// flow and step: three states of fixed values, never an error code. +static_assert(std::is_same_v, unsigned char>); +static_assert(static_cast(codecs::flow::needs_input) == 1); +static_assert(static_cast(codecs::flow::output_pending) == 2); +static_assert(static_cast(codecs::flow::finished) == 3); +static_assert(!boost::system::is_error_code_enum::value); +static_assert(!boost::system::is_error_condition_enum::value); +static_assert(!std::is_convertible_v); +static_assert(std::is_aggregate_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); + +// The tags. +static_assert(codecs::capacity_t<64>::value == 64); +static_assert(std::is_same_v), codecs::capacity_t<64> const>); +static_assert(std::is_same_v); +static_assert(std::is_empty_v); +// The secret tag is named, never made by `{}`: an argument `{}` does not stand for it. +static_assert(!made_from_empty_braces); +static_assert(made_from_empty_braces); + +// is_constant_time_v: the stated constant, false when absent. +static_assert(!codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(!codecs::is_constant_time_v); +static_assert(!codecs::is_constant_time_v); + +// default_capacity_v: 512 bytes of elements, at least one element (B32). +static_assert(codecs::default_capacity_v == 512); +static_assert(codecs::default_capacity_v == 512); +static_assert(codecs::default_capacity_v == 128); +static_assert(codecs::default_capacity_v> == 1); +static_assert(codecs::default_capacity_v> == 1); +static_assert(codecs::default_capacity_v> == 1); + +// compatible_elements: the same type, or two one-byte character or byte types (D19). +static_assert(codecs::detail::compatible_elements); +static_assert(codecs::detail::compatible_elements); +static_assert(codecs::detail::compatible_elements); +static_assert(codecs::detail::compatible_elements); +static_assert(codecs::detail::compatible_elements); +static_assert(codecs::detail::compatible_elements); +static_assert(!codecs::detail::compatible_elements); +static_assert(!codecs::detail::compatible_elements); +static_assert(!codecs::detail::compatible_elements); +static_assert(!codecs::detail::compatible_elements); + +// The bounds of a transformer's output: a static bound, a constant one, neither. +static_assert(!codecs::detail::has_max_output_size); +static_assert(!codecs::detail::has_constant_max_output_size); +static_assert(codecs::detail::has_max_output_size); +static_assert(!codecs::detail::has_constant_max_output_size); +static_assert(codecs::detail::has_max_output_size); +static_assert(codecs::detail::has_constant_max_output_size); +static_assert(!codecs::detail::has_max_output_size); + +/** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ +bool is_step(codecs::result const& actual, std::size_t expected_count, + codecs::flow expected_flow) { + return actual.has_value() && actual->count == expected_count && actual->flow == expected_flow; +} + +/** Whether `actual` is the value `expected_flow`. */ +bool is_flow(codecs::result const& actual, codecs::flow expected_flow) { + return actual.has_value() && *actual == expected_flow; +} + +/** The protocol's states, D18's order, over the doubler. */ +void check_protocol() { + test::doubler transformer; + std::string_view const input = "ab"; + std::array output{}; + + // A transformer starts in needs_input: a receive gives nothing and says so. + BOOST_TEST(is_step(transformer.receive(output), 0, codecs::flow::needs_input)); + + // send accepts all of "ab" and has output; a second send accepts nothing. + BOOST_TEST(is_step(transformer.send(input), 2, codecs::flow::output_pending)); + BOOST_TEST(is_step(transformer.send(input), 0, codecs::flow::output_pending)); + + // An empty span gives nothing and the state. + BOOST_TEST(is_step(transformer.receive(std::span{}), 0, codecs::flow::output_pending)); + + // A span of 3: "aab", the second 'b' held. + BOOST_TEST( + is_step(transformer.receive(std::span{output}.first(3)), 3, codecs::flow::output_pending)); + BOOST_TEST_EQ((std::string_view{output.data(), 3}), "aab"); + + // A span of 8: the held "b", and everything accepted is processed. + BOOST_TEST(is_step(transformer.receive(output), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(output[0], 'b'); + BOOST_TEST(is_step(transformer.receive(std::span{}), 0, codecs::flow::needs_input)); + + // The input is free again: a second send is accepted. + BOOST_TEST(is_step(transformer.send(std::string_view{"c"}), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(transformer.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "cc"); + + // flush with nothing pending: finished; then send and receive give nothing, and a second flush + // returns the state. + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::finished)); + BOOST_TEST(is_step(transformer.send(input), 0, codecs::flow::finished)); + BOOST_TEST(is_step(transformer.receive(output), 0, codecs::flow::finished)); + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::finished)); + + // reset: needs_input, and send is accepted. + transformer.reset(); + BOOST_TEST(is_step(transformer.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST(is_step(transformer.send(input), 2, codecs::flow::output_pending)); + BOOST_TEST(is_step(transformer.receive(output), 4, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 4}), "aabb"); +} + +/** flush while output remains: output_pending, then the receives end in finished. */ +void check_flush_with_output_pending() { + test::doubler transformer; + std::array output{}; + BOOST_TEST(is_step(transformer.send(std::string_view{"xyz"}), 3, codecs::flow::output_pending)); + BOOST_TEST( + is_step(transformer.receive(std::span{output}.first(1)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::output_pending)); + // Nothing more is accepted after flush, even once the output is received. + BOOST_TEST(is_step(transformer.send(std::string_view{"w"}), 0, codecs::flow::output_pending)); + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_step(transformer.receive(output), 5, codecs::flow::finished)); + BOOST_TEST_EQ((std::string_view{output.data(), 5}), "xyyzz"); + BOOST_TEST(is_step(transformer.send(std::string_view{"w"}), 0, codecs::flow::finished)); + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::finished)); +} + +/** flush with nothing sent: finished at once, no output. */ +void check_empty_stream() { + test::doubler transformer; + std::array output{}; + BOOST_TEST(is_step(transformer.send(std::string_view{}), 0, codecs::flow::needs_input)); + BOOST_TEST(is_flow(transformer.flush(), codecs::flow::finished)); + BOOST_TEST(is_step(transformer.receive(output), 0, codecs::flow::finished)); +} + +/** A moved-from doubler is in reset's state and converts a new input from the start. */ +void check_moved_from() { + std::array output{}; + test::doubler source; + BOOST_TEST(is_step(source.send(std::string_view{"pq"}), 2, codecs::flow::output_pending)); + BOOST_TEST( + is_step(source.receive(std::span{output}.first(1)), 1, codecs::flow::output_pending)); + + // The target goes on where the source stopped. + test::doubler target{std::move(source)}; + BOOST_TEST(is_step(target.receive(output), 3, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 3}), "pqq"); + + // NOLINTBEGIN(bugprone-use-after-move): a moved-from transformer is reused (Review Focus 5) + BOOST_TEST(is_step(source.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST(is_step(source.send(std::string_view{"r"}), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(source.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "rr"); + + // Move assignment alike, from a flushed source. + BOOST_TEST(is_flow(source.flush(), codecs::flow::finished)); + target = std::move(source); + BOOST_TEST(is_step(target.send(std::string_view{"s"}), 0, codecs::flow::finished)); + BOOST_TEST(is_step(source.send(std::string_view{"s"}), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(source.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "ss"); + // NOLINTEND(bugprone-use-after-move) +} + +} // namespace + +int main() { + check_protocol(); + check_flush_with_output_pending(); + check_empty_stream(); + check_moved_from(); + return boost::report_errors(); +} From 76ca042c8a9726f7e0b10e1269ac50078102566b Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:42:29 -0300 Subject: [PATCH 046/157] codecs: transformer contract lint fix, designated initializers of step and the toy media, the ranges algorithms, the protocol test in two --- test/allocation_test.cpp | 6 +++- test/support/doubler.hpp | 6 ++-- test/support/toy_media.hpp | 21 +++++------ test/toy_media_test.cpp | 73 ++++++++++++++++++++++++-------------- test/transformer_test.cpp | 6 ++-- 5 files changed, 69 insertions(+), 43 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 9f73888..b185a19 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -549,7 +549,11 @@ void check_over() { /** The transformers of the tests' own, a stream and the one-shots of the toy media, convert in the caller's spans and allocate nothing (D17, D18). */ void check_transformers() { - std::array const packets{{{0, 1}, {1, 2}, {2, 0}}}; + std::array const packets{{ + {.index = 0, .frames = 1}, + {.index = 1, .frames = 2}, + {.index = 2, .frames = 0}, + }}; std::array frames{}; std::array frame_bytes{}; std::array images{}; diff --git a/test/support/doubler.hpp b/test/support/doubler.hpp index dec5f85..fd2a98b 100644 --- a/test/support/doubler.hpp +++ b/test/support/doubler.hpp @@ -66,11 +66,11 @@ class doubler { /** Borrows all of `input` in `needs_input`; accepts nothing in another state. */ result send(std::span input) noexcept { if (state() != flow::needs_input) { - return step{0, state()}; + return step{.count = 0, .flow = state()}; } borrowed_ = input; position_ = 0; - return step{input.size(), state()}; + return step{.count = input.size(), .flow = state()}; } /** Writes the held character, then each borrowed one twice, as far as `output` has room. */ @@ -95,7 +95,7 @@ class doubler { borrowed_ = {}; position_ = 0; } - return step{written, state()}; + return step{.count = written, .flow = state()}; } /** Ends the input: `output_pending` while output remains, else `finished`. */ diff --git a/test/support/toy_media.hpp b/test/support/toy_media.hpp index e8620fa..d9bcefb 100644 --- a/test/support/toy_media.hpp +++ b/test/support/toy_media.hpp @@ -60,10 +60,11 @@ struct image { /** The frame of index `frame_index`, whose pixels are `frame_index` and the three that follow. */ constexpr frame make_frame(std::uint32_t frame_index) noexcept { - return frame{ - frame_index, - {static_cast(frame_index), static_cast(frame_index + 1), - static_cast(frame_index + 2), static_cast(frame_index + 3)}}; + frame made{.index = frame_index, .pixels = {}}; + for (std::size_t pixel = 0; pixel < made.pixels.size(); ++pixel) { + made.pixels[pixel] = static_cast(frame_index + pixel); + } + return made; } /** Decodes packets into frames, as a stream, holding the last frame back. */ @@ -113,25 +114,25 @@ class packets_to_frames { */ result send(std::span input) noexcept { if (state() != flow::needs_input || input.empty()) { - return step{0, state()}; + return step{.count = 0, .flow = state()}; } packet const accepted = input.front(); auto const frame_count = std::min(accepted.frames, most_frames); for (std::size_t rank = 0; rank < frame_count; ++rank) { queued_[queued_count_++] = - make_frame(static_cast((accepted.index * 2U) + rank)); + make_frame((accepted.index * 2U) + static_cast(rank)); } // The next packet releases the frame held back, even a packet of no frame; this packet's // last frame is held back in its turn. ready_count_ = frame_count == 0 ? queued_count_ : queued_count_ - 1; - return step{1, state()}; + return step{.count = 1, .flow = state()}; } /** Writes the frames that are not held back, as far as `output` has room. */ result receive(std::span output) noexcept { std::size_t const written = std::min(ready_count_, output.size()); if (written == 0) { - return step{0, state()}; + return step{.count = 0, .flow = state()}; } std::copy_n(queued_.begin(), written, output.begin()); // The frames left move to the front: a copy to the left, which std::copy allows. @@ -139,7 +140,7 @@ class packets_to_frames { queued_.begin() + static_cast(queued_count_), queued_.begin()); queued_count_ -= written; ready_count_ -= written; - return step{written, state()}; + return step{.count = written, .flow = state()}; } /** Ends the input, which releases the frame held back. */ @@ -247,7 +248,7 @@ struct frame_to_image { for (std::size_t pixel = 0; pixel < input_frame.pixels.size(); ++pixel) { checksum |= std::uint64_t{input_frame.pixels[pixel]} << (16U * pixel); } - output[written++] = image{input_frame.index, checksum}; + output[written++] = image{.index = input_frame.index, .checksum = checksum}; } return written; } diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index d505d5f..a55c491 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -49,7 +49,13 @@ static_assert(!codecs::is_constant_time_v); static_assert(!codecs::is_constant_time_v); /** Five packets of 1, 0, 2, 1 and 2 frames. */ -constexpr std::array packets{{{0, 1}, {1, 0}, {2, 2}, {3, 1}, {4, 2}}}; +constexpr std::array packets{{ + {.index = 0, .frames = 1}, + {.index = 1, .frames = 0}, + {.index = 2, .frames = 2}, + {.index = 3, .frames = 1}, + {.index = 4, .frames = 2}, +}}; /** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ bool is_step(codecs::result const& actual, std::size_t expected_count, @@ -57,14 +63,18 @@ bool is_step(codecs::result const& actual, std::size_t expected_co return actual.has_value() && actual->count == expected_count && actual->flow == expected_flow; } +/** Whether `actual` is the value `expected_flow`. */ +bool is_flow(codecs::result const& actual, codecs::flow expected_flow) { + return actual.has_value() && *actual == expected_flow; +} + /** Whether `actual` is frame `expected_index`, its pixels the index and the three that follow. */ bool is_frame(test::frame const& actual, std::uint32_t expected_index) { - return actual.index == expected_index && - actual.pixels == - std::array{static_cast(expected_index), - static_cast(expected_index + 1), - static_cast(expected_index + 2), - static_cast(expected_index + 3)}; + bool same = actual.index == expected_index; + for (std::size_t pixel = 0; pixel < actual.pixels.size(); ++pixel) { + same = same && actual.pixels[pixel] == static_cast(expected_index + pixel); + } + return same; } /** Sends one packet a send and receives one frame a receive, until each send's needs_input. */ @@ -99,17 +109,15 @@ void check_packets_to_frames() { // The hold-back delays frame 9 until flush. test::frame received{}; - auto const flushed = decoder.flush(); - BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::output_pending); + BOOST_TEST(is_flow(decoder.flush(), codecs::flow::output_pending)); BOOST_TEST(is_step(decoder.receive(std::span{&received, 1}), 1, codecs::flow::finished)); BOOST_TEST(is_frame(received, 9)); BOOST_TEST(is_step(decoder.receive(std::span{&received, 1}), 0, codecs::flow::finished)); BOOST_TEST(is_step(decoder.send(std::span{packets}.first(1)), 0, codecs::flow::finished)); } -/** The steps one by one: a packet of one frame gives nothing until the next packet. */ -void check_packets_to_frames_steps() { - test::packets_to_frames decoder; +/** Packets 0 to 3 one by one: a packet of one frame gives nothing until the next packet. */ +void step_through_first_packets(test::packets_to_frames& decoder) { std::array output{}; std::span const all{packets}; @@ -128,23 +136,35 @@ void check_packets_to_frames_steps() { BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::needs_input)); BOOST_TEST(is_frame(output[0], 4)); BOOST_TEST(is_step(decoder.send(all.subspan(3)), 1, codecs::flow::output_pending)); +} + +/** Packet 4 and flush, after step_through_first_packets: frames 5, 6, 8, then 9 after flush. */ +void step_through_last_packet(test::packets_to_frames& decoder) { + std::array output{}; + std::span const last = std::span{packets}.subspan(4); + // Packet 4 before frame 5 is received is refused; then it releases 6 and gives 8, holding 9. - BOOST_TEST(is_step(decoder.send(all.subspan(4)), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.send(last), 0, codecs::flow::output_pending)); BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::needs_input)); BOOST_TEST(is_frame(output[0], 5)); - BOOST_TEST(is_step(decoder.send(all.subspan(4)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.send(last), 1, codecs::flow::output_pending)); BOOST_TEST(is_step(decoder.receive(output), 2, codecs::flow::needs_input)); BOOST_TEST(is_frame(output[0], 6)); BOOST_TEST(is_frame(output[1], 8)); // flush releases 9; a second flush returns the state. - auto const flushed = decoder.flush(); - BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::output_pending); - auto const flushed_again = decoder.flush(); - BOOST_TEST(flushed_again.has_value() && *flushed_again == codecs::flow::output_pending); + BOOST_TEST(is_flow(decoder.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_flow(decoder.flush(), codecs::flow::output_pending)); BOOST_TEST(is_step(decoder.receive(output), 1, codecs::flow::finished)); BOOST_TEST(is_frame(output[0], 9)); +} + +/** The steps one by one, then reset, after which the stream starts again. */ +void check_packets_to_frames_steps() { + test::packets_to_frames decoder; + step_through_first_packets(decoder); + step_through_last_packet(decoder); - // reset: the stream starts again. + std::array output{}; decoder.reset(); BOOST_TEST(is_step(decoder.receive(output), 0, codecs::flow::needs_input)); std::vector const again = decode_one_by_one(decoder); @@ -155,8 +175,7 @@ void check_packets_to_frames_steps() { void check_packets_to_frames_empty_and_moved() { test::packets_to_frames decoder; std::array output{}; - auto const flushed = decoder.flush(); - BOOST_TEST(flushed.has_value() && *flushed == codecs::flow::finished); + BOOST_TEST(is_flow(decoder.flush(), codecs::flow::finished)); BOOST_TEST(is_step(decoder.receive(output), 0, codecs::flow::finished)); test::packets_to_frames source; @@ -176,8 +195,11 @@ void check_packets_to_frames_empty_and_moved() { /** The one-shot transformers' outputs for frame 4, and frames 5 and 6 for each byte count. */ void check_one_shot_outputs() { - std::array const frames{test::make_frame(4), test::make_frame(5), - test::make_frame(6)}; + std::array const frames{ + test::make_frame(4), + test::make_frame(5), + test::make_frame(6), + }; // frame_to_bytes: frame 4 writes 2 + 4 % 3 = 3 bytes, its index's low byte, then two pixels. std::array bytes{}; @@ -190,15 +212,14 @@ void check_one_shot_outputs() { auto const all_written = test::frame_to_bytes::transform(frames, bytes); BOOST_TEST(all_written.has_value() && *all_written == 9); std::array const expected_bytes{4, 4, 5, 5, 5, 6, 7, 6, 6}; - BOOST_TEST(std::equal(expected_bytes.begin(), expected_bytes.end(), bytes.begin())); + BOOST_TEST(std::ranges::equal(expected_bytes, std::span{bytes}.first(expected_bytes.size()))); // A short output: output_too_small, nothing written. std::array short_bytes{}; short_bytes.fill(0xAA); auto const refused = test::frame_to_bytes::transform(frames, short_bytes); BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::output_too_small); - BOOST_TEST(std::all_of(short_bytes.begin(), short_bytes.end(), - [](std::uint8_t value) { return value == 0xAA; })); + BOOST_TEST(std::ranges::all_of(short_bytes, [](std::uint8_t value) { return value == 0xAA; })); // The bounded one writes the same. std::array bounded{}; diff --git a/test/transformer_test.cpp b/test/transformer_test.cpp index fb07f0b..232d229 100644 --- a/test/transformer_test.cpp +++ b/test/transformer_test.cpp @@ -68,13 +68,13 @@ struct both_kinds { /** Accepts nothing. */ static webcpp::codecs::result send( std::span /*input*/) noexcept { - return webcpp::codecs::step{0, webcpp::codecs::flow::needs_input}; + return webcpp::codecs::step{.count = 0, .flow = webcpp::codecs::flow::needs_input}; } /** Writes nothing. */ static webcpp::codecs::result receive( std::span /*output*/) noexcept { - return webcpp::codecs::step{0, webcpp::codecs::flow::needs_input}; + return webcpp::codecs::step{.count = 0, .flow = webcpp::codecs::flow::needs_input}; } /** Ends at once. */ @@ -96,7 +96,7 @@ struct throwing_reset : both_kinds { struct wrong_flush : both_kinds { /** The wrong type. */ static webcpp::codecs::result flush() noexcept { - return webcpp::codecs::step{0, webcpp::codecs::flow::finished}; + return webcpp::codecs::step{.count = 0, .flow = webcpp::codecs::flow::finished}; } }; From 2a80c9304a8d465656e38cbd6ea3e6db4dabcb53 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 15:42:54 -0300 Subject: [PATCH 047/157] codecs: transformer contract lint fix, the packet arrays of typed elements --- test/allocation_test.cpp | 10 +++++----- test/toy_media_test.cpp | 12 +++++------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index b185a19..d86d33f 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -549,11 +549,11 @@ void check_over() { /** The transformers of the tests' own, a stream and the one-shots of the toy media, convert in the caller's spans and allocate nothing (D17, D18). */ void check_transformers() { - std::array const packets{{ - {.index = 0, .frames = 1}, - {.index = 1, .frames = 2}, - {.index = 2, .frames = 0}, - }}; + std::array const packets{ + test::packet{.index = 0, .frames = 1}, + test::packet{.index = 1, .frames = 2}, + test::packet{.index = 2, .frames = 0}, + }; std::array frames{}; std::array frame_bytes{}; std::array images{}; diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index a55c491..1231b8c 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -49,13 +49,11 @@ static_assert(!codecs::is_constant_time_v); static_assert(!codecs::is_constant_time_v); /** Five packets of 1, 0, 2, 1 and 2 frames. */ -constexpr std::array packets{{ - {.index = 0, .frames = 1}, - {.index = 1, .frames = 0}, - {.index = 2, .frames = 2}, - {.index = 3, .frames = 1}, - {.index = 4, .frames = 2}, -}}; +constexpr std::array packets{ + test::packet{.index = 0, .frames = 1}, test::packet{.index = 1, .frames = 0}, + test::packet{.index = 2, .frames = 2}, test::packet{.index = 3, .frames = 1}, + test::packet{.index = 4, .frames = 2}, +}; /** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ bool is_step(codecs::result const& actual, std::size_t expected_count, From 375b2794896c6fc71b084c2729d30ba5737a97ef Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 16:16:11 -0300 Subject: [PATCH 048/157] codecs: the transformer test without the unused --- test/transformer_test.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/test/transformer_test.cpp b/test/transformer_test.cpp index 232d229..c53af1e 100644 --- a/test/transformer_test.cpp +++ b/test/transformer_test.cpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include #include From ea97d4bc25338b624d33281862d4e70be4976bc2 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 16:30:40 -0300 Subject: [PATCH 049/157] codecs: pipe and drain, composed by element types alone, in place, with their refusals --- include/webcpp/codecs.hpp | 1 + include/webcpp/codecs/detail/core/pipe.hpp | 679 ++++++++++++++++++ test/Jamfile | 7 + test/allocation_test.cpp | 37 + test/drain_test.cpp | 203 ++++++ test/messages/Jamfile | 2 + test/messages/pipe_incompatible/Jamfile | 16 + .../pipe_incompatible/pipe_incompatible.cpp | 28 + test/messages/pipe_one_shot/Jamfile | 16 + test/messages/pipe_one_shot/pipe_one_shot.cpp | 27 + test/noexcept_test.cpp | 65 ++ test/pipe_test.cpp | 562 +++++++++++++++ 12 files changed, 1643 insertions(+) create mode 100644 include/webcpp/codecs/detail/core/pipe.hpp create mode 100644 test/drain_test.cpp create mode 100644 test/messages/pipe_incompatible/Jamfile create mode 100644 test/messages/pipe_incompatible/pipe_incompatible.cpp create mode 100644 test/messages/pipe_one_shot/Jamfile create mode 100644 test/messages/pipe_one_shot/pipe_one_shot.cpp create mode 100644 test/pipe_test.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 8846c74..20ff44a 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp new file mode 100644 index 0000000..acbf780 --- /dev/null +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -0,0 +1,679 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The composition of stream transformers (D19): `pipe`, which joins two by their element types + alone through an intermediate in place, and `drain`, which receives from one into a sink. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_PIPE_HPP +#define WEBCPP_CODECS_DETAIL_CORE_PIPE_HPP + +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** + The capacity of a pipe's intermediate when the call names none: the default of the first + transformer's output elements, and one element for a type that states none, which `pipe` refuses. +*/ +template +constexpr std::size_t default_intermediate_capacity() noexcept { + if constexpr (transformer_types) { + return default_capacity_v; + } else { + return 1; + } +} + +/** Whether every call of the stream transformer `T` is `noexcept`. */ +template +concept nothrow_stream_calls = + requires(T& transformer, std::span input, + std::span output) { + { transformer.send(input) } noexcept; + { transformer.receive(output) } noexcept; + { transformer.flush() } noexcept; + }; + +/** The element types of a pipe's two parts, the first's output and the second's input. */ +template +struct element_pair {}; + +/** + Whether elements of `From` are read as elements of `To`. The types are deduced from the pair, + which drops the names they were spelled by (`typename First::output_type`): clang prints a + concept's requirement as its first check spelled it, and this check comes first, so that a + refusal's requirement names both element types in full on every clang (ruling R2). +*/ +template +constexpr bool elements_compatible(element_pair /*elements*/) noexcept { + // Spelled as the refusal spells it, which prints this spelling. + return detail::compatible_elements; +} + +/** + Whether `First` and `Second` are stream transformers and the first's output elements are read + as the second's input. +*/ +template +concept pipeable = + stream_transformer && stream_transformer && + elements_compatible(element_pair{}); + +/** + Stops the build: `pipe` was given two transformers, the first of which writes elements of `From` + that the second, which reads elements of `To`, cannot read. +*/ +template +constexpr void refuse_elements(element_pair /*elements*/) noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(detail::compatible_elements, + "webcpp::codecs: the first transformer's output_type is not the second's " + "input_type"); +} + +/** Whether each of `Types` is moved without throwing. */ +template +inline constexpr bool nothrow_movable_v = (std::is_nothrow_move_constructible_v && ...); + +} // namespace detail + +/** + A stream transformer that sends its input through `First` and then through `Second`, holding the + elements between them in an intermediate of `Capacity` elements in place (D19). + + It is made by @ref pipe. + + `send` gives the input to `First`, which borrows it as the protocol says. `receive` moves + `First`'s output into the intermediate, sends it to `Second`, which borrows it until it reports + `flow::needs_input`, and receives `Second`'s output into the caller's span, as long as the span + has room. `flush` flushes `First`, and `Second` once `First` is finished and `Second` has taken + the whole intermediate. `reset` resets both. The first error of either part is the pipe's, and + every later call returns it until `reset`; a `receive` that has already written output when it + meets the error returns that output, and the next call returns the error, so that a call that + reports an error writes nothing. + + The pipe allocates nothing. It is constant time when both parts are, and each call is `noexcept` + when the parts' calls are. It is not copyable: `Second` may borrow its intermediate. A move takes + the parts and the intermediate's elements that `Second` has not taken, and leaves the moved-from + pipe in the state `reset` leaves, so that it converts a new input from the start. Between a + `receive` that reports `flow::output_pending` and the next call that reports `flow::needs_input` + or `flow::finished`, `Second` may still borrow the intermediate, which a move would carry away + from it: the pipe must not be moved in that window. + + @tparam First The first transformer, whose input is the pipe's. + @tparam Second The second transformer, whose output is the pipe's. + @tparam Capacity The intermediate's elements, at least one. +*/ +template +class piped { + static_assert(Capacity > 0, "webcpp::codecs: a pipe's intermediate holds at least one element"); + + /** The elements between the parts. */ + using intermediate_type = typename First::output_type; + /** The elements `Second` reads. */ + using second_input_type = typename Second::input_type; + + /** Whether every call of both parts is `noexcept`. */ + static constexpr bool nothrow_calls = + detail::nothrow_stream_calls && detail::nothrow_stream_calls; + + /** Whether the parts and the intermediate's elements are moved without throwing. */ + static constexpr bool nothrow_moves = + detail::nothrow_movable_v && + std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v && + std::is_nothrow_move_assignable_v; + +public: + /** The elements the pipe reads: `First`'s. */ + using input_type = typename First::input_type; + /** The elements the pipe writes: `Second`'s. */ + using output_type = typename Second::output_type; + + /** The pipe runs in a time that does not depend on its data when both parts do. */ + static constexpr bool constant_time = is_constant_time_v && is_constant_time_v; + + /** + Makes a pipe of `first` and then `second`, in `flow::needs_input`; both are reset, so that the + pipe starts with nothing borrowed or pending. + + @param first The first transformer. + @param second The second transformer. + */ + piped(First first, Second second) noexcept(detail::nothrow_movable_v) + : first_(std::move(first)), second_(std::move(second)) { + first_.reset(); + second_.reset(); + } + + /** Not copyable: `Second` may borrow the intermediate. */ + piped(piped const&) = delete; + /** Not copyable: `Second` may borrow the intermediate. */ + piped& operator=(piped const&) = delete; + + /** + Takes `other`'s parts, state and the intermediate's elements that `Second` has not taken, and + leaves `other` as `reset` does. + + `other`'s `Second` must not borrow its intermediate. + + @param other The pipe moved from. + */ + piped(piped&& other) noexcept(nothrow_moves) + : first_(std::move(other.first_)), second_(std::move(other.second_)) { + take_state(other); + } + + /** + Takes `other`'s parts, state and the intermediate's elements that `Second` has not taken, and + leaves `other` as `reset` does. + + `other`'s `Second` must not borrow its intermediate. + + @param other The pipe moved from. + @return This pipe. + */ + piped& operator=(piped&& other) noexcept(nothrow_moves) { + if (this != &other) { + first_ = std::move(other.first_); + second_ = std::move(other.second_); + take_state(other); + } + return *this; + } + + /** Destroys both parts. */ + ~piped() = default; + + /** + Gives `input` to `First` in `flow::needs_input`; accepts nothing in another state. + + @param input The elements to convert, borrowed as `First` borrows them. + @return The elements accepted and the state after, or the pipe's error. + */ + result send(std::span input) noexcept(nothrow_calls) { + if (error_) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + auto const sent = first_.send(input); + if (!sent) { + error_ = sent.error(); + return error_; + } + first_flow_ = sent->flow; + return step{.count = sent->count, .flow = state()}; + } + + /** + Writes `Second`'s output into `output`, moving `First`'s output through the intermediate as + long as `output` has room. + + @param output The span to write into. + @return The elements written and the state after, or the pipe's error. + */ + result receive(std::span output) noexcept(nothrow_calls) { + if (error_) { + return error_; + } + std::size_t written = 0; + bool progressed = true; + while (progressed && written < output.size()) { + auto const advanced = advance(output.subspan(written)); + if (!advanced) { + return fail(advanced.error(), written); + } + written += advanced->written; + progressed = advanced->progressed; + } + if (auto const flushed = flush_second_when_due(); !flushed) { + return fail(flushed.error(), written); + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input: flushes `First`, and `Second` once `First` is finished and `Second` has taken + the whole intermediate. + + @return `flow::output_pending` while output remains, `flow::finished` when none does, or the + pipe's error. + */ + result flush() noexcept(nothrow_calls) { + if (error_) { + return error_; + } + auto const flushed = first_.flush(); + if (!flushed) { + error_ = flushed.error(); + return error_; + } + first_flow_ = *flushed; + if (auto const second_flushed = flush_second_when_due(); !second_flushed) { + error_ = second_flushed.error(); + return error_; + } + return state(); + } + + /** Resets both parts and returns to `flow::needs_input`, with nothing pending and no error. */ + void reset() noexcept { + first_.reset(); + second_.reset(); + first_flow_ = flow::needs_input; + second_flow_ = flow::needs_input; + sent_ = 0; + size_ = 0; + lent_ = false; + error_.clear(); + } + +private: + /** What one step of `receive`'s work did. */ + struct advanced_step { + /** The elements written into the caller's span. */ + std::size_t written; + /** Whether a part wrote, accepted or changed its state. */ + bool progressed; + }; + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (second_flow_ == flow::finished) { + return flow::finished; + } + if (first_flow_ != flow::needs_input || sent_ < size_ || + second_flow_ == flow::output_pending) { + return flow::output_pending; + } + return flow::needs_input; + } + + /** The intermediate's elements not yet sent to `Second`, as it reads them. */ + [[nodiscard]] std::span unsent() const noexcept { + std::span const elements = + std::span{intermediate_}.subspan(sent_, size_ - sent_); + if constexpr (std::is_same_v) { + return elements; + } else { + // One-byte elements are read as each other's type, as any object is read through a + // char, an unsigned char or a std::byte (D19). + return {reinterpret_cast(elements.data()), elements.size()}; + } + } + + /** + One step of `receive`'s work, `Second`'s output first: receive from `Second` while it has + output; send it the rest of the intermediate while it needs input; when it has taken the + whole intermediate, refill it from `First`, or flush `Second` once `First` is finished. + */ + result advance(std::span output) noexcept(nothrow_calls) { + if (second_flow_ == flow::output_pending) { + auto const received = second_.receive(output); + if (!received) { + return received.error(); + } + bool const progressed = received->count > 0 || received->flow != second_flow_; + second_flow_ = received->flow; + lent_ = lent_ && second_flow_ == flow::output_pending; + return advanced_step{.written = received->count, .progressed = progressed}; + } + if (second_flow_ == flow::finished) { + return advanced_step{.written = 0, .progressed = false}; + } + if (sent_ < size_) { + auto const sent = second_.send(unsent()); + if (!sent) { + return sent.error(); + } + bool const progressed = sent->count > 0 || sent->flow != second_flow_; + sent_ += sent->count; + second_flow_ = sent->flow; + lent_ = second_flow_ == flow::output_pending && (lent_ || sent->count > 0); + return advanced_step{.written = 0, .progressed = progressed}; + } + // Second has taken the whole intermediate and handed it back: it is free. + sent_ = 0; + size_ = 0; + if (first_flow_ == flow::output_pending) { + auto const received = first_.receive(std::span{intermediate_}); + if (!received) { + return received.error(); + } + bool const progressed = received->count > 0 || received->flow != first_flow_; + size_ = received->count; + first_flow_ = received->flow; + return advanced_step{.written = 0, .progressed = progressed}; + } + auto const flushed = flush_second_when_due(); + if (!flushed) { + return flushed.error(); + } + return advanced_step{.written = 0, .progressed = *flushed}; + } + + /** + Flushes `Second` when `First` is finished and `Second` has taken and handed back the whole + intermediate, once. + + @return Whether it flushed `Second`, or `Second`'s error. + */ + result flush_second_when_due() noexcept(nothrow_calls) { + if (first_flow_ != flow::finished || sent_ < size_ || second_flow_ != flow::needs_input) { + return false; + } + auto const flushed = second_.flush(); + if (!flushed) { + return flushed.error(); + } + second_flow_ = *flushed; + return true; + } + + /** + Keeps `error` as the pipe's. A `receive` that has written `written` elements returns them, + and the next call the error. + */ + result fail(boost::system::error_code error, std::size_t written) noexcept { + error_ = error; + if (written == 0) { + return error_; + } + return step{.count = written, .flow = flow::output_pending}; + } + + /** + Takes `other`'s state and the intermediate's elements `Second` has not taken, its parts being + moved already, and leaves `other` as `reset` does. + */ + void take_state(piped& other) noexcept(nothrow_moves) { + // Second's borrow of the intermediate cannot follow it to another object. + BOOST_ASSERT(!other.lent_); + std::span const unsent_elements = + std::span{other.intermediate_}.subspan(other.sent_, other.size_ - other.sent_); + std::ranges::move(unsent_elements, intermediate_.begin()); + first_flow_ = other.first_flow_; + second_flow_ = other.second_flow_; + sent_ = 0; + size_ = unsent_elements.size(); + lent_ = false; + error_ = other.error_; + other.reset(); + } + + /** The first transformer. */ + First first_; + /** The second transformer. */ + Second second_; + /** The elements `First` wrote and `Second` reads. */ + std::array intermediate_{}; + /** `First`'s state after its last call. */ + flow first_flow_ = flow::needs_input; + /** `Second`'s state after its last call. */ + flow second_flow_ = flow::needs_input; + /** The intermediate's elements sent to `Second`. */ + std::size_t sent_ = 0; + /** The intermediate's elements `First` wrote. */ + std::size_t size_ = 0; + /** Whether `Second` borrows elements of the intermediate. */ + bool lent_ = false; + /** The pipe's error, which every call returns until `reset`. */ + boost::system::error_code error_; +}; + +/** + A stream transformer of `first` and then `second`, with an intermediate in place of `N` elements + of `first`'s output (D19). + + It compiles only when both are stream transformers and `first`'s `output_type` is compatible with + `second`'s `input_type`: the same type, or both one-byte character or byte types. A one-shot + transformer is made a stream by `codecs::each` (per item) or `codecs::buffered` (accumulating). + + @tparam First The first transformer's type. + @tparam Second The second transformer's type. + @tparam N The intermediate's elements. + @param first The first transformer. + @param second The second transformer. + @return A @ref piped of the two. +*/ +template +[[nodiscard]] auto pipe(First first, Second second, capacity_t /*capacity*/) noexcept( + detail::nothrow_movable_v) { + if constexpr (!(stream_transformer && stream_transformer)) { + static_assert(stream_transformer && stream_transformer, + "webcpp::codecs: pipe and drain take stream transformers; make a one-shot " + "transformer one with codecs::each (per item) or codecs::buffered " + "(accumulating)"); + } else if constexpr (!detail::pipeable) { + detail::refuse_elements( + detail::element_pair{}); + } else { + return piped{std::move(first), std::move(second)}; + } +} + +/** + A stream transformer of `first` and then `second`, with an intermediate in place of + `codecs::default_capacity_v` elements of `first`'s output (D19). + + `codecs::capacity` as a third argument sets another capacity. It compiles only when both are + stream transformers and `first`'s `output_type` is compatible with `second`'s `input_type`. + + @tparam First The first transformer's type. + @tparam Second The second transformer's type. + @param first The first transformer. + @param second The second transformer. + @return A @ref piped of the two. +*/ +template +[[nodiscard]] auto pipe(First first, + Second second) noexcept(detail::nothrow_movable_v) { + return codecs::pipe(std::move(first), std::move(second), + capacity()>); +} + +namespace detail { + +/** + Whether the pipe of three or more transformers cannot throw: the moves of its arguments and the + pipes it makes; true when it refuses them. +*/ +template +constexpr bool nothrow_pipe_of_many() noexcept { + if constexpr (pipeable) { + using first_two = piped()>; + if constexpr (sizeof...(Rest) == 0) { + return nothrow_movable_v; + } else { + return nothrow_movable_v && + nothrow_pipe_of_many(); + } + } else { + return true; + } +} + +} // namespace detail + +/** + The pipe of three or more stream transformers, from the left: `pipe(a, b, c)` is + `pipe(pipe(a, b), c)`, each intermediate of the default capacity. + + @tparam First The first transformer's type. + @tparam Second The second transformer's type. + @tparam Third The third transformer's type. + @tparam Rest The types of the transformers after the third. + @param first The first transformer. + @param second The second transformer. + @param third The third transformer. + @param rest The transformers after the third. + @return A @ref piped whose first part is the pipe of the transformers before the last. +*/ +template +[[nodiscard]] auto pipe(First first, Second second, Third third, Rest... rest) noexcept( + detail::nothrow_pipe_of_many()) { + if constexpr (detail::pipeable) { + return codecs::pipe(codecs::pipe(std::move(first), std::move(second)), std::move(third), + std::move(rest)...); + } else { + // Refuses the first two, with their message. + return codecs::pipe(std::move(first), std::move(second)); + } +} + +namespace detail { + +/** Whether a drain of `T` into `Sink` cannot throw: `T`'s `receive` and the sink's call cannot. */ +template +constexpr bool nothrow_drain() noexcept { + if constexpr (stream_transformer) { + using output_type = typename T::output_type; + return noexcept(std::declval().receive(std::declval>())) && + std::is_nothrow_invocable_v>; + } else { + return true; + } +} + +/** + Receives from `transformer` into `buffer` until it reports `flow::needs_input` or + `flow::finished`, giving each non-empty piece to `sink`. +*/ +template +result drain_through( + T& transformer, Sink& sink, + std::span buffer) noexcept(nothrow_drain()) { + using output_type = typename T::output_type; + for (;;) { + auto const received = transformer.receive(buffer); + if (!received) { + return received.error(); + } + if (received->count > 0) { + std::span const piece = buffer.first(received->count); + if constexpr (std::is_void_v< + std::invoke_result_t>>) { + sink(piece); + } else if (auto const sunk = sink(piece); !sunk) { + return sunk.error(); + } + } + if (received->flow != flow::output_pending) { + return received->flow; + } + if (received->count == 0) { + // Output is pending and the buffer took none of it: another call would not either. + return error::output_too_small; + } + } +} + +} // namespace detail + +/** + Receives from `transformer` until it reports `flow::needs_input` or `flow::finished`, and calls + `sink(std::span)` with each non-empty piece, through a buffer in place of + `codecs::default_capacity_v` elements (D19). + + The sink is called directly, as a template parameter, and returns `void` or + `codecs::result`, whose error stops the drain. When output is pending and the transformer + writes none of it into the buffer, the drain stops with `error::output_too_small`. + + @tparam T The transformer's type. + @tparam Sink The sink's type. + @param transformer A stream transformer; a one-shot transformer is made one by `codecs::each` + (per item) or `codecs::buffered` (accumulating). + @param sink What takes each piece. + @return The state the drain stopped at, or the first error, the transformer's or the sink's. +*/ +template +[[nodiscard]] result drain(T& transformer, + Sink&& sink) noexcept(detail::nothrow_drain()) { + if constexpr (stream_transformer) { + using output_type = typename T::output_type; + std::array> buffer{}; + return detail::drain_through(transformer, sink, std::span{buffer}); + } else { + static_assert(stream_transformer, + "webcpp::codecs: pipe and drain take stream transformers; make a one-shot " + "transformer one with codecs::each (per item) or codecs::buffered " + "(accumulating)"); + return error::output_too_small; + } +} + +/** + Receives from `transformer` into `sink` as @ref drain does, through a buffer in place of `N` + elements. + + @tparam T The transformer's type. + @tparam Sink The sink's type. + @tparam N The buffer's elements. + @param transformer A stream transformer. + @param sink What takes each piece, of at most `N` elements. + @return The state the drain stopped at, or the first error, the transformer's or the sink's. +*/ +template +[[nodiscard]] result drain(T& transformer, Sink&& sink, capacity_t /*capacity*/) noexcept( + detail::nothrow_drain()) { + if constexpr (stream_transformer) { + std::array buffer{}; + return detail::drain_through(transformer, sink, std::span{buffer}); + } else { + static_assert(stream_transformer, + "webcpp::codecs: pipe and drain take stream transformers; make a one-shot " + "transformer one with codecs::each (per item) or codecs::buffered " + "(accumulating)"); + return error::output_too_small; + } +} + +/** + Receives from `transformer` into `sink` as @ref drain does, through the caller's `buffer`: each + piece is a view of its first elements. + + @tparam T The transformer's type. + @tparam Sink The sink's type. + @param transformer A stream transformer. + @param sink What takes each piece. + @param buffer The span the transformer writes each piece into. + @return The state the drain stopped at, or the first error, the transformer's or the sink's. +*/ +template +[[nodiscard]] result drain( + T& transformer, Sink&& sink, + std::span buffer) noexcept(detail::nothrow_drain()) { + if constexpr (stream_transformer) { + return detail::drain_through(transformer, sink, buffer); + } else { + static_assert(stream_transformer, + "webcpp::codecs: pipe and drain take stream transformers; make a one-shot " + "transformer one with codecs::each (per item) or codecs::buffered " + "(accumulating)"); + return error::output_too_small; + } +} + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_PIPE_HPP diff --git a/test/Jamfile b/test/Jamfile index 8c3a5bb..f068054 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -80,6 +80,13 @@ codecs-run transformer : transformer_test.cpp ; # The toy media types: transformers of packets, frames and images, no byte or # character among their elements, satisfy the contract. codecs-run toy_media : toy_media_test.cpp ; +# pipe (D19): two stream transformers composed by their element types alone, +# with an intermediate in place; the first error of either is the pipe's; a +# moved-from pipe starts again. +codecs-run pipe : pipe_test.cpp ; +# drain (D19): the pieces a sink is given, through drain's own buffer, a +# capacity or the caller's span; a sink's error stops it. +codecs-run drain : drain_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index d86d33f..d0328eb 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -602,6 +602,42 @@ void check_transformers() { static_cast(sink); } +/** + pipe and drain allocate nothing (D21): a pipe made, streamed, flushed, moved and reset, and + drains through drain's own buffer, a capacity and the caller's span. +*/ +void check_pipe_and_drain() { + std::array piped_output{}; + std::array drain_buffer{}; + bool volatile verdict = false; + expect_no_allocation("pipe of two doublers", [&] { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); + bool streamed = piped.send(std::string_view{"abc"}).has_value(); + auto const received = piped.receive(piped_output); + streamed = + streamed && received.has_value() && received->count == 12 && piped.flush().has_value(); + auto moved{std::move(piped)}; + moved.reset(); + verdict = streamed && std::string_view{piped_output.data(), 12} == "aaaabbbbcccc"; + }); + BOOST_TEST(verdict); + expect_no_allocation("drain of a pipe of three doublers", [&] { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}); + std::size_t total = 0; + auto sink = [&total](std::span piece) noexcept { total += piece.size(); }; + bool drained = piped.send(std::string_view{"abc"}).has_value() && + codecs::drain(piped, sink).has_value(); + drained = drained && piped.send(std::string_view{"de"}).has_value() && + codecs::drain(piped, sink, codecs::capacity<3>).has_value(); + drained = + drained && piped.send(std::string_view{"f"}).has_value() && piped.flush().has_value(); + auto const last = codecs::drain(piped, sink, std::span{drain_buffer}); + verdict = + drained && last.has_value() && last.value() == codecs::flow::finished && total == 48; + }); + BOOST_TEST(verdict); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -652,6 +688,7 @@ int main() { check_assign_to_scratch(); check_over(); check_transformers(); + check_pipe_and_drain(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/drain_test.cpp b/test/drain_test.cpp new file mode 100644 index 0000000..1ef0c5e --- /dev/null +++ b/test/drain_test.cpp @@ -0,0 +1,203 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// drain (D19): receives from a stream transformer until it reports needs_input or finished and +// gives each non-empty piece to a sink, through its own buffer in place, one of capacity, or +// the caller's span; a sink's error stops it and is returned (the spec's scenario). + +#include "support/doubler.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** A sink that keeps every piece it is given. */ +struct collector { + /** The pieces, in order. */ + std::vector pieces; + + /** Keeps `piece`. */ + void operator()(std::span piece) { + pieces.emplace_back(piece.begin(), piece.end()); + } + + /** The pieces joined. */ + [[nodiscard]] std::string joined() const { + std::string all; + for (std::string const& piece : pieces) { + all += piece; + } + return all; + } + + /** Whether every piece holds at least one character and at most `most`. */ + [[nodiscard]] bool pieces_within(std::size_t most) const { + for (std::string const& piece : pieces) { + if (piece.empty() || piece.size() > most) { + return false; + } + } + return true; + } +}; + +/** Whether `drained` is the state `state`. */ +bool is_flow(codecs::result const& drained, codecs::flow state) { + return drained.has_value() && drained.value() == state; +} + +/** drain stops at needs_input after a send and at finished after flush. */ +void stops() { + test::doubler transformer; + collector sink; + BOOST_TEST(transformer.send(std::string_view{"abc"}).has_value()); + BOOST_TEST(is_flow(codecs::drain(transformer, sink), codecs::flow::needs_input)); + BOOST_TEST_EQ(sink.joined(), "aabbcc"); + BOOST_TEST(sink.pieces_within(codecs::default_capacity_v)); + // Nothing pending: drain returns the state at once and calls no sink. + BOOST_TEST(is_flow(codecs::drain(transformer, sink), codecs::flow::needs_input)); + BOOST_TEST_EQ(sink.pieces.size(), 1U); + BOOST_TEST(transformer.send(std::string_view{"de"}).has_value()); + BOOST_TEST(transformer.flush().has_value()); + BOOST_TEST(is_flow(codecs::drain(transformer, sink), codecs::flow::finished)); + BOOST_TEST_EQ(sink.joined(), "aabbccddee"); + BOOST_TEST(is_flow(codecs::drain(transformer, sink), codecs::flow::finished)); + BOOST_TEST_EQ(sink.pieces.size(), 2U); +} + +/** With capacity<3>, the pieces hold at most 3 elements; their concatenation is the output. */ +void capacity_pieces() { + test::doubler transformer; + collector sink; + BOOST_TEST(transformer.send(std::string_view{"abcdefgh"}).has_value()); + BOOST_TEST( + is_flow(codecs::drain(transformer, sink, codecs::capacity<3>), codecs::flow::needs_input)); + BOOST_TEST(transformer.flush().has_value()); + BOOST_TEST( + is_flow(codecs::drain(transformer, sink, codecs::capacity<3>), codecs::flow::finished)); + BOOST_TEST_EQ(sink.joined(), "aabbccddeeffgghh"); + BOOST_TEST(sink.pieces_within(3)); + BOOST_TEST_EQ(sink.pieces.size(), 6U); +} + +/** With the caller's span of 5, the pieces hold at most 5 elements and are views of that span. */ +void span_pieces() { + test::doubler transformer; + std::array buffer{}; + std::string joined; + std::size_t pieces = 0; + bool in_buffer = true; + auto sink = [&](std::span piece) noexcept { + ++pieces; + in_buffer = in_buffer && piece.data() == buffer.data() && piece.size() <= buffer.size() && + !piece.empty(); + joined.append(piece.begin(), piece.end()); + }; + BOOST_TEST(transformer.send(std::string_view{"abcdefgh"}).has_value()); + BOOST_TEST(transformer.flush().has_value()); + BOOST_TEST( + is_flow(codecs::drain(transformer, sink, std::span{buffer}), codecs::flow::finished)); + BOOST_TEST_EQ(joined, "aabbccddeeffgghh"); + BOOST_TEST_EQ(pieces, 4U); + BOOST_TEST(in_buffer); +} + +/** A sink that returns an error at its second piece stops the drain, which returns that error. */ +void sink_error() { + test::doubler transformer; + std::size_t calls = 0; + std::string joined; + auto sink = [&](std::span piece) -> codecs::result { + ++calls; + if (calls == 2) { + return codecs::error::invalid_character; + } + joined.append(piece.begin(), piece.end()); + return {}; + }; + BOOST_TEST(transformer.send(std::string_view{"abcdefgh"}).has_value()); + auto const drained = codecs::drain(transformer, sink, codecs::capacity<3>); + BOOST_TEST(!drained.has_value()); + BOOST_TEST(drained.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(calls, 2U); + BOOST_TEST_EQ(joined, "aab"); + // The piece the sink refused was received: a sink that succeeds takes what follows it. + std::string all; + auto accepting = [&](std::span piece) -> codecs::result { + all.append(piece.begin(), piece.end()); + return {}; + }; + BOOST_TEST(is_flow(codecs::drain(transformer, accepting, codecs::capacity<3>), + codecs::flow::needs_input)); + BOOST_TEST_EQ(all, "ddeeffgghh"); +} + +/** A temporary sink, and a pipe drained like any stream transformer. */ +void pipes_and_temporaries() { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<2>); + std::string joined; + BOOST_TEST(piped.send(std::string_view{"xyz"}).has_value()); + BOOST_TEST(piped.flush().has_value()); + BOOST_TEST(is_flow( + codecs::drain( + piped, + [&joined](std::span piece) { joined.append(piece.begin(), piece.end()); }, + codecs::capacity<5>), + codecs::flow::finished)); + BOOST_TEST_EQ(joined, "xxxxyyyyzzzz"); + // A std::function, called as any sink. + piped.reset(); + std::string through_function; + std::function)> const function_sink = + [&through_function](std::span piece) { + through_function.append(piece.begin(), piece.end()); + }; + BOOST_TEST(piped.send(std::string_view{"q"}).has_value()); + BOOST_TEST(is_flow(codecs::drain(piped, function_sink), codecs::flow::needs_input)); + BOOST_TEST_EQ(through_function, "qqqq"); +} + +/** + A buffer of no element cannot take output that is pending: drain reports output_too_small rather + than calling forever; with nothing pending, it returns the state. +*/ +void empty_buffer() { + test::doubler transformer; + collector sink; + BOOST_TEST( + is_flow(codecs::drain(transformer, sink, std::span{}), codecs::flow::needs_input)); + BOOST_TEST(transformer.send(std::string_view{"a"}).has_value()); + auto const drained = codecs::drain(transformer, sink, std::span{}); + BOOST_TEST(!drained.has_value()); + BOOST_TEST(drained.error() == codecs::error::output_too_small); + BOOST_TEST(sink.pieces.empty()); +} + +} // namespace + +int main() { + stops(); + capacity_pieces(); + span_pieces(); + sink_error(); + pipes_and_temporaries(); + empty_buffer(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index a3c492b..6b718b3 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -23,3 +23,5 @@ build-project refused_allocator ; build-project refused_secret_overload ; build-project refused_secret_parameters ; build-project refused_secret_value_overload ; +build-project pipe_incompatible ; +build-project pipe_one_shot ; diff --git a/test/messages/pipe_incompatible/Jamfile b/test/messages/pipe_incompatible/Jamfile new file mode 100644 index 0000000..4fe6fde --- /dev/null +++ b/test/messages/pipe_incompatible/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pipe_incompatible : pipe_incompatible.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail pipe_incompatible_refused : pipe_incompatible.cpp + : clang:no : native emscripten ; diff --git a/test/messages/pipe_incompatible/pipe_incompatible.cpp b/test/messages/pipe_incompatible/pipe_incompatible.cpp new file mode 100644 index 0000000..0194d3d --- /dev/null +++ b/test/messages/pipe_incompatible/pipe_incompatible.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A pipe whose first transformer's output_type is not its second's input_type stops in pipe's +// refusal, whose requirement names both element types (ruling R2): a doubler writes characters +// and packets_to_frames reads packets. The requirement is a concept, which clang prints in the +// note that follows the error rather than in the error's own line. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: the first transformer's output_type is not the second's input_type}} +// expected-note@webcpp/codecs/detail/core/pipe.hpp:* {{because 'detail::compatible_elements' evaluated to false}} +// clang-format on + +#include "../../support/doubler.hpp" +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + static_cast(codecs::pipe(codecs::test::doubler{}, codecs::test::packets_to_frames{})); + return 0; +} diff --git a/test/messages/pipe_one_shot/Jamfile b/test/messages/pipe_one_shot/Jamfile new file mode 100644 index 0000000..2d7ea3e --- /dev/null +++ b/test/messages/pipe_one_shot/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pipe_one_shot : pipe_one_shot.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail pipe_one_shot_refused : pipe_one_shot.cpp + : clang:no : native emscripten ; diff --git a/test/messages/pipe_one_shot/pipe_one_shot.cpp b/test/messages/pipe_one_shot/pipe_one_shot.cpp new file mode 100644 index 0000000..dbd3aad --- /dev/null +++ b/test/messages/pipe_one_shot/pipe_one_shot.cpp @@ -0,0 +1,27 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A pipe of a one-shot transformer stops in pipe's refusal, whose message names the two ways to +// make it a stream (B31): frame_to_image converts whole frames at once. The note that follows the +// error names the type refused. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: pipe and drain take stream transformers; make a one-shot transformer one with codecs::each (per item) or codecs::buffered (accumulating)}} +// expected-note@webcpp/codecs/detail/core/pipe.hpp:* {{because 'webcpp::codecs::test::frame_to_image' does not satisfy 'stream_transformer'}} +// clang-format on + +#include "../../support/doubler.hpp" +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + static_cast(codecs::pipe(codecs::test::doubler{}, codecs::test::frame_to_image{})); + return 0; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index cbf2126..9105e1d 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -9,6 +9,7 @@ // add their rows, both ways. #include "support/be16.hpp" +#include "support/doubler.hpp" #include "support/letters.hpp" #include @@ -244,4 +245,68 @@ static_assert(!codecs::detail::text_token< static_assert(codecs::detail::byte_token< decltype(tokens::append_to(std::declval&>()))>); +// pipe and drain (Task 9): a pipe of parts whose calls are noexcept is noexcept in every member, +// and is made without throwing. +using doubled = codecs::piped; +static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}))); +static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<1>))); +static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}))); +static_assert(std::is_nothrow_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_destructible_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +/** A doubler whose send and receive may throw, as an allocating transformer's may. */ +struct throwing_doubler : test::doubler { + /** Sends as a doubler does, not noexcept. */ + codecs::result send(std::span input) { + return test::doubler::send(input); + } + + /** Receives as a doubler does, not noexcept. */ + codecs::result receive(std::span output) { + return test::doubler::receive(output); + } +}; + +static_assert(codecs::stream_transformer); + +// A part's call that may throw makes the pipe's calls that make it not noexcept, so that its +// exception propagates (owner decision 24); reset stays noexcept, as the concept requires. +using partly_throwing = codecs::piped; +static_assert(!noexcept(std::declval().send(std::span{}))); +static_assert(!noexcept(std::declval().receive(std::span{}))); +static_assert(!noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +/** A sink that cannot throw. */ +struct nothrow_sink { + /** Takes a piece. */ + void operator()(std::span /*piece*/) const noexcept {} +}; + +/** A sink that may throw. */ +struct throwing_sink { + /** Takes a piece. */ + void operator()(std::span /*piece*/) const {} +}; + +// drain is noexcept when the transformer's receive and the sink are, in each form. +static_assert(noexcept(codecs::drain(std::declval(), nothrow_sink{}))); +static_assert(noexcept(codecs::drain(std::declval(), nothrow_sink{}))); +static_assert(noexcept(codecs::drain(std::declval(), nothrow_sink{}, + codecs::capacity<3>))); +static_assert(noexcept(codecs::drain(std::declval(), nothrow_sink{}, + std::span{}))); +static_assert(!noexcept(codecs::drain(std::declval(), throwing_sink{}))); +static_assert(!noexcept(codecs::drain(std::declval(), throwing_sink{}, + codecs::capacity<3>))); +static_assert(!noexcept(codecs::drain(std::declval(), throwing_sink{}, + std::span{}))); +static_assert(!noexcept(codecs::drain(std::declval(), nothrow_sink{}))); + } // namespace diff --git a/test/pipe_test.cpp b/test/pipe_test.cpp new file mode 100644 index 0000000..4596614 --- /dev/null +++ b/test/pipe_test.cpp @@ -0,0 +1,562 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// pipe (D19): two stream transformers composed by their element types alone, in place. A pipe of +// two doublers quadruples every character for every chunking of the input and every size of the +// caller's span, with the default intermediate and with one of one element; three links are a +// pipe of a pipe; one-byte element types meet through the intermediate; the first error of +// either part is the pipe's until reset; a moved-from pipe converts a new input from the start +// (Review Focus 5). + +#include "support/doubler.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** + Copies each element it is sent to a character, as a stream, accepting at most `Limit` elements a + send; constant time. +*/ +template +class echo { +public: + /** The elements read. */ + using input_type = Input; + /** The characters written. */ + using output_type = char; + + /** The transformer runs in a time that does not depend on its data. */ + static constexpr bool constant_time = true; + + /** An echo in `needs_input`. */ + echo() noexcept = default; + /** Copies are not needed. */ + echo(echo const&) = delete; + /** Copies are not needed. */ + echo& operator=(echo const&) = delete; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + echo(echo&& other) noexcept + : borrowed_(other.borrowed_), position_(other.position_), flushed_(other.flushed_) { + other.reset(); + } + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + echo& operator=(echo&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + flushed_ = other.flushed_; + other.reset(); + } + return *this; + } + + ~echo() = default; + + /** Borrows at most `Limit` elements of `input` in `needs_input`. */ + codecs::result send(std::span input) noexcept { + if (state() != codecs::flow::needs_input) { + return codecs::step{.count = 0, .flow = state()}; + } + borrowed_ = input.first(std::min(input.size(), Limit)); + position_ = 0; + return codecs::step{.count = borrowed_.size(), .flow = state()}; + } + + /** Writes each borrowed element as a character. */ + codecs::result receive(std::span output) noexcept { + std::size_t written = 0; + while (position_ < borrowed_.size() && written < output.size()) { + output[written++] = static_cast(borrowed_[position_++]); + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return codecs::step{.count = written, .flow = state()}; + } + + /** Ends the input. */ + codecs::result flush() noexcept { + flushed_ = true; + return state(); + } + + /** Back to `needs_input`. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + flushed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] codecs::flow state() const noexcept { + if (position_ < borrowed_.size()) { + return codecs::flow::output_pending; + } + return flushed_ ? codecs::flow::finished : codecs::flow::needs_input; + } + + /** The input `send` accepted. */ + std::span borrowed_; + /** The next borrowed element to read. */ + std::size_t position_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; +}; + +/** Every byte it is sent, as a character. */ +using byte_echo = echo::max()>; +/** Every character it is sent, taking two a send. */ +using two_at_a_time = echo; + +/** Echoes the characters it is sent, and reports `invalid_character` at `flush`. */ +class failing { +public: + /** The characters read. */ + using input_type = char; + /** The characters written. */ + using output_type = char; + + /** A failing transformer in `needs_input`. */ + failing() noexcept = default; + /** Copies are not needed. */ + failing(failing const&) = delete; + /** Copies are not needed. */ + failing& operator=(failing const&) = delete; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + failing(failing&& other) noexcept + : borrowed_(other.borrowed_), position_(other.position_), failed_(other.failed_) { + other.reset(); + } + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + failing& operator=(failing&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + failed_ = other.failed_; + other.reset(); + } + return *this; + } + + ~failing() = default; + + /** Borrows all of `input` in `needs_input`. */ + codecs::result send(std::span input) noexcept { + if (failed_) { + return codecs::error::invalid_character; + } + if (state() != codecs::flow::needs_input) { + return codecs::step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return codecs::step{.count = input.size(), .flow = state()}; + } + + /** Writes the borrowed characters. */ + codecs::result receive(std::span output) noexcept { + if (failed_) { + return codecs::error::invalid_character; + } + std::size_t written = 0; + while (position_ < borrowed_.size() && written < output.size()) { + output[written++] = borrowed_[position_++]; + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return codecs::step{.count = written, .flow = state()}; + } + + /** Reports the error, and every call returns it until `reset`. */ + codecs::result flush() noexcept { + failed_ = true; + return codecs::error::invalid_character; + } + + /** Back to `needs_input`, the error forgotten. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + failed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] codecs::flow state() const noexcept { + return position_ < borrowed_.size() ? codecs::flow::output_pending + : codecs::flow::needs_input; + } + + /** The input `send` accepted. */ + std::span borrowed_; + /** The next borrowed character to read. */ + std::size_t position_ = 0; + /** Whether `flush` reported the error. */ + bool failed_ = false; +}; + +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); + +/** Every character of `text` written `times` times. */ +std::string repeated(std::string_view text, std::size_t times) { + std::string repeated_text; + for (char const character : text) { + repeated_text.append(times, character); + } + return repeated_text; +} + +/** + Receives from `transformer` into spans of `span_size` until it reports `needs_input` or + `finished`, appending to `output`; false on an error or a call that makes no progress. +*/ +template +bool receive_all(Transformer& transformer, std::size_t span_size, std::string& output) { + std::array buffer{}; + for (;;) { + auto const received = transformer.receive(std::span{buffer}.first(span_size)); + if (!received.has_value()) { + return false; + } + output.append(buffer.data(), received->count); + if (received->flow != codecs::flow::output_pending) { + return true; + } + if (received->count == 0) { + return false; + } + } +} + +/** + Streams `input` through `transformer` in chunks of `chunk_size`, receiving into spans of + `span_size` after each send and after `flush`, and returns everything received, or "" + when a call fails or a state is not the protocol's. +*/ +template +std::string stream(Transformer& transformer, std::string_view input, std::size_t chunk_size, + std::size_t span_size) { + std::string output; + std::string_view rest = input; + while (!rest.empty()) { + std::string_view const chunk = rest.substr(0, chunk_size); + auto const sent = transformer.send(chunk); + if (!sent.has_value() || sent->count == 0 || sent->count > chunk.size()) { + return ""; + } + rest.remove_prefix(sent->count); + if (!receive_all(transformer, span_size, output)) { + return ""; + } + } + auto const flushed = transformer.flush(); + if (!flushed.has_value()) { + return ""; + } + if (*flushed == codecs::flow::output_pending && !receive_all(transformer, span_size, output)) { + return ""; + } + auto const after = transformer.receive(std::span{}); + if (!after.has_value() || after->flow != codecs::flow::finished) { + return ""; + } + return output; +} + +constexpr std::string_view sentence = "the quick brown fox jumps over 13 lazy dogs"; + +/** A pipe of two doublers quadruples every character for each chunking and span size. */ +template +void check_quadruples(Capacity capacity) { + std::string const expected = repeated(sentence, 4); + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{2}, std::size_t{7}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, capacity); + BOOST_TEST_EQ(stream(piped, sentence, chunk_size, span_size), expected); + // Reset, the same pipe converts the same input again. + piped.reset(); + BOOST_TEST_EQ(stream(piped, sentence, chunk_size, span_size), expected); + } + } +} + +void quadruples() { + // The default intermediate. + using default_pipe = decltype(codecs::pipe(test::doubler{}, test::doubler{})); + static_assert(std::is_same_v>); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + static_assert(codecs::stream_transformer); + check_quadruples(codecs::capacity>); + // An intermediate of one element. + static_assert(std::is_same_v)), + codecs::piped>); + check_quadruples(codecs::capacity<1>); + check_quadruples(codecs::capacity<3>); +} + +/** Three links are a pipe of a pipe, each with the default intermediate. */ +void three_links() { + using three = decltype(codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{})); + static_assert( + std::is_same_v, + test::doubler, 512>>); + std::string const expected = repeated(sentence, 8); + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{2}, std::size_t{7}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}); + BOOST_TEST_EQ(stream(piped, sentence, chunk_size, span_size), expected); + } + } + // Four links. + auto four = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}, test::doubler{}); + BOOST_TEST_EQ(stream(four, "ab", 1, 5), repeated("ab", 16)); +} + +/** One-byte element types meet through the intermediate: a char is read as a std::uint8_t. */ +void compatible_elements() { + static_assert(codecs::detail::compatible_elements); + static_assert(codecs::detail::compatible_elements); + static_assert(!codecs::detail::compatible_elements); + + // char to std::uint8_t, then std::uint8_t to char. + auto chars_to_bytes = codecs::pipe(test::doubler{}, byte_echo{}); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{2}, std::size_t{7}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + chars_to_bytes.reset(); + BOOST_TEST_EQ(stream(chars_to_bytes, sentence, chunk_size, span_size), + repeated(sentence, 2)); + } + } + // Every byte value goes through the view unchanged, char signed or not. + std::string every_byte; + for (unsigned value = 0; value < 256; ++value) { + every_byte.push_back(static_cast(value)); + } + auto echoed = codecs::pipe(test::doubler{}, byte_echo{}, codecs::capacity<5>); + BOOST_TEST(stream(echoed, every_byte, 7, 3) == repeated(every_byte, 2)); +} + +/** The pipe is constant time when both parts are. */ +void constant_time() { + using both = codecs::piped; + using one = codecs::piped; + static_assert(codecs::is_constant_time_v); + static_assert(!codecs::is_constant_time_v); + static_assert(!codecs::is_constant_time_v>); +} + +/** Whether `received` is the step `{count, state}`. */ +bool is_step(codecs::result const& received, std::size_t count, codecs::flow state) { + return received.has_value() && received->count == count && received->flow == state; +} + +/** Whether `returned` is the error `invalid_character`. */ +template +bool is_invalid_character(Result const& returned) { + return !returned.has_value() && returned.error() == codecs::error::invalid_character; +} + +/** The protocol's states of a pipe: it starts in needs_input and refuses input in another. */ +void protocol() { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}); + std::array output{}; + // It starts in needs_input; an empty span returns {0, state}. + BOOST_TEST(is_step(piped.receive(std::span{}), 0, codecs::flow::needs_input)); + BOOST_TEST(is_step(piped.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); + // Output pending: no more input. + BOOST_TEST(is_step(piped.send(std::string_view{"c"}), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(std::span{}), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(std::span{output}.first(3)), 3, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(output), 5, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 5}), "abbbb"); + // Flushed with nothing pending: finished, and nothing more is accepted. + BOOST_TEST(piped.flush().has_value() && piped.flush().value() == codecs::flow::finished); + BOOST_TEST(is_step(piped.send(std::string_view{"c"}), 0, codecs::flow::finished)); + BOOST_TEST(is_step(piped.receive(output), 0, codecs::flow::finished)); + // A flush while output is pending. + piped.reset(); + BOOST_TEST(is_step(piped.send(std::string_view{"xy"}), 2, codecs::flow::output_pending)); + auto const flushed = piped.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST(is_step(piped.receive(output), 8, codecs::flow::finished)); + BOOST_TEST_EQ((std::string_view{output.data(), 8}), "xxxxyyyy"); + // A flush of an empty stream. + piped.reset(); + auto const empty = piped.flush(); + BOOST_TEST(empty.has_value() && empty.value() == codecs::flow::finished); +} + +/** The first error of either part is the pipe's, and every call returns it until reset. */ +void errors() { + std::array output{}; + { + // The error at the pipe's flush, which flushes the second part at once. + auto piped = codecs::pipe(test::doubler{}, failing{}); + BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 4}), "aabb"); + BOOST_TEST(is_invalid_character(piped.flush())); + BOOST_TEST(is_invalid_character(piped.flush())); + BOOST_TEST(is_invalid_character(piped.send(std::string_view{"c"}))); + BOOST_TEST(is_invalid_character(piped.receive(output))); + BOOST_TEST(is_invalid_character(piped.receive(std::span{}))); + // Reset forgets it: the pipe converts again, and fails again at the end. + piped.reset(); + BOOST_TEST(is_step(piped.send(std::string_view{"x"}), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "xx"); + BOOST_TEST(is_invalid_character(piped.flush())); + } + { + // The error in a receive that has written output: that receive returns its output, and + // the next call returns the error, so a call that reports it writes nothing. + auto piped = codecs::pipe(test::doubler{}, failing{}); + BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); + auto const flushed = piped.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + output.fill('-'); + BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ((std::string_view{output.data(), 5}), "aabb-"); + output.fill('-'); + BOOST_TEST(is_invalid_character(piped.receive(output))); + BOOST_TEST_EQ(output[0], '-'); + BOOST_TEST(is_invalid_character(piped.send(std::string_view{"c"}))); + BOOST_TEST(is_invalid_character(piped.flush())); + piped.reset(); + BOOST_TEST(is_step(piped.receive(output), 0, codecs::flow::needs_input)); + } + { + // The first part's error. + auto piped = codecs::pipe(failing{}, test::doubler{}); + BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::needs_input)); + BOOST_TEST(is_invalid_character(piped.flush())); + BOOST_TEST(is_invalid_character(piped.receive(output))); + piped.reset(); + BOOST_TEST(is_step(piped.send(std::string_view{"c"}), 1, codecs::flow::output_pending)); + } +} + +/** + A moved-from pipe is in reset's state and converts a new input from the start, whether it was + moved from by construction or by assignment, mid-stream (Review Focus 5); the moved-to pipe + carries on with the stream. +*/ +void moved_from() { + std::string const expected_first = repeated("abcdef", 4); + std::string const expected_new = repeated("xyz", 4); + { + // Mid-stream, in needs_input: one chunk sent and received, the stream not ended. + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); + std::string output; + BOOST_TEST(is_step(piped.send(std::string_view{"abc"}), 3, codecs::flow::output_pending)); + BOOST_TEST(receive_all(piped, 5, output)); + auto moved{std::move(piped)}; + // The moved-to pipe carries on. + BOOST_TEST(is_step(moved.send(std::string_view{"def"}), 3, codecs::flow::output_pending)); + BOOST_TEST(receive_all(moved, 5, output)); + BOOST_TEST(moved.flush().has_value()); + BOOST_TEST(receive_all(moved, 5, output)); + BOOST_TEST_EQ(output, expected_first); + // The moved-from pipe starts again. + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(piped, "xyz", 2, 1), expected_new); + } + { + // Mid-stream, with output pending: a chunk sent, nothing received yet. + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); + auto moved = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); + std::string output; + BOOST_TEST(is_step(piped.send(std::string_view{"abc"}), 3, codecs::flow::output_pending)); + moved = std::move(piped); + BOOST_TEST(receive_all(moved, 1024, output)); + BOOST_TEST(is_step(moved.send(std::string_view{"def"}), 3, codecs::flow::output_pending)); + BOOST_TEST(moved.flush().has_value()); + BOOST_TEST(receive_all(moved, 1, output)); + BOOST_TEST_EQ(output, expected_first); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(piped, "xyz", 7, 1024), expected_new); + } + { + // Mid-stream with elements in the intermediate that the second part has not taken: it + // takes two a send, and the caller's span of 2 is full when it hands them back. The + // moved-to pipe holds the rest of the intermediate. + auto piped = codecs::pipe(test::doubler{}, two_at_a_time{}, codecs::capacity<8>); + std::array output{}; + BOOST_TEST(is_step(piped.send(std::string_view{"abc"}), 3, codecs::flow::output_pending)); + BOOST_TEST(is_step(piped.receive(output), 2, codecs::flow::output_pending)); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "aa"); + auto moved{std::move(piped)}; + std::string rest; + BOOST_TEST(receive_all(moved, 1024, rest)); + BOOST_TEST_EQ(rest, "bbcc"); + BOOST_TEST(is_step(moved.send(std::string_view{"d"}), 1, codecs::flow::output_pending)); + BOOST_TEST(moved.flush().has_value()); + BOOST_TEST(receive_all(moved, 1, rest)); + BOOST_TEST_EQ(rest, "bbccdd"); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(piped, "xyz", 1, 3), repeated("xyz", 2)); + } +} + +/** A second part that accepts a prefix of each send takes the rest of the intermediate later. */ +void partial_sends() { + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{2}, std::size_t{7}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + auto piped = codecs::pipe(test::doubler{}, two_at_a_time{}); + BOOST_TEST_EQ(stream(piped, sentence, chunk_size, span_size), repeated(sentence, 2)); + auto small = codecs::pipe(test::doubler{}, two_at_a_time{}, codecs::capacity<5>); + BOOST_TEST_EQ(stream(small, sentence, chunk_size, span_size), repeated(sentence, 2)); + } + } +} + +} // namespace + +int main() { + quadruples(); + three_links(); + compatible_elements(); + constant_time(); + protocol(); + errors(); + moved_from(); + partial_sends(); + return boost::report_errors(); +} From e9bd5222864083077e5a67659ce38b6d2149d1d2 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 16:35:45 -0300 Subject: [PATCH 050/157] codecs: pipe and drain lint fix, a result's value read unchecked after its check, the redundant typenames, a throwing doubler that wraps one --- include/webcpp/codecs/detail/core/pipe.hpp | 63 ++++++++++++---------- test/drain_test.cpp | 12 ++--- test/noexcept_test.cpp | 24 +++++++-- 3 files changed, 58 insertions(+), 41 deletions(-) diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index acbf780..a77baaf 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -128,9 +128,9 @@ class piped { static_assert(Capacity > 0, "webcpp::codecs: a pipe's intermediate holds at least one element"); /** The elements between the parts. */ - using intermediate_type = typename First::output_type; + using intermediate_type = First::output_type; /** The elements `Second` reads. */ - using second_input_type = typename Second::input_type; + using second_input_type = Second::input_type; /** Whether every call of both parts is `noexcept`. */ static constexpr bool nothrow_calls = @@ -144,9 +144,9 @@ class piped { public: /** The elements the pipe reads: `First`'s. */ - using input_type = typename First::input_type; + using input_type = First::input_type; /** The elements the pipe writes: `Second`'s. */ - using output_type = typename Second::output_type; + using output_type = Second::output_type; /** The pipe runs in a time that does not depend on its data when both parts do. */ static constexpr bool constant_time = is_constant_time_v && is_constant_time_v; @@ -221,8 +221,9 @@ class piped { error_ = sent.error(); return error_; } - first_flow_ = sent->flow; - return step{.count = sent->count, .flow = state()}; + step const accepted = sent.unsafe_value(); + first_flow_ = accepted.flow; + return step{.count = accepted.count, .flow = state()}; } /** @@ -243,8 +244,8 @@ class piped { if (!advanced) { return fail(advanced.error(), written); } - written += advanced->written; - progressed = advanced->progressed; + written += advanced.unsafe_value().written; + progressed = advanced.unsafe_value().progressed; } if (auto const flushed = flush_second_when_due(); !flushed) { return fail(flushed.error(), written); @@ -268,7 +269,7 @@ class piped { error_ = flushed.error(); return error_; } - first_flow_ = *flushed; + first_flow_ = flushed.unsafe_value(); if (auto const second_flushed = flush_second_when_due(); !second_flushed) { error_ = second_flushed.error(); return error_; @@ -333,10 +334,11 @@ class piped { if (!received) { return received.error(); } - bool const progressed = received->count > 0 || received->flow != second_flow_; - second_flow_ = received->flow; + step const taken = received.unsafe_value(); + bool const progressed = taken.count > 0 || taken.flow != second_flow_; + second_flow_ = taken.flow; lent_ = lent_ && second_flow_ == flow::output_pending; - return advanced_step{.written = received->count, .progressed = progressed}; + return advanced_step{.written = taken.count, .progressed = progressed}; } if (second_flow_ == flow::finished) { return advanced_step{.written = 0, .progressed = false}; @@ -346,10 +348,11 @@ class piped { if (!sent) { return sent.error(); } - bool const progressed = sent->count > 0 || sent->flow != second_flow_; - sent_ += sent->count; - second_flow_ = sent->flow; - lent_ = second_flow_ == flow::output_pending && (lent_ || sent->count > 0); + step const accepted = sent.unsafe_value(); + bool const progressed = accepted.count > 0 || accepted.flow != second_flow_; + sent_ += accepted.count; + second_flow_ = accepted.flow; + lent_ = second_flow_ == flow::output_pending && (lent_ || accepted.count > 0); return advanced_step{.written = 0, .progressed = progressed}; } // Second has taken the whole intermediate and handed it back: it is free. @@ -360,16 +363,17 @@ class piped { if (!received) { return received.error(); } - bool const progressed = received->count > 0 || received->flow != first_flow_; - size_ = received->count; - first_flow_ = received->flow; + step const taken = received.unsafe_value(); + bool const progressed = taken.count > 0 || taken.flow != first_flow_; + size_ = taken.count; + first_flow_ = taken.flow; return advanced_step{.written = 0, .progressed = progressed}; } auto const flushed = flush_second_when_due(); if (!flushed) { return flushed.error(); } - return advanced_step{.written = 0, .progressed = *flushed}; + return advanced_step{.written = 0, .progressed = flushed.unsafe_value()}; } /** @@ -386,7 +390,7 @@ class piped { if (!flushed) { return flushed.error(); } - second_flow_ = *flushed; + second_flow_ = flushed.unsafe_value(); return true; } @@ -547,7 +551,7 @@ namespace detail { template constexpr bool nothrow_drain() noexcept { if constexpr (stream_transformer) { - using output_type = typename T::output_type; + using output_type = T::output_type; return noexcept(std::declval().receive(std::declval>())) && std::is_nothrow_invocable_v>; } else { @@ -563,14 +567,15 @@ template result drain_through( T& transformer, Sink& sink, std::span buffer) noexcept(nothrow_drain()) { - using output_type = typename T::output_type; + using output_type = T::output_type; for (;;) { auto const received = transformer.receive(buffer); if (!received) { return received.error(); } - if (received->count > 0) { - std::span const piece = buffer.first(received->count); + step const taken = received.unsafe_value(); + if (taken.count > 0) { + std::span const piece = buffer.first(taken.count); if constexpr (std::is_void_v< std::invoke_result_t>>) { sink(piece); @@ -578,10 +583,10 @@ result drain_through( return sunk.error(); } } - if (received->flow != flow::output_pending) { - return received->flow; + if (taken.flow != flow::output_pending) { + return taken.flow; } - if (received->count == 0) { + if (taken.count == 0) { // Output is pending and the buffer took none of it: another call would not either. return error::output_too_small; } @@ -610,7 +615,7 @@ template [[nodiscard]] result drain(T& transformer, Sink&& sink) noexcept(detail::nothrow_drain()) { if constexpr (stream_transformer) { - using output_type = typename T::output_type; + using output_type = T::output_type; std::array> buffer{}; return detail::drain_through(transformer, sink, std::span{buffer}); } else { diff --git a/test/drain_test.cpp b/test/drain_test.cpp index 1ef0c5e..bb454da 100644 --- a/test/drain_test.cpp +++ b/test/drain_test.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -49,12 +50,9 @@ struct collector { /** Whether every piece holds at least one character and at most `most`. */ [[nodiscard]] bool pieces_within(std::size_t most) const { - for (std::string const& piece : pieces) { - if (piece.empty() || piece.size() > most) { - return false; - } - } - return true; + return std::ranges::all_of(pieces, [most](std::string const& piece) { + return !piece.empty() && piece.size() <= most; + }); } }; @@ -104,7 +102,7 @@ void span_pieces() { std::string joined; std::size_t pieces = 0; bool in_buffer = true; - auto sink = [&](std::span piece) noexcept { + auto sink = [&](std::span piece) { ++pieces; in_buffer = in_buffer && piece.data() == buffer.data() && piece.size() <= buffer.size() && !piece.empty(); diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 9105e1d..fb1fcca 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -261,16 +261,30 @@ static_assert(noexcept(std::declval().flush())); static_assert(noexcept(std::declval().reset())); /** A doubler whose send and receive may throw, as an allocating transformer's may. */ -struct throwing_doubler : test::doubler { +class throwing_doubler { +public: + /** The characters read. */ + using input_type = char; + /** The characters written. */ + using output_type = char; + /** Sends as a doubler does, not noexcept. */ - codecs::result send(std::span input) { - return test::doubler::send(input); - } + codecs::result send(std::span input) { return doubler_.send(input); } /** Receives as a doubler does, not noexcept. */ codecs::result receive(std::span output) { - return test::doubler::receive(output); + return doubler_.receive(output); } + + /** Flushes as a doubler does. */ + codecs::result flush() noexcept { return doubler_.flush(); } + + /** Resets as a doubler does. */ + void reset() noexcept { doubler_.reset(); } + +private: + /** The doubler that does the work. */ + test::doubler doubler_; }; static_assert(codecs::stream_transformer); From 4392fdfc52072782aafecbd08ec3c96fa7da2b9f Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 16:55:30 -0300 Subject: [PATCH 051/157] codecs: pipe and drain lint fix, the results of the pipe's calls and of drain_through nodiscard --- include/webcpp/codecs/detail/core/pipe.hpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index a77baaf..f257058 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -209,7 +209,7 @@ class piped { @param input The elements to convert, borrowed as `First` borrows them. @return The elements accepted and the state after, or the pipe's error. */ - result send(std::span input) noexcept(nothrow_calls) { + [[nodiscard]] result send(std::span input) noexcept(nothrow_calls) { if (error_) { return error_; } @@ -233,7 +233,7 @@ class piped { @param output The span to write into. @return The elements written and the state after, or the pipe's error. */ - result receive(std::span output) noexcept(nothrow_calls) { + [[nodiscard]] result receive(std::span output) noexcept(nothrow_calls) { if (error_) { return error_; } @@ -260,7 +260,7 @@ class piped { @return `flow::output_pending` while output remains, `flow::finished` when none does, or the pipe's error. */ - result flush() noexcept(nothrow_calls) { + [[nodiscard]] result flush() noexcept(nothrow_calls) { if (error_) { return error_; } @@ -328,7 +328,8 @@ class piped { output; send it the rest of the intermediate while it needs input; when it has taken the whole intermediate, refill it from `First`, or flush `Second` once `First` is finished. */ - result advance(std::span output) noexcept(nothrow_calls) { + [[nodiscard]] result advance(std::span output) noexcept( + nothrow_calls) { if (second_flow_ == flow::output_pending) { auto const received = second_.receive(output); if (!received) { @@ -382,7 +383,7 @@ class piped { @return Whether it flushed `Second`, or `Second`'s error. */ - result flush_second_when_due() noexcept(nothrow_calls) { + [[nodiscard]] result flush_second_when_due() noexcept(nothrow_calls) { if (first_flow_ != flow::finished || sent_ < size_ || second_flow_ != flow::needs_input) { return false; } @@ -398,7 +399,7 @@ class piped { Keeps `error` as the pipe's. A `receive` that has written `written` elements returns them, and the next call the error. */ - result fail(boost::system::error_code error, std::size_t written) noexcept { + [[nodiscard]] result fail(boost::system::error_code error, std::size_t written) noexcept { error_ = error; if (written == 0) { return error_; @@ -564,7 +565,7 @@ constexpr bool nothrow_drain() noexcept { `flow::finished`, giving each non-empty piece to `sink`. */ template -result drain_through( +[[nodiscard]] result drain_through( T& transformer, Sink& sink, std::span buffer) noexcept(nothrow_drain()) { using output_type = T::output_type; From f3c70018a8c3cb670fc76a7131cc79f8f653e0a8 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 16:59:47 -0300 Subject: [PATCH 052/157] codecs: pipe's review minors, an errored pipe movable, piped checking its elements itself, a transformer's error through drain and a first part's receive, a capacity after three links --- include/webcpp/codecs/detail/core/pipe.hpp | 27 +++- test/drain_test.cpp | 37 +++++- test/messages/Jamfile | 1 + test/messages/piped_incompatible/Jamfile | 16 +++ .../piped_incompatible/piped_incompatible.cpp | 29 ++++ test/noexcept_test.cpp | 2 + test/pipe_test.cpp | 125 ++++++++++++++---- test/support/failing.hpp | 115 ++++++++++++++++ 8 files changed, 321 insertions(+), 31 deletions(-) create mode 100644 test/messages/piped_incompatible/Jamfile create mode 100644 test/messages/piped_incompatible/piped_incompatible.cpp create mode 100644 test/support/failing.hpp diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index f257058..295cd15 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -117,7 +117,8 @@ inline constexpr bool nothrow_movable_v = (std::is_nothrow_move_constructible_v< pipe in the state `reset` leaves, so that it converts a new input from the start. Between a `receive` that reports `flow::output_pending` and the next call that reports `flow::needs_input` or `flow::finished`, `Second` may still borrow the intermediate, which a move would carry away - from it: the pipe must not be moved in that window. + from it: the pipe must not be moved in that window, unless the pipe has reported an error (it + calls `Second` no more until `reset`). @tparam First The first transformer, whose input is the pipe's. @tparam Second The second transformer, whose output is the pipe's. @@ -126,6 +127,13 @@ inline constexpr bool nothrow_movable_v = (std::is_nothrow_move_constructible_v< template class piped { static_assert(Capacity > 0, "webcpp::codecs: a pipe's intermediate holds at least one element"); + // pipe() refuses incompatible elements first; this check stops a piped named directly, whose + // Second would otherwise read the intermediate's elements as wider ones. Through the element + // pair, so that the requirement clang prints names both element types in full (ruling R2). + static_assert(detail::elements_compatible(detail::element_pair{}), + "webcpp::codecs: the first transformer's output_type is not the second's " + "input_type"); /** The elements between the parts. */ using intermediate_type = First::output_type; @@ -173,7 +181,7 @@ class piped { Takes `other`'s parts, state and the intermediate's elements that `Second` has not taken, and leaves `other` as `reset` does. - `other`'s `Second` must not borrow its intermediate. + `other`'s `Second` must not borrow its intermediate, unless `other` has reported an error. @param other The pipe moved from. */ @@ -186,7 +194,7 @@ class piped { Takes `other`'s parts, state and the intermediate's elements that `Second` has not taken, and leaves `other` as `reset` does. - `other`'s `Second` must not borrow its intermediate. + `other`'s `Second` must not borrow its intermediate, unless `other` has reported an error. @param other The pipe moved from. @return This pipe. @@ -412,8 +420,9 @@ class piped { moved already, and leaves `other` as `reset` does. */ void take_state(piped& other) noexcept(nothrow_moves) { - // Second's borrow of the intermediate cannot follow it to another object. - BOOST_ASSERT(!other.lent_); + // Second's borrow of the intermediate cannot follow it to another object; a pipe that has + // reported an error never calls Second again before reset, which ends the borrow. + BOOST_ASSERT(!other.lent_ || other.error_); std::span const unsent_elements = std::span{other.intermediate_}.subspan(other.sent_, other.size_ - other.sent_); std::ranges::move(unsent_elements, intermediate_.begin()); @@ -524,14 +533,18 @@ constexpr bool nothrow_pipe_of_many() noexcept { The pipe of three or more stream transformers, from the left: `pipe(a, b, c)` is `pipe(pipe(a, b), c)`, each intermediate of the default capacity. + A `codecs::capacity` after the last transformer, `pipe(a, b, c, codecs::capacity)`, is + `pipe(pipe(a, b), c, codecs::capacity)`: it sets the last intermediate's capacity alone, and + the others keep the default. + @tparam First The first transformer's type. @tparam Second The second transformer's type. @tparam Third The third transformer's type. - @tparam Rest The types of the transformers after the third. + @tparam Rest The types of the transformers after the third, and of a last capacity tag. @param first The first transformer. @param second The second transformer. @param third The third transformer. - @param rest The transformers after the third. + @param rest The transformers after the third, and optionally a `codecs::capacity` last. @return A @ref piped whose first part is the pipe of the transformers before the last. */ template diff --git a/test/drain_test.cpp b/test/drain_test.cpp index bb454da..b9bc425 100644 --- a/test/drain_test.cpp +++ b/test/drain_test.cpp @@ -6,9 +6,11 @@ // drain (D19): receives from a stream transformer until it reports needs_input or finished and // gives each non-empty piece to a sink, through its own buffer in place, one of capacity, or -// the caller's span; a sink's error stops it and is returned (the spec's scenario). +// the caller's span; a sink's error stops it and is returned (the spec's scenario), and so does the +// transformer's own. #include "support/doubler.hpp" +#include "support/failing.hpp" #include @@ -172,6 +174,38 @@ void pipes_and_temporaries() { BOOST_TEST_EQ(through_function, "qqqq"); } +/** + A transformer's own error stops the drain, which returns it: a pipe whose second part fails at + its flush gives the sink the output written before the error, and then the error; drained after + a flush that has already reported it, the drain returns it at once and calls no sink. +*/ +void transformer_error() { + { + auto piped = codecs::pipe(test::doubler{}, test::failing{}); + collector sink; + BOOST_TEST(piped.send(std::string_view{"ab"}).has_value()); + auto const flushed = piped.flush(); + BOOST_TEST(is_flow(flushed, codecs::flow::output_pending)); + auto const drained = codecs::drain(piped, sink); + BOOST_TEST(!drained.has_value()); + BOOST_TEST(drained.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(sink.joined(), "aabb"); + } + { + auto piped = codecs::pipe(test::doubler{}, test::failing{}); + collector sink; + BOOST_TEST(piped.send(std::string_view{"ab"}).has_value()); + BOOST_TEST(is_flow(codecs::drain(piped, sink), codecs::flow::needs_input)); + auto const flushed = piped.flush(); + BOOST_TEST(!flushed.has_value() && flushed.error() == codecs::error::invalid_character); + auto const drained = codecs::drain(piped, sink); + BOOST_TEST(!drained.has_value()); + BOOST_TEST(drained.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(sink.joined(), "aabb"); + BOOST_TEST_EQ(sink.pieces.size(), 1U); + } +} + /** A buffer of no element cannot take output that is pending: drain reports output_too_small rather than calling forever; with nothing pending, it returns the state. @@ -196,6 +230,7 @@ int main() { span_pieces(); sink_error(); pipes_and_temporaries(); + transformer_error(); empty_buffer(); return boost::report_errors(); } diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 6b718b3..b7ae5d0 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -25,3 +25,4 @@ build-project refused_secret_parameters ; build-project refused_secret_value_overload ; build-project pipe_incompatible ; build-project pipe_one_shot ; +build-project piped_incompatible ; diff --git a/test/messages/piped_incompatible/Jamfile b/test/messages/piped_incompatible/Jamfile new file mode 100644 index 0000000..69abfe4 --- /dev/null +++ b/test/messages/piped_incompatible/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic piped_incompatible : piped_incompatible.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail piped_incompatible_refused : piped_incompatible.cpp + : clang:no : native emscripten ; diff --git a/test/messages/piped_incompatible/piped_incompatible.cpp b/test/messages/piped_incompatible/piped_incompatible.cpp new file mode 100644 index 0000000..9d7f977 --- /dev/null +++ b/test/messages/piped_incompatible/piped_incompatible.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A piped named directly, not made by pipe, whose first transformer's output_type is not its +// second's input_type stops in the class's own check, before its second part could read the +// intermediate's characters as packets: a doubler writes characters and packets_to_frames reads +// packets. The requirement clang prints in the error names both element types (ruling R2). + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed due to requirement 'detail::elements_compatible(webcpp::codecs::detail::element_pair{})': webcpp::codecs: the first transformer's output_type is not the second's input_type}} +// clang-format on + +#include "../../support/doubler.hpp" +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::piped const piped{ + codecs::test::doubler{}, codecs::test::packets_to_frames{}}; + static_cast(piped); + return 0; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index fb1fcca..4564ac9 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -251,6 +251,8 @@ using doubled = codecs::piped; static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}))); static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<1>))); static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}))); +static_assert(noexcept(codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}, + codecs::capacity<3>))); static_assert(std::is_nothrow_constructible_v); static_assert(std::is_nothrow_move_constructible_v); static_assert(std::is_nothrow_move_assignable_v); diff --git a/test/pipe_test.cpp b/test/pipe_test.cpp index 4596614..4789ac4 100644 --- a/test/pipe_test.cpp +++ b/test/pipe_test.cpp @@ -12,6 +12,7 @@ // (Review Focus 5). #include "support/doubler.hpp" +#include "support/failing.hpp" #include @@ -133,39 +134,47 @@ using byte_echo = echo::max()>; /** Every character it is sent, taking two a send. */ using two_at_a_time = echo; -/** Echoes the characters it is sent, and reports `invalid_character` at `flush`. */ -class failing { +/** + Echoes the characters it is sent and refuses `!`: a `receive` whose next character is `!` reports + `invalid_character` and writes nothing, a fault met in the middle of the stream, as a decoder of + other data may meet one in a packet; every call returns it until `reset`. +*/ +class refusing { public: /** The characters read. */ using input_type = char; /** The characters written. */ using output_type = char; - /** A failing transformer in `needs_input`. */ - failing() noexcept = default; + /** A refusing transformer in `needs_input`. */ + refusing() noexcept = default; /** Copies are not needed. */ - failing(failing const&) = delete; + refusing(refusing const&) = delete; /** Copies are not needed. */ - failing& operator=(failing const&) = delete; + refusing& operator=(refusing const&) = delete; /** Takes `other`'s state and leaves `other` as `reset` does. */ - failing(failing&& other) noexcept - : borrowed_(other.borrowed_), position_(other.position_), failed_(other.failed_) { + refusing(refusing&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + flushed_(other.flushed_), + failed_(other.failed_) { other.reset(); } /** Takes `other`'s state and leaves `other` as `reset` does. */ - failing& operator=(failing&& other) noexcept { + refusing& operator=(refusing&& other) noexcept { if (this != &other) { borrowed_ = other.borrowed_; position_ = other.position_; + flushed_ = other.flushed_; failed_ = other.failed_; other.reset(); } return *this; } - ~failing() = default; + ~refusing() = default; /** Borrows all of `input` in `needs_input`. */ codecs::result send(std::span input) noexcept { @@ -180,13 +189,15 @@ class failing { return codecs::step{.count = input.size(), .flow = state()}; } - /** Writes the borrowed characters. */ + /** Writes the borrowed characters up to a `!`, or refuses the `!` that comes next. */ codecs::result receive(std::span output) noexcept { - if (failed_) { + if (failed_ || (position_ < borrowed_.size() && borrowed_[position_] == '!')) { + failed_ = true; return codecs::error::invalid_character; } std::size_t written = 0; - while (position_ < borrowed_.size() && written < output.size()) { + while (position_ < borrowed_.size() && written < output.size() && + borrowed_[position_] != '!') { output[written++] = borrowed_[position_++]; } if (position_ == borrowed_.size()) { @@ -196,37 +207,46 @@ class failing { return codecs::step{.count = written, .flow = state()}; } - /** Reports the error, and every call returns it until `reset`. */ + /** Ends the input. */ codecs::result flush() noexcept { - failed_ = true; - return codecs::error::invalid_character; + if (failed_) { + return codecs::error::invalid_character; + } + flushed_ = true; + return state(); } /** Back to `needs_input`, the error forgotten. */ void reset() noexcept { borrowed_ = {}; position_ = 0; + flushed_ = false; failed_ = false; } private: /** The state the next call sees. */ [[nodiscard]] codecs::flow state() const noexcept { - return position_ < borrowed_.size() ? codecs::flow::output_pending - : codecs::flow::needs_input; + if (position_ < borrowed_.size()) { + return codecs::flow::output_pending; + } + return flushed_ ? codecs::flow::finished : codecs::flow::needs_input; } /** The input `send` accepted. */ std::span borrowed_; /** The next borrowed character to read. */ std::size_t position_ = 0; - /** Whether `flush` reported the error. */ + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether a `!` was refused. */ bool failed_ = false; }; static_assert(codecs::stream_transformer); static_assert(codecs::stream_transformer); -static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); /** Every character of `text` written `times` times. */ std::string repeated(std::string_view text, std::size_t times) { @@ -343,6 +363,28 @@ void three_links() { // Four links. auto four = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}, test::doubler{}); BOOST_TEST_EQ(stream(four, "ab", 1, 5), repeated("ab", 16)); + // A capacity after the last link sets the last intermediate's alone; the others keep the + // default. + using three_with_capacity = decltype(codecs::pipe(test::doubler{}, test::doubler{}, + test::doubler{}, codecs::capacity<3>)); + static_assert( + std::is_same_v< + three_with_capacity, + codecs::piped, test::doubler, 3>>); + using four_with_capacity = decltype(codecs::pipe( + test::doubler{}, test::doubler{}, test::doubler{}, test::doubler{}, codecs::capacity<5>)); + static_assert( + std::is_same_v, + test::doubler, 512>, + test::doubler, 5>>); + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{7}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}, + codecs::capacity<3>); + BOOST_TEST_EQ(stream(piped, sentence, chunk_size, span_size), expected); + } + } } /** One-byte element types meet through the intermediate: a char is read as a std::uint8_t. */ @@ -427,7 +469,7 @@ void errors() { std::array output{}; { // The error at the pipe's flush, which flushes the second part at once. - auto piped = codecs::pipe(test::doubler{}, failing{}); + auto piped = codecs::pipe(test::doubler{}, test::failing{}); BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::needs_input)); BOOST_TEST_EQ((std::string_view{output.data(), 4}), "aabb"); @@ -446,7 +488,7 @@ void errors() { { // The error in a receive that has written output: that receive returns its output, and // the next call returns the error, so a call that reports it writes nothing. - auto piped = codecs::pipe(test::doubler{}, failing{}); + auto piped = codecs::pipe(test::doubler{}, test::failing{}); BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); auto const flushed = piped.flush(); BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); @@ -463,7 +505,7 @@ void errors() { } { // The first part's error. - auto piped = codecs::pipe(failing{}, test::doubler{}); + auto piped = codecs::pipe(test::failing{}, test::doubler{}); BOOST_TEST(is_step(piped.send(std::string_view{"ab"}), 2, codecs::flow::output_pending)); BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::needs_input)); BOOST_TEST(is_invalid_character(piped.flush())); @@ -471,6 +513,24 @@ void errors() { piped.reset(); BOOST_TEST(is_step(piped.send(std::string_view{"c"}), 1, codecs::flow::output_pending)); } + { + // The first part's error in a receive, met while the pipe refills the intermediate: the + // receive returns what the second part wrote from the first refill, and the next call the + // error. + auto piped = codecs::pipe(refusing{}, test::doubler{}, codecs::capacity<2>); + BOOST_TEST(is_step(piped.send(std::string_view{"ab!c"}), 4, codecs::flow::output_pending)); + output.fill('-'); + BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ((std::string_view{output.data(), 5}), "aabb-"); + output.fill('-'); + BOOST_TEST(is_invalid_character(piped.receive(output))); + BOOST_TEST_EQ(output[0], '-'); + BOOST_TEST(is_invalid_character(piped.send(std::string_view{"c"}))); + BOOST_TEST(is_invalid_character(piped.flush())); + // Reset forgets it. + piped.reset(); + BOOST_TEST_EQ(stream(piped, "xyz", 2, 1), repeated("xyz", 2)); + } } /** @@ -533,6 +593,25 @@ void moved_from() { // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test BOOST_TEST_EQ(stream(piped, "xyz", 1, 3), repeated("xyz", 2)); } + { + // A pipe that has reported an error while its second part borrows the intermediate may + // be moved: it never calls that part again before reset. The moved-to pipe keeps the + // error; the moved-from one starts again. + auto piped = codecs::pipe(test::doubler{}, refusing{}); + std::array output{}; + BOOST_TEST(is_step(piped.send(std::string_view{"a!"}), 2, codecs::flow::output_pending)); + BOOST_TEST( + is_step(piped.receive(std::span{output}.first(1)), 1, codecs::flow::output_pending)); + // The second part borrows "aa!!" and refuses the first "!" after writing the second "a". + BOOST_TEST(is_step(piped.receive(output), 1, codecs::flow::output_pending)); + auto moved{std::move(piped)}; + BOOST_TEST(is_invalid_character(moved.receive(output))); + BOOST_TEST(is_invalid_character(moved.flush())); + moved.reset(); + BOOST_TEST_EQ(stream(moved, "xyz", 2, 1), repeated("xyz", 2)); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(piped, "xyz", 7, 1024), repeated("xyz", 2)); + } } /** A second part that accepts a prefix of each send takes the rest of the intermediate later. */ diff --git a/test/support/failing.hpp b/test/support/failing.hpp new file mode 100644 index 0000000..a62e3cf --- /dev/null +++ b/test/support/failing.hpp @@ -0,0 +1,115 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// failing, a stream transformer of the tests' own whose data is always at fault: `char` to `char`, +// it echoes what it is sent and reports `invalid_character` at `flush`, the first call that has +// processed the whole input, as the stream protocol (D18) places a data fault; every call returns +// it until `reset`. It is not constant time and is not secret. A moved-from failing is in the +// state `reset` leaves (Review Focus 5). + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_FAILING_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_FAILING_HPP + +#include + +#include +#include + +namespace webcpp::codecs::test { + +/** Echoes the characters it is sent, and reports `invalid_character` at `flush`. */ +class failing { +public: + /** The characters read. */ + using input_type = char; + /** The characters written. */ + using output_type = char; + + /** A failing transformer in `needs_input`. */ + failing() noexcept = default; + /** Copies are not needed. */ + failing(failing const&) = delete; + /** Copies are not needed. */ + failing& operator=(failing const&) = delete; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + failing(failing&& other) noexcept + : borrowed_(other.borrowed_), position_(other.position_), failed_(other.failed_) { + other.reset(); + } + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + failing& operator=(failing&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + failed_ = other.failed_; + other.reset(); + } + return *this; + } + + ~failing() = default; + + /** Borrows all of `input` in `needs_input`. */ + result send(std::span input) noexcept { + if (failed_) { + return error::invalid_character; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return step{.count = input.size(), .flow = state()}; + } + + /** Writes the borrowed characters. */ + result receive(std::span output) noexcept { + if (failed_) { + return error::invalid_character; + } + std::size_t written = 0; + while (position_ < borrowed_.size() && written < output.size()) { + output[written++] = borrowed_[position_++]; + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** Reports the error, and every call returns it until `reset`. */ + result flush() noexcept { + failed_ = true; + return error::invalid_character; + } + + /** Back to `needs_input`, the error forgotten. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + failed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + return position_ < borrowed_.size() ? flow::output_pending : flow::needs_input; + } + + /** The input `send` accepted. */ + std::span borrowed_; + /** The next borrowed character to read. */ + std::size_t position_ = 0; + /** Whether `flush` reported the error. */ + bool failed_ = false; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_FAILING_HPP From 557eeca0f65952efa5cc3c5d5de52c06734c9332 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 17:17:54 -0300 Subject: [PATCH 053/157] codecs: each and buffered, a one-shot transformer as a stream per item or accumulating, in place or with an allocator --- include/webcpp/codecs.hpp | 1 + .../webcpp/codecs/detail/core/adapters.hpp | 984 ++++++++++++++++++ .../webcpp/codecs/detail/core/transformer.hpp | 22 +- test/Jamfile | 8 + test/allocation_test.cpp | 76 ++ test/allocator_test.cpp | 91 +- test/allocator_throw_test.cpp | 150 ++- test/buffered_test.cpp | 469 +++++++++ test/each_test.cpp | 471 +++++++++ test/messages/Jamfile | 4 + .../buffered_bound_not_constant/Jamfile | 16 + .../buffered_bound_not_constant.cpp | 72 ++ test/messages/buffered_without_bound/Jamfile | 16 + .../buffered_without_bound.cpp | 28 + test/messages/each_capacity_too_small/Jamfile | 16 + .../each_capacity_too_small.cpp | 28 + test/messages/each_without_bound/Jamfile | 16 + .../each_without_bound/each_without_bound.cpp | 29 + test/noexcept_test.cpp | 74 ++ test/toy_media_test.cpp | 70 +- 20 files changed, 2630 insertions(+), 11 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/adapters.hpp create mode 100644 test/buffered_test.cpp create mode 100644 test/each_test.cpp create mode 100644 test/messages/buffered_bound_not_constant/Jamfile create mode 100644 test/messages/buffered_bound_not_constant/buffered_bound_not_constant.cpp create mode 100644 test/messages/buffered_without_bound/Jamfile create mode 100644 test/messages/buffered_without_bound/buffered_without_bound.cpp create mode 100644 test/messages/each_capacity_too_small/Jamfile create mode 100644 test/messages/each_capacity_too_small/each_capacity_too_small.cpp create mode 100644 test/messages/each_without_bound/Jamfile create mode 100644 test/messages/each_without_bound/each_without_bound.cpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 20ff44a..3a52708 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -14,6 +14,7 @@ #define WEBCPP_CODECS_HPP #include +#include #include #include #include diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp new file mode 100644 index 0000000..fc64495 --- /dev/null +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -0,0 +1,984 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + A one-shot transformer as a stream (D19, D22): `each`, which converts each input element on its + own, as a whole unit, and `buffered`, which accumulates the whole input and converts it at + `flush`; each in place, with `codecs::capacity`, or with an allocator. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP +#define WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +namespace detail { + +/** Whether a storage is a capacity in place, `capacity_t`, rather than an allocator. */ +template +inline constexpr bool is_capacity_v = false; + +/** `capacity_t` is a capacity in place. */ +template +inline constexpr bool is_capacity_v> = true; + +/** Whether `T` states the exact size of its output, `transformer.output_size(input)`. */ +template +concept has_output_size = requires(T& transformer, std::span input) { + { transformer.output_size(input) } -> std::convertible_to; +}; + +/** Whether `T`'s `transform` cannot throw. */ +template +inline constexpr bool nothrow_transform_v = + noexcept(std::declval().transform(std::declval>(), + std::declval>())); + +/** + Whether one item's output of `T` fits in `N` elements in place: `T` states `max_output_size(1)` as + a constant expression, and `N` is at least that. +*/ +template +concept item_fits_in_place = has_constant_max_output_size && (T::max_output_size(1) <= N); + +/** + The output elements `buffered>` holds in place: `T::max_output_size(N)`, or none + when `T` does not state it as a constant expression, which the class refuses. +*/ +template +constexpr std::size_t in_place_output_size() noexcept { + if constexpr (has_constant_max_output_size) { + return T::max_output_size(N); + } else { + return 0; + } +} + +/** The first size of a heap output for `input`: the exact size, else the bound, else the input's. + */ +template +std::size_t first_output_size(T& transformer, std::span input) { + if constexpr (has_output_size) { + return transformer.output_size(input); + } else if constexpr (has_max_output_size) { + return T::max_output_size(input.size()); + } else { + return input.size(); + } +} + +/** An output of `Size` elements in place, which a transformer writes into. */ +template +class in_place_output { +public: + /** An output for the capacity in place `capacity_t`. */ + template + explicit in_place_output(capacity_t /*capacity*/) noexcept {} + + /** + Transforms `input` into the output. + + @param transformer The one-shot transformer. + @param input The elements to convert. + @return The elements written, or the transformer's error. + */ + template + [[nodiscard]] result transform( + T& transformer, + std::span input) noexcept(nothrow_transform_v) { + return transformer.transform(input, std::span{elements_}); + } + + /** The output's elements. */ + [[nodiscard]] std::span elements() const noexcept { return elements_; } + +private: + /** The elements. */ + std::array elements_{}; +}; + +/** + An output from `Allocator`, rebound to `Element`, which grows for each conversion as D19 says: to + the transformer's exact size when it states one, else to its static bound, else to the input's + size, and then doubles while `transform` reports `output_too_small`. It never shrinks, so that a + later conversion reuses its memory. +*/ +template +class heap_output { + /** The allocator of the elements. */ + using element_allocator = std::allocator_traits::template rebind_alloc; + +public: + /** An empty output that allocates from `allocator`. */ + explicit heap_output(Allocator const& allocator) : elements_(element_allocator(allocator)) {} + + /** + Transforms `input` into the output, growing it as the class says. + + @param transformer The one-shot transformer. + @param input The elements to convert. + @return The elements written, the transformer's error, or `input_too_long` when the output + would exceed what the allocator can hold. + */ + template + [[nodiscard]] result transform(T& transformer, + std::span input) { + std::size_t wanted = first_output_size(transformer, input); + for (;;) { + if (elements_.size() < wanted) { + if (wanted > elements_.max_size()) { + return error::input_too_long; + } + elements_.resize(wanted); + } + auto const written = transformer.transform(input, std::span{elements_}); + if (written || written.error() != error::output_too_small) { + return written; + } + std::size_t const held = elements_.size(); + wanted = held == 0 ? 1 : saturating_multiply(held, 2); + if (wanted == held) { + // Saturated: there is no larger output to try. + return error::input_too_long; + } + } + } + + /** The output's elements, as many as it has grown to. */ + [[nodiscard]] std::span elements() const noexcept { return elements_; } + + /** The allocator, as given. */ + [[nodiscard]] Allocator get_allocator() const noexcept { + return Allocator(elements_.get_allocator()); + } + +private: + /** The elements. */ + std::vector elements_; +}; + +/** An input of at most `Capacity` elements in place, which records an input past it. */ +template +class in_place_input { +public: + /** An empty input for the capacity in place `capacity_t`. */ + explicit in_place_input(capacity_t /*capacity*/) noexcept {} + + /** + Appends `input`, or records that the input is past the capacity and keeps nothing more. + + @param input The elements to append. + */ + void append(std::span input) noexcept( + std::is_nothrow_copy_assignable_v) { + if (too_long_ || input.size() > Capacity - size_) { + too_long_ = true; + return; + } + std::ranges::copy(input, std::span{elements_}.subspan(size_).begin()); + size_ += input.size(); + } + + /** Whether an input past the capacity was appended. */ + [[nodiscard]] bool too_long() const noexcept { return too_long_; } + + /** The elements appended. */ + [[nodiscard]] std::span elements() const noexcept { + return std::span{elements_}.first(size_); + } + + /** Empties the input. */ + void clear() noexcept { + size_ = 0; + too_long_ = false; + } + +private: + /** The elements. */ + std::array elements_{}; + /** The elements appended. */ + std::size_t size_ = 0; + /** Whether an input past the capacity was appended. */ + bool too_long_ = false; +}; + +/** + Erases the elements of a vector past a size it kept, when a scope is left by an exception, so + that a failed append leaves the vector as it was. +*/ +template +class truncation_guard { +public: + /** Guards `elements`, keeping its first `kept` elements. */ + truncation_guard(Vector& elements, std::size_t kept) noexcept + : elements_(elements), kept_(kept) {} + + /** Not copyable: one guard for one scope. */ + truncation_guard(truncation_guard const&) = delete; + /** Not copyable: one guard for one scope. */ + truncation_guard& operator=(truncation_guard const&) = delete; + /** Not movable: the guard is the scope's. */ + truncation_guard(truncation_guard&&) = delete; + /** Not movable: the guard is the scope's. */ + truncation_guard& operator=(truncation_guard&&) = delete; + + /** Erases the elements past the kept ones, unless the scope completed. */ + ~truncation_guard() { + if (engaged_) { + elements_.erase(elements_.begin() + static_cast(kept_), + elements_.end()); + } + } + + /** The scope completed: the elements stay. */ + void release() noexcept { engaged_ = false; } + +private: + /** The vector guarded. */ + Vector& elements_; + /** The elements it kept. */ + std::size_t kept_; + /** Whether the scope is still running. */ + bool engaged_ = true; +}; + +/** + An input from `Allocator`, rebound to `Element`, grown geometrically as it is appended to; it + records an input past what the allocator can hold. A failed append keeps what it held. +*/ +template +class heap_input { + /** The allocator of the elements. */ + using element_allocator = std::allocator_traits::template rebind_alloc; + +public: + /** An empty input that allocates from `allocator`. */ + explicit heap_input(Allocator const& allocator) : elements_(element_allocator(allocator)) {} + + /** + Appends `input`, or records that the input is past what the allocator can hold and keeps + nothing more. When the allocator or an element's copy throws, the input is as it was. + + @param input The elements to append. + */ + void append(std::span input) { + std::size_t const kept = elements_.size(); + if (too_long_ || input.size() > elements_.max_size() - kept) { + too_long_ = true; + return; + } + if (input.size() > elements_.capacity() - kept) { + // Geometric growth, so that many small sends copy each element a bounded number of + // times; reserve keeps the elements as they were when it throws. + std::size_t const doubled = + std::min(saturating_multiply(elements_.capacity(), 2), elements_.max_size()); + elements_.reserve(std::max(kept + input.size(), doubled)); + } + truncation_guard> guard{elements_, kept}; + elements_.insert(elements_.end(), input.begin(), input.end()); + guard.release(); + } + + /** Whether an input past what the allocator can hold was appended. */ + [[nodiscard]] bool too_long() const noexcept { return too_long_; } + + /** The elements appended. */ + [[nodiscard]] std::span elements() const noexcept { return elements_; } + + /** Empties the input and keeps its memory. */ + void clear() noexcept { + elements_.clear(); + too_long_ = false; + } + + /** The allocator, as given. */ + [[nodiscard]] Allocator get_allocator() const noexcept { + return Allocator(elements_.get_allocator()); + } + +private: + /** The elements. */ + std::vector elements_; + /** Whether an input past what the allocator can hold was appended. */ + bool too_long_ = false; +}; + +/** The item storage of `each`: one item's output from the allocator `Storage`. */ +template +struct each_storage { + /** The output of one item. */ + using output = heap_output; +}; + +/** The item storage of `each>`: one item's output, `N` elements in place. */ +template +struct each_storage> { + /** The output of one item. */ + using output = in_place_output; + + // After the alias: clang leaves a member declared after a failed check undeclared, and the + // class's use of it would add a second error to the refusal. + static_assert(detail::item_fits_in_place, + "webcpp::codecs: each(transformer, capacity) needs T::max_output_size(1) as a " + "constant expression and N >= it; declare max_output_size, raise N, or pass an " + "allocator"); +}; + +/** The storage of `buffered`: the input and the output from the allocator `Storage`. */ +template +struct buffered_storage { + /** The input accumulated. */ + using input = heap_input; + /** The output of the whole input. */ + using output = heap_output; +}; + +/** + The storage of `buffered>`: `N` input elements and `T::max_output_size(N)` + output elements, in place. +*/ +template +struct buffered_storage> { + /** The input accumulated. */ + using input = in_place_input; + /** The output of the whole input. */ + using output = in_place_output()>; + + // After the aliases, as each_storage's check. + static_assert(detail::has_constant_max_output_size, + "webcpp::codecs: buffered(transformer, capacity) needs T::max_output_size(N) " + "as a constant expression; declare it, or pass an allocator"); +}; + +} // namespace detail + +/** + A stream transformer that converts each input element on its own, as a whole unit, through the + one-shot transformer `T` (D19): a decoded video frame to an image, the stream of frames becoming + a stream of images, with nothing accumulated. + + It is made by `codecs::each(transformer)`, `codecs::each(transformer, codecs::capacity)` or + `codecs::each(transformer, allocator)`. + + `send` accepts one element, the item, which it borrows until the item is delivered + (`{1, flow::output_pending}`). `receive` transforms the item straight into the caller's span when + `T` states a static `max_output_size(1)` and the span has that room, and otherwise into its own + storage for one item's output, which it delivers over as many receives as the caller's spans + need: a short span is never an error. A `receive` never writes from two items, and + `completed_items()` counts the items fully delivered, so that a caller whose output is bytes sees + each item's boundary. An item's error is reported by the `receive` that transforms it, which + writes nothing, and every later call returns it until `reset`. `flush` has nothing to gather: it + returns `flow::output_pending` while an item is pending and `flow::finished` once the last item is + received. + + With `codecs::capacity`, the storage holds `N` elements in place, which requires `T` to state + `max_output_size(1)` as a constant expression no larger than `N` (a `static_assert` names the fix + otherwise), and nothing is allocated; every member is `noexcept` when `T`'s `transform` and the + copy of its output elements are. With an allocator, the only form for a `T` with no constant + bound, the storage comes from it, rebound through `std::allocator_traits`, and grows as an item + needs: to `T`'s exact `output_size(input)` when it states one, else to its static + `max_output_size(1)`, else by doubling while `transform` reports `output_too_small`. A bound of + the object's own (a non-static `max_output_size`, as a configured format's may be) is not read, + and such a `T` is sized by doubling. `reset` keeps that memory. Construction and `receive` may + then allocate and are not `noexcept`, and an allocator's exception propagates: a `receive` that + throws leaves the item pending, and the stream valid and resettable. + + It is constant time when `T` is. A move takes the item, its output and the state, and leaves the + moved-from `each` in the state `reset` leaves, so that it converts a new input from the start; + the item stays the caller's, and a move never carries a borrow away from it. + + @tparam T The one-shot transformer. + @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. +*/ +template > +class each { + /** Whether the storage is in place. */ + static constexpr bool in_place = detail::is_capacity_v; + + /** One item's output. */ + using output_storage = detail::each_storage::output; + + /** Whether construction cannot throw. */ + static constexpr bool nothrow_construction = + in_place && std::is_nothrow_move_constructible_v; + + /** Whether `receive` cannot throw. */ + static constexpr bool nothrow_receive = + in_place && detail::nothrow_transform_v && + std::is_nothrow_copy_assignable_v; + +public: + /** The elements read: `T`'s. */ + using input_type = T::input_type; + /** The elements written: `T`'s. */ + using output_type = T::output_type; + + /** The stream runs in a time that does not depend on its data when `T` does. */ + static constexpr bool constant_time = is_constant_time_v; + + /** + Makes a stream of `transformer`, in `flow::needs_input`, with a default `Storage`. + + @param transformer The one-shot transformer. + */ + explicit each(T transformer) noexcept(nothrow_construction) + : each(std::move(transformer), Storage{}) {} + + /** + Makes a stream of `transformer`, in `flow::needs_input`. + + @param transformer The one-shot transformer. + @param storage `codecs::capacity`, or the allocator of the item storage. + */ + each(T transformer, Storage const& storage) noexcept(nothrow_construction) + : transformer_(std::move(transformer)), output_(storage) {} + + /** + A copy borrows the item `other` borrows. + + @param other The stream copied. + */ + each(each const& other) = default; + + /** + A copy borrows the item `other` borrows. + + @param other The stream copied. + @return This stream. + */ + each& operator=(each const& other) = default; + + /** + Takes `other`'s transformer, item, output and state, and leaves `other` as `reset` does. + + @param other The stream moved from. + */ + each(each&& other) noexcept(std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v) + : transformer_(std::move(other.transformer_)), + output_(std::move(other.output_)), + item_(other.item_), + stored_(other.stored_), + delivered_(other.delivered_), + transformed_(other.transformed_), + completed_(other.completed_), + flushed_(other.flushed_), + error_(other.error_) { + other.reset(); + } + + /** + Takes `other`'s transformer, item, output and state, and leaves `other` as `reset` does. + + @param other The stream moved from. + @return This stream. + */ + each& operator=(each&& other) noexcept(std::is_nothrow_move_assignable_v && + std::is_nothrow_move_assignable_v) { + if (this != &other) { + transformer_ = std::move(other.transformer_); + output_ = std::move(other.output_); + item_ = other.item_; + stored_ = other.stored_; + delivered_ = other.delivered_; + transformed_ = other.transformed_; + completed_ = other.completed_; + flushed_ = other.flushed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Destroys the transformer and the storage. */ + ~each() = default; + + /** + Accepts the first element of `input` as the item in `flow::needs_input`; accepts nothing in + another state, or from an empty span. + + @param input The elements to convert, the first borrowed until it is delivered. + @return `{1, flow::output_pending}`, `{0, state}`, or the stream's error. + */ + [[nodiscard]] result send(std::span input) noexcept { + if (error_) { + return error_; + } + if (state() != flow::needs_input || input.empty()) { + return step{.count = 0, .flow = state()}; + } + item_ = input.first(1); + return step{.count = 1, .flow = flow::output_pending}; + } + + /** + Writes the item's output into `output`: transformed straight into it when it has room for + `T`'s bound, else through the storage, delivered over as many receives as it takes. + + @param output The span to write into. + @return The elements written and the state after, or the stream's error, which the receive + that transforms the item reports, writing nothing. + */ + [[nodiscard]] result receive(std::span output) noexcept(nothrow_receive) { + if (error_) { + return error_; + } + if (item_.empty() || output.empty()) { + return step{.count = 0, .flow = state()}; + } + if (!transformed_) { + if constexpr (detail::has_max_output_size) { + if (output.size() >= T::max_output_size(1)) { + auto const written = transformer_.transform(item_, output); + if (!written) { + error_ = written.error(); + return error_; + } + complete_item(); + return step{.count = written.unsafe_value(), .flow = state()}; + } + } + auto const stored = output_.transform(transformer_, item_); + if (!stored) { + error_ = stored.error(); + return error_; + } + stored_ = stored.unsafe_value(); + delivered_ = 0; + transformed_ = true; + } + std::span const pending = + output_.elements().subspan(delivered_, stored_ - delivered_); + std::size_t const count = std::min(pending.size(), output.size()); + std::ranges::copy(pending.first(count), output.begin()); + delivered_ += count; + if (delivered_ == stored_) { + complete_item(); + } + return step{.count = count, .flow = state()}; + } + + /** + Ends the input: there is nothing to gather. + + @return `flow::output_pending` while an item is pending, `flow::finished` when none is, or the + stream's error. + */ + [[nodiscard]] result flush() noexcept { + if (error_) { + return error_; + } + flushed_ = true; + return state(); + } + + /** + Returns to `flow::needs_input` with no item, no error and a count of zero; the allocated + storage is kept for the next stream. + */ + void reset() noexcept { + item_ = {}; + stored_ = 0; + delivered_ = 0; + transformed_ = false; + completed_ = 0; + flushed_ = false; + error_.clear(); + } + + /** + The items fully delivered since the stream started or was reset. + + @return The count of items whose output was received whole. + */ + [[nodiscard]] std::size_t completed_items() const noexcept { return completed_; } + + /** + The allocator of the item storage: the heap form alone. + + @return The allocator, as given. + */ + [[nodiscard]] Storage get_allocator() const noexcept + requires(!in_place) + { + return output_.get_allocator(); + } + +private: + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (!item_.empty()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The item is delivered: the caller's input is free, and the count grows. */ + void complete_item() noexcept { + item_ = {}; + stored_ = 0; + delivered_ = 0; + transformed_ = false; + ++completed_; + } + + /** The one-shot transformer. */ + T transformer_; + /** The storage of one item's output. */ + output_storage output_; + /** The item `send` accepted, the caller's until it is delivered; empty when none is. */ + std::span item_; + /** The elements of the item's output in the storage. */ + std::size_t stored_ = 0; + /** The elements of the stored output already delivered. */ + std::size_t delivered_ = 0; + /** Whether the item's output is in the storage. */ + bool transformed_ = false; + /** The items fully delivered. */ + std::size_t completed_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** The stream's error, which every call returns until `reset`. */ + boost::system::error_code error_; +}; + +/** + Deduces `each`, the heap form with `std::allocator`, from `each(transformer)`. + + @tparam T The one-shot transformer's type. +*/ +template +each(T) -> each; + +/** + Deduces `each>`, the form in place, from + `each(transformer, codecs::capacity)`. + + @tparam T The one-shot transformer's type. + @tparam N The capacity, in elements. +*/ +template +each(T, capacity_t) -> each>; + +/** + Deduces `each`, the heap form with the allocator, from + `each(transformer, allocator)`. + + @tparam T The one-shot transformer's type. + @tparam Allocator The allocator's type. +*/ +template +each(T, Allocator) -> each; + +/** + A stream transformer that accumulates its whole input and converts it at `flush` through the + one-shot transformer `T` (D19): a conversion that cannot stream, as base58's, has the whole input + as its minimal state. + + It is made by `codecs::buffered(transformer)`, + `codecs::buffered(transformer, codecs::capacity)` or `codecs::buffered(transformer, allocator)`. + + `send` copies what it accepts into its storage, so that it never borrows, and returns + `flow::needs_input`; every `receive` before `flush` gives nothing. `flush` runs `transform` over + the whole input into the output storage and returns `flow::output_pending` while output remains, + `flow::finished` when none does; `receive` then delivers the output over as many receives as the + caller's spans need. A fault, `T`'s or the input's length, is reported by `flush`, and every later + call returns it until `reset`. + + With `codecs::capacity`, the storage holds `N` input elements and `T::max_output_size(N)` + output elements in place, which `T` must state as a constant expression at `N` (a `static_assert` + names the fix otherwise), and nothing is allocated; an input past `N` is accepted, counted, and + reported at `flush` as `error::input_too_long`; every member is `noexcept` when `T`'s `transform` + and the copies of its elements are. With an allocator, the storage comes from it, rebound through + `std::allocator_traits` for each element type: the input grows as `send` accepts, and the output + is sized at `flush` by `T`'s exact `output_size(input)` when it states one, else by its static + `max_output_size`, else by doubling while `transform` reports `output_too_small`. A bound of the + object's own (a non-static `max_output_size`, as a configured format's may be) is not read, and + such a `T` is sized by doubling. `reset` keeps that memory. Construction, `send` and `flush` may + then allocate and are not `noexcept`, and an allocator's exception propagates: a `send` that throws + accepts nothing and leaves the stream as it was, and a `flush` that throws leaves it as it was + before the flush, valid and resettable. `receive` allocates nothing in either form. + + It is constant time when `T` is. A move takes the input, the output and the state, and leaves the + moved-from `buffered` in the state `reset` leaves, so that it converts a new input from the start. + + @tparam T The one-shot transformer. + @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. +*/ +template > +class buffered { + /** Whether the storage is in place. */ + static constexpr bool in_place = detail::is_capacity_v; + + /** The input accumulated. */ + using input_storage = detail::buffered_storage::input; + /** The output of the whole input. */ + using output_storage = detail::buffered_storage::output; + + /** Whether construction cannot throw. */ + static constexpr bool nothrow_construction = + in_place && std::is_nothrow_move_constructible_v; + + /** Whether `send` cannot throw. */ + static constexpr bool nothrow_send = + in_place && std::is_nothrow_copy_assignable_v; + + /** Whether `receive` cannot throw. */ + static constexpr bool nothrow_receive = + std::is_nothrow_copy_assignable_v; + + /** Whether `flush` cannot throw. */ + static constexpr bool nothrow_flush = in_place && detail::nothrow_transform_v; + +public: + /** The elements read: `T`'s. */ + using input_type = T::input_type; + /** The elements written: `T`'s. */ + using output_type = T::output_type; + + /** The stream runs in a time that does not depend on its data when `T` does. */ + static constexpr bool constant_time = is_constant_time_v; + + /** + Makes a stream of `transformer`, in `flow::needs_input`, with a default `Storage`. + + @param transformer The one-shot transformer. + */ + explicit buffered(T transformer) noexcept(nothrow_construction) + : buffered(std::move(transformer), Storage{}) {} + + /** + Makes a stream of `transformer`, in `flow::needs_input`. + + @param transformer The one-shot transformer. + @param storage `codecs::capacity`, or the allocator of the storage. + */ + buffered(T transformer, Storage const& storage) noexcept(nothrow_construction) + : transformer_(std::move(transformer)), input_(storage), output_(storage) {} + + /** + A copy holds what `other` holds. + + @param other The stream copied. + */ + buffered(buffered const& other) = default; + + /** + A copy holds what `other` holds. + + @param other The stream copied. + @return This stream. + */ + buffered& operator=(buffered const& other) = default; + + /** + Takes `other`'s transformer, input, output and state, and leaves `other` as `reset` does. + + @param other The stream moved from. + */ + buffered(buffered&& other) noexcept(std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v && + std::is_nothrow_move_constructible_v) + : transformer_(std::move(other.transformer_)), + input_(std::move(other.input_)), + output_(std::move(other.output_)), + stored_(other.stored_), + delivered_(other.delivered_), + flushed_(other.flushed_), + error_(other.error_) { + other.reset(); + } + + /** + Takes `other`'s transformer, input, output and state, and leaves `other` as `reset` does. + + @param other The stream moved from. + @return This stream. + */ + buffered& operator=(buffered&& other) noexcept( + std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v && + std::is_nothrow_move_assignable_v) { + if (this != &other) { + transformer_ = std::move(other.transformer_); + input_ = std::move(other.input_); + output_ = std::move(other.output_); + stored_ = other.stored_; + delivered_ = other.delivered_; + flushed_ = other.flushed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Destroys the transformer and the storage. */ + ~buffered() = default; + + /** + Copies all of `input` into the storage in `flow::needs_input`, and accepts nothing in another + state. + + An input past the storage's capacity is accepted and counted, and reported at `flush`. + + @param input The elements to convert, copied. + @return The elements accepted and `flow::needs_input`, `{0, state}`, or the stream's error. + */ + [[nodiscard]] result send(std::span input) noexcept(nothrow_send) { + if (error_) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + input_.append(input); + return step{.count = input.size(), .flow = flow::needs_input}; + } + + /** + Writes the output of the whole input into `output`, after `flush`; nothing before it. + + @param output The span to write into. + @return The elements written and the state after, or the stream's error. + */ + [[nodiscard]] result receive(std::span output) noexcept(nothrow_receive) { + if (error_) { + return error_; + } + if (!flushed_ || output.empty()) { + return step{.count = 0, .flow = state()}; + } + std::span const pending = + output_.elements().subspan(delivered_, stored_ - delivered_); + std::size_t const count = std::min(pending.size(), output.size()); + std::ranges::copy(pending.first(count), output.begin()); + delivered_ += count; + return step{.count = count, .flow = state()}; + } + + /** + Ends the input and converts it whole; a second call returns the state. + + @return `flow::output_pending` while output remains, `flow::finished` when none does, or the + stream's error: `T`'s, or `error::input_too_long` for an input past the storage's capacity. + */ + [[nodiscard]] result flush() noexcept(nothrow_flush) { + if (error_) { + return error_; + } + if (flushed_) { + return state(); + } + if (input_.too_long()) { + error_ = error::input_too_long; + return error_; + } + auto const written = output_.transform(transformer_, input_.elements()); + if (!written) { + error_ = written.error(); + return error_; + } + stored_ = written.unsafe_value(); + delivered_ = 0; + flushed_ = true; + return state(); + } + + /** + Returns to `flow::needs_input` with nothing held, pending or in error; the allocated storage is + kept for the next stream. + */ + void reset() noexcept { + input_.clear(); + stored_ = 0; + delivered_ = 0; + flushed_ = false; + error_.clear(); + } + + /** + The allocator of the storage: the heap form alone. + + @return The allocator, as given. + */ + [[nodiscard]] Storage get_allocator() const noexcept + requires(!in_place) + { + return input_.get_allocator(); + } + +private: + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (!flushed_) { + return flow::needs_input; + } + return delivered_ < stored_ ? flow::output_pending : flow::finished; + } + + /** The one-shot transformer. */ + T transformer_; + /** The input accumulated. */ + input_storage input_; + /** The output of the whole input, after `flush`. */ + output_storage output_; + /** The elements of the output. */ + std::size_t stored_ = 0; + /** The elements of the output already delivered. */ + std::size_t delivered_ = 0; + /** Whether `flush` converted the input. */ + bool flushed_ = false; + /** The stream's error, which every call returns until `reset`. */ + boost::system::error_code error_; +}; + +/** + Deduces `buffered`, the heap form with `std::allocator`, from `buffered(transformer)`. + + @tparam T The one-shot transformer's type. +*/ +template +buffered(T) -> buffered; + +/** + Deduces `buffered>`, the form in place, from + `buffered(transformer, codecs::capacity)`. + + @tparam T The one-shot transformer's type. + @tparam N The capacity, in elements. +*/ +template +buffered(T, capacity_t) -> buffered>; + +/** + Deduces `buffered`, the heap form with the allocator, from + `buffered(transformer, allocator)`. + + @tparam T The one-shot transformer's type. + @tparam Allocator The allocator's type. +*/ +template +buffered(T, Allocator) -> buffered; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP diff --git a/include/webcpp/codecs/detail/core/transformer.hpp b/include/webcpp/codecs/detail/core/transformer.hpp index cc28afe..d8aad82 100644 --- a/include/webcpp/codecs/detail/core/transformer.hpp +++ b/include/webcpp/codecs/detail/core/transformer.hpp @@ -77,9 +77,11 @@ concept transformer_types = std::movable && requires { may add overloads of its own; the concept requires the span form alone, and assumes no bytes, characters, constant time or secrecy. - Optional members, read when present and never required: `max_output_size(std::size_t)`, a bound - on the output of that many input elements, constexpr where it can be, and `output_size(input)`, - the exact size; `static constexpr bool constant_time`, read through @ref is_constant_time_v. + Optional members, read when present and never required: a static `max_output_size(std::size_t)`, + a bound on the output of that many input elements, constexpr where it can be (a bound of the + object's own, a non-static member, is not read, and `each` and `buffered` size such a + transformer's output by doubling), and `output_size(input)`, the exact size; + `static constexpr bool constant_time`, read through @ref is_constant_time_v. @tparam T The type to check. */ @@ -203,19 +205,23 @@ namespace detail { template concept compatible_elements = std::same_as || (byte_element && byte_element); -/** Whether `T` states a bound on its output, `T::max_output_size(std::size_t)`. */ +/** + Whether `T` states a bound on its output, `T::max_output_size(std::size_t)`, a static member: a + bound of the object's own (a non-static member, which a configured format's may be) is not one. +*/ template concept has_max_output_size = requires(std::size_t input_size) { { T::max_output_size(input_size) } -> std::convertible_to; }; /** - Whether `T` states its bound as a constant expression, which an in-place storage sizes itself by - (checked at one element). + Whether `T` states its bound for `InputSize` input elements as a constant expression, which an + in-place storage sizes itself by: `each` reads it at one element, `buffered` at its capacity, + where a bound constant at one element may not be. */ -template +template concept has_constant_max_output_size = has_max_output_size && requires { - typename std::integral_constant; + typename std::integral_constant; }; } // namespace detail diff --git a/test/Jamfile b/test/Jamfile index f068054..8c59601 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -87,6 +87,14 @@ codecs-run pipe : pipe_test.cpp ; # drain (D19): the pieces a sink is given, through drain's own buffer, a # capacity or the caller's span; a sink's error stops it. codecs-run drain : drain_test.cpp ; +# each (D19, D22): a one-shot transformer as a stream, one input element an item; +# frames to images and to bytes, in place and from an allocator; an item's +# error with its item; a moved-from each starts again. +codecs-run each : each_test.cpp ; +# buffered (D19, D22): a one-shot transformer as a stream that accumulates until +# flush, in place and from an allocator; input_too_long past the capacity; the +# heap form's sizing; a moved-from buffered starts again. +codecs-run buffered : buffered_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index d0328eb..12cd763 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -638,6 +638,81 @@ void check_pipe_and_drain() { BOOST_TEST(verdict); } +/** + each and buffered in place allocate nothing (D21): each made, streamed into spans shorter than an + item's output and into spans that take it whole, flushed, moved and reset; buffered made, sent in + chunks, flushed, received, moved and reset; and a pipe of packets into each. +*/ +void check_each_and_buffered() { + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + std::array frame_bytes{}; + std::array images{}; + bool volatile verdict = false; + expect_no_allocation("each(frame_to_bytes_bounded, capacity<4>)", [&] { + auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>); + std::size_t total = 0; + bool streamed = true; + for (std::size_t index = 0; index < frames.size(); ++index) { + streamed = streamed && adapter.send(std::span{frames}.subspan(index)).has_value(); + // Spans of 3, then 4: through the storage, then straight into the span. + std::size_t const span_size = index % 2 == 0 ? 3 : 4; + for (;;) { + auto const received = + adapter.receive(std::span{frame_bytes}.subspan(total, span_size)); + streamed = streamed && received.has_value(); + if (!received.has_value()) { + break; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + break; + } + } + } + streamed = streamed && adapter.flush().has_value(); + auto moved{std::move(adapter)}; + moved.reset(); + verdict = streamed && total == 14 && moved.completed_items() == 0; + }); + BOOST_TEST(verdict); + expect_no_allocation("buffered(frame_to_image, capacity<8>)", [&] { + auto adapter = codecs::buffered(test::frame_to_image{}, codecs::capacity<8>); + bool streamed = adapter.send(std::span{frames}.first(2)).has_value() && + adapter.send(std::span{frames}.subspan(2)).has_value() && + adapter.flush().has_value(); + auto const received = adapter.receive(images); + streamed = streamed && received.has_value() && received->count == 5; + auto moved{std::move(adapter)}; + moved.reset(); + verdict = streamed && images[4].index == 4; + }); + BOOST_TEST(verdict); + std::array const packets{ + test::packet{.index = 0, .frames = 1}, + test::packet{.index = 1, .frames = 2}, + }; + expect_no_allocation("pipe(packets_to_frames, each(frame_to_image, capacity<1>))", [&] { + auto piped = codecs::pipe(test::packets_to_frames{}, + codecs::each(test::frame_to_image{}, codecs::capacity<1>)); + std::size_t total = 0; + bool streamed = true; + for (test::packet const& input_packet : packets) { + streamed = streamed && piped.send(std::span{&input_packet, 1}).has_value(); + auto const received = piped.receive(std::span{images}.subspan(total)); + streamed = streamed && received.has_value(); + total += received.has_value() ? received->count : 0; + } + streamed = streamed && piped.flush().has_value(); + auto const last = piped.receive(std::span{images}.subspan(total)); + total += last.has_value() ? last->count : 0; + verdict = streamed && total == 3 && images[2].index == 3; + }); + BOOST_TEST(verdict); +} + /** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they allocate anything: the heap results are never built. */ void check_saturating_refusals() { @@ -689,6 +764,7 @@ int main() { check_over(); check_transformers(); check_pipe_and_drain(); + check_each_and_buffered(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index 20828f0..a96f7e4 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -12,7 +12,8 @@ // allocator, is no allocation of an operation: the arena leaves it out (support/bookkeeping.hpp), // as document's and trystero's tests do, and it reaches the global operator new never. The secret // heap types over the arena, and tokens::secret with the arena's allocator, give it back every -// buffer wiped. Later tasks add their rows. +// buffer wiped. each and buffered with the arena's allocator take their storage from it. Later +// tasks add their rows. #include "support/counting.hpp" @@ -20,6 +21,7 @@ #include "support/arena.hpp" #include "support/be16.hpp" #include "support/letters.hpp" +#include "support/toy_media.hpp" #include @@ -31,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -382,6 +385,91 @@ void a_secret_over_gives_its_intermediates_back_wiped() { expect_every_block_zero(arena); } +/** Frames 0 to `Count - 1`. */ +template +std::array frames_from_zero() { + std::array frames{}; + for (std::size_t index = 0; index < Count; ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** + Streams `frames` through `adapter`, receiving into `output` after each send and after flush, and + returns the bytes received, or 0 when a call fails; it allocates nothing of its own. +*/ +template +std::size_t frames_through(Adapter& adapter, std::span frames, + std::span output) { + std::size_t total = 0; + auto const receive_all = [&]() -> bool { + for (;;) { + auto const received = adapter.receive(output); + if (!received.has_value()) { + return false; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return true; + } + } + }; + std::span rest = frames; + while (!rest.empty()) { + auto const sent = adapter.send(rest.first(std::min(rest.size(), 2))); + if (!sent.has_value() || sent->count == 0 || !receive_all()) { + return 0; + } + rest = rest.subspan(sent->count); + } + if (!adapter.flush().has_value() || !receive_all()) { + return 0; + } + return total; +} + +/** + each and buffered with an allocator (Task 10): each over a frame-to-bytes transformer with no + constant bound (the spec's scenario "An arena receives every allocation") and buffered over the + bounded one take their storage from the arena, rebound to their elements, and the global + operator new sees none of it. +*/ +void each_and_buffered_over_an_arena() { + auto const frames = frames_from_zero<5>(); + std::array small_output{}; + std::array output{}; + test::recording_resource each_arena; + std::pmr::polymorphic_allocator const each_allocator{&each_arena}; + std::size_t total = 0; + expect_no_global_allocation("each(frame_to_bytes) over an arena", [&] { + auto adapter = codecs::each(test::frame_to_bytes{}, each_allocator); + total = frames_through(adapter, frames, small_output); + }); + // Frames 0 to 4 are 2, 3, 4, 2 and 3 bytes. + BOOST_TEST_EQ(total, 14U); + BOOST_TEST_GE(each_arena.allocation_count(), 1U); + for (std::size_t index = 0; + index < std::min(each_arena.allocation_count(), test::recording_resource::most_records); + ++index) { + BOOST_TEST(each_arena.owns(each_arena.allocation(index).pointer)); + } + test::recording_resource buffered_arena; + std::pmr::polymorphic_allocator const buffered_allocator{&buffered_arena}; + expect_no_global_allocation("buffered(frame_to_bytes_bounded) over an arena", [&] { + auto adapter = codecs::buffered(test::frame_to_bytes_bounded{}, buffered_allocator); + total = frames_through(adapter, frames, output); + }); + BOOST_TEST_EQ(total, 14U); + // The frames and the bytes, at least one block each. + BOOST_TEST_GE(buffered_arena.allocation_count(), 2U); + for (std::size_t index = 0; index < std::min(buffered_arena.allocation_count(), + test::recording_resource::most_records); + ++index) { + BOOST_TEST(buffered_arena.owns(buffered_arena.allocation(index).pointer)); + } +} + void the_allocators_of_the_tests_own() { // non_propagating_allocator: equal only to a copy. test::non_propagating_allocator const first_allocator{1}; @@ -426,6 +514,7 @@ int main() { the_secret_token_over_an_arena(); over_takes_its_intermediate_from_its_allocator(); a_secret_over_gives_its_intermediates_back_wiped(); + each_and_buffered_over_an_arena(); the_allocators_of_the_tests_own(); return boost::report_errors(); } diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index fcee4a6..178f76c 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -12,10 +12,13 @@ // throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). A secret heap // type whose allocation throws keeps its value, and every buffer it gives back reads zero; so does // every buffer of a secret operation through tokens::secret(allocator), and assign_to's scratch -// of a secret operation. Later tasks add their rows. +// of a secret operation. buffered and each with the allocator: a send that throws accepts nothing, +// and the stream converts the same input after the exception; a receive that throws leaves its +// item pending; a flush that throws leaves the stream resettable. Later tasks add their rows. #include "support/allocators.hpp" #include "support/letters.hpp" +#include "support/toy_media.hpp" #include #include @@ -471,6 +474,149 @@ void an_over_throws_through_and_wipes_when_secret() { BOOST_TEST(thrown); } +/** Frames 0 to 19, whose bytes frame_to_bytes writes 2 + index % 3 a frame. */ +std::array twenty_frames() { + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** The bytes of `frames`, the one-shot form. */ +std::vector bytes_of_frames(std::span frames) { + std::vector bytes(4 * frames.size()); + bytes.resize(test::frame_to_bytes::transform(frames, bytes).value()); + return bytes; +} + +/** + Receives everything `adapter` holds into `received`, one span of up to 5 bytes at a time, while + it reports output_pending; a receive that throws is called again, and true is returned when one + did: the item stays pending, and the stream delivers it. +*/ +template +bool receive_all(Adapter& adapter, std::vector& received) { + std::array output{}; + bool thrown = false; + for (;;) { + codecs::result step_taken = codecs::step{}; + try { + step_taken = adapter.receive(output); + } catch (std::bad_alloc const&) { + thrown = true; + continue; + } + if (!BOOST_TEST(step_taken.has_value())) { + return thrown; + } + received.insert(received.end(), output.begin(), + output.begin() + static_cast(step_taken->count)); + if (step_taken->flow != codecs::flow::output_pending) { + return thrown; + } + } +} + +/** + buffered with an allocator that throws on its fail_at-th allocation, for every fail_at until the + stream needs fewer (Task 10): the frames go in chunks of 3, growing the input, and flush sizes the + output. A send that throws accepts nothing: the same chunk sent again gives the right bytes, with + no frame twice. A flush that throws leaves the stream resettable: reset, the same frames give the + right bytes. Every block is given back. +*/ +void buffered_throws_through() { + auto const frames = twenty_frames(); + std::vector const expected = bytes_of_frames(frames); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + { + codecs::buffered adapter{test::frame_to_bytes_bounded{}, allocator}; + auto const send_all = [&] { + for (std::size_t first = 0; first < frames.size(); first += 3) { + std::span const chunk = + std::span{frames}.subspan(first, std::min(3, 20 - first)); + codecs::result sent = codecs::step{}; + try { + sent = adapter.send(chunk); + } catch (std::bad_alloc const&) { + thrown = true; + sent = adapter.send(chunk); + } + BOOST_TEST(sent.has_value() && sent->count == chunk.size()); + } + }; + send_all(); + codecs::result flushed = codecs::flow::needs_input; + try { + flushed = adapter.flush(); + } catch (std::bad_alloc const&) { + thrown = true; + adapter.reset(); + send_all(); + flushed = adapter.flush(); + } + BOOST_TEST(flushed.has_value()); + std::vector received; + static_cast(receive_all(adapter, received)); + BOOST_TEST(received == expected); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + // The input's growths and the output. + BOOST_TEST_GE(attempts, 2U); +} + +/** + each with an allocator that throws on its fail_at-th allocation, for every fail_at until the + stream needs fewer (Task 10): frame_to_bytes states no bound, so that receive grows the item + storage by doubling. A receive that throws leaves the item pending: receiving again delivers it, + and the stream gives the right bytes; reset, it converts the frames again. Every block is given + back. +*/ +void each_throws_through() { + auto const frames = twenty_frames(); + std::vector const expected = bytes_of_frames(frames); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + { + codecs::each adapter{test::frame_to_bytes{}, allocator}; + std::vector received; + for (std::size_t index = 0; index < frames.size(); ++index) { + auto const sent = adapter.send(std::span{frames}.subspan(index)); + BOOST_TEST(sent.has_value() && sent->count == 1); + thrown = receive_all(adapter, received) || thrown; + } + BOOST_TEST(received == expected); + BOOST_TEST_EQ(adapter.completed_items(), frames.size()); + adapter.reset(); + received.clear(); + for (std::size_t index = 0; index < frames.size(); ++index) { + BOOST_TEST(adapter.send(std::span{frames}.subspan(index)).has_value()); + static_cast(receive_all(adapter, received)); + } + BOOST_TEST(received == expected); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + // The storage's doublings. + BOOST_TEST_GE(attempts, 2U); +} + } // namespace int main() { @@ -485,5 +631,7 @@ int main() { the_secret_token_throws_through(); a_secret_assign_to_wipes_its_scratch_when_the_target_throws(); an_over_throws_through_and_wipes_when_secret(); + buffered_throws_through(); + each_throws_through(); return boost::report_errors(); } diff --git a/test/buffered_test.cpp b/test/buffered_test.cpp new file mode 100644 index 0000000..6eae3c9 --- /dev/null +++ b/test/buffered_test.cpp @@ -0,0 +1,469 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// buffered (D19, D22): a one-shot transformer as a stream that accumulates the whole input and +// converts it at flush. 40 bytes through buffered(letters_one_shot, capacity<64>) in chunks of 7 +// give nothing before flush and the one-shot text after, with no allocation (the spec's scenario +// "Accumulating", on letters; Task 19 adds base58's); an input past the capacity is +// input_too_long at flush; the heap form takes its storage from its allocator and sizes its output +// by output_size, then max_output_size, then doubling; a transformer's error is reported at flush; +// a moved-from buffered converts from the start (Review Focus 5). + +#include "support/counting.hpp" + +#include "support/arena.hpp" +#include "support/letters.hpp" +#include "support/toy_media.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +/** The bytes of the format letters' text, as a one-shot transformer: letters' codec, forwarded. */ +struct letters_one_shot { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The letters written. */ + using output_type = char; + + /** Two letters a byte: letters' bound. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return codecs::codec::max_encoded_size(input_size); + } + + /** letters' encode. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + return codecs::codec::encode(test::letters, input, output); + } +}; + +/** + letters' encode with no static bound, counting its calls: its bound is the object's (as a + configured format's may depend on its label or its part), or it states the exact size, or + nothing, by `Sizing`. +*/ +enum class sizing : unsigned char { exact, object_bound, none }; + +/** letters' encode, sized as `Sizing` says, counting the calls of `transform` in `*calls`. */ +template +struct counted_letters { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The letters written. */ + using output_type = char; + + /** Where the calls of `transform` are counted. */ + std::size_t* calls; + + /** The exact size of `input`'s text, when `Sizing` is `exact`. */ + [[nodiscard]] std::size_t output_size(std::span input) const noexcept + requires(Sizing == sizing::exact) + { + return codecs::codec::encoded_size(test::letters, input); + } + + /** A bound of this object's, which a static check does not see, when `Sizing` says so. */ + [[nodiscard]] std::size_t max_output_size(std::size_t input_size) const noexcept + requires(Sizing == sizing::object_bound) + { + return codecs::codec::max_encoded_size(input_size); + } + + /** letters' encode, counted. */ + codecs::result transform(std::span input, + std::span output) const noexcept { + ++*calls; + return codecs::codec::encode(test::letters, input, output); + } +}; + +/** letters' encode that refuses a byte 0xFF with `invalid_character`, writing nothing. */ +struct refusing_letters : letters_one_shot { + /** letters' encode, or the refusal. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + if (std::ranges::find(input, std::uint8_t{0xFF}) != input.end()) { + return codecs::error::invalid_character; + } + return letters_one_shot::transform(input, output); + } +}; + +static_assert(codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer); +// The object's bound is not a static one: buffered's heap form sizes such a transformer by +// doubling (review note (a) of Task 8). +static_assert(!codecs::detail::has_max_output_size>); + +/** `count` bytes, each its index times 37 plus 1. */ +std::vector bytes_of(std::size_t count) { + std::vector held_bytes(count); + for (std::size_t index = 0; index < count; ++index) { + held_bytes[index] = static_cast((index * 37U) + 1U); + } + return held_bytes; +} + +/** letters' text of `input`, the one-shot form. */ +std::string letters_of(std::span input) { + return codecs::encode(test::letters, input, tokens::return_string).value(); +} + +/** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ +bool is_step(codecs::result const& actual, std::size_t expected_count, + codecs::flow expected_flow) { + return actual.has_value() && actual->count == expected_count && actual->flow == expected_flow; +} + +/** Whether `actual` is the value `expected_flow`. */ +bool is_flow(codecs::result const& actual, codecs::flow expected_flow) { + return actual.has_value() && *actual == expected_flow; +} + +/** Whether `actual` is the error `expected`. */ +template +bool is_error(Result const& actual, codecs::error expected) { + return !actual.has_value() && actual.error() == expected; +} + +/** What stream_into returns when a call fails or a state is not the protocol's. */ +constexpr std::size_t stream_failed = static_cast(-1); + +/** + Sends `input` to `adapter` in chunks of `chunk_size`, each accepted whole with needs_input and + every receive before flush giving nothing; flushes, and receives into spans of `span_size` of + `text` until finished. Returns the characters written into `text`, or stream_failed when a call + fails, a state is not the protocol's or `text` is full; it allocates nothing of its own. +*/ +template +std::size_t stream_into(Adapter& adapter, std::span input, + std::size_t chunk_size, std::size_t span_size, std::span text) { + std::span rest = input; + while (!rest.empty()) { + std::span const chunk = rest.first(std::min(chunk_size, rest.size())); + if (!is_step(adapter.send(chunk), chunk.size(), codecs::flow::needs_input) || + !is_step(adapter.receive(text.first(std::min(span_size, text.size()))), 0, + codecs::flow::needs_input)) { + return stream_failed; + } + rest = rest.subspan(chunk.size()); + } + auto const flushed = adapter.flush(); + if (!flushed.has_value()) { + return stream_failed; + } + std::size_t written = 0; + codecs::flow state = *flushed; + while (state == codecs::flow::output_pending) { + std::span const room = text.subspan(written); + auto const received = adapter.receive(room.first(std::min(span_size, room.size()))); + if (!received.has_value() || received->count == 0) { + return stream_failed; + } + written += received->count; + state = received->flow; + } + return state == codecs::flow::finished ? written : stream_failed; +} + +/** stream_into a text of its own, returned, or "". */ +template +std::string stream(Adapter& adapter, std::span input, std::size_t chunk_size, + std::size_t span_size) { + std::vector text(4096); + std::size_t const written = stream_into(adapter, input, chunk_size, span_size, text); + if (written == stream_failed) { + return ""; + } + return {text.data(), written}; +} + +/** The deduction guides and the types: the heap form by default, in place with a capacity. */ +void types() { + using heap_form = decltype(codecs::buffered(letters_one_shot{})); + static_assert(std::is_same_v>); + static_assert(std::is_same_v>>); + static_assert(codecs::stream_transformer); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + using in_place = decltype(codecs::buffered(letters_one_shot{}, codecs::capacity<64>)); + static_assert( + std::is_same_v>>); + static_assert(codecs::stream_transformer); + using pmr_form = decltype(codecs::buffered(letters_one_shot{}, + std::pmr::polymorphic_allocator{})); + static_assert( + std::is_same_v>>); + static_assert(!codecs::is_constant_time_v); + // The bound is read at the capacity, constant there. + static_assert(codecs::detail::has_constant_max_output_size); +} + +/** + The spec's scenario "Accumulating", on letters: 40 bytes sent to buffered(letters_one_shot, + capacity<64>) in chunks of 7, then flushed and received: every receive before flush gives + nothing, the text after flush equals the one-shot form, and no allocation is counted. +*/ +void accumulating() { + std::vector const input = bytes_of(40); + std::string const expected = letters_of(input); + std::array first_text{}; + std::array second_text{}; + std::size_t first_size = 0; + std::size_t second_size = 0; + std::size_t const before = test::allocations(); + { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + first_size = stream_into(adapter, input, 7, 16, first_text); + adapter.reset(); + second_size = stream_into(adapter, input, 7, 1024, second_text); + } + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf("allocated: buffered(letters_one_shot, capacity<64>)\n"); + } + BOOST_TEST_EQ(allocated, 0U); + BOOST_TEST_EQ(first_size, expected.size()); + BOOST_TEST_EQ(second_size, expected.size()); + BOOST_TEST_EQ((std::string{first_text.data(), first_text.size()}), expected); + BOOST_TEST_EQ((std::string{second_text.data(), second_text.size()}), expected); + // Every chunking and every span size gives the same. + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{3}, std::size_t{40}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{5}, std::size_t{80}}) { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST_EQ(stream(adapter, input, chunk_size, span_size), expected); + } + } + // Frames to images, elements of no byte: five frames, five images at flush. + auto images = codecs::buffered(test::frame_to_image{}, codecs::capacity<8>); + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + BOOST_TEST(is_step(images.send(std::span{frames}.first(2)), 2, codecs::flow::needs_input)); + BOOST_TEST(is_step(images.send(std::span{frames}.subspan(2)), 3, codecs::flow::needs_input)); + BOOST_TEST(is_flow(images.flush(), codecs::flow::output_pending)); + std::array received{}; + BOOST_TEST(is_step(images.receive(received), 5, codecs::flow::finished)); + BOOST_TEST_EQ(received[4].index, 4U); +} + +/** + An input past the capacity is accepted and counted, and flush reports input_too_long, as does + every call after it until reset; the capacity itself is accepted. +*/ +void past_the_capacity() { + std::vector const input = bytes_of(65); + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST(is_step(adapter.send(std::span{input}.first(60)), 60, codecs::flow::needs_input)); + BOOST_TEST(is_step(adapter.send(std::span{input}.subspan(60)), 5, codecs::flow::needs_input)); + BOOST_TEST(is_step(adapter.send(std::span{input}.subspan(60)), 5, codecs::flow::needs_input)); + BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); + std::array output{}; + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + BOOST_TEST(is_error(adapter.send(input), codecs::error::input_too_long)); + BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, std::span{input}.first(64), 7, 32), + letters_of(std::span{input}.first(64))); + // 65 bytes in one send. + adapter.reset(); + BOOST_TEST(is_step(adapter.send(input), 65, codecs::flow::needs_input)); + BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); +} + +/** + The protocol's edges: flush with nothing sent finishes at once, with the empty text (Review Focus + 3); an empty send accepts nothing; after flush nothing is accepted, and an empty receive returns + the state. +*/ +void protocol_edges() { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<8>); + std::array output{}; + BOOST_TEST( + is_step(adapter.send(std::span{}), 0, codecs::flow::needs_input)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); + BOOST_TEST(is_step(adapter.receive(output), 0, codecs::flow::finished)); + adapter.reset(); + std::vector const input = bytes_of(3); + BOOST_TEST(is_step(adapter.send(input), 3, codecs::flow::needs_input)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.send(input), 0, codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(std::span{}), 0, codecs::flow::output_pending)); + BOOST_TEST( + is_step(adapter.receive(std::span{output}.first(4)), 4, codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(output), 2, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), 2}), letters_of(input).substr(4)); + BOOST_TEST(is_step(adapter.send(input), 0, codecs::flow::finished)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); +} + +/** A transformer's error is reported at flush, and by every call after it until reset. */ +void transformer_error() { + std::vector input = bytes_of(10); + input[6] = 0xFF; + auto adapter = codecs::buffered(refusing_letters{}, codecs::capacity<16>); + BOOST_TEST(is_step(adapter.send(input), 10, codecs::flow::needs_input)); + BOOST_TEST(is_error(adapter.flush(), codecs::error::invalid_character)); + std::array output{}; + output.fill('-'); + BOOST_TEST(is_error(adapter.receive(output), codecs::error::invalid_character)); + BOOST_TEST_EQ(output[0], '-'); + BOOST_TEST(is_error(adapter.send(input), codecs::error::invalid_character)); + adapter.reset(); + input[6] = 0; + BOOST_TEST_EQ(stream(adapter, input, 3, 4), letters_of(input)); +} + +/** + The heap form: every allocation goes to the arena, the output sized by the transformer's bound; + reset keeps the storage, so that the same input again allocates nothing more. +*/ +void heap_form() { + std::vector const input = bytes_of(1000); + std::string const expected = letters_of(input); + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto adapter = codecs::buffered(letters_one_shot{}, allocator); + BOOST_TEST(adapter.get_allocator() == allocator); + BOOST_TEST_EQ(stream(adapter, input, 7, 64), expected); + std::size_t const allocated = arena.allocation_count(); + BOOST_TEST_GE(allocated, 2U); + for (std::size_t index = 0; index < std::min(allocated, arena.most_records); ++index) { + BOOST_TEST(arena.owns(arena.allocation(index).pointer)); + } + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, input, 7, 64), expected); + BOOST_TEST_EQ(arena.allocation_count(), allocated); + // With std::allocator, by default. + auto by_default = codecs::buffered(letters_one_shot{}); + static_assert( + std::is_same_v>); + BOOST_TEST_EQ(stream(by_default, input, 13, 1024), expected); +} + +/** + The heap form sizes its output by the exact size when the transformer states one, then by its + static bound, then by doubling while transform reports output_too_small: one call of transform + for the first two, more for the last. A bound of the object's own is not a static one, and is + sized by doubling (D19 allows it; review note (a) of Task 8). +*/ +void heap_growth() { + std::vector const input = bytes_of(100); + std::string const expected = letters_of(input); + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_GT(calls, 1U); + // The storage is kept: the same input again needs one call. + calls = 0; + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_GT(calls, 1U); + } +} + +/** + A moved-from buffered is in reset's state and converts from the start (Review Focus 5), moved by + construction mid-input or by assignment mid-output; the moved-to one carries on. +*/ +template +void moved_mid_stream(Adapter source, Adapter target) { + std::vector const input = bytes_of(40); + std::string const expected = letters_of(input); + BOOST_TEST(is_step(source.send(std::span{input}.first(20)), 20, codecs::flow::needs_input)); + Adapter moved{std::move(source)}; + BOOST_TEST(is_step(moved.send(std::span{input}.subspan(20)), 20, codecs::flow::needs_input)); + BOOST_TEST(is_flow(moved.flush(), codecs::flow::output_pending)); + std::array output{}; + BOOST_TEST(is_step(moved.receive(output), 80, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), output.size()}), expected); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST(is_step(source.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST_EQ(stream(source, input, 7, 16), expected); + // By assignment, mid-output. + source.reset(); + BOOST_TEST(is_step(source.send(input), 40, codecs::flow::needs_input)); + BOOST_TEST(is_flow(source.flush(), codecs::flow::output_pending)); + BOOST_TEST( + is_step(source.receive(std::span{output}.first(30)), 30, codecs::flow::output_pending)); + target = std::move(source); + BOOST_TEST(is_step(target.receive(output), 50, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), 50}), expected.substr(30)); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(source, input, 40, 3), expected); +} + +void moved_from() { + moved_mid_stream(codecs::buffered(letters_one_shot{}, codecs::capacity<64>), + codecs::buffered(letters_one_shot{}, codecs::capacity<64>)); + moved_mid_stream(codecs::buffered(letters_one_shot{}), codecs::buffered(letters_one_shot{})); + // A buffered that has reported an error: the moved-to one keeps it, the moved-from starts + // again. + std::vector const input = bytes_of(65); + auto too_long = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST(is_step(too_long.send(input), 65, codecs::flow::needs_input)); + BOOST_TEST(is_error(too_long.flush(), codecs::error::input_too_long)); + auto moved{std::move(too_long)}; + BOOST_TEST(is_error(moved.flush(), codecs::error::input_too_long)); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(too_long, std::span{input}.first(10), 3, 7), + letters_of(std::span{input}.first(10))); +} + +} // namespace + +int main() { + types(); + accumulating(); + past_the_capacity(); + protocol_edges(); + transformer_error(); + heap_form(); + heap_growth(); + moved_from(); + return boost::report_errors(); +} diff --git a/test/each_test.cpp b/test/each_test.cpp new file mode 100644 index 0000000..2e51fc2 --- /dev/null +++ b/test/each_test.cpp @@ -0,0 +1,471 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// each (D19, D22): a one-shot transformer as a stream that converts each input element as a whole +// unit. Five frames through each(frame_to_image) give five images, one a receive (the spec's +// scenario "Per item"); frames through each(frame_to_bytes_bounded, capacity<64>) into spans of 3 +// bytes give each frame's bytes with no receive mixing two frames, completed_items() counting the +// boundaries, and neither allocates; an item's error is reported by the receive that transforms +// it; the heap form of a transformer with no constant bound takes its storage from its allocator; +// a moved-from each converts from the start (Review Focus 5). + +#include "support/counting.hpp" + +#include "support/arena.hpp" +#include "support/toy_media.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** frame_to_bytes_bounded that refuses frame 3 with `invalid_character`, writing nothing. */ +struct refusing_frame_three : test::frame_to_bytes_bounded { + /** Writes each frame's bytes, or refuses frame 3. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + if (std::ranges::any_of( + input, [](test::frame const& input_frame) { return input_frame.index == 3; })) { + return codecs::error::invalid_character; + } + return test::frame_to_bytes::transform(input, output); + } +}; + +/** Copies bytes, one a byte, in a time that does not depend on them. */ +struct copy_bytes { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** The copy runs in a time that does not depend on its data. */ + static constexpr bool constant_time = true; + + /** One byte a byte. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Copies `input` into `output`, or writes nothing when `output` is short. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size()) { + return codecs::error::output_too_small; + } + std::ranges::copy(input, output.begin()); + return input.size(); + } +}; + +static_assert(codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer); + +/** The frames 0 to 4, whose bytes number 2, 3, 4, 2 and 3. */ +std::array five_frames() { + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** + The bytes of up to eight items, each of up to eight bytes, held in place, so that a test that + counts the heap's allocations sees none of the test's own. +*/ +struct item_bytes { + /** The most items held. */ + static constexpr std::size_t most_items = 8; + /** The most bytes an item holds. */ + static constexpr std::size_t most_bytes = 8; + + /** Each item's bytes. */ + std::array, most_items> bytes{}; + /** Each item's size. */ + std::array sizes{}; + /** The items held. */ + std::size_t count = 0; + + /** Starts a new item; false when there is no room for one. */ + bool start_item() noexcept { + if (count == most_items) { + return false; + } + ++count; + return true; + } + + /** Appends `piece` to the last item; false when it has no room for it. */ + bool append(std::span piece) noexcept { + std::size_t& size = sizes[count - 1]; + if (piece.size() > most_bytes - size) { + return false; + } + std::ranges::copy(piece, std::span{bytes[count - 1]}.subspan(size).begin()); + size += piece.size(); + return true; + } + + /** The same items, of the same bytes. */ + bool operator==(item_bytes const& other) const = default; +}; + +/** The bytes of each frame, as frame_to_bytes writes one frame alone. */ +item_bytes expected_items(std::span frames) { + item_bytes items; + for (test::frame const& input_frame : frames) { + std::array written_bytes{}; + auto const written = + test::frame_to_bytes::transform(std::span{&input_frame, 1}, written_bytes); + BOOST_TEST(items.start_item()); + BOOST_TEST(items.append(std::span{written_bytes}.first(written.value()))); + } + return items; +} + +/** Whether `actual` is a value of `expected_count` elements and `expected_flow`. */ +bool is_step(codecs::result const& actual, std::size_t expected_count, + codecs::flow expected_flow) { + return actual.has_value() && actual->count == expected_count && actual->flow == expected_flow; +} + +/** Whether `actual` is the value `expected_flow`. */ +bool is_flow(codecs::result const& actual, codecs::flow expected_flow) { + return actual.has_value() && *actual == expected_flow; +} + +/** Whether `actual` is the error `invalid_character`. */ +template +bool is_invalid_character(Result const& actual) { + return !actual.has_value() && actual.error() == codecs::error::invalid_character; +} + +/** + Sends `frames` to `adapter` with every frame left in the span, as a caller does, and receives into + spans of `span_size` until each item is delivered; returns the bytes of each receive, grouped by + item. Checks the protocol on the way: one frame accepted a send, every receive of an item but its + last reporting output_pending with progress, and completed_items() counting each boundary. +*/ +template +item_bytes items_through(Adapter& adapter, std::span frames, + std::size_t span_size) { + item_bytes items; + std::array buffer{}; + std::span rest = frames; + std::size_t const completed_before = adapter.completed_items(); + while (!rest.empty()) { + if (!BOOST_TEST(is_step(adapter.send(rest), 1, codecs::flow::output_pending)) || + !BOOST_TEST(items.start_item())) { + return items; + } + // Output is pending: nothing more is accepted. + BOOST_TEST(is_step(adapter.send(rest), 0, codecs::flow::output_pending)); + rest = rest.subspan(1); + for (;;) { + BOOST_TEST_EQ(adapter.completed_items(), completed_before + items.count - 1); + auto const received = adapter.receive(std::span{buffer}.first(span_size)); + if (!BOOST_TEST(received.has_value()) || + !BOOST_TEST(items.append(std::span{buffer}.first(received->count)))) { + return items; + } + if (received->flow != codecs::flow::output_pending) { + BOOST_TEST(received->flow == codecs::flow::needs_input); + break; + } + if (!BOOST_TEST(received->count > 0)) { + return items; + } + } + BOOST_TEST_EQ(adapter.completed_items(), completed_before + items.count); + } + return items; +} + +/** The deduction guides and the types: the heap form by default, in place with a capacity. */ +void types() { + using images = decltype(codecs::each(test::frame_to_image{})); + static_assert(std::is_same_v>); + static_assert( + std::is_same_v>>); + static_assert(codecs::stream_transformer); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + using in_place = decltype(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<64>)); + static_assert( + std::is_same_v>>); + static_assert(codecs::stream_transformer); + using pmr_form = decltype(codecs::each(test::frame_to_bytes{}, + std::pmr::polymorphic_allocator{})); + static_assert( + std::is_same_v>>); + static_assert(codecs::stream_transformer); + // Constant time exactly when the transformer is. + static_assert(!codecs::is_constant_time_v); + static_assert(codecs::is_constant_time_v>>); + static_assert(codecs::is_constant_time_v>); +} + +/** Runs `body` and checks that it allocated nothing, through operator new or the C library. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const before = test::allocations(); + body(); + std::size_t const after = test::allocations(); + if (after != before) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(after - before, 0U); +} + +/** + The spec's scenario "Per item", first part: five frames streamed through each(frame_to_image) into + a span of one image at a time give five images in order, each receive giving one, and flush after + the last item gives finished at once; nothing allocates, in the heap form (the item goes straight + into the caller's span) and in place. +*/ +template +void images_one_a_receive(Adapter& adapter) { + std::array const frames = five_frames(); + std::array received_image{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + BOOST_TEST(is_step(adapter.send(std::span{frames}.subspan(index)), 1, + codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(received_image), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(received_image[0].index, index); + std::array expected_image{}; + BOOST_TEST( + test::frame_to_image::transform(std::span{frames}.subspan(index, 1), expected_image) + .has_value()); + BOOST_TEST_EQ(received_image[0].checksum, expected_image[0].checksum); + BOOST_TEST_EQ(adapter.completed_items(), index + 1); + } + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); + BOOST_TEST(is_step(adapter.receive(received_image), 0, codecs::flow::finished)); + BOOST_TEST(is_step(adapter.send(frames), 0, codecs::flow::finished)); +} + +void per_item_images() { + // The heap form is made outside the count: a container may allocate when it is constructed + // (the MSVC STL's debug proxy), and its calls allocate nothing here. + auto heap_adapter = codecs::each(test::frame_to_image{}); + expect_no_allocation("each(frame_to_image)", [&] { images_one_a_receive(heap_adapter); }); + expect_no_allocation("each(frame_to_image, capacity<1>)", [] { + auto adapter = codecs::each(test::frame_to_image{}, codecs::capacity<1>); + images_one_a_receive(adapter); + }); +} + +/** + The spec's scenario "Per item", second part: frames through each(frame_to_bytes_bounded, + capacity<64>) into spans of 3 bytes give each frame's bytes, no receive mixing two frames, and + completed_items() counting 1 to 5 at the boundaries; flush after the last item gives finished at + once; nothing allocates. Spans of 1, 4 (the bound, straight into the span) and 64 give the same, + and so does a storage of exactly the bound. +*/ +void per_item_bytes() { + std::array const frames = five_frames(); + auto const expected = expected_items(frames); + for (std::size_t const span_size : + {std::size_t{3}, std::size_t{1}, std::size_t{4}, std::size_t{64}}) { + expect_no_allocation("each(frame_to_bytes_bounded, capacity<64>)", [&] { + auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<64>); + BOOST_TEST(items_through(adapter, frames, span_size) == expected); + BOOST_TEST_EQ(adapter.completed_items(), 5U); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); + std::array after{}; + BOOST_TEST(is_step(adapter.receive(after), 0, codecs::flow::finished)); + // Reset: the count starts again, and so does the stream. + adapter.reset(); + BOOST_TEST_EQ(adapter.completed_items(), 0U); + BOOST_TEST(items_through(adapter, frames, span_size) == expected); + }); + auto exact = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>); + BOOST_TEST(items_through(exact, frames, span_size) == expected); + } +} + +/** + The protocol's edges: an empty send accepts nothing; an empty receive returns the state; a flush + while an item is pending returns output_pending, and finished once the item is received; flush + with nothing sent finishes at once (Review Focus 3). +*/ +void protocol_edges() { + std::array const frames = five_frames(); + auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>); + std::array output{}; + BOOST_TEST(is_step(adapter.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST(is_step(adapter.send(std::span{}), 0, codecs::flow::needs_input)); + BOOST_TEST( + is_step(adapter.send(std::span{frames}.subspan(2)), 1, codecs::flow::output_pending)); + BOOST_TEST( + is_step(adapter.receive(std::span{}), 0, codecs::flow::output_pending)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.send(frames), 0, codecs::flow::output_pending)); + BOOST_TEST( + is_step(adapter.receive(std::span{output}.first(3)), 3, codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(output), 1, codecs::flow::finished)); + BOOST_TEST_EQ(adapter.completed_items(), 1U); + BOOST_TEST(is_step(adapter.send(frames), 0, codecs::flow::finished)); + adapter.reset(); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); + BOOST_TEST(is_step(adapter.receive(output), 0, codecs::flow::finished)); + BOOST_TEST_EQ(adapter.completed_items(), 0U); +} + +/** + An item's error is reported by the receive that transforms it, which writes nothing: frames 0 to + 2 are delivered, frame 3 is refused, and every call returns the error until reset; whether the + item goes straight into the caller's span or through the storage. +*/ +template +void refuses_frame_three(Adapter& adapter, std::size_t span_size) { + std::array const frames = five_frames(); + auto const delivered = items_through(adapter, std::span{frames}.first(3), span_size); + BOOST_TEST(delivered == expected_items(std::span{frames}.first(3))); + BOOST_TEST( + is_step(adapter.send(std::span{frames}.subspan(3)), 1, codecs::flow::output_pending)); + std::array output{}; + output.fill(0xAA); + BOOST_TEST(is_invalid_character(adapter.receive(std::span{output}.first(span_size)))); + BOOST_TEST(std::ranges::all_of(output, [](std::uint8_t value) { return value == 0xAA; })); + BOOST_TEST_EQ(adapter.completed_items(), 3U); + BOOST_TEST(is_invalid_character(adapter.receive(output))); + BOOST_TEST(is_invalid_character(adapter.receive(std::span{}))); + BOOST_TEST(is_invalid_character(adapter.send(frames))); + BOOST_TEST(is_invalid_character(adapter.flush())); + // Reset forgets it, and the stream converts frames that are not refused. + adapter.reset(); + BOOST_TEST_EQ(adapter.completed_items(), 0U); + BOOST_TEST(items_through(adapter, std::span{frames}.first(2), span_size) == + expected_items(std::span{frames}.first(2))); +} + +void item_errors() { + for (std::size_t const span_size : {std::size_t{3}, std::size_t{64}}) { + auto in_place = codecs::each(refusing_frame_three{}, codecs::capacity<4>); + refuses_frame_three(in_place, span_size); + auto heap = codecs::each(refusing_frame_three{}); + refuses_frame_three(heap, span_size); + } +} + +/** + each(frame_to_bytes, allocator), the only form of a transformer with no constant bound: its item + storage comes from the allocator, growing by doubling, and every allocation goes to the arena; + reset keeps the storage, so that the same frames again allocate nothing more. +*/ +void heap_form() { + std::array const frames = five_frames(); + auto const expected = expected_items(frames); + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto adapter = codecs::each(test::frame_to_bytes{}, allocator); + BOOST_TEST(adapter.get_allocator() == allocator); + for (std::size_t const span_size : {std::size_t{3}, std::size_t{1}, std::size_t{64}}) { + adapter.reset(); + BOOST_TEST(items_through(adapter, frames, span_size) == expected); + } + std::size_t const allocated = arena.allocation_count(); + BOOST_TEST_GE(allocated, 1U); + for (std::size_t index = 0; index < std::min(allocated, arena.most_records); ++index) { + BOOST_TEST(arena.owns(arena.allocation(index).pointer)); + } + adapter.reset(); + BOOST_TEST(items_through(adapter, frames, 3) == expected); + BOOST_TEST_EQ(arena.allocation_count(), allocated); + // With std::allocator, by default. + auto by_default = codecs::each(test::frame_to_bytes{}); + static_assert( + std::is_same_v>); + BOOST_TEST(items_through(by_default, frames, 2) == expected); +} + +/** + A moved-from each is in reset's state and converts from the start (Review Focus 5), moved by + construction or by assignment mid-item, its item's bytes partly delivered from the storage; the + moved-to each delivers the rest of that item and carries on. The same for the heap form, and for + an each that has reported an error. +*/ +template +void moved_mid_item(Adapter source, Adapter target) { + std::array const frames = five_frames(); + auto const expected = expected_items(frames); + std::array output{}; + // Frame 2's four bytes, two delivered. + BOOST_TEST(is_step(source.send(std::span{frames}.subspan(2)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(source.receive(output), 2, codecs::flow::output_pending)); + BOOST_TEST(output[0] == expected.bytes[2][0] && output[1] == expected.bytes[2][1]); + Adapter moved{std::move(source)}; + BOOST_TEST(is_step(moved.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST(output[0] == expected.bytes[2][2] && output[1] == expected.bytes[2][3]); + BOOST_TEST_EQ(moved.completed_items(), 1U); + BOOST_TEST(items_through(moved, std::span{frames}.subspan(3), 3) == + expected_items(std::span{frames}.subspan(3))); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(source.completed_items(), 0U); + BOOST_TEST(is_step(source.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST(items_through(source, frames, 3) == expected); + // By assignment, mid-item. + BOOST_TEST(is_step(source.send(std::span{frames}.subspan(2)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(source.receive(output), 2, codecs::flow::output_pending)); + target = std::move(source); + BOOST_TEST(is_step(target.receive(output), 2, codecs::flow::needs_input)); + BOOST_TEST(output[0] == expected.bytes[2][2] && output[1] == expected.bytes[2][3]); + BOOST_TEST_EQ(target.completed_items(), 6U); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST(items_through(source, frames, 64) == expected); +} + +void moved_from() { + moved_mid_item(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>), + codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>)); + moved_mid_item(codecs::each(test::frame_to_bytes{}), codecs::each(test::frame_to_bytes{})); + // An each that has reported an error: the moved-to one keeps it, the moved-from starts again. + std::array const frames = five_frames(); + auto refusing = codecs::each(refusing_frame_three{}, codecs::capacity<4>); + std::array output{}; + BOOST_TEST( + is_step(refusing.send(std::span{frames}.subspan(3)), 1, codecs::flow::output_pending)); + BOOST_TEST(is_invalid_character(refusing.receive(output))); + auto moved{std::move(refusing)}; + BOOST_TEST(is_invalid_character(moved.receive(output))); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST(items_through(refusing, std::span{frames}.first(3), 1) == + expected_items(std::span{frames}.first(3))); +} + +} // namespace + +int main() { + types(); + per_item_images(); + per_item_bytes(); + protocol_edges(); + item_errors(); + heap_form(); + moved_from(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index b7ae5d0..7bcb624 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -26,3 +26,7 @@ build-project refused_secret_value_overload ; build-project pipe_incompatible ; build-project pipe_one_shot ; build-project piped_incompatible ; +build-project each_capacity_too_small ; +build-project each_without_bound ; +build-project buffered_without_bound ; +build-project buffered_bound_not_constant ; diff --git a/test/messages/buffered_bound_not_constant/Jamfile b/test/messages/buffered_bound_not_constant/Jamfile new file mode 100644 index 0000000..9761bff --- /dev/null +++ b/test/messages/buffered_bound_not_constant/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic buffered_bound_not_constant : buffered_bound_not_constant.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail buffered_bound_not_constant_refused : buffered_bound_not_constant.cpp + : clang:no : native emscripten ; diff --git a/test/messages/buffered_bound_not_constant/buffered_bound_not_constant.cpp b/test/messages/buffered_bound_not_constant/buffered_bound_not_constant.cpp new file mode 100644 index 0000000..ae1ef1a --- /dev/null +++ b/test/messages/buffered_bound_not_constant/buffered_bound_not_constant.cpp @@ -0,0 +1,72 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// buffered in place reads the bound at its capacity, not at one element: a bound that is a +// constant expression for small inputs alone (it calls a function that is not constexpr past +// eight elements) stops the build with buffered's message, which names the fix, rather than with +// an error about a constant expression in the storage's size. + +// The notes that follow the error say the bound at sixteen is not a constant expression. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: buffered(transformer, capacity) needs T::max_output_size(N) as a constant expression; declare it, or pass an allocator}} +// expected-note@webcpp/codecs/detail/core/transformer.hpp:* {{non-type template argument is not a constant expression}} +// clang-format on + +#include + +#include +#include +#include + +namespace { + +/** A bound past eight elements that is not a constant expression. */ +std::size_t computed_bound(std::size_t input_size) noexcept { + return input_size * 2; +} + +/** Copies bytes twice each; its bound is a constant expression up to eight elements alone. */ +struct short_bound { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** Two bytes a byte: a constant expression up to eight elements. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size <= 8 ? input_size * 2 : computed_bound(input_size); + } + + /** Writes each byte twice. */ + static webcpp::codecs::result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size() * 2) { + return webcpp::codecs::error::output_too_small; + } + for (std::size_t index = 0; index < input.size(); ++index) { + output[2 * index] = input[index]; + output[(2 * index) + 1] = input[index]; + } + return input.size() * 2; + } +}; + +// The bound is a constant expression at one element, which the trait's default reads, and not at +// sixteen. +static_assert(webcpp::codecs::detail::has_constant_max_output_size); +static_assert(!webcpp::codecs::detail::has_constant_max_output_size); + +} // namespace + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::buffered(short_bound{}, codecs::capacity<16>); + static_cast(adapter); + return 0; +} diff --git a/test/messages/buffered_without_bound/Jamfile b/test/messages/buffered_without_bound/Jamfile new file mode 100644 index 0000000..58e73a8 --- /dev/null +++ b/test/messages/buffered_without_bound/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic buffered_without_bound : buffered_without_bound.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail buffered_without_bound_refused : buffered_without_bound.cpp + : clang:no : native emscripten ; diff --git a/test/messages/buffered_without_bound/buffered_without_bound.cpp b/test/messages/buffered_without_bound/buffered_without_bound.cpp new file mode 100644 index 0000000..18ccf11 --- /dev/null +++ b/test/messages/buffered_without_bound/buffered_without_bound.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// buffered in place sizes its output by the bound at its capacity: frame_to_bytes states none, and +// the build stops with buffered's message, which names the fix. + +// The note that follows the error names the requirement the type does not satisfy. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: buffered(transformer, capacity) needs T::max_output_size(N) as a constant expression; declare it, or pass an allocator}} +// expected-note@webcpp/codecs/detail/core/transformer.hpp:* {{because 'webcpp::codecs::test::frame_to_bytes' does not satisfy 'has_max_output_size'}} +// clang-format on + +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::buffered(codecs::test::frame_to_bytes{}, codecs::capacity<8>); + static_cast(adapter); + return 0; +} diff --git a/test/messages/each_capacity_too_small/Jamfile b/test/messages/each_capacity_too_small/Jamfile new file mode 100644 index 0000000..d46eb1c --- /dev/null +++ b/test/messages/each_capacity_too_small/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic each_capacity_too_small : each_capacity_too_small.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail each_capacity_too_small_refused : each_capacity_too_small.cpp + : clang:no : native emscripten ; diff --git a/test/messages/each_capacity_too_small/each_capacity_too_small.cpp b/test/messages/each_capacity_too_small/each_capacity_too_small.cpp new file mode 100644 index 0000000..05179e6 --- /dev/null +++ b/test/messages/each_capacity_too_small/each_capacity_too_small.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// each in place holds one item's output: frame_to_bytes_bounded states four bytes a frame, which +// a capacity of two cannot hold, and the build stops with each's message, which names the fix. + +// The note that follows the error gives the bound and the capacity. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: each(transformer, capacity) needs T::max_output_size(1) as a constant expression and N >= it; declare max_output_size, raise N, or pass an allocator}} +// expected-note@webcpp/codecs/detail/core/adapters.hpp:* {{(4 <= 2) evaluated to false}} +// clang-format on + +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::each(codecs::test::frame_to_bytes_bounded{}, codecs::capacity<2>); + static_cast(adapter); + return 0; +} diff --git a/test/messages/each_without_bound/Jamfile b/test/messages/each_without_bound/Jamfile new file mode 100644 index 0000000..e3a3ff9 --- /dev/null +++ b/test/messages/each_without_bound/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic each_without_bound : each_without_bound.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail each_without_bound_refused : each_without_bound.cpp + : clang:no : native emscripten ; diff --git a/test/messages/each_without_bound/each_without_bound.cpp b/test/messages/each_without_bound/each_without_bound.cpp new file mode 100644 index 0000000..b1b85a6 --- /dev/null +++ b/test/messages/each_without_bound/each_without_bound.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// each in place needs a bound stated as a constant expression: frame_to_bytes states none, so +// only the allocator form exists for it, and the build stops with each's message, which names the +// fix. + +// The note that follows the error names the requirement the type does not satisfy. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: each(transformer, capacity) needs T::max_output_size(1) as a constant expression and N >= it; declare max_output_size, raise N, or pass an allocator}} +// expected-note@webcpp/codecs/detail/core/adapters.hpp:* {{because 'webcpp::codecs::test::frame_to_bytes' does not satisfy 'has_constant_max_output_size'}} +// clang-format on + +#include "../../support/toy_media.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::each(codecs::test::frame_to_bytes{}, codecs::capacity<8>); + static_cast(adapter); + return 0; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 4564ac9..9975595 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -11,6 +11,7 @@ #include "support/be16.hpp" #include "support/doubler.hpp" #include "support/letters.hpp" +#include "support/toy_media.hpp" #include #include @@ -325,4 +326,77 @@ static_assert(!noexcept(codecs::drain(std::declval(), throwing_s std::span{}))); static_assert(!noexcept(codecs::drain(std::declval(), nothrow_sink{}))); +// each and buffered (Task 10): in place, every member is noexcept when the transformer's transform +// is; with an allocator, construction and the calls that allocate are not, and the others are. +using bytes_in_place = codecs::each>; +static_assert(noexcept(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>))); +static_assert(std::is_nothrow_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +static_assert(noexcept(std::declval().completed_items())); + +using bytes_on_heap = codecs::each; +static_assert(!noexcept(codecs::each(test::frame_to_bytes{}))); +static_assert(!std::is_nothrow_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(!noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +static_assert(noexcept(std::declval().get_allocator())); + +using images_in_place = codecs::buffered>; +static_assert(noexcept(codecs::buffered(test::frame_to_image{}, codecs::capacity<8>))); +static_assert(std::is_nothrow_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +using images_on_heap = + codecs::buffered>; +static_assert(!noexcept(codecs::buffered(test::frame_to_image{}))); +static_assert(!std::is_nothrow_constructible_v>); +static_assert(!noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(!noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +/** frame_to_image whose transform may throw, as a transformer that allocates may. */ +struct throwing_frame_to_image { + /** The frames read. */ + using input_type = test::frame; + /** The images written. */ + using output_type = test::image; + + /** One image a frame. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** frame_to_image's transform, not noexcept. */ + static codecs::result transform(std::span input, + std::span output) { + return test::frame_to_image::transform(input, output); + } +}; + +// A transform that may throw makes the calls that run it not noexcept, in place too, so that its +// exception propagates; the others stay noexcept. +using throwing_each = codecs::each>; +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(!noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +using throwing_buffered = codecs::buffered>; +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(!noexcept(std::declval().flush())); + } // namespace diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index 1231b8c..64a3bb5 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -8,7 +8,10 @@ // their elements (D17, the spec's "A toy media transformer satisfies the contract"): the packet // decoder is a stream transformer whose frames come out in index order, the frame held back // until the next packet or flush; the frame encoders are one-shot transformers whose outputs are -// checked for frame 4, and which write nothing into a short output. +// checked for frame 4, and which write nothing into a short output. Through a pipe and each, the +// packet decoder and the frame-to-image encoder turn packets into images, allocating nothing. + +#include "support/counting.hpp" #include "support/toy_media.hpp" @@ -20,7 +23,9 @@ #include #include #include +#include #include +#include #include #include @@ -251,6 +256,68 @@ void check_one_shot_outputs() { BOOST_TEST(no_image.has_value() && *no_image == 0); } +/** + Five packets through pipe(packets_to_frames, each(frame_to_image, capacity<1>)) into a span of + one image at a time give an image of each frame, 0, 4, 5, 6, 8 and 9, in order, each receive + giving one, and nothing is allocated once the pipe is made. +*/ +void packets_to_images() { + auto piped = codecs::pipe(test::packets_to_frames{}, + codecs::each(test::frame_to_image{}, codecs::capacity<1>)); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + std::array images{}; + std::size_t received_count = 0; + bool protocol_kept = true; + std::size_t const before = test::allocations(); + // Receives one image a receive until the pipe stops reporting output_pending. + auto const receive_all = [&] { + for (;;) { + if (received_count == images.size()) { + protocol_kept = false; + return; + } + auto const received = piped.receive(std::span{images}.subspan(received_count, 1)); + if (!received.has_value()) { + protocol_kept = false; + return; + } + received_count += received->count; + if (received->flow != codecs::flow::output_pending) { + return; + } + } + }; + for (test::packet const& input_packet : packets) { + auto const sent = piped.send(std::span{&input_packet, 1}); + protocol_kept = protocol_kept && sent.has_value() && sent->count == 1; + receive_all(); + } + auto const flushed = piped.flush(); + protocol_kept = protocol_kept && flushed.has_value(); + receive_all(); + auto const finished = piped.receive(std::span{}); + protocol_kept = + protocol_kept && finished.has_value() && finished->flow == codecs::flow::finished; + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf("allocated: pipe(packets_to_frames, each(frame_to_image, capacity<1>))\n"); + } + BOOST_TEST_EQ(allocated, 0U); + BOOST_TEST(protocol_kept); + BOOST_TEST_EQ(received_count, images.size()); + std::array const expected_indices{0, 4, 5, 6, 8, 9}; + for (std::size_t index = 0; index < images.size(); ++index) { + std::array expected{}; + BOOST_TEST( + test::frame_to_image::transform( + std::array{test::make_frame(expected_indices[index])}, expected) + .has_value()); + BOOST_TEST_EQ(images[index].index, expected_indices[index]); + BOOST_TEST_EQ(images[index].checksum, expected[0].checksum); + } +} + } // namespace int main() { @@ -258,5 +325,6 @@ int main() { check_packets_to_frames_steps(); check_packets_to_frames_empty_and_moved(); check_one_shot_outputs(); + packets_to_images(); return boost::report_errors(); } From ff76e3e8b014434a8bbe1d81356a40304c96f3ff Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 17:28:39 -0300 Subject: [PATCH 054/157] codecs: each and buffered lint fix, the noexcept of transform as a requirement, the derived aggregates value-initialised, the complex tests in parts, a step's flow named --- .../webcpp/codecs/detail/core/adapters.hpp | 13 ++-- test/Jamfile | 6 +- test/allocation_test.cpp | 60 ++++++++++++------ test/allocator_test.cpp | 2 +- test/allocator_throw_test.cpp | 8 ++- test/buffered_test.cpp | 9 +-- test/each_test.cpp | 63 +++++++++++-------- test/noexcept_test.cpp | 2 +- test/pipe_test.cpp | 40 ++++++------ 9 files changed, 122 insertions(+), 81 deletions(-) diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index fc64495..4bdde6f 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -50,9 +50,10 @@ concept has_output_size = requires(T& transformer, std::span -inline constexpr bool nothrow_transform_v = - noexcept(std::declval().transform(std::declval>(), - std::declval>())); +concept nothrow_transform = requires(T& transformer, std::span input, + std::span output) { + { transformer.transform(input, output) } noexcept; +}; /** Whether one item's output of `T` fits in `N` elements in place: `T` states `max_output_size(1)` as @@ -105,7 +106,7 @@ class in_place_output { template [[nodiscard]] result transform( T& transformer, - std::span input) noexcept(nothrow_transform_v) { + std::span input) noexcept(nothrow_transform) { return transformer.transform(input, std::span{elements_}); } @@ -424,7 +425,7 @@ class each { /** Whether `receive` cannot throw. */ static constexpr bool nothrow_receive = - in_place && detail::nothrow_transform_v && + in_place && detail::nothrow_transform && std::is_nothrow_copy_assignable_v; public: @@ -748,7 +749,7 @@ class buffered { std::is_nothrow_copy_assignable_v; /** Whether `flush` cannot throw. */ - static constexpr bool nothrow_flush = in_place && detail::nothrow_transform_v; + static constexpr bool nothrow_flush = in_place && detail::nothrow_transform; public: /** The elements read: `T`'s. */ diff --git a/test/Jamfile b/test/Jamfile index 8c59601..722bf89 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -87,9 +87,9 @@ codecs-run pipe : pipe_test.cpp ; # drain (D19): the pieces a sink is given, through drain's own buffer, a # capacity or the caller's span; a sink's error stops it. codecs-run drain : drain_test.cpp ; -# each (D19, D22): a one-shot transformer as a stream, one input element an item; -# frames to images and to bytes, in place and from an allocator; an item's -# error with its item; a moved-from each starts again. +# each (D19, D22): a one-shot transformer as a stream, one input element an +# item; frames to images and to bytes, in place and from an allocator; an +# item's error with its item; a moved-from each starts again. codecs-run each : each_test.cpp ; # buffered (D19, D22): a one-shot transformer as a stream that accumulates until # flush, in place and from an allocator; input_too_long past the capacity; the diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 12cd763..04de828 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -638,39 +638,52 @@ void check_pipe_and_drain() { BOOST_TEST(verdict); } +/** Frames 0 to 4, whose bytes number 2, 3, 4, 2 and 3. */ +std::array five_frames() { + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** + Receives the item `adapter` holds into spans of `span_size` of `output` from `total` on, adding + what it receives to `total`; false when a call fails. +*/ +template +bool receive_item(Adapter& adapter, std::span output, std::size_t span_size, + std::size_t& total) { + for (;;) { + auto const received = adapter.receive(output.subspan(total, span_size)); + if (!received.has_value()) { + return false; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return true; + } + } +} + /** each and buffered in place allocate nothing (D21): each made, streamed into spans shorter than an item's output and into spans that take it whole, flushed, moved and reset; buffered made, sent in - chunks, flushed, received, moved and reset; and a pipe of packets into each. + chunks, flushed, received, moved and reset. */ void check_each_and_buffered() { - std::array frames{}; - for (std::size_t index = 0; index < frames.size(); ++index) { - frames[index] = test::make_frame(static_cast(index)); - } + std::array const frames = five_frames(); std::array frame_bytes{}; std::array images{}; bool volatile verdict = false; expect_no_allocation("each(frame_to_bytes_bounded, capacity<4>)", [&] { - auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>); + auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<4>); std::size_t total = 0; bool streamed = true; for (std::size_t index = 0; index < frames.size(); ++index) { - streamed = streamed && adapter.send(std::span{frames}.subspan(index)).has_value(); // Spans of 3, then 4: through the storage, then straight into the span. - std::size_t const span_size = index % 2 == 0 ? 3 : 4; - for (;;) { - auto const received = - adapter.receive(std::span{frame_bytes}.subspan(total, span_size)); - streamed = streamed && received.has_value(); - if (!received.has_value()) { - break; - } - total += received->count; - if (received->flow != codecs::flow::output_pending) { - break; - } - } + streamed = streamed && adapter.send(std::span{frames}.subspan(index)).has_value() && + receive_item(adapter, frame_bytes, index % 2 == 0 ? 3 : 4, total); } streamed = streamed && adapter.flush().has_value(); auto moved{std::move(adapter)}; @@ -690,6 +703,12 @@ void check_each_and_buffered() { verdict = streamed && images[4].index == 4; }); BOOST_TEST(verdict); +} + +/** A pipe of packets_to_frames into each(frame_to_image, capacity<1>) allocates nothing (D21). */ +void check_pipe_of_packets_into_each() { + std::array images{}; + bool volatile verdict = false; std::array const packets{ test::packet{.index = 0, .frames = 1}, test::packet{.index = 1, .frames = 2}, @@ -765,6 +784,7 @@ int main() { check_transformers(); check_pipe_and_drain(); check_each_and_buffered(); + check_pipe_of_packets_into_each(); check_saturating_refusals(); return boost::report_errors(); } diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp index a96f7e4..c1540c6 100644 --- a/test/allocator_test.cpp +++ b/test/allocator_test.cpp @@ -457,7 +457,7 @@ void each_and_buffered_over_an_arena() { test::recording_resource buffered_arena; std::pmr::polymorphic_allocator const buffered_allocator{&buffered_arena}; expect_no_global_allocation("buffered(frame_to_bytes_bounded) over an arena", [&] { - auto adapter = codecs::buffered(test::frame_to_bytes_bounded{}, buffered_allocator); + auto adapter = codecs::buffered(test::frame_to_bytes_bounded(), buffered_allocator); total = frames_through(adapter, frames, output); }); BOOST_TEST_EQ(total, 14U); diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp index 178f76c..fa9b5fc 100644 --- a/test/allocator_throw_test.cpp +++ b/test/allocator_throw_test.cpp @@ -500,7 +500,8 @@ bool receive_all(Adapter& adapter, std::vector& received) { std::array output{}; bool thrown = false; for (;;) { - codecs::result step_taken = codecs::step{}; + codecs::result step_taken = + codecs::step{.count = 0, .flow = codecs::flow::needs_input}; try { step_taken = adapter.receive(output); } catch (std::bad_alloc const&) { @@ -533,12 +534,13 @@ void buffered_throws_through() { test::throwing_allocator const allocator{fail_at}; bool thrown = false; { - codecs::buffered adapter{test::frame_to_bytes_bounded{}, allocator}; + codecs::buffered adapter{test::frame_to_bytes_bounded(), allocator}; auto const send_all = [&] { for (std::size_t first = 0; first < frames.size(); first += 3) { std::span const chunk = std::span{frames}.subspan(first, std::min(3, 20 - first)); - codecs::result sent = codecs::step{}; + codecs::result sent = + codecs::step{.count = 0, .flow = codecs::flow::needs_input}; try { sent = adapter.send(chunk); } catch (std::bad_alloc const&) { diff --git a/test/buffered_test.cpp b/test/buffered_test.cpp index 6eae3c9..8785683 100644 --- a/test/buffered_test.cpp +++ b/test/buffered_test.cpp @@ -94,8 +94,8 @@ struct counted_letters { } /** letters' encode, counted. */ - codecs::result transform(std::span input, - std::span output) const noexcept { + [[nodiscard]] codecs::result transform(std::span input, + std::span output) const noexcept { ++*calls; return codecs::codec::encode(test::letters, input, output); } @@ -332,7 +332,7 @@ void protocol_edges() { void transformer_error() { std::vector input = bytes_of(10); input[6] = 0xFF; - auto adapter = codecs::buffered(refusing_letters{}, codecs::capacity<16>); + auto adapter = codecs::buffered(refusing_letters(), codecs::capacity<16>); BOOST_TEST(is_step(adapter.send(input), 10, codecs::flow::needs_input)); BOOST_TEST(is_error(adapter.flush(), codecs::error::invalid_character)); std::array output{}; @@ -359,7 +359,8 @@ void heap_form() { BOOST_TEST_EQ(stream(adapter, input, 7, 64), expected); std::size_t const allocated = arena.allocation_count(); BOOST_TEST_GE(allocated, 2U); - for (std::size_t index = 0; index < std::min(allocated, arena.most_records); ++index) { + for (std::size_t index = 0; index < std::min(allocated, test::recording_resource::most_records); + ++index) { BOOST_TEST(arena.owns(arena.allocation(index).pointer)); } adapter.reset(); diff --git a/test/each_test.cpp b/test/each_test.cpp index 2e51fc2..ae4cd87 100644 --- a/test/each_test.cpp +++ b/test/each_test.cpp @@ -160,6 +160,31 @@ bool is_invalid_character(Result const& actual) { return !actual.has_value() && actual.error() == codecs::error::invalid_character; } +/** + Receives the item `adapter` holds into spans of `span_size`, appending its bytes to the last of + `items`, until it reports needs_input; false when a call fails, makes no progress or the bytes + have no room. completed_items() stays `completed_before` and the items before this one. +*/ +template +bool receive_item(Adapter& adapter, std::size_t span_size, std::size_t completed_before, + item_bytes& items) { + std::array buffer{}; + for (;;) { + BOOST_TEST_EQ(adapter.completed_items(), completed_before + items.count - 1); + auto const received = adapter.receive(std::span{buffer}.first(span_size)); + if (!BOOST_TEST(received.has_value()) || + !BOOST_TEST(items.append(std::span{buffer}.first(received->count)))) { + return false; + } + if (received->flow != codecs::flow::output_pending) { + return BOOST_TEST(received->flow == codecs::flow::needs_input); + } + if (!BOOST_TEST(received->count > 0)) { + return false; + } + } +} + /** Sends `frames` to `adapter` with every frame left in the span, as a caller does, and receives into spans of `span_size` until each item is delivered; returns the bytes of each receive, grouped by @@ -170,7 +195,6 @@ template item_bytes items_through(Adapter& adapter, std::span frames, std::size_t span_size) { item_bytes items; - std::array buffer{}; std::span rest = frames; std::size_t const completed_before = adapter.completed_items(); while (!rest.empty()) { @@ -181,20 +205,8 @@ item_bytes items_through(Adapter& adapter, std::span frames, // Output is pending: nothing more is accepted. BOOST_TEST(is_step(adapter.send(rest), 0, codecs::flow::output_pending)); rest = rest.subspan(1); - for (;;) { - BOOST_TEST_EQ(adapter.completed_items(), completed_before + items.count - 1); - auto const received = adapter.receive(std::span{buffer}.first(span_size)); - if (!BOOST_TEST(received.has_value()) || - !BOOST_TEST(items.append(std::span{buffer}.first(received->count)))) { - return items; - } - if (received->flow != codecs::flow::output_pending) { - BOOST_TEST(received->flow == codecs::flow::needs_input); - break; - } - if (!BOOST_TEST(received->count > 0)) { - return items; - } + if (!receive_item(adapter, span_size, completed_before, items)) { + return items; } BOOST_TEST_EQ(adapter.completed_items(), completed_before + items.count); } @@ -210,7 +222,7 @@ void types() { static_assert(codecs::stream_transformer); static_assert(std::is_same_v); static_assert(std::is_same_v); - using in_place = decltype(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<64>)); + using in_place = decltype(codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<64>)); static_assert( std::is_same_v>>); @@ -290,7 +302,7 @@ void per_item_bytes() { for (std::size_t const span_size : {std::size_t{3}, std::size_t{1}, std::size_t{4}, std::size_t{64}}) { expect_no_allocation("each(frame_to_bytes_bounded, capacity<64>)", [&] { - auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<64>); + auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<64>); BOOST_TEST(items_through(adapter, frames, span_size) == expected); BOOST_TEST_EQ(adapter.completed_items(), 5U); BOOST_TEST(is_flow(adapter.flush(), codecs::flow::finished)); @@ -302,7 +314,7 @@ void per_item_bytes() { BOOST_TEST_EQ(adapter.completed_items(), 0U); BOOST_TEST(items_through(adapter, frames, span_size) == expected); }); - auto exact = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>); + auto exact = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<4>); BOOST_TEST(items_through(exact, frames, span_size) == expected); } } @@ -314,7 +326,7 @@ void per_item_bytes() { */ void protocol_edges() { std::array const frames = five_frames(); - auto adapter = codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>); + auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<8>); std::array output{}; BOOST_TEST(is_step(adapter.receive(output), 0, codecs::flow::needs_input)); BOOST_TEST(is_step(adapter.send(std::span{}), 0, codecs::flow::needs_input)); @@ -365,9 +377,9 @@ void refuses_frame_three(Adapter& adapter, std::size_t span_size) { void item_errors() { for (std::size_t const span_size : {std::size_t{3}, std::size_t{64}}) { - auto in_place = codecs::each(refusing_frame_three{}, codecs::capacity<4>); + auto in_place = codecs::each(refusing_frame_three(), codecs::capacity<4>); refuses_frame_three(in_place, span_size); - auto heap = codecs::each(refusing_frame_three{}); + auto heap = codecs::each(refusing_frame_three()); refuses_frame_three(heap, span_size); } } @@ -390,7 +402,8 @@ void heap_form() { } std::size_t const allocated = arena.allocation_count(); BOOST_TEST_GE(allocated, 1U); - for (std::size_t index = 0; index < std::min(allocated, arena.most_records); ++index) { + for (std::size_t index = 0; index < std::min(allocated, test::recording_resource::most_records); + ++index) { BOOST_TEST(arena.owns(arena.allocation(index).pointer)); } adapter.reset(); @@ -440,12 +453,12 @@ void moved_mid_item(Adapter source, Adapter target) { } void moved_from() { - moved_mid_item(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>), - codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<8>)); + moved_mid_item(codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<8>), + codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<8>)); moved_mid_item(codecs::each(test::frame_to_bytes{}), codecs::each(test::frame_to_bytes{})); // An each that has reported an error: the moved-to one keeps it, the moved-from starts again. std::array const frames = five_frames(); - auto refusing = codecs::each(refusing_frame_three{}, codecs::capacity<4>); + auto refusing = codecs::each(refusing_frame_three(), codecs::capacity<4>); std::array output{}; BOOST_TEST( is_step(refusing.send(std::span{frames}.subspan(3)), 1, codecs::flow::output_pending)); diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 9975595..c2e6a80 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -329,7 +329,7 @@ static_assert(!noexcept(codecs::drain(std::declval(), nothrow // each and buffered (Task 10): in place, every member is noexcept when the transformer's transform // is; with an allocator, construction and the calls that allocate are not, and the others are. using bytes_in_place = codecs::each>; -static_assert(noexcept(codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<4>))); +static_assert(noexcept(codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<4>))); static_assert(std::is_nothrow_constructible_v); static_assert(std::is_nothrow_move_constructible_v); static_assert(std::is_nothrow_move_assignable_v); diff --git a/test/pipe_test.cpp b/test/pipe_test.cpp index 4789ac4..e3bc21b 100644 --- a/test/pipe_test.cpp +++ b/test/pipe_test.cpp @@ -513,24 +513,27 @@ void errors() { piped.reset(); BOOST_TEST(is_step(piped.send(std::string_view{"c"}), 1, codecs::flow::output_pending)); } - { - // The first part's error in a receive, met while the pipe refills the intermediate: the - // receive returns what the second part wrote from the first refill, and the next call the - // error. - auto piped = codecs::pipe(refusing{}, test::doubler{}, codecs::capacity<2>); - BOOST_TEST(is_step(piped.send(std::string_view{"ab!c"}), 4, codecs::flow::output_pending)); - output.fill('-'); - BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::output_pending)); - BOOST_TEST_EQ((std::string_view{output.data(), 5}), "aabb-"); - output.fill('-'); - BOOST_TEST(is_invalid_character(piped.receive(output))); - BOOST_TEST_EQ(output[0], '-'); - BOOST_TEST(is_invalid_character(piped.send(std::string_view{"c"}))); - BOOST_TEST(is_invalid_character(piped.flush())); - // Reset forgets it. - piped.reset(); - BOOST_TEST_EQ(stream(piped, "xyz", 2, 1), repeated("xyz", 2)); - } +} + +/** + The first part's error in a receive, met while the pipe refills the intermediate: the receive + returns what the second part wrote from the first refill, and the next call the error. +*/ +void first_part_error_while_refilling() { + std::array output{}; + auto piped = codecs::pipe(refusing{}, test::doubler{}, codecs::capacity<2>); + BOOST_TEST(is_step(piped.send(std::string_view{"ab!c"}), 4, codecs::flow::output_pending)); + output.fill('-'); + BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ((std::string_view{output.data(), 5}), "aabb-"); + output.fill('-'); + BOOST_TEST(is_invalid_character(piped.receive(output))); + BOOST_TEST_EQ(output[0], '-'); + BOOST_TEST(is_invalid_character(piped.send(std::string_view{"c"}))); + BOOST_TEST(is_invalid_character(piped.flush())); + // Reset forgets it. + piped.reset(); + BOOST_TEST_EQ(stream(piped, "xyz", 2, 1), repeated("xyz", 2)); } /** @@ -635,6 +638,7 @@ int main() { constant_time(); protocol(); errors(); + first_part_error_while_refilling(); moved_from(); partial_sends(); return boost::report_errors(); From 56a79fad1ab0dbe490d9b5accc7883341dc9ddc8 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 17:55:45 -0300 Subject: [PATCH 055/157] codecs: each and buffered fix round 1, construction noexcept for every storage, the heap output clamped to the allocator's most, a moved-from transformer's condition, limit tests, one echo with a fault for the tests --- .../webcpp/codecs/detail/core/adapters.hpp | 63 ++++++---- .../webcpp/codecs/detail/core/transformer.hpp | 5 +- test/buffered_test.cpp | 76 +++++++++++- test/each_test.cpp | 44 +++++++ test/noexcept_test.cpp | 60 ++++++++- test/pipe_test.cpp | 115 +----------------- test/support/failing.hpp | 76 ++++++++---- test/support/limits.hpp | 114 +++++++++++++++++ 8 files changed, 389 insertions(+), 164 deletions(-) create mode 100644 test/support/limits.hpp diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index 4bdde6f..d97ba6f 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -94,7 +94,8 @@ class in_place_output { public: /** An output for the capacity in place `capacity_t`. */ template - explicit in_place_output(capacity_t /*capacity*/) noexcept {} + explicit in_place_output(capacity_t /*capacity*/) noexcept( + std::is_nothrow_default_constructible_v) {} /** Transforms `input` into the output. @@ -131,7 +132,8 @@ class heap_output { public: /** An empty output that allocates from `allocator`. */ - explicit heap_output(Allocator const& allocator) : elements_(element_allocator(allocator)) {} + explicit heap_output(Allocator const& allocator) noexcept + : elements_(element_allocator(allocator)) {} /** Transforms `input` into the output, growing it as the class says. @@ -144,10 +146,11 @@ class heap_output { template [[nodiscard]] result transform(T& transformer, std::span input) { + std::size_t const largest = elements_.max_size(); std::size_t wanted = first_output_size(transformer, input); for (;;) { if (elements_.size() < wanted) { - if (wanted > elements_.max_size()) { + if (wanted > largest) { return error::input_too_long; } elements_.resize(wanted); @@ -157,11 +160,12 @@ class heap_output { return written; } std::size_t const held = elements_.size(); - wanted = held == 0 ? 1 : saturating_multiply(held, 2); - if (wanted == held) { - // Saturated: there is no larger output to try. + if (held >= largest) { + // The largest output the allocator holds was too small: there is none to try. return error::input_too_long; } + // Doubling, an output between half of the largest and the largest tried at the largest. + wanted = held == 0 ? 1 : std::min(saturating_multiply(held, 2), largest); } } @@ -183,7 +187,8 @@ template class in_place_input { public: /** An empty input for the capacity in place `capacity_t`. */ - explicit in_place_input(capacity_t /*capacity*/) noexcept {} + explicit in_place_input(capacity_t /*capacity*/) noexcept( + std::is_nothrow_default_constructible_v) {} /** Appends `input`, or records that the input is past the capacity and keeps nothing more. @@ -274,7 +279,8 @@ class heap_input { public: /** An empty input that allocates from `allocator`. */ - explicit heap_input(Allocator const& allocator) : elements_(element_allocator(allocator)) {} + explicit heap_input(Allocator const& allocator) noexcept + : elements_(element_allocator(allocator)) {} /** Appends `input`, or records that the input is past what the allocator can hold and keeps @@ -400,13 +406,16 @@ struct buffered_storage> { needs: to `T`'s exact `output_size(input)` when it states one, else to its static `max_output_size(1)`, else by doubling while `transform` reports `output_too_small`. A bound of the object's own (a non-static `max_output_size`, as a configured format's may be) is not read, - and such a `T` is sized by doubling. `reset` keeps that memory. Construction and `receive` may - then allocate and are not `noexcept`, and an allocator's exception propagates: a `receive` that - throws leaves the item pending, and the stream valid and resettable. + and such a `T` is sized by doubling, up to the most the allocator holds. `reset` keeps that + memory. Construction allocates nothing; `receive` may allocate and is not `noexcept`, and an + allocator's exception propagates: a `receive` that throws leaves the item pending, and the stream + valid and resettable. It is constant time when `T` is. A move takes the item, its output and the state, and leaves the moved-from `each` in the state `reset` leaves, so that it converts a new input from the start; - the item stays the caller's, and a move never carries a borrow away from it. + the item stays the caller's, and a move never carries a borrow away from it. The moved-from + stream still calls its `T`, which the move left as `T`'s own move leaves it, so it converts anew + only when a moved-from `T` still transforms (a requirement of @ref one_shot_transformer). @tparam T The one-shot transformer. @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. @@ -419,9 +428,10 @@ class each { /** One item's output. */ using output_storage = detail::each_storage::output; - /** Whether construction cannot throw. */ + /** Whether making the storage from `Storage` cannot throw: an allocator is only copied. */ static constexpr bool nothrow_construction = - in_place && std::is_nothrow_move_constructible_v; + std::is_nothrow_move_constructible_v && + std::is_nothrow_constructible_v; /** Whether `receive` cannot throw. */ static constexpr bool nothrow_receive = @@ -442,7 +452,8 @@ class each { @param transformer The one-shot transformer. */ - explicit each(T transformer) noexcept(nothrow_construction) + explicit each(T transformer) noexcept(nothrow_construction && + std::is_nothrow_default_constructible_v) : each(std::move(transformer), Storage{}) {} /** @@ -715,13 +726,16 @@ each(T, Allocator) -> each; is sized at `flush` by `T`'s exact `output_size(input)` when it states one, else by its static `max_output_size`, else by doubling while `transform` reports `output_too_small`. A bound of the object's own (a non-static `max_output_size`, as a configured format's may be) is not read, and - such a `T` is sized by doubling. `reset` keeps that memory. Construction, `send` and `flush` may - then allocate and are not `noexcept`, and an allocator's exception propagates: a `send` that throws - accepts nothing and leaves the stream as it was, and a `flush` that throws leaves it as it was - before the flush, valid and resettable. `receive` allocates nothing in either form. + such a `T` is sized by doubling, up to the most the allocator holds. `reset` keeps that memory. + Construction allocates nothing; `send` and `flush` may allocate and are not `noexcept`, and an + allocator's exception propagates: a `send` that throws accepts nothing and leaves the stream as it + was, and a `flush` that throws leaves it as it was before the flush, valid and resettable. + `receive` allocates nothing in either form. It is constant time when `T` is. A move takes the input, the output and the state, and leaves the - moved-from `buffered` in the state `reset` leaves, so that it converts a new input from the start. + moved-from `buffered` in the state `reset` leaves, so that it converts a new input from the start, + provided that a moved-from `T` still transforms (a requirement of @ref one_shot_transformer): it + keeps calling the `T` the move left it. @tparam T The one-shot transformer. @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. @@ -736,9 +750,11 @@ class buffered { /** The output of the whole input. */ using output_storage = detail::buffered_storage::output; - /** Whether construction cannot throw. */ + /** Whether making the storage from `Storage` cannot throw: an allocator is only copied. */ static constexpr bool nothrow_construction = - in_place && std::is_nothrow_move_constructible_v; + std::is_nothrow_move_constructible_v && + std::is_nothrow_constructible_v && + std::is_nothrow_constructible_v; /** Whether `send` cannot throw. */ static constexpr bool nothrow_send = @@ -765,7 +781,8 @@ class buffered { @param transformer The one-shot transformer. */ - explicit buffered(T transformer) noexcept(nothrow_construction) + explicit buffered(T transformer) noexcept(nothrow_construction && + std::is_nothrow_default_constructible_v) : buffered(std::move(transformer), Storage{}) {} /** diff --git a/include/webcpp/codecs/detail/core/transformer.hpp b/include/webcpp/codecs/detail/core/transformer.hpp index d8aad82..ab98c32 100644 --- a/include/webcpp/codecs/detail/core/transformer.hpp +++ b/include/webcpp/codecs/detail/core/transformer.hpp @@ -75,7 +75,10 @@ concept transformer_types = std::movable && requires { @ref error::output_too_small, with nothing written. `transform` takes the transformer by non-const reference, so that it may keep state between calls (a media encoder's context). A type may add overloads of its own; the concept requires the span form alone, and assumes no bytes, - characters, constant time or secrecy. + characters, constant time or secrecy. A moved-from `T` must still transform: `each` and `buffered` + move their transformer along with the rest of their state, and a moved-from one keeps calling the + `T` it was left holding, so a stateful move-only `T` has to leave its moved-from object able to + convert (the concept cannot check it). Optional members, read when present and never required: a static `max_output_size(std::size_t)`, a bound on the output of that many input elements, constexpr where it can be (a bound of the diff --git a/test/buffered_test.cpp b/test/buffered_test.cpp index 8785683..22f8e28 100644 --- a/test/buffered_test.cpp +++ b/test/buffered_test.cpp @@ -16,6 +16,7 @@ #include "support/arena.hpp" #include "support/letters.hpp" +#include "support/limits.hpp" #include "support/toy_media.hpp" #include @@ -66,7 +67,7 @@ struct letters_one_shot { configured format's may depend on its label or its part), or it states the exact size, or nothing, by `Sizing`. */ -enum class sizing : unsigned char { exact, object_bound, none }; +enum class sizing : unsigned char { exact, object_bound, static_bound, none }; /** letters' encode, sized as `Sizing` says, counting the calls of `transform` in `*calls`. */ template @@ -93,6 +94,13 @@ struct counted_letters { return codecs::codec::max_encoded_size(input_size); } + /** A static bound, the heap form's second choice, when `Sizing` is `static_bound`. */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept + requires(Sizing == sizing::static_bound) + { + return codecs::codec::max_encoded_size(input_size); + } + /** letters' encode, counted. */ [[nodiscard]] codecs::result transform(std::span input, std::span output) const noexcept { @@ -116,11 +124,13 @@ struct refusing_letters : letters_one_shot { static_assert(codecs::one_shot_transformer); static_assert(codecs::one_shot_transformer>); static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); static_assert(codecs::one_shot_transformer>); static_assert(codecs::one_shot_transformer); // The object's bound is not a static one: buffered's heap form sizes such a transformer by // doubling (review note (a) of Task 8). static_assert(!codecs::detail::has_max_output_size>); +static_assert(codecs::detail::has_max_output_size>); /** `count` bytes, each its index times 37 plus 1. */ std::vector bytes_of(std::size_t count) { @@ -388,6 +398,12 @@ void heap_growth() { BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); BOOST_TEST_EQ(calls, 1U); } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } { std::size_t calls = 0; auto adapter = codecs::buffered(counted_letters{.calls = &calls}); @@ -407,6 +423,63 @@ void heap_growth() { } } +/** Runs `body` and checks that it allocated nothing, through operator new or the C library. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const before = test::allocations(); + body(); + std::size_t const after = test::allocations(); + if (after != before) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(after - before, 0U); +} + +/** + The heap form's limits (Review Focus 2): an output wanted past what the allocator holds is + input_too_long at flush, with nothing allocated for it, and a doubling that reaches the most the + allocator holds tries that most before giving up. +*/ +void heap_limits() { + std::array const input{1, 2, 3, 4, 5}; + std::array output{}; + { + // A static bound saturated past 4 input elements: wanted exceeds max_size(). + auto adapter = codecs::buffered(test::saturated_bound<4>{}); + BOOST_TEST(is_step(adapter.send(input), 5, codecs::flow::needs_input)); + expect_no_allocation("a flush past max_size", [&] { + BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + }); + // Within the bound the same transformer converts. + adapter.reset(); + BOOST_TEST(is_step(adapter.send(std::span{input}.first(4)), 4, codecs::flow::needs_input)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(output), 4, codecs::flow::finished)); + } + // An allocator that holds 10 elements, a transformer with no bound that writes `Need` bytes: + // doubling goes 1, 2, 4, 8 and is then clamped to the 10 that fit. + using ten = test::limited_allocator; + { + auto adapter = codecs::buffered(test::needs_bytes<9>{}, ten{}); + BOOST_TEST(is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + std::array wide{}; + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(wide), 9, codecs::flow::finished)); + } + { + auto adapter = codecs::buffered(test::needs_bytes<10>{}, ten{}); + BOOST_TEST(is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + BOOST_TEST(is_flow(adapter.flush(), codecs::flow::output_pending)); + } + { + auto adapter = codecs::buffered(test::needs_bytes<11>{}, ten{}); + BOOST_TEST(is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + } +} + /** A moved-from buffered is in reset's state and converts from the start (Review Focus 5), moved by construction mid-input or by assignment mid-output; the moved-to one carries on. @@ -465,6 +538,7 @@ int main() { transformer_error(); heap_form(); heap_growth(); + heap_limits(); moved_from(); return boost::report_errors(); } diff --git a/test/each_test.cpp b/test/each_test.cpp index ae4cd87..cc2c736 100644 --- a/test/each_test.cpp +++ b/test/each_test.cpp @@ -15,6 +15,7 @@ #include "support/counting.hpp" #include "support/arena.hpp" +#include "support/limits.hpp" #include "support/toy_media.hpp" #include @@ -154,6 +155,12 @@ bool is_flow(codecs::result const& actual, codecs::flow expected_f return actual.has_value() && *actual == expected_flow; } +/** Whether `actual` is the error `expected`. */ +template +bool is_error(Result const& actual, codecs::error expected) { + return !actual.has_value() && actual.error() == expected; +} + /** Whether `actual` is the error `invalid_character`. */ template bool is_invalid_character(Result const& actual) { @@ -416,6 +423,42 @@ void heap_form() { BOOST_TEST(items_through(by_default, frames, 2) == expected); } +/** + The heap form's limits (Review Focus 2): an item whose output is wanted past what the allocator + holds is input_too_long at the receive, with nothing allocated for it, and a doubling that reaches + the most the allocator holds tries that most before giving up. +*/ +void heap_limits() { + std::array const item{7}; + std::array output{}; + { + // A static bound saturated for any item: wanted exceeds max_size(). + auto adapter = codecs::each(test::saturated_bound<0>{}); + BOOST_TEST(is_step(adapter.send(item), 1, codecs::flow::output_pending)); + expect_no_allocation("a receive past max_size", [&] { + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + }); + } + // An allocator that holds 10 elements, a transformer with no bound that writes `Need` bytes. + using ten = test::limited_allocator; + { + auto adapter = codecs::each(test::needs_bytes<9>{}, ten{}); + BOOST_TEST(is_step(adapter.send(item), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(output), 9, codecs::flow::needs_input)); + } + { + auto adapter = codecs::each(test::needs_bytes<10>{}, ten{}); + BOOST_TEST(is_step(adapter.send(item), 1, codecs::flow::output_pending)); + BOOST_TEST(is_step(adapter.receive(output), 10, codecs::flow::needs_input)); + } + { + auto adapter = codecs::each(test::needs_bytes<11>{}, ten{}); + BOOST_TEST(is_step(adapter.send(item), 1, codecs::flow::output_pending)); + BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); + } +} + /** A moved-from each is in reset's state and converts from the start (Review Focus 5), moved by construction or by assignment mid-item, its item's bytes partly delivered from the storage; the @@ -479,6 +522,7 @@ int main() { protocol_edges(); item_errors(); heap_form(); + heap_limits(); moved_from(); return boost::report_errors(); } diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index c2e6a80..af4443d 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -340,9 +341,19 @@ static_assert(noexcept(std::declval().reset())); static_assert(noexcept(std::declval().completed_items())); using bytes_on_heap = codecs::each; -static_assert(!noexcept(codecs::each(test::frame_to_bytes{}))); -static_assert(!std::is_nothrow_constructible_v); +// Construction only copies the allocator: it allocates nothing, so it is noexcept; a copy +// allocates. +static_assert(noexcept(codecs::each(test::frame_to_bytes{}))); +static_assert(std::is_nothrow_constructible_v); static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_nothrow_copy_constructible_v); +// A move assignment that may allocate (an allocator that does not propagate) is not noexcept. +using bytes_on_pmr = + codecs::each>; +static_assert(std::is_nothrow_constructible_v>); +static_assert(!std::is_nothrow_move_assignable_v); static_assert(noexcept(std::declval().send(std::span{}))); static_assert(!noexcept(std::declval().receive(std::span{}))); static_assert(noexcept(std::declval().flush())); @@ -361,9 +372,13 @@ static_assert(noexcept(std::declval().reset())); using images_on_heap = codecs::buffered>; -static_assert(!noexcept(codecs::buffered(test::frame_to_image{}))); -static_assert(!std::is_nothrow_constructible_v>); +static_assert(noexcept(codecs::buffered(test::frame_to_image{}))); +static_assert(std::is_nothrow_constructible_v>); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(!std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_move_assignable_v>); +static_assert(!std::is_nothrow_copy_constructible_v); static_assert(!noexcept(std::declval().send(std::span{}))); static_assert(noexcept(std::declval().receive(std::span{}))); static_assert(!noexcept(std::declval().flush())); @@ -399,4 +414,39 @@ static_assert(noexcept(std::declval().send(std::span().receive(std::span{}))); static_assert(!noexcept(std::declval().flush())); +/** An element whose default construction may throw. */ +struct careful_element { + /** May throw, as far as the type says. */ + careful_element() noexcept(false) {} +}; + +/** Copies elements one for one. */ +struct careful_copy { + /** The elements read. */ + using input_type = careful_element; + /** The elements written. */ + using output_type = careful_element; + + /** One element for one. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Writes nothing: only the types count here. */ + static codecs::result transform(std::span /*input*/, + std::span /*output*/) noexcept { + return std::size_t{0}; + } +}; + +// The storage in place value-initialises arrays of the elements, so that its construction is +// noexcept when their default construction is, and not otherwise; an allocator's is, whatever they +// are. +static_assert(!std::is_nothrow_constructible_v>, + careful_copy>); +static_assert(!std::is_nothrow_constructible_v< + codecs::buffered>, careful_copy>); +static_assert(std::is_nothrow_constructible_v, careful_copy>); +static_assert(std::is_nothrow_constructible_v, careful_copy>); + } // namespace diff --git a/test/pipe_test.cpp b/test/pipe_test.cpp index e3bc21b..f3aca50 100644 --- a/test/pipe_test.cpp +++ b/test/pipe_test.cpp @@ -134,119 +134,10 @@ using byte_echo = echo::max()>; /** Every character it is sent, taking two a send. */ using two_at_a_time = echo; -/** - Echoes the characters it is sent and refuses `!`: a `receive` whose next character is `!` reports - `invalid_character` and writes nothing, a fault met in the middle of the stream, as a decoder of - other data may meet one in a packet; every call returns it until `reset`. -*/ -class refusing { -public: - /** The characters read. */ - using input_type = char; - /** The characters written. */ - using output_type = char; - - /** A refusing transformer in `needs_input`. */ - refusing() noexcept = default; - /** Copies are not needed. */ - refusing(refusing const&) = delete; - /** Copies are not needed. */ - refusing& operator=(refusing const&) = delete; - - /** Takes `other`'s state and leaves `other` as `reset` does. */ - refusing(refusing&& other) noexcept - : borrowed_(other.borrowed_), - position_(other.position_), - flushed_(other.flushed_), - failed_(other.failed_) { - other.reset(); - } - - /** Takes `other`'s state and leaves `other` as `reset` does. */ - refusing& operator=(refusing&& other) noexcept { - if (this != &other) { - borrowed_ = other.borrowed_; - position_ = other.position_; - flushed_ = other.flushed_; - failed_ = other.failed_; - other.reset(); - } - return *this; - } - - ~refusing() = default; - - /** Borrows all of `input` in `needs_input`. */ - codecs::result send(std::span input) noexcept { - if (failed_) { - return codecs::error::invalid_character; - } - if (state() != codecs::flow::needs_input) { - return codecs::step{.count = 0, .flow = state()}; - } - borrowed_ = input; - position_ = 0; - return codecs::step{.count = input.size(), .flow = state()}; - } - - /** Writes the borrowed characters up to a `!`, or refuses the `!` that comes next. */ - codecs::result receive(std::span output) noexcept { - if (failed_ || (position_ < borrowed_.size() && borrowed_[position_] == '!')) { - failed_ = true; - return codecs::error::invalid_character; - } - std::size_t written = 0; - while (position_ < borrowed_.size() && written < output.size() && - borrowed_[position_] != '!') { - output[written++] = borrowed_[position_++]; - } - if (position_ == borrowed_.size()) { - borrowed_ = {}; - position_ = 0; - } - return codecs::step{.count = written, .flow = state()}; - } - - /** Ends the input. */ - codecs::result flush() noexcept { - if (failed_) { - return codecs::error::invalid_character; - } - flushed_ = true; - return state(); - } - - /** Back to `needs_input`, the error forgotten. */ - void reset() noexcept { - borrowed_ = {}; - position_ = 0; - flushed_ = false; - failed_ = false; - } - -private: - /** The state the next call sees. */ - [[nodiscard]] codecs::flow state() const noexcept { - if (position_ < borrowed_.size()) { - return codecs::flow::output_pending; - } - return flushed_ ? codecs::flow::finished : codecs::flow::needs_input; - } - - /** The input `send` accepted. */ - std::span borrowed_; - /** The next borrowed character to read. */ - std::size_t position_ = 0; - /** Whether `flush` ended the input. */ - bool flushed_ = false; - /** Whether a `!` was refused. */ - bool failed_ = false; -}; - static_assert(codecs::stream_transformer); static_assert(codecs::stream_transformer); static_assert(codecs::stream_transformer); -static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); /** Every character of `text` written `times` times. */ std::string repeated(std::string_view text, std::size_t times) { @@ -521,7 +412,7 @@ void errors() { */ void first_part_error_while_refilling() { std::array output{}; - auto piped = codecs::pipe(refusing{}, test::doubler{}, codecs::capacity<2>); + auto piped = codecs::pipe(test::refusing{}, test::doubler{}, codecs::capacity<2>); BOOST_TEST(is_step(piped.send(std::string_view{"ab!c"}), 4, codecs::flow::output_pending)); output.fill('-'); BOOST_TEST(is_step(piped.receive(output), 4, codecs::flow::output_pending)); @@ -600,7 +491,7 @@ void moved_from() { // A pipe that has reported an error while its second part borrows the intermediate may // be moved: it never calls that part again before reset. The moved-to pipe keeps the // error; the moved-from one starts again. - auto piped = codecs::pipe(test::doubler{}, refusing{}); + auto piped = codecs::pipe(test::doubler{}, test::refusing{}); std::array output{}; BOOST_TEST(is_step(piped.send(std::string_view{"a!"}), 2, codecs::flow::output_pending)); BOOST_TEST( diff --git a/test/support/failing.hpp b/test/support/failing.hpp index a62e3cf..a612d8e 100644 --- a/test/support/failing.hpp +++ b/test/support/failing.hpp @@ -4,10 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// failing, a stream transformer of the tests' own whose data is always at fault: `char` to `char`, -// it echoes what it is sent and reports `invalid_character` at `flush`, the first call that has -// processed the whole input, as the stream protocol (D18) places a data fault; every call returns -// it until `reset`. It is not constant time and is not secret. A moved-from failing is in the +// failing and refusing, stream transformers of the tests' own whose data is at fault: `char` to +// `char`, they echo what they are sent and report `invalid_character`, the one where the stream +// protocol (D18) places a data fault found at the end, at `flush` (failing), the other a fault met +// in the middle of the stream, in the `receive` whose next character is `!` (refusing); every call +// returns it until `reset`. They are not constant time and not secret. A moved-from one is in the // state `reset` leaves (Review Focus 5). #ifndef WEBCPP_CODECS_TEST_SUPPORT_FAILING_HPP @@ -20,39 +21,52 @@ namespace webcpp::codecs::test { -/** Echoes the characters it is sent, and reports `invalid_character` at `flush`. */ -class failing { +/** Where an echoing transformer finds its data at fault. */ +enum class fault_at : unsigned char { + /** `flush` reports the error, the first call that has processed the whole input. */ + flush, + /** The `receive` whose next character is `!` reports it, writing nothing. */ + bang +}; + +/** Echoes the characters it is sent, and reports `invalid_character` where `Where` says. */ +template +class echo_fault { public: /** The characters read. */ using input_type = char; /** The characters written. */ using output_type = char; - /** A failing transformer in `needs_input`. */ - failing() noexcept = default; + /** An echoing transformer in `needs_input`. */ + echo_fault() noexcept = default; /** Copies are not needed. */ - failing(failing const&) = delete; + echo_fault(echo_fault const&) = delete; /** Copies are not needed. */ - failing& operator=(failing const&) = delete; + echo_fault& operator=(echo_fault const&) = delete; /** Takes `other`'s state and leaves `other` as `reset` does. */ - failing(failing&& other) noexcept - : borrowed_(other.borrowed_), position_(other.position_), failed_(other.failed_) { + echo_fault(echo_fault&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + flushed_(other.flushed_), + failed_(other.failed_) { other.reset(); } /** Takes `other`'s state and leaves `other` as `reset` does. */ - failing& operator=(failing&& other) noexcept { + echo_fault& operator=(echo_fault&& other) noexcept { if (this != &other) { borrowed_ = other.borrowed_; position_ = other.position_; + flushed_ = other.flushed_; failed_ = other.failed_; other.reset(); } return *this; } - ~failing() = default; + ~echo_fault() = default; /** Borrows all of `input` in `needs_input`. */ result send(std::span input) noexcept { @@ -67,13 +81,16 @@ class failing { return step{.count = input.size(), .flow = state()}; } - /** Writes the borrowed characters. */ + /** Writes the borrowed characters, up to a `!` for `fault_at::bang`, which it refuses. */ result receive(std::span output) noexcept { - if (failed_) { + if (failed_ || (Where == fault_at::bang && position_ < borrowed_.size() && + borrowed_[position_] == '!')) { + failed_ = true; return error::invalid_character; } std::size_t written = 0; - while (position_ < borrowed_.size() && written < output.size()) { + while (position_ < borrowed_.size() && written < output.size() && + !(Where == fault_at::bang && borrowed_[position_] == '!')) { output[written++] = borrowed_[position_++]; } if (position_ == borrowed_.size()) { @@ -83,33 +100,48 @@ class failing { return step{.count = written, .flow = state()}; } - /** Reports the error, and every call returns it until `reset`. */ + /** Ends the input; reports the error for `fault_at::flush`, which every call then returns. */ result flush() noexcept { - failed_ = true; - return error::invalid_character; + if (failed_ || Where == fault_at::flush) { + failed_ = true; + return error::invalid_character; + } + flushed_ = true; + return state(); } /** Back to `needs_input`, the error forgotten. */ void reset() noexcept { borrowed_ = {}; position_ = 0; + flushed_ = false; failed_ = false; } private: /** The state the next call sees. */ [[nodiscard]] flow state() const noexcept { - return position_ < borrowed_.size() ? flow::output_pending : flow::needs_input; + if (position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; } /** The input `send` accepted. */ std::span borrowed_; /** The next borrowed character to read. */ std::size_t position_ = 0; - /** Whether `flush` reported the error. */ + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the error was reported. */ bool failed_ = false; }; +/** Reports `invalid_character` at `flush`. */ +using failing = echo_fault; +/** Refuses a `!` in `receive`. */ +using refusing = echo_fault; + } // namespace webcpp::codecs::test #endif // WEBCPP_CODECS_TEST_SUPPORT_FAILING_HPP diff --git a/test/support/limits.hpp b/test/support/limits.hpp new file mode 100644 index 0000000..a2cdeb6 --- /dev/null +++ b/test/support/limits.hpp @@ -0,0 +1,114 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Toys for the limits of the heap forms of each and buffered (D19): a transformer whose static +// bound is past what any allocator holds, a transformer with no bound that needs a stated number +// of bytes, and an allocator that holds at most a few elements. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_LIMITS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_LIMITS_HPP + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** + Copies bytes; its static bound is the input's size up to `Past` elements and `SIZE_MAX` for an + input past them, as a bound saturated by a huge input is. +*/ +template +struct saturated_bound { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** The input's size, or `SIZE_MAX` past `Past`. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size > Past ? std::numeric_limits::max() : input_size; + } + + /** Copies the bytes, or reports `output_too_small`. */ + static result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size()) { + return error::output_too_small; + } + std::ranges::copy(input, output.begin()); + return input.size(); + } +}; + +/** + Writes `Need` bytes for any input and states no size, so that a heap form finds it by doubling; + it reports `output_too_small` for a shorter output. +*/ +template +struct needs_bytes { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** Writes `Need` zero bytes, or reports `output_too_small`. */ + static result transform(std::span /*input*/, + std::span output) noexcept { + if (output.size() < Need) { + return error::output_too_small; + } + std::ranges::fill(output.first(Need), std::uint8_t{0}); + return Need; + } +}; + +/** An allocator of `std::allocator`'s memory that holds at most `Max` elements, in any rebind. */ +template +struct limited_allocator { + /** The element. */ + using value_type = T; + + /** A default allocator. */ + limited_allocator() noexcept = default; + + /** The allocator of other elements, which `std::allocator_traits` cannot deduce. */ + template + struct rebind { + /** The allocator of `U`. */ + using other = limited_allocator; + }; + + /** A rebind of `other`. */ + template + explicit limited_allocator(limited_allocator const& /*other*/) noexcept {} + + /** The most elements: `Max`. */ + [[nodiscard]] static std::size_t max_size() noexcept { return Max; } + + /** Memory for `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + /** Gives back memory for `count` elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** All are equal. */ + template + [[nodiscard]] bool operator==(limited_allocator const& /*other*/) const noexcept { + return true; + } +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_LIMITS_HPP From cf63ce3b0a1d17007481216378517912087dee40 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 17:59:16 -0300 Subject: [PATCH 056/157] codecs: each and buffered fix round 1 lint fix --- test/noexcept_test.cpp | 2 +- test/support/failing.hpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index af4443d..374a0f1 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -417,7 +417,7 @@ static_assert(!noexcept(std::declval().flush())); /** An element whose default construction may throw. */ struct careful_element { /** May throw, as far as the type says. */ - careful_element() noexcept(false) {} + careful_element() noexcept(false) = default; }; /** Copies elements one for one. */ diff --git a/test/support/failing.hpp b/test/support/failing.hpp index a612d8e..0b8830f 100644 --- a/test/support/failing.hpp +++ b/test/support/failing.hpp @@ -26,7 +26,7 @@ enum class fault_at : unsigned char { /** `flush` reports the error, the first call that has processed the whole input. */ flush, /** The `receive` whose next character is `!` reports it, writing nothing. */ - bang + bang, }; /** Echoes the characters it is sent, and reports `invalid_character` where `Where` says. */ @@ -90,7 +90,7 @@ class echo_fault { } std::size_t written = 0; while (position_ < borrowed_.size() && written < output.size() && - !(Where == fault_at::bang && borrowed_[position_] == '!')) { + (Where != fault_at::bang || borrowed_[position_] != '!')) { output[written++] = borrowed_[position_++]; } if (position_ == borrowed_.size()) { From 9c9d247546675780dac1ad87bd07c54e236c8ad0 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 17:59:38 -0300 Subject: [PATCH 057/157] codecs: each and buffered fix round 1 doc fix --- include/webcpp/codecs/detail/core/adapters.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index d97ba6f..652f8fd 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -734,8 +734,8 @@ each(T, Allocator) -> each; It is constant time when `T` is. A move takes the input, the output and the state, and leaves the moved-from `buffered` in the state `reset` leaves, so that it converts a new input from the start, - provided that a moved-from `T` still transforms (a requirement of @ref one_shot_transformer): it - keeps calling the `T` the move left it. + provided that a moved-from `T` still transforms (a requirement of @ref one_shot_transformer), since + it keeps calling the `T` the move left it. @tparam T The one-shot transformer. @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. From 271c4a78b0adfa7b5bece4975a9f151ff65b7604 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 18:34:47 -0300 Subject: [PATCH 058/157] codecs: the noexcept test's element of a throwing default constructor made non-trivial, which gcc otherwise reads as never called and so as noexcept --- test/noexcept_test.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 374a0f1..7653996 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -414,8 +414,15 @@ static_assert(noexcept(std::declval().send(std::span().receive(std::span{}))); static_assert(!noexcept(std::declval().flush())); -/** An element whose default construction may throw. */ +/** + An element whose default construction may throw. Its member's initializer makes the constructor + non-trivial, so that value-initialization calls it: gcc reads the value-initialization of a + trivial constructor declared `noexcept(false)` as calling none, and so as `noexcept`. +*/ struct careful_element { + /** A value, whose initializer makes the default constructor non-trivial. */ + int value = 0; + /** May throw, as far as the type says. */ careful_element() noexcept(false) = default; }; From 1581e173786e20ea72f710eedb39e02479cfef7d Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 18:34:47 -0300 Subject: [PATCH 059/157] codecs: encoder and decoder, a format's one-shot transformer always and its stream through stream_codec, with the protocol's error rules --- include/webcpp/codecs.hpp | 1 + .../codecs/detail/core/format_transformer.hpp | 861 ++++++++++++++++++ include/webcpp/codecs/detail/core/sizes.hpp | 42 +- test/Jamfile | 5 + test/allocation_test.cpp | 59 ++ test/format_transformer_test.cpp | 674 ++++++++++++++ test/messages/Jamfile | 4 + test/messages/capacity_without_hold/Jamfile | 16 + .../capacity_without_hold.cpp | 25 + test/messages/drain_of_one_shot/Jamfile | 16 + .../drain_of_one_shot/drain_of_one_shot.cpp | 30 + test/messages/encoder_of_value_format/Jamfile | 16 + .../encoder_of_value_format.cpp | 26 + test/messages/encoder_of_value_over/Jamfile | 16 + .../encoder_of_value_over.cpp | 28 + test/noexcept_test.cpp | 46 + test/support/chunkings.hpp | 192 ++++ test/support/letters.hpp | 457 +++++++++- 18 files changed, 2493 insertions(+), 21 deletions(-) create mode 100644 include/webcpp/codecs/detail/core/format_transformer.hpp create mode 100644 test/format_transformer_test.cpp create mode 100644 test/messages/capacity_without_hold/Jamfile create mode 100644 test/messages/capacity_without_hold/capacity_without_hold.cpp create mode 100644 test/messages/drain_of_one_shot/Jamfile create mode 100644 test/messages/drain_of_one_shot/drain_of_one_shot.cpp create mode 100644 test/messages/encoder_of_value_format/Jamfile create mode 100644 test/messages/encoder_of_value_format/encoder_of_value_format.cpp create mode 100644 test/messages/encoder_of_value_over/Jamfile create mode 100644 test/messages/encoder_of_value_over/encoder_of_value_over.cpp create mode 100644 test/support/chunkings.hpp diff --git a/include/webcpp/codecs.hpp b/include/webcpp/codecs.hpp index 3a52708..2a067c1 100644 --- a/include/webcpp/codecs.hpp +++ b/include/webcpp/codecs.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp new file mode 100644 index 0000000..8dbf9e3 --- /dev/null +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -0,0 +1,861 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The formats as transformers (D20): `encoder(format)` and `decoder(format)`, a format's one-shot + transformer always and its stream transformer where the format's header specializes + `stream_codec`; the options of a stream; and the stream of `over`, a pipe of its links' streams. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_FORMAT_TRANSFORMER_HPP +#define WEBCPP_CODECS_DETAIL_CORE_FORMAT_TRANSFORMER_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The options of a format's stream transformer, a structural type that `stream_codec`'s `encoder` + and `decoder` templates take (B37). + + `encoder(format, codecs::secret_operation)` and `decoder(format, codecs::secret_operation)` set + `secret`; `decoder(format, codecs::capacity)` sets `capacity`, the hold of a decoder that holds + its input (bech32's, in characters, B47). +*/ +struct stream_options { + /** Whether the stream is secret: its state wiped, its calls under secure's timing guard. */ + bool secret = false; + /** The hold of a decoder that holds its input; 0 for the decoder's default. */ + std::size_t capacity = 0; +}; + +/** + The stream conversion of a format between bytes and text: declared by the core, never defined, + and specialized by a format's header when the format streams natively, as `codec` is (D20). + + A specialization has two class templates over the stream's options: + + @code + template <> struct stream_codec { + template class encoder; // std::uint8_t to char + template class decoder; // char to std::uint8_t + }; + @endcode + + Each is a `stream_transformer` constructed from the format's value (`formats::hex_t const&`), + with `input_type` and `output_type` as written above and every call `noexcept`. It keeps the + format's minimal pending state and nothing else, and reads the caller's input and writes the + caller's output as the protocol says (D18). The error rules every stream codec keeps (D18, B23, + B44): a fault of the format's configuration is checked before any data and reported by the first + call, whatever it is; a fault of the data is reported once, after `flush`, by the first call that + has processed the whole input (`flush` itself when nothing is still borrowed, otherwise the + `receive` that reaches the end), and it is the error the one-shot form reports for the same whole + input; that call writes nothing, the verdict running over everything still borrowed before the + tail is written; after an error every call returns it until `reset`. A moved-from encoder or + decoder is in the state `reset` leaves. + + A decoder that holds its input until its verdict (bech32's) declares + `static constexpr bool holds = true` and holds `Options.capacity` elements, or its default when it + is 0; `decoder(format, codecs::capacity)` of any other format stops the build. A decoder that + gives a part of its input after a successful `flush` has `human_readable_part()` or `label()`, + which `format_decoder` forwards (B39). + + @tparam Format The format's type. +*/ +template +struct stream_codec; + +namespace detail { + +/** Whether `stream_codec` is specialized: the format streams natively. */ +template +concept has_stream_codec = requires { sizeof(stream_codec); }; + +/** + The stream state of a format that does not stream natively: nothing, made from the format's + value as a stream codec's state is. +*/ +struct no_stream { + /** Nothing to make from `format_value`. */ + template + explicit constexpr no_stream(Format const& /*format_value*/) noexcept {} +}; + +/** The stream encoder of `F` with `Options`, or @ref no_stream when `F` has no stream codec. */ +template +struct stream_encoder_of { + /** No stream. */ + using type = no_stream; +}; + +/** The stream encoder of a format that streams natively. */ +template + requires has_stream_codec +struct stream_encoder_of { + /** The format's stream encoder. */ + using type = stream_codec::template encoder; +}; + +/** The stream decoder of `F` with `Options`, or @ref no_stream when `F` has no stream codec. */ +template +struct stream_decoder_of { + /** No stream. */ + using type = no_stream; +}; + +/** The stream decoder of a format that streams natively. */ +template + requires has_stream_codec +struct stream_decoder_of { + /** The format's stream decoder. */ + using type = stream_codec::template decoder; +}; + +/** Whether `Stream`, a stream codec's encoder or decoder, reads `Input` and writes `Output`. */ +template +concept stream_of = + stream_transformer && std::same_as && + std::same_as; + +/** Whether a stream decoder holds its input until its verdict, as bech32's does (B47). */ +template +concept holding_decoder = requires { requires static_cast(Decoder::holds); }; + +/** Whether a stream decoder gives the human-readable part it read, after `flush` (B39). */ +template +concept gives_human_readable_part = + requires(Decoder const& stream_decoder) { stream_decoder.human_readable_part(); }; + +/** Whether a stream decoder gives the label it read, after `flush` (B39). */ +template +concept gives_label = requires(Decoder const& stream_decoder) { stream_decoder.label(); }; + +/** Whether `human_readable_part()` of a stream decoder cannot throw. */ +template +concept nothrow_human_readable_part = requires(Decoder const& stream_decoder) { + { stream_decoder.human_readable_part() } noexcept; +}; + +/** Whether `label()` of a stream decoder cannot throw. */ +template +concept nothrow_label = requires(Decoder const& stream_decoder) { + { stream_decoder.label() } noexcept; +}; + +/** + Stops the build: `F` has no `codec`, so it is a value codec's format, whose typed values are + converted whole and never streamed (D20). +*/ +template +constexpr void refuse_value_format() noexcept { + static_assert(has_codec, + "webcpp::codecs: a value codec's format has no transformer; typed values are " + "converted whole by codecs::encode and codecs::decode"); +} + +/** + Stops the build: `codecs::capacity` was given to the decoder of a format whose stream decoder + holds nothing (`Decoder`, or @ref no_stream for a format that does not stream natively). +*/ +template +constexpr void refuse_hold() noexcept { + static_assert(holding_decoder, + "webcpp::codecs: codecs::capacity sets the hold of a decoder that holds its " + "input, as bech32's; this format's decoder holds nothing"); +} + +} // namespace detail + +/** + The transformer of a format's encoding, bytes to text (D20): a one-shot transformer always, and a + stream transformer when the format's header specializes @ref stream_codec. + + It is made by `codecs::encoder(format)`. + + `transform(input, output)` is the buffer form of `codecs::encode`: an input whose encoding does + not fit in `std::size_t` is @ref error::input_too_long and an output shorter than the exact size + @ref error::output_too_small, both with nothing written, and then `codec::encode` writes + the text at the start of `output`. `max_output_size` is `codec::max_encoded_size` and + `output_size(input)` its `encoded_size`, which `buffered` and `each` read. With `Options.secret` + the format's secret arithmetic runs where it has one (ruling R7), so that + `codecs::buffered(codecs::encoder(format, codecs::secret_operation))` runs it at `flush`. + + The stream members, `send`, `receive`, `flush` and `reset`, exist when `stream_codec` is + specialized and forward to its `encoder`, which keeps the protocol (D18) and its error + rules. A move copies the format and moves the stream state, whose own move leaves the moved-from + state as `reset` does, so that the moved-from encoder converts a new input from the start (Review + Focus 5). It is copyable when the stream state is. + + It is constant time when `codec` is, and `noexcept` in every call but the ones that + allocate (`over`'s encode with a heap intermediate, owner decision 24). + + @tparam Format The format's type, which has a `codec`. + @tparam Options The stream's options. +*/ +template +class format_encoder { + static_assert(detail::has_codec, + "webcpp::codecs: a value codec's format has no transformer; typed values are " + "converted whole by codecs::encode and codecs::decode"); + + /** The format's stream encoder, or nothing. */ + using stream_type = detail::stream_encoder_of::type; + + /** Whether the format streams natively. */ + static constexpr bool streams = detail::has_stream_codec; + + static_assert(!streams || detail::stream_of, + "webcpp::codecs: stream_codec::encoder is a stream_transformer " + "of std::uint8_t to char"); + + /** Whether the calls of the stream encoder cannot throw. */ + static constexpr bool nothrow_stream = detail::nothrow_stream_calls; + + /** Whether a move cannot throw: the format's copy and the stream state's move. */ + static constexpr bool nothrow_move = std::is_nothrow_copy_constructible_v && + std::is_nothrow_move_constructible_v; + + /** Whether a move assignment cannot throw. */ + static constexpr bool nothrow_move_assignment = + std::is_nothrow_copy_assignable_v && std::is_nothrow_move_assignable_v; + +public: + /** The bytes the encoder reads. */ + using input_type = std::uint8_t; + /** The characters the encoder writes. */ + using output_type = char; + + /** The encoder runs in a time that does not depend on its data when the format's codec does. */ + static constexpr bool constant_time = codec::constant_time; + + /** + Makes the encoder of `format_value`, in `flow::needs_input`. + + @param format_value The format, copied. + */ + explicit format_encoder(Format const& format_value) noexcept( + std::is_nothrow_copy_constructible_v && + std::is_nothrow_constructible_v) + : format_(format_value), stream_(format_) {} + + /** + Copies `other`'s format and stream state, when the stream state is copyable. + + @param other The encoder copied. + */ + format_encoder(format_encoder const& other) = default; + + /** + Copies `other`'s format and stream state, when the stream state is copyable. + + @param other The encoder copied. + @return This encoder. + */ + format_encoder& operator=(format_encoder const& other) = default; + + /** + Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. + + @param other The encoder moved from, which keeps its format. + */ + // The format is copied, so that the moved-from encoder still converts (Review Focus 5). + // NOLINTNEXTLINE(performance-move-constructor-init) + format_encoder(format_encoder&& other) noexcept(nothrow_move) + : format_(other.format_), stream_(std::move(other.stream_)) {} + + /** + Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. + + @param other The encoder moved from, which keeps its format. + @return This encoder. + */ + format_encoder& operator=(format_encoder&& other) noexcept(nothrow_move_assignment) { + if (this != &other) { + format_ = other.format_; + stream_ = std::move(other.stream_); + } + return *this; + } + + /** Destroys the encoder. */ + ~format_encoder() = default; + + /** + A bound on the characters of `input_size` bytes: `codec::max_encoded_size`. + + @param input_size The bytes of an input. + @return The bound, `SIZE_MAX` when it does not fit. + */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return codec::max_encoded_size(input_size); + } + + /** + The exact size of the text `transform` writes for `input`: `codec::encoded_size`, or 0 + for an input whose encoding does not fit, which `transform` refuses. + + @param input The bytes. + @return The characters. + */ + [[nodiscard]] std::size_t output_size(std::span input) const + noexcept(detail::codec_encoded_size_is_noexcept>()) { + if (detail::input_size_fault(format_, input.size())) { + return 0; + } + return detail::codec_encoded_size(format_, input); + } + + /** + Writes the text of `input` at the start of `output`, or nothing and the error. + + @param input The bytes. + @param output The buffer the text is written to. + @return The characters written, or the error. + */ + [[nodiscard]] result transform(std::span input, + std::span output) const + noexcept(detail::encode_calls_are_noexcept, + Options.secret>()) { + return detail::encode_into_buffer(format_, input, output); + } + + /** + Gives `input` to the stream encoder, which borrows it as the protocol says. + + @param input The bytes to encode. + @return The bytes accepted and the state after, or the error. + */ + [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) + requires streams + { + return stream_.send(input); + } + + /** + Writes the stream's text into `output`. + + @param output The span to write into. + @return The characters written and the state after, or the error. + */ + [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) + requires streams + { + return stream_.receive(output); + } + + /** + Ends the stream's input. + + @return `flow::output_pending` while text remains, `flow::finished` when none does, or the + error. + */ + [[nodiscard]] result flush() noexcept(nothrow_stream) + requires streams + { + return stream_.flush(); + } + + /** Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error. */ + void reset() noexcept + requires streams + { + stream_.reset(); + } + +private: + /** The format. */ + Format format_; + /** The stream encoder's state, made from the format. */ + stream_type stream_; +}; + +/** + The transformer of a format's decoding, text to bytes (D20): a one-shot transformer always, and a + stream transformer when the format's header specializes @ref stream_codec. + + It is made by `codecs::decoder(format)`. + + `transform(input, output)` is the buffer form of `codecs::decode`: a text whose bytes do not fit + in `std::size_t` is @ref error::input_too_long, then the whole text is checked and its data error + with the lowest value returned, then an output shorter than the exact size is + @ref error::output_too_small, all with nothing written, and then `codec::decode` writes + the bytes at the start of `output`. `max_output_size` is `codec::max_decoded_size` and + `output_size(input)` its `decoded_size`, 0 for a text it refuses. With `Options.secret` the + format's secret arithmetic runs where it has one (ruling R7). + + The stream members, `send`, `receive`, `flush` and `reset`, exist when `stream_codec` is + specialized and forward to its `decoder`, which keeps the protocol (D18) and its error + rules; `human_readable_part()` and `label()` exist when that decoder has them (B39). A move + copies the format and moves the stream state, so that the moved-from decoder converts a new input + from the start (Review Focus 5). It is copyable when the stream state is. + + It is constant time when `codec` is, and `noexcept` in every call but the ones that + allocate (`over`'s decode with a heap intermediate, owner decision 24). + + @tparam Format The format's type, which has a `codec`. + @tparam Options The stream's options. +*/ +template +class format_decoder { + static_assert(detail::has_codec, + "webcpp::codecs: a value codec's format has no transformer; typed values are " + "converted whole by codecs::encode and codecs::decode"); + + /** The format's stream decoder, or nothing. */ + using stream_type = detail::stream_decoder_of::type; + + /** Whether the format streams natively. */ + static constexpr bool streams = detail::has_stream_codec; + + static_assert(!streams || detail::stream_of, + "webcpp::codecs: stream_codec::decoder is a stream_transformer " + "of char to std::uint8_t"); + + /** Whether the calls of the stream decoder cannot throw. */ + static constexpr bool nothrow_stream = detail::nothrow_stream_calls; + + /** Whether a move cannot throw: the format's copy and the stream state's move. */ + static constexpr bool nothrow_move = std::is_nothrow_copy_constructible_v && + std::is_nothrow_move_constructible_v; + + /** Whether a move assignment cannot throw. */ + static constexpr bool nothrow_move_assignment = + std::is_nothrow_copy_assignable_v && std::is_nothrow_move_assignable_v; + +public: + /** The characters the decoder reads. */ + using input_type = char; + /** The bytes the decoder writes. */ + using output_type = std::uint8_t; + + /** The decoder runs in a time that does not depend on its data when the format's codec does. */ + static constexpr bool constant_time = codec::constant_time; + + /** + Makes the decoder of `format_value`, in `flow::needs_input`. + + @param format_value The format, copied. + */ + explicit format_decoder(Format const& format_value) noexcept( + std::is_nothrow_copy_constructible_v && + std::is_nothrow_constructible_v) + : format_(format_value), stream_(format_) {} + + /** + Copies `other`'s format and stream state, when the stream state is copyable. + + @param other The decoder copied. + */ + format_decoder(format_decoder const& other) = default; + + /** + Copies `other`'s format and stream state, when the stream state is copyable. + + @param other The decoder copied. + @return This decoder. + */ + format_decoder& operator=(format_decoder const& other) = default; + + /** + Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. + + @param other The decoder moved from, which keeps its format. + */ + // The format is copied, so that the moved-from decoder still converts (Review Focus 5). + // NOLINTNEXTLINE(performance-move-constructor-init) + format_decoder(format_decoder&& other) noexcept(nothrow_move) + : format_(other.format_), stream_(std::move(other.stream_)) {} + + /** + Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. + + @param other The decoder moved from, which keeps its format. + @return This decoder. + */ + format_decoder& operator=(format_decoder&& other) noexcept(nothrow_move_assignment) { + if (this != &other) { + format_ = other.format_; + stream_ = std::move(other.stream_); + } + return *this; + } + + /** Destroys the decoder. */ + ~format_decoder() = default; + + /** + A bound on the bytes of `input_size` characters: `codec::max_decoded_size`. + + @param input_size The characters of a text. + @return The bound, `SIZE_MAX` when it does not fit. + */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return codec::max_decoded_size(input_size); + } + + /** + The exact size of the bytes `transform` writes for `input`: `codec::decoded_size`, or + 0 for a text `transform` refuses, which writes nothing. + + @param input The text. + @return The bytes. + */ + [[nodiscard]] std::size_t output_size(std::span input) const noexcept( + detail::codec_decoded_size_is_noexcept()) { + std::string_view const text_characters{input.data(), input.size()}; + if (detail::text_size_fault(format_, text_characters.size())) { + return 0; + } + auto const byte_count = + detail::codec_decoded_size(format_, text_characters); + return byte_count ? byte_count.unsafe_value() : 0; + } + + /** + Writes the bytes of `input` at the start of `output`, or nothing and the error. + + @param input The text. + @param output The buffer the bytes are written to. + @return The bytes written, or the error. + */ + [[nodiscard]] result transform(std::span input, + std::span output) const + noexcept(detail::decode_calls_are_noexcept()) { + return detail::decode_into_buffer( + format_, std::string_view{input.data(), input.size()}, output); + } + + /** + Gives `input` to the stream decoder, which borrows it as the protocol says. + + @param input The characters to decode. + @return The characters accepted and the state after, or the error. + */ + [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) + requires streams + { + return stream_.send(input); + } + + /** + Writes the stream's bytes into `output`. + + @param output The span to write into. + @return The bytes written and the state after, or the error. + */ + [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) + requires streams + { + return stream_.receive(output); + } + + /** + Ends the stream's input. + + @return `flow::output_pending` while bytes remain, `flow::finished` when none do, or the + error. + */ + [[nodiscard]] result flush() noexcept(nothrow_stream) + requires streams + { + return stream_.flush(); + } + + /** Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error. */ + void reset() noexcept + requires streams + { + stream_.reset(); + } + + /** + The human-readable part the stream read, after a successful `flush`, as the stream decoder + gives it (B39). + + @return The stream decoder's human-readable part. + */ + [[nodiscard]] decltype(auto) human_readable_part() const + noexcept(detail::nothrow_human_readable_part) + requires detail::gives_human_readable_part + { + return stream_.human_readable_part(); + } + + /** + The label the stream read, after a successful `flush`, as the stream decoder gives it (B39). + + @return The stream decoder's label. + */ + [[nodiscard]] decltype(auto) label() const noexcept(detail::nothrow_label) + requires detail::gives_label + { + return stream_.label(); + } + +private: + /** The format. */ + Format format_; + /** The stream decoder's state, made from the format. */ + stream_type stream_; +}; + +/** + The stream of `over` when both links stream natively: the encoder is a + pipe of the inner link's encoder and then the outer link's, the decoder a pipe of the outer link's + decoder and then the inner link's, each with an intermediate in place of the default capacity + (D11, B43). + + The pipe's rules are the stream's: the first error of either link is the chain's, a call that + reports it writes nothing, and a move leaves the moved-from stream as `reset` does; the chain's + stream must not be moved while the second link borrows the intermediate, between a `receive` that + reports `flow::output_pending` and the next call that reports `flow::needs_input` or + `flow::finished`, unless it has reported an error (@ref piped). + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. + @tparam Allocator The allocator's type, which the stream does not use. +*/ +template + requires(detail::has_stream_codec && detail::has_stream_codec) +struct stream_codec> { + /** + The chain's stream encoder: the inner link's encoder, then the outer link's. + + @tparam Options The stream's options, which both links take. + */ + template + class encoder : public piped, format_encoder, + default_capacity_v> { + /** The pipe of the two links. */ + using links = piped, format_encoder, + default_capacity_v>; + + public: + /** + Makes the pipe of the encoders of `chain`'s links. + + @param chain The chain. + */ + explicit encoder(over const& chain) noexcept( + std::is_nothrow_constructible_v, Inner const&> && + std::is_nothrow_constructible_v, Outer const&> && + std::is_nothrow_constructible_v, + format_encoder>) + : links(format_encoder{chain.inner}, + format_encoder{chain.outer}) {} + }; + + /** + The chain's stream decoder: the outer link's decoder, then the inner link's. + + @tparam Options The stream's options, which both links take. + */ + template + class decoder : public piped, format_decoder, + default_capacity_v> { + /** The pipe of the two links. */ + using links = piped, format_decoder, + default_capacity_v>; + + public: + /** + Makes the pipe of the decoders of `chain`'s links. + + @param chain The chain. + */ + explicit decoder(over const& chain) noexcept( + std::is_nothrow_constructible_v, Outer const&> && + std::is_nothrow_constructible_v, Inner const&> && + std::is_nothrow_constructible_v, + format_decoder>) + : links(format_decoder{chain.outer}, + format_decoder{chain.inner}) {} + }; +}; + +namespace detail { + +/** Whether making the encoder of `F` with `Options` cannot throw; true when it is refused. */ +template +constexpr bool nothrow_encoder() noexcept { + if constexpr (has_codec) { + return std::is_nothrow_constructible_v, F const&>; + } else { + return true; + } +} + +/** Whether making the decoder of `F` with `Options` cannot throw; true when it is refused. */ +template +constexpr bool nothrow_decoder() noexcept { + if constexpr (has_codec) { + return std::is_nothrow_constructible_v, F const&>; + } else { + return true; + } +} + +/** + The encoder of `format_value` with `Options`, or the refusal of a value codec's format. +*/ +template +[[nodiscard]] auto make_encoder(F const& format_value) noexcept(nothrow_encoder()) { + if constexpr (!has_codec) { + refuse_value_format(); + } else { + return format_encoder{format_value}; + } +} + +/** + The decoder of `format_value` with `Options`, or the refusal of a value codec's format, or, when + the call named a capacity (`Held`), of a format whose decoder holds nothing. +*/ +template +[[nodiscard]] auto make_decoder(F const& format_value) noexcept(nothrow_decoder()) { + if constexpr (!has_codec) { + refuse_value_format(); + } else if constexpr (Held && !holding_decoder::type>) { + refuse_hold::type>(); + } else { + return format_decoder{format_value}; + } +} + +} // namespace detail + +/** + The transformer of `format`'s encoding, bytes to text (D20): a @ref format_encoder, a one-shot + transformer always and a stream transformer when the format streams natively. + + `encoder(over{outer, inner})` streams through a pipe of the links' encoders when both stream + natively (B43). A value codec's format has no transformer: typed values are converted whole, and + the call stops the build with a message that says so. + + @tparam F The format's type. + @param format_value The format. + @return The format's encoder. +*/ +template +[[nodiscard]] auto encoder(F const& format_value) noexcept( + detail::nothrow_encoder()) { + return detail::make_encoder(format_value); +} + +/** + The secret transformer of `format`'s encoding (D20, D21): as `encoder(format)`, its stream secret + and the format's secret arithmetic run where it has one (ruling R7). + + @tparam F The format's type. + @param format_value The format. + @return The format's secret encoder. +*/ +template +[[nodiscard]] auto encoder(F const& format_value, secret_operation_t /*secret*/) noexcept( + detail::nothrow_encoder()) { + return detail::make_encoder(format_value); +} + +/** + The transformer of `format`'s decoding, text to bytes (D20): a @ref format_decoder, a one-shot + transformer always and a stream transformer when the format streams natively. + + `decoder(over{outer, inner})` streams through a pipe of the outer link's decoder and then the + inner link's when both stream natively (B43). A value codec's format has no transformer, and the + call stops the build with a message that says so. + + @tparam F The format's type. + @param format_value The format. + @return The format's decoder. +*/ +template +[[nodiscard]] auto decoder(F const& format_value) noexcept( + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); +} + +/** + The secret transformer of `format`'s decoding (D20, D21): as `decoder(format)`, its stream secret + and the format's secret arithmetic run where it has one (ruling R7). + + @tparam F The format's type. + @param format_value The format. + @return The format's secret decoder. +*/ +template +[[nodiscard]] auto decoder(F const& format_value, secret_operation_t /*secret*/) noexcept( + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); +} + +/** + The transformer of `format`'s decoding whose stream decoder holds `N` elements of its input + (bech32's, in characters, B47). + + A format whose decoder holds nothing stops the build with a message that says so. + + @tparam F The format's type. + @tparam N The hold. + @param format_value The format. + @return The format's decoder, of the hold `N`. +*/ +template +[[nodiscard]] auto decoder(F const& format_value, capacity_t /*hold*/) noexcept( + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); +} + +/** + The secret transformer of `format`'s decoding whose stream decoder holds `N` elements of its + input, as `decoder(format, codecs::capacity)` with `codecs::secret_operation`. + + @tparam F The format's type. + @tparam N The hold. + @param format_value The format. + @return The format's secret decoder, of the hold `N`. +*/ +template +[[nodiscard]] auto +decoder(F const& format_value, secret_operation_t /*secret*/, capacity_t /*hold*/) noexcept( + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); +} + +/** + The secret transformer of `format`'s decoding whose stream decoder holds `N` elements of its + input: the tags in the other order. + + @tparam F The format's type. + @tparam N The hold. + @param format_value The format. + @return The format's secret decoder, of the hold `N`. +*/ +template +[[nodiscard]] auto +decoder(F const& format_value, capacity_t /*hold*/, secret_operation_t /*secret*/) noexcept( + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); +} + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_FORMAT_TRANSFORMER_HPP diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index e88d24d..65e48bc 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -156,6 +156,31 @@ template return codec_encode(format_value, input_view, output_buffer.first(text_size)); } +/** + Decodes `text_value` into `output_buffer`, with the format's secret arithmetic where `Secret` and + the format has one (R7): the buffer form's checks, the whole text checked, then the conversion. +*/ +template +[[nodiscard]] result decode_into_buffer( + F const& format_value, Text const& text_value, + std::span output_buffer) noexcept(decode_calls_are_noexcept()) { + auto const text_characters = bounded_text_view(text_value); + if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { + return *size_fault; + } + result const byte_count = + codec_decoded_size(format_value, text_characters); + if (!byte_count) { + return byte_count; + } + // Read unchecked: the error was returned above. + std::size_t const bytes_size = byte_count.unsafe_value(); + if (output_buffer.size() < bytes_size) { + return error::output_too_small; + } + return codec_decode(format_value, text_characters, output_buffer.first(bytes_size)); +} + } // namespace detail /** @@ -285,22 +310,7 @@ template std::span output_buffer) noexcept(detail::decode_calls_are_noexcept()) { if constexpr (detail::has_codec) { - auto const text_characters = detail::bounded_text_view(text_value); - if (auto const size_fault = detail::text_size_fault(format_value, text_characters.size())) { - return *size_fault; - } - result const byte_count = - detail::codec_decoded_size(format_value, text_characters); - if (!byte_count) { - return byte_count; - } - // Read unchecked: the error was returned above. - std::size_t const bytes_size = byte_count.unsafe_value(); - if (output_buffer.size() < bytes_size) { - return error::output_too_small; - } - return detail::codec_decode(format_value, text_characters, - output_buffer.first(bytes_size)); + return detail::decode_into_buffer(format_value, text_value, output_buffer); } else { detail::refuse(); return std::size_t{0}; diff --git a/test/Jamfile b/test/Jamfile index 722bf89..a0e13f9 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -95,6 +95,11 @@ codecs-run each : each_test.cpp ; # flush, in place and from an allocator; input_too_long past the capacity; the # heap form's sizing; a moved-from buffered starts again. codecs-run buffered : buffered_test.cpp ; +# The formats as transformers (D20): encoder and decoder, one-shot always and +# streaming through stream_codec, on letters; every chunking equals the +# one-shot form; the protocol's error rules (D18, B23, B44); over's stream +# through a pipe of its links; a moved-from transformer restarts. +codecs-run format_transformer : format_transformer_test.cpp ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 04de828..c5df5d9 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -638,6 +638,64 @@ void check_pipe_and_drain() { BOOST_TEST(verdict); } +/** + A format's transformers allocate nothing in a stream call (D21): letters' encoder and decoder, + sent in chunks, received into short spans, flushed, drained, moved and reset, their one-shot + transform, and over's stream, a pipe of its links' streams. +*/ +void check_format_transformers() { + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + bool volatile verdict = false; + expect_no_allocation("encoder(letters) and decoder(letters)", [&] { + auto encoder = codecs::encoder(test::letters); + bool streamed = encoder.send(std::span{bytes}.first(2)).has_value(); + auto const first = encoder.receive(std::span{text}.first(3)); + auto const second = encoder.receive(std::span{text}.subspan(3, 1)); + streamed = streamed && first.has_value() && second.has_value() && + encoder.send(std::span{bytes}.subspan(2)).has_value() && + encoder.flush().has_value(); + std::size_t written = 4; + auto sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + streamed = streamed && codecs::drain(encoder, sink, codecs::capacity<5>).has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto decoder = codecs::decoder(test::letters); + streamed = streamed && written == text.size() && + decoder.send(std::span{text}.first(5)).has_value() && + decoder.receive(decoded).has_value() && + decoder.send(std::span{text}.subspan(5)).has_value() && + decoder.flush().has_value(); + auto const last = decoder.receive(std::span{decoded}.subspan(2)); + auto moved_decoder{std::move(decoder)}; + moved_decoder.reset(); + auto const transformed = moved.transform(bytes, text); + verdict = streamed && last.has_value() && last->flow == codecs::flow::finished && + decoded == bytes && transformed.has_value(); + }); + BOOST_TEST(verdict); + expect_no_allocation("encoder(over{letters, letters}) as a stream", [&] { + std::array chain_text{}; + auto encoder = codecs::encoder(codecs::over{test::letters, test::letters}); + bool streamed = encoder.send(bytes).has_value() && encoder.flush().has_value(); + auto const received = encoder.receive(chain_text); + auto decoder = codecs::decoder(codecs::over{test::letters, test::letters}); + streamed = streamed && received.has_value() && received->count == chain_text.size() && + decoder.send(std::span{chain_text}).has_value() && + decoder.flush().has_value(); + auto const decoded_chain = decoder.receive(decoded); + auto moved{std::move(decoder)}; + moved.reset(); + verdict = streamed && decoded_chain.has_value() && + decoded_chain->flow == codecs::flow::finished && decoded == bytes; + }); + BOOST_TEST(verdict); +} + /** Frames 0 to 4, whose bytes number 2, 3, 4, 2 and 3. */ std::array five_frames() { std::array frames{}; @@ -783,6 +841,7 @@ int main() { check_over(); check_transformers(); check_pipe_and_drain(); + check_format_transformers(); check_each_and_buffered(); check_pipe_of_packets_into_each(); check_saturating_refusals(); diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp new file mode 100644 index 0000000..6ade5c1 --- /dev/null +++ b/test/format_transformer_test.cpp @@ -0,0 +1,674 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The formats as transformers (D20): encoder and decoder are a format's one-shot transformer +// always and its stream transformer through stream_codec, here on letters, whose stream codec +// keeps the protocol's error rules (D18, B23, B44). Every chunking of an input equals the one-shot +// form, the valid and the invalid ones; a send while output is pending accepts nothing; the call +// that reports a data error writes nothing; a fault of the configuration comes first, in both +// forms; an error stays until reset; over's transformers stream through a pipe of its links when +// both stream; a moved-from encoder or decoder converts from the start (Review Focus 5); a secret +// transformer runs the format's secret arithmetic (R7); a decoder that holds takes a capacity and +// gives what it read (B39). The refusals are message cases (test/messages). + +#include "support/chunkings.hpp" +#include "support/letters.hpp" +#include "support/tagged_letters.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** + The type of the format holding_letters, of this test's own: whole_letters' codec, and a stream + decoder that declares that it holds its input and gives what it read, as bech32's and the + armor's do; its streams are letters'. +*/ +struct holding_letters_t : whole_letters_t { + /** The format's name. */ + static constexpr std::string_view name = "holding_letters"; +}; + +/** The format holding_letters. */ +inline constexpr holding_letters_t holding_letters{}; + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** The codec of holding_letters: whole_letters', which takes it as its base. */ +template <> +struct codec : codec {}; + +/** The stream codec of holding_letters: letters', its decoder holding and giving its parts. */ +template <> +struct stream_codec { + /** letters' encoder. */ + template + class encoder : public stream_codec::encoder { + public: + /** letters' encoder. */ + explicit encoder(test::holding_letters_t const& /*format*/) noexcept + : stream_codec::encoder(test::letters) {} + }; + + /** letters' decoder, which says that it holds `Options.capacity` letters. */ + template + class decoder : public stream_codec::decoder { + public: + /** The decoder holds its input. */ + static constexpr bool holds = true; + /** Its hold: the capacity, or 90 letters. */ + static constexpr std::size_t hold = Options.capacity == 0 ? 90 : Options.capacity; + + /** letters' decoder. */ + explicit decoder(test::holding_letters_t const& /*format*/) noexcept + : stream_codec::decoder(test::letters) {} + + /** The human-readable part it read. */ + [[nodiscard]] std::string_view human_readable_part() const noexcept { return "hl"; } + + /** The label it read. */ + [[nodiscard]] std::string_view label() const noexcept { return "HOLDING"; } + }; +}; + +} // namespace webcpp::codecs + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** Whether a transformer has `reset`, a stream member. */ +template +concept resettable = requires(T& transformer) { transformer.reset(); }; + +/** Whether a transformer gives a label. */ +template +concept gives_label = requires(T const& transformer) { transformer.label(); }; + +/** Whether a transformer gives a human-readable part. */ +template +concept gives_human_readable_part = + requires(T const& transformer) { transformer.human_readable_part(); }; + +using letters_encoder = decltype(codecs::encoder(test::letters)); +using letters_decoder = decltype(codecs::decoder(test::letters)); +using whole_encoder = decltype(codecs::encoder(test::whole_letters)); +using whole_decoder = decltype(codecs::decoder(test::whole_letters)); +using letters_over_letters = codecs::over; +using over_encoder = decltype(codecs::encoder(letters_over_letters{test::letters, test::letters})); +using over_decoder = decltype(codecs::decoder(letters_over_letters{test::letters, test::letters})); +using one_shot_over = codecs::over; + +// A format's transformers are its one-shot transformers always, and stream transformers when it +// streams natively (D20). +static_assert(std::same_as>); +static_assert(std::same_as>); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::same_as); +static_assert(std::same_as); +static_assert(std::same_as); +static_assert(std::same_as); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!resettable); + +// over streams through a pipe of its links when both stream, and is one-shot otherwise (B43). +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(!codecs::stream_transformer); +static_assert(!codecs::stream_transformer); + +// The bounds and constant time come from the format's codec. +static_assert(letters_encoder::max_output_size(3) == 6); +static_assert(letters_decoder::max_output_size(7) == 3); +static_assert(over_encoder::max_output_size(3) == 12); +static_assert(!codecs::is_constant_time_v); +static_assert(!codecs::is_constant_time_v); + +// secret_operation and capacity are options of the stream, in either order (D20). +static_assert( + std::same_as>); +static_assert( + std::same_as>); +static_assert(std::same_as)), + codecs::format_decoder>); +static_assert( + std::same_as)), + codecs::format_decoder>); +static_assert( + std::same_as, + codecs::secret_operation)), + codecs::format_decoder>); +static_assert(codecs::stream_codec::decoder::hold == 8); +static_assert( + codecs::stream_codec::decoder::hold == 90); + +// A decoder forwards what its stream decoder gives after flush, where it has it (B39). +static_assert(!gives_label); +static_assert(!gives_human_readable_part); +static_assert(!gives_label); +static_assert(gives_label); +static_assert(gives_human_readable_part); + +/** `size` bytes from a generator of a fixed seed. */ +std::vector random_bytes(std::size_t size) { + std::mt19937_64 generator{20261126}; + std::uniform_int_distribution byte_value{0, 255}; + std::vector bytes(size); + for (std::uint8_t& byte : bytes) { + byte = static_cast(byte_value(generator)); + } + return bytes; +} + +/** The characters of `text` as the span a decoder reads. */ +std::span characters_of(std::string_view text) { + return {text.data(), text.size()}; +} + +/** The bytes of `text` as the span an encoder reads. */ +std::span bytes_of(std::span bytes) { + return bytes; +} + +/** + Streams every chunking of `input` through `transformer`, reset before each, with output spans of + one element and of 1024, and checks that each gives `expected`. +*/ +template +void expect_every_chunking(Transformer& transformer, std::span input, + Output const& expected) { + std::size_t chunkings = 0; + test::for_each_chunking(input, [&](std::span const> chunks) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + transformer.reset(); + auto const streamed = test::stream_whole(transformer, chunks, span_size); + BOOST_TEST(streamed.has_value()); + if (streamed) { + BOOST_TEST(std::ranges::equal(streamed.value(), expected)); + } + } + ++chunkings; + }); + BOOST_TEST(chunkings > 0); +} + +/** encoder(letters) and decoder(letters) over every chunking equal the one-shot forms. */ +void every_chunking_equals_the_one_shot_form() { + auto encoder = codecs::encoder(test::letters); + auto decoder = codecs::decoder(test::letters); + for (std::size_t const size : std::array{0, 1, 31, 32, 33, 1000}) { + std::vector const bytes = random_bytes(size); + auto const text = codecs::encode(test::letters, bytes); + BOOST_TEST_EQ(text.value().size(), 2 * size); + expect_every_chunking(encoder, bytes_of(bytes), text.value()); + expect_every_chunking(decoder, characters_of(text.value()), bytes); + } +} + +/** + Sends `chunks` to `transformer`, receiving into spans of `span_size` after each but the last, and + checks that no call fails before flush; then returns the error of flush, or of the receive after + it when the last chunk is still borrowed, which must write nothing (B44). +*/ +template +boost::system::error_code error_after_flush( + Transformer& transformer, + std::span const> chunks, + std::size_t span_size) { + using output_type = Transformer::output_type; + std::vector span_buffer(span_size); + for (std::size_t index = 0; index < chunks.size(); ++index) { + auto const sent = transformer.send(chunks[index]); + BOOST_TEST(sent.has_value() && sent->count == chunks[index].size()); + while (index + 1 < chunks.size()) { + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(received.has_value()); + if (!received || received->flow != codecs::flow::output_pending) { + break; + } + } + } + auto const flushed = transformer.flush(); + if (!flushed) { + return flushed.error(); + } + BOOST_TEST(flushed.value() == codecs::flow::output_pending); + std::ranges::fill(span_buffer, static_cast(0x5a)); + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(!received.has_value()); + BOOST_TEST(std::ranges::all_of(span_buffer, [](output_type element) { + return element == static_cast(0x5a); + })); + return received ? boost::system::error_code{} : received.error(); +} + +/** + An invalid text gives the one-shot form's error after flush, for every chunking, and nothing + before it: "abq" split everywhere is invalid_character, a text of an odd length invalid_length, + and a character from 0x80 up is invalid_character with `char` signed (Review Focus 1). +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + auto decoder = codecs::decoder(test::letters); + std::string const high_character{'a', 'b', static_cast(0xc1), 'b'}; + for (std::string_view const text : + {std::string_view{"abq"}, std::string_view{"abc"}, std::string_view{"qbc"}, + std::string_view{"abcdeq"}, std::string_view{high_character}}) { + auto const one_shot = codecs::decode(test::letters, text); + BOOST_TEST(!one_shot.has_value()); + test::for_each_chunking( + characters_of(text), [&](std::span const> chunks) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + decoder.reset(); + BOOST_TEST(error_after_flush(decoder, chunks, span_size) == one_shot.error()); + decoder.reset(); + auto const streamed = test::stream_whole(decoder, chunks, span_size); + BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); + } + }); + } + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abq"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abc"}).error() == + codecs::error::invalid_length); +} + +/** Receives from `transformer` into `span_size` spans until it needs input or finishes. */ +template +std::size_t receive_until_done(Transformer& transformer, std::size_t span_size) { + std::vector span_buffer(span_size); + std::size_t total = 0; + for (;;) { + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(received.has_value()); + if (!received) { + return total; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return total; + } + } +} + +/** + The spec's "Send while output is pending", on letters: 64 bytes then 4 more before any receive + give {64, output_pending} then {0, output_pending}, and the second send is accepted once the + output is received. A finished encoder accepts nothing: {0, finished}. +*/ +void send_while_output_is_pending() { + std::vector const bytes = random_bytes(68); + auto encoder = codecs::encoder(test::letters); + auto const first = encoder.send(std::span{bytes}.first(64)); + BOOST_TEST(first.has_value() && first->count == 64 && + first->flow == codecs::flow::output_pending); + auto const second = encoder.send(std::span{bytes}.subspan(64)); + BOOST_TEST(second.has_value() && second->count == 0 && + second->flow == codecs::flow::output_pending); + BOOST_TEST_EQ(receive_until_done(encoder, 100), 128U); + auto const again = encoder.send(std::span{bytes}.subspan(64)); + BOOST_TEST(again.has_value() && again->count == 4 && + again->flow == codecs::flow::output_pending); + BOOST_TEST_EQ(receive_until_done(encoder, 3), 8U); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + auto const after_end = encoder.send(std::span{bytes}.first(1)); + BOOST_TEST(after_end.has_value() && after_end->count == 0 && + after_end->flow == codecs::flow::finished); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + + // An empty input is accepted whole and absorbed: needs_input. + encoder.reset(); + auto const nothing = encoder.send({}); + BOOST_TEST(nothing.has_value() && nothing->count == 0 && + nothing->flow == codecs::flow::needs_input); + // A lone letter is absorbed into the decoder's state, which frees the input at once. + auto decoder = codecs::decoder(test::letters); + auto const lone = decoder.send(characters_of("a")); + BOOST_TEST(lone.has_value() && lone->count == 1 && lone->flow == codecs::flow::needs_input); +} + +/** + The spec's "The call that fails writes nothing", on letters (B44): 4000 valid letters drained, + then 96 letters whose last is `z`, flushed and received into a span of 1024, which the receive + that reports invalid_character leaves unchanged. +*/ +void the_call_that_fails_writes_nothing() { + std::vector const bytes = random_bytes(2048); + std::string const text = codecs::encode(test::letters, bytes).value(); + auto decoder = codecs::decoder(test::letters); + std::vector delivered; + auto sink = [&delivered](std::span piece) { + delivered.insert(delivered.end(), piece.begin(), piece.end()); + }; + BOOST_TEST(decoder.send(characters_of(std::string_view{text}.substr(0, 4000))).has_value()); + auto const drained = codecs::drain(decoder, sink); + BOOST_TEST(drained.has_value() && drained.value() == codecs::flow::needs_input); + BOOST_TEST(std::ranges::equal(delivered, std::span{bytes}.first(2000))); + + std::string tail = text.substr(4000, 96); + tail.back() = 'z'; + BOOST_TEST(decoder.send(characters_of(tail)).has_value()); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + std::array span{}; + span.fill(0x5a); + auto const received = decoder.receive(span); + BOOST_TEST(!received.has_value() && received.error() == codecs::error::invalid_character); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** + A fault of the format's configuration is reported by the first call, before any data, whatever + the call, and wins over a data fault, in the stream form and the one-shot form (B23). +*/ +void a_configuration_fault_comes_first() { + std::array const bytes{1, 2, 3}; + std::array text_buffer{}; + BOOST_TEST(codecs::encode(test::letters(true), bytes).error() == codecs::error::invalid_prefix); + BOOST_TEST(codecs::decode(test::letters(true), std::string_view{"abq"}).error() == + codecs::error::invalid_prefix); + + auto encoder = codecs::encoder(test::letters(true)); + auto const transformed = encoder.transform(bytes, text_buffer); + BOOST_TEST(!transformed.has_value() && transformed.error() == codecs::error::invalid_prefix); + auto const sent = encoder.send(bytes); + BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_prefix); + encoder.reset(); + auto const flushed = encoder.flush(); + BOOST_TEST(!flushed.has_value() && flushed.error() == codecs::error::invalid_prefix); + encoder.reset(); + auto const received = encoder.receive(text_buffer); + BOOST_TEST(!received.has_value() && received.error() == codecs::error::invalid_prefix); + + auto decoder = codecs::decoder(test::letters(true)); + std::array byte_buffer{}; + auto const decoded = decoder.transform(characters_of("abq"), byte_buffer); + BOOST_TEST(!decoded.has_value() && decoded.error() == codecs::error::invalid_prefix); + auto const decoder_sent = decoder.send(characters_of("abq")); + BOOST_TEST(!decoder_sent.has_value() && decoder_sent.error() == codecs::error::invalid_prefix); + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(!decoder_flushed.has_value() && + decoder_flushed.error() == codecs::error::invalid_prefix); + decoder.reset(); + auto const decoder_received = decoder.receive(byte_buffer); + BOOST_TEST(!decoder_received.has_value() && + decoder_received.error() == codecs::error::invalid_prefix); +} + +/** + The spec's "After the end and after an error", on letters: after flush reports + invalid_character, every call returns it, two receives among them, and after reset the decoder + decodes a valid text. +*/ +void an_error_stays_until_reset() { + auto decoder = codecs::decoder(test::letters); + BOOST_TEST(decoder.send(characters_of("abq")).has_value()); + BOOST_TEST_EQ(receive_until_done(decoder, 8), 1U); + auto const flushed = decoder.flush(); + BOOST_TEST(!flushed.has_value() && flushed.error() == codecs::error::invalid_character); + std::array output{}; + for (int call = 0; call < 2; ++call) { + auto const received = decoder.receive(output); + BOOST_TEST(!received.has_value() && received.error() == codecs::error::invalid_character); + } + auto const sent = decoder.send(characters_of("ab")); + BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_character); + auto const flushed_again = decoder.flush(); + BOOST_TEST(!flushed_again.has_value() && + flushed_again.error() == codecs::error::invalid_character); + + decoder.reset(); + std::array const, 1> const chunks{characters_of("abcd")}; + auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); + BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); +} + +/** transform is the buffer form: everything written or nothing, and output_size exact. */ +void transform_is_the_buffer_form() { + std::array const bytes{0x01, 0x23, 0xfe}; + auto const encoder = codecs::encoder(test::letters); + std::array text{}; + text.fill('x'); + auto const short_output = encoder.transform(bytes, std::span{text}.first(5)); + BOOST_TEST(!short_output.has_value() && + short_output.error() == codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(text, [](char character) { return character == 'x'; })); + auto const written = encoder.transform(bytes, text); + BOOST_TEST(written.has_value() && written.value() == 6); + BOOST_TEST(std::string_view(text.data(), 6) == "abcdpo"); + BOOST_TEST_EQ(encoder.output_size(bytes), 6U); + + auto const decoder = codecs::decoder(test::letters); + std::array decoded{}; + decoded.fill(0x5a); + auto const invalid = decoder.transform(characters_of("abq"), decoded); + BOOST_TEST(!invalid.has_value() && invalid.error() == codecs::error::invalid_character); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); + auto const read = decoder.transform(characters_of("abcdpo"), decoded); + BOOST_TEST(read.has_value() && read.value() == 3); + BOOST_TEST(std::ranges::equal(std::span{decoded}.first(3), bytes)); + BOOST_TEST_EQ(decoder.output_size(characters_of("abcdpo")), 3U); + BOOST_TEST_EQ(decoder.output_size(characters_of("abq")), 0U); + + // A format that does not stream natively streams through buffered (D20). + auto whole = codecs::buffered(codecs::encoder(test::whole_letters)); + std::array const, 2> const chunks{std::span{bytes}.first(1), + std::span{bytes}.subspan(1)}; + auto const streamed = test::stream_whole(whole, std::span{chunks}, 1); + BOOST_TEST(streamed.has_value() && + std::string_view(streamed->data(), streamed->size()) == "abcdpo"); +} + +/** + encoder(over{letters, letters}) and its decoder stream through a pipe of the links and equal the + one-shot over for every chunking, the errors of either link included (B43); an over whose link + does not stream is one-shot and transforms as over. +*/ +void over_streams_through_a_pipe() { + letters_over_letters const chain{test::letters, test::letters}; + auto encoder = codecs::encoder(chain); + auto decoder = codecs::decoder(chain); + for (std::size_t const size : std::array{0, 1, 33, 1000}) { + std::vector const bytes = random_bytes(size); + auto const text = codecs::encode(chain, bytes); + BOOST_TEST_EQ(text.value().size(), 4 * size); + expect_every_chunking(encoder, bytes_of(bytes), text.value()); + expect_every_chunking(decoder, characters_of(text.value()), bytes); + } + // The outer link's error, and the inner link's: "abq" is the letters of "abq" over letters. + std::string const inner_fault = codecs::encode(test::letters, std::string_view{"abq"}).value(); + for (std::string_view const text : {std::string_view{"abq"}, std::string_view{inner_fault}}) { + auto const one_shot = codecs::decode(chain, text); + BOOST_TEST(!one_shot.has_value()); + test::for_each_chunking( + characters_of(text), [&](std::span const> chunks) { + decoder.reset(); + auto const streamed = test::stream_whole(decoder, chunks, 3); + BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); + }); + } + + std::array const bytes{0x12, 0xab}; + auto const one_shot_encoder = + codecs::encoder(one_shot_over{test::letters, test::whole_letters}); + std::array text{}; + auto const written = one_shot_encoder.transform(bytes, text); + auto const expected = codecs::encode(one_shot_over{test::letters, test::whole_letters}, bytes); + BOOST_TEST(written.has_value() && written.value() == 8); + BOOST_TEST(std::string_view(text.data(), 8) == expected.value()); +} + +/** + A moved-from encoder or decoder is in the state reset leaves and converts a new input from the + start, while the target goes on with the stream it took (Review Focus 5): letters' encoder with a + letter pending, its decoder with a letter held, and over's encoder, moved by construction and by + assignment. +*/ +void a_moved_from_transformer_restarts() { + std::vector const bytes = random_bytes(31); + std::string const text = codecs::encode(test::letters, bytes).value(); + std::array const, 1> const byte_chunks{bytes_of(bytes)}; + std::array const, 1> const text_chunks{characters_of(text)}; + + auto source = codecs::encoder(test::letters); + BOOST_TEST(source.send(bytes).has_value()); + std::array start{}; + auto const begun = source.receive(start); + BOOST_TEST(begun.has_value() && begun->count == 3 && + begun->flow == codecs::flow::output_pending); + auto target{std::move(source)}; + std::string rest(text.size() - 3, '\0'); + auto const continued = target.receive(std::span{rest}); + BOOST_TEST(continued.has_value() && continued->count == rest.size()); + BOOST_TEST(std::string(start.data(), 3) + rest == text); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from encoder converts from the start + auto const restarted = test::stream_whole(source, std::span{byte_chunks}, 7); + BOOST_TEST(restarted.has_value() && + std::string_view(restarted->data(), restarted->size()) == text); + + auto decoder_source = codecs::decoder(test::letters); + BOOST_TEST(decoder_source.send(characters_of(std::string_view{text}.substr(0, 3))).has_value()); + BOOST_TEST_EQ(receive_until_done(decoder_source, 4), 1U); + auto decoder_target = codecs::decoder(test::letters); + decoder_target = std::move(decoder_source); + BOOST_TEST(decoder_target.send(characters_of(std::string_view{text}.substr(3))).has_value()); + BOOST_TEST_EQ(receive_until_done(decoder_target, 64), bytes.size() - 1); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from decoder converts from the start + auto const decoded = test::stream_whole(decoder_source, std::span{text_chunks}, 5); + BOOST_TEST(decoded.has_value() && decoded.value() == bytes); + + letters_over_letters const chain{test::letters, test::letters}; + std::string const chain_text = codecs::encode(chain, bytes).value(); + auto over_source = codecs::encoder(chain); + BOOST_TEST(over_source.send(bytes).has_value()); + auto over_target{std::move(over_source)}; + BOOST_TEST(over_target.flush().has_value()); + std::string chain_output(chain_text.size() + 1, '\0'); + auto const chain_received = over_target.receive(std::span{chain_output}); + BOOST_TEST(chain_received.has_value() && chain_received->count == chain_text.size() && + chain_received->flow == codecs::flow::finished); + BOOST_TEST(std::string_view(chain_output.data(), chain_text.size()) == chain_text); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from encoder converts from the start + auto const chain_restarted = test::stream_whole(over_source, std::span{byte_chunks}, 11); + BOOST_TEST(chain_restarted.has_value() && + std::string_view(chain_restarted->data(), chain_restarted->size()) == chain_text); +} + +/** + A secret transformer runs the format's secret arithmetic, a public one never (ruling R7), in + transform and output_size, and so does buffered over it at flush (D21). +*/ +void a_secret_transformer_runs_the_secret_arithmetic() { + std::array const bytes{0x12, 0xab}; + std::array text{}; + std::array decoded{}; + + test::tagged_calls.reset(); + auto const public_encoder = codecs::encoder(test::tagged_letters); + BOOST_TEST(public_encoder.transform(bytes, text).has_value()); + BOOST_TEST_EQ(public_encoder.output_size(bytes), 4U); + auto const public_decoder = codecs::decoder(test::tagged_letters); + BOOST_TEST(public_decoder.transform(characters_of("bcklpo"), decoded).error() == + codecs::error::output_too_small); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + + auto const secret_encoder = codecs::encoder(test::tagged_letters, codecs::secret_operation); + BOOST_TEST(secret_encoder.transform(bytes, text).has_value()); + BOOST_TEST(std::string_view(text.data(), text.size()) == "bckl"); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(secret_encoder.output_size(bytes), 4U); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 2U); + + auto const secret_decoder = codecs::decoder(test::tagged_letters, codecs::secret_operation); + BOOST_TEST(secret_decoder.transform(characters_of("bckl"), decoded).has_value()); + BOOST_TEST(std::ranges::equal(decoded, bytes)); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(secret_decoder.output_size(characters_of("bckl")), 2U); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 2U); + + test::tagged_calls.reset(); + auto accumulated = codecs::buffered( + codecs::encoder(test::tagged_letters, codecs::secret_operation), codecs::capacity<8>); + std::array const, 1> const chunks{std::span{bytes}}; + auto const streamed = test::stream_whole(accumulated, std::span{chunks}, 4); + BOOST_TEST(streamed.has_value() && + std::string_view(streamed->data(), streamed->size()) == "bckl"); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); +} + +/** + A decoder that holds takes a capacity, and forwards what its stream decoder gives after flush + (B39, B47). +*/ +void a_holding_decoder_gives_what_it_read() { + auto decoder = codecs::decoder(test::holding_letters, codecs::capacity<8>); + std::array const, 1> const chunks{characters_of("abcd")}; + auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); + BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); + BOOST_TEST(decoder.label() == "HOLDING"); + BOOST_TEST(decoder.human_readable_part() == "hl"); + static_assert(noexcept(decoder.label())); + static_assert(noexcept(decoder.human_readable_part())); +} + +} // namespace + +int main() { + every_chunking_equals_the_one_shot_form(); + invalid_texts_give_the_one_shot_error_after_flush(); + send_while_output_is_pending(); + the_call_that_fails_writes_nothing(); + a_configuration_fault_comes_first(); + an_error_stays_until_reset(); + transform_is_the_buffer_form(); + over_streams_through_a_pipe(); + a_moved_from_transformer_restarts(); + a_secret_transformer_runs_the_secret_arithmetic(); + a_holding_decoder_gives_what_it_read(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 7bcb624..73d5973 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -30,3 +30,7 @@ build-project each_capacity_too_small ; build-project each_without_bound ; build-project buffered_without_bound ; build-project buffered_bound_not_constant ; +build-project encoder_of_value_format ; +build-project encoder_of_value_over ; +build-project capacity_without_hold ; +build-project drain_of_one_shot ; diff --git a/test/messages/capacity_without_hold/Jamfile b/test/messages/capacity_without_hold/Jamfile new file mode 100644 index 0000000..862c9c0 --- /dev/null +++ b/test/messages/capacity_without_hold/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic capacity_without_hold : capacity_without_hold.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail capacity_without_hold_refused : capacity_without_hold.cpp + : clang:no : native emscripten ; diff --git a/test/messages/capacity_without_hold/capacity_without_hold.cpp b/test/messages/capacity_without_hold/capacity_without_hold.cpp new file mode 100644 index 0000000..94dae54 --- /dev/null +++ b/test/messages/capacity_without_hold/capacity_without_hold.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// codecs::capacity sets the hold of a decoder that holds its input, as bech32's (D20, B47): +// letters' decoder holds one letter of a pair and nothing more, so the build stops with a message +// that says so. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/format_transformer.hpp:* {{static assertion failed: webcpp::codecs: codecs::capacity sets the hold of a decoder that holds its input, as bech32's; this format's decoder holds nothing}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::decoder(codecs::test::letters, codecs::capacity<8>); + return 0; +} diff --git a/test/messages/drain_of_one_shot/Jamfile b/test/messages/drain_of_one_shot/Jamfile new file mode 100644 index 0000000..6d8a678 --- /dev/null +++ b/test/messages/drain_of_one_shot/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic drain_of_one_shot : drain_of_one_shot.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail drain_of_one_shot_refused : drain_of_one_shot.cpp + : clang:no : native emscripten ; diff --git a/test/messages/drain_of_one_shot/drain_of_one_shot.cpp b/test/messages/drain_of_one_shot/drain_of_one_shot.cpp new file mode 100644 index 0000000..f6ae9bf --- /dev/null +++ b/test/messages/drain_of_one_shot/drain_of_one_shot.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A format that does not stream natively has a one-shot transformer alone (D20): drain of +// whole_letters' encoder stops in drain's refusal, the message of pipe, which names the two ways +// to make it a stream (B31). The encoder is a named object, which drain's reference binds (ruling +// F2). The note that follows the error names the type refused. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: pipe and drain take stream transformers; make a one-shot transformer one with codecs::each (per item) or codecs::buffered (accumulating)}} +// expected-note@webcpp/codecs/detail/core/pipe.hpp:* {{because 'webcpp::codecs::format_encoder' does not satisfy 'stream_transformer'}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto encoder_object = codecs::encoder(codecs::test::whole_letters); + auto const drained = codecs::drain(encoder_object, [](std::span /*piece*/) {}); + return drained.has_value() ? 0 : 1; +} diff --git a/test/messages/encoder_of_value_format/Jamfile b/test/messages/encoder_of_value_format/Jamfile new file mode 100644 index 0000000..2a3afe4 --- /dev/null +++ b/test/messages/encoder_of_value_format/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic encoder_of_value_format : encoder_of_value_format.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail encoder_of_value_format_refused : encoder_of_value_format.cpp + : clang:no : native emscripten ; diff --git a/test/messages/encoder_of_value_format/encoder_of_value_format.cpp b/test/messages/encoder_of_value_format/encoder_of_value_format.cpp new file mode 100644 index 0000000..fac822d --- /dev/null +++ b/test/messages/encoder_of_value_format/encoder_of_value_format.cpp @@ -0,0 +1,26 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A value codec's format has no transformer (D20): be16 converts typed values whole, so encoder +// of it stops the build with a message that says so. The note that follows the error names the +// format refused. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/format_transformer.hpp:* {{static assertion failed: webcpp::codecs: a value codec's format has no transformer; typed values are converted whole by codecs::encode and codecs::decode}} +// expected-note@webcpp/codecs/detail/core/format_transformer.hpp:* {{because 'webcpp::codecs::test::be16_t' does not satisfy 'has_codec'}} +// clang-format on + +#include "../../support/be16.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::encoder(codecs::test::be16); + return 0; +} diff --git a/test/messages/encoder_of_value_over/Jamfile b/test/messages/encoder_of_value_over/Jamfile new file mode 100644 index 0000000..5992003 --- /dev/null +++ b/test/messages/encoder_of_value_over/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic encoder_of_value_over : encoder_of_value_over.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail encoder_of_value_over_refused : encoder_of_value_over.cpp + : clang:no : native emscripten ; diff --git a/test/messages/encoder_of_value_over/encoder_of_value_over.cpp b/test/messages/encoder_of_value_over/encoder_of_value_over.cpp new file mode 100644 index 0000000..972b7e0 --- /dev/null +++ b/test/messages/encoder_of_value_over/encoder_of_value_over.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// An over with a value codec's format has no transformer (D11, D20): over{letters, be16} converts +// a typed value whole, so encoder of it stops the build with the value codec's message (ruling +// F2: a refusal is a message case, never a requires probe). The note that follows the error names +// the chain refused. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/format_transformer.hpp:* {{static assertion failed: webcpp::codecs: a value codec's format has no transformer; typed values are converted whole by codecs::encode and codecs::decode}} +// expected-note@webcpp/codecs/detail/core/format_transformer.hpp:* {{because 'webcpp::codecs::over' does not satisfy 'has_codec'}} +// clang-format on + +#include "../../support/be16.hpp" +#include "../../support/letters.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::encoder(codecs::over{codecs::test::letters, codecs::test::be16}); + return 0; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 7653996..e77f8b4 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -456,4 +456,50 @@ static_assert(!std::is_nothrow_constructible_v< static_assert(std::is_nothrow_constructible_v, careful_copy>); static_assert(std::is_nothrow_constructible_v, careful_copy>); +// The formats as transformers (Task 11): making them and every call allocates nothing and is +// noexcept, but over's transform and sizes over a heap intermediate, which allocate. +using letters_encoder = decltype(codecs::encoder(test::letters)); +using letters_decoder = decltype(codecs::decoder(test::letters)); +static_assert(noexcept(codecs::encoder(test::letters))); +static_assert(noexcept(codecs::encoder(test::letters, codecs::secret_operation))); +static_assert(noexcept(codecs::decoder(test::letters))); +static_assert(noexcept(codecs::decoder(test::letters, codecs::secret_operation))); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(noexcept(std::declval().transform( + std::span{}, std::span{}))); +static_assert( + noexcept(std::declval().output_size(std::span{}))); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +static_assert(noexcept(std::declval().transform( + std::span{}, std::span{}))); +static_assert( + noexcept(std::declval().output_size(std::span{}))); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +using chain_encoder = decltype(codecs::encoder(codecs::over{test::letters, test::letters})); +using chain_decoder = decltype(codecs::decoder(codecs::over{test::letters, test::letters})); +using letters_chain = codecs::over; +static_assert(noexcept(codecs::encoder(std::declval()))); +static_assert(noexcept(codecs::decoder(std::declval()))); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(!noexcept(std::declval().transform( + std::span{}, std::span{}))); +static_assert( + !noexcept(std::declval().output_size(std::span{}))); +static_assert(!noexcept(std::declval().transform(std::span{}, + std::span{}))); +static_assert(!noexcept(std::declval().output_size(std::span{}))); + } // namespace diff --git a/test/support/chunkings.hpp b/test/support/chunkings.hpp new file mode 100644 index 0000000..c0ee295 --- /dev/null +++ b/test/support/chunkings.hpp @@ -0,0 +1,192 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The chunkings a stream test sends an input in (D15, "every chunking equals the one-shot form"): +// for_each_chunking calls back with the input whole, every split into two chunks and into three, +// chunks of one element, and 32 random chunkings, some of their chunks empty, drawn from +// std::mt19937_64{20261126} so that every lane sees the same. Of an input longer than +// every_cut_limit elements the three-chunk splits are those whose two cuts are each at one of the +// first and last cut_edge positions or on a grid of cut_steps steps between, so that 1000 elements +// give hundreds of splits and not half a million, every boundary near the ends included. +// stream_whole sends the chunks to a stream transformer, receiving into spans of a given size after +// each, flushes and receives until it finishes, and checks that a call that reports an error wrote +// nothing (B44). + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP + +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** Up to this many elements, an input is split into three chunks at every pair of cuts. */ +inline constexpr std::size_t every_cut_limit = 64; +/** Past `every_cut_limit`, the cuts at each end of the input that a three-chunk split takes. */ +inline constexpr std::size_t cut_edge = 8; +/** Past `every_cut_limit`, the steps of the grid of cuts between the ends. */ +inline constexpr std::size_t cut_steps = 16; + +namespace chunkings_detail { + +/** The cut positions of the three-chunk splits of an input of `size` elements. */ +inline std::vector three_chunk_cuts(std::size_t size) { + std::vector cuts; + if (size <= every_cut_limit) { + for (std::size_t cut = 0; cut <= size; ++cut) { + cuts.push_back(cut); + } + return cuts; + } + std::size_t const step = size / cut_steps; + for (std::size_t cut = 0; cut <= size; ++cut) { + if (cut <= cut_edge || cut >= size - cut_edge || cut % step == 0) { + cuts.push_back(cut); + } + } + return cuts; +} + +} // namespace chunkings_detail + +/** + Calls `callback(std::span const>)` with each chunking of `input`: the input + whole, every split into two chunks and into three (on a grid past `every_cut_limit`), chunks of + one element, and 32 random chunkings. +*/ +template +void for_each_chunking(std::span input, Callback callback) { + using chunk = std::span; + std::vector chunks; + auto const call_back = [&] { callback(std::span{chunks}); }; + + chunks = {input}; + call_back(); + for (std::size_t cut = 0; cut <= input.size(); ++cut) { + chunks = {input.first(cut), input.subspan(cut)}; + call_back(); + } + std::vector const cuts = chunkings_detail::three_chunk_cuts(input.size()); + for (std::size_t const first_cut : cuts) { + for (std::size_t const second_cut : cuts) { + if (second_cut < first_cut) { + continue; + } + chunks = {input.first(first_cut), input.subspan(first_cut, second_cut - first_cut), + input.subspan(second_cut)}; + call_back(); + } + } + chunks.clear(); + for (std::size_t index = 0; index < input.size(); ++index) { + chunks.push_back(input.subspan(index, 1)); + } + call_back(); + + std::mt19937_64 generator{20261126}; + std::uniform_int_distribution chunk_size{ + 0, std::max(4, input.size() / 8)}; + for (int chunking = 0; chunking < 32; ++chunking) { + chunks.clear(); + std::size_t position = 0; + while (position < input.size()) { + std::size_t const size = std::min(chunk_size(generator), input.size() - position); + chunks.push_back(input.subspan(position, size)); + position += size; + } + call_back(); + } +} + +namespace chunkings_detail { + +/** The value a span is filled with before a receive, to see that a failing call wrote nothing. */ +template +inline constexpr Element untouched = static_cast(0x5a); + +/** + Receives from `transformer` into spans of `span_size` elements until it reports another state + than `flow::output_pending`, appending to `output`; a receive that fails must have written nothing. +*/ +template +result receive_all(Transformer& transformer, + std::vector& output, + std::vector& span_buffer) { + using output_type = Transformer::output_type; + for (;;) { + std::ranges::fill(span_buffer, untouched); + auto const received = transformer.receive(std::span{span_buffer}); + if (!received) { + BOOST_TEST(std::ranges::all_of(span_buffer, [](output_type element) { + return element == untouched; + })); + return received.error(); + } + output.insert(output.end(), span_buffer.begin(), + span_buffer.begin() + static_cast(received->count)); + if (received->flow != flow::output_pending) { + return received->flow; + } + } +} + +} // namespace chunkings_detail + +/** + Streams `chunks` through `transformer`: sends each, receiving into spans of `output_span_size` + elements until the transformer needs input, then flushes and receives until it finishes. + + @return Everything received, or the first error. +*/ +template +result> stream_whole( + Transformer& transformer, + std::span const> chunks, + std::size_t output_span_size) { + using output_type = Transformer::output_type; + std::vector output; + std::vector span_buffer(output_span_size); + for (auto const chunk : chunks) { + std::size_t sent = 0; + do { + auto const accepted = transformer.send(chunk.subspan(sent)); + if (!accepted) { + return accepted.error(); + } + sent += accepted->count; + if (auto const received = + chunkings_detail::receive_all(transformer, output, span_buffer); + !received) { + return received.error(); + } + } while (sent < chunk.size()); + } + auto const flushed = transformer.flush(); + if (!flushed) { + return flushed.error(); + } + if (flushed.value() == flow::output_pending) { + auto const received = chunkings_detail::receive_all(transformer, output, span_buffer); + if (!received) { + return received.error(); + } + BOOST_TEST(received.value() == flow::finished); + } else { + BOOST_TEST(flushed.value() == flow::finished); + } + return output; +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP diff --git a/test/support/letters.hpp b/test/support/letters.hpp index a3df9a9..b26a503 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -6,13 +6,20 @@ // letters, a format of the tests' own: every byte is written as two letters `a` to `p`, its high // half then its low half, so that the contract is proven before any real format exists. Its codec -// is the six functions of D3 and nothing else; it is not constant time. +// is the six functions of D3 and nothing else; it is not constant time. `letters(true)` is the +// format with a fault of its configuration, which every form reports as `invalid_prefix` before +// any data (B23). Its stream codec (D20) keeps the protocol's error rules (D18, B44): the encoder +// holds the one letter its output had no room for, the decoder one letter of a pair and the lowest +// data error seen. whole_letters is letters' codec under another name, with no stream codec, so +// that its transformers are one-shot alone. #ifndef WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP #include +#include + #include #include #include @@ -24,11 +31,28 @@ namespace webcpp::codecs::test { struct letters_t { /** The format's name. */ static constexpr std::string_view name = "letters"; + + /** Whether the format's configuration is at fault, which every form reports first. */ + bool configured_fault = false; + + /** The format, its configuration at fault when `fault` is true. */ + [[nodiscard]] constexpr letters_t operator()(bool fault) const noexcept { + return letters_t{.configured_fault = fault}; + } }; /** The format letters: byte `b` as `'a' + (b >> 4)` then `'a' + (b & 15)`. */ inline constexpr letters_t letters{}; +/** The type of the format whole_letters: letters, with no stream codec. */ +struct whole_letters_t { + /** The format's name. */ + static constexpr std::string_view name = "whole_letters"; +}; + +/** The format whole_letters, whose transformers are one-shot alone. */ +inline constexpr whole_letters_t whole_letters{}; + } // namespace webcpp::codecs::test namespace webcpp::codecs { @@ -56,11 +80,15 @@ struct codec { } /** - The bytes of a text: `invalid_character` for a character outside `a` to `p`, else - `invalid_length` for an odd length (the lowest value wins, B23). + The bytes of a text: `invalid_prefix` for a format whose configuration is at fault, else + `invalid_character` for a character outside `a` to `p`, else `invalid_length` for an odd + length (the lowest value wins, B23). */ - static result decoded_size(test::letters_t const& /*format*/, + static result decoded_size(test::letters_t const& format_value, std::string_view text_characters) noexcept { + if (format_value.configured_fault) { + return error::invalid_prefix; + } for (char const text_character : text_characters) { // Read as an unsigned byte first: a signed char from 0x80 up is negative. auto const character_value = static_cast(text_character); @@ -75,10 +103,16 @@ struct codec { return text_characters.size() / 2; } - /** Writes two letters a byte into `output_characters`, which must hold them. */ + /** + Writes two letters a byte into `output_characters`, which must hold them; `invalid_prefix` + first for a format whose configuration is at fault. + */ static result encode(test::letters_t const& format_value, std::span input_bytes, std::span output_characters) noexcept { + if (format_value.configured_fault) { + return error::invalid_prefix; + } std::size_t const written_size = encoded_size(format_value, input_bytes); if (output_characters.size() < written_size) { return error::output_too_small; @@ -119,6 +153,419 @@ struct codec { } }; +/** The codec of whole_letters: letters', forwarded. */ +template <> +struct codec { + /** letters branches on its data. */ + static constexpr bool constant_time = false; + + /** The letters of `input_size` bytes. */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return codec::max_encoded_size(input_size); + } + + /** The bytes of `text_size` letters. */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return codec::max_decoded_size(text_size); + } + + /** The letters of `input_bytes`. */ + static constexpr std::size_t encoded_size(test::whole_letters_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::letters, input_bytes); + } + + /** The bytes of `text_characters`, as letters checks them. */ + static result decoded_size(test::whole_letters_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::letters, text_characters); + } + + /** Writes the letters of `input_bytes`. */ + static result encode(test::whole_letters_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::letters, input_bytes, output_characters); + } + + /** Writes the bytes of `text_characters`. */ + static result decode(test::whole_letters_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::letters, text_characters, output_bytes); + } +}; + +/** The stream codec of letters (D20): an encoder and a decoder of the protocol's rules. */ +template <> +struct stream_codec { + /** + The stream encoder: two letters a borrowed byte, written straight into the caller's span; the + low letter of a byte whose high letter filled the span waits for the next `receive`. + + @tparam Options The stream's options. + */ + template + class encoder { + public: + /** The bytes read. */ + using input_type = std::uint8_t; + /** The letters written. */ + using output_type = char; + + /** An encoder of `format_value` in `needs_input`. */ + explicit encoder(test::letters_t const& format_value) noexcept + : configured_fault_(format_value.configured_fault) {} + + /** A copy of the state, borrowing what `other` borrows. */ + encoder(encoder const&) noexcept = default; + /** A copy of the state, borrowing what `other` borrows. */ + encoder& operator=(encoder const&) noexcept = default; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + encoder(encoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + pending_(other.pending_), + has_pending_(other.has_pending_), + flushed_(other.flushed_), + configured_fault_(other.configured_fault_), + error_(other.error_) { + other.reset(); + } + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + encoder& operator=(encoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + pending_ = other.pending_; + has_pending_ = other.has_pending_; + flushed_ = other.flushed_; + configured_fault_ = other.configured_fault_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + ~encoder() = default; + + /** Borrows all of `input` in `needs_input`. */ + result send(std::span input) noexcept { + if (failed()) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return step{.count = input.size(), .flow = state()}; + } + + /** Writes the waiting letter, then two letters a borrowed byte, as `output` has room. */ + result receive(std::span output) noexcept { + if (failed()) { + return error_; + } + std::size_t written = 0; + if (has_pending_ && written < output.size()) { + output[written++] = pending_; + has_pending_ = false; + } + while (position_ < borrowed_.size() && written < output.size()) { + std::uint8_t const input_byte = borrowed_[position_++]; + output[written++] = static_cast('a' + (input_byte >> 4U)); + auto const low_letter = static_cast('a' + (input_byte & 15U)); + if (written < output.size()) { + output[written++] = low_letter; + } else { + pending_ = low_letter; + has_pending_ = true; + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** Ends the input: letters has no data fault to find. */ + result flush() noexcept { + if (failed()) { + return error_; + } + flushed_ = true; + return state(); + } + + /** Back to `needs_input`, nothing borrowed or pending, the error forgotten. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + pending_ = 0; + has_pending_ = false; + flushed_ = false; + error_.clear(); + } + + private: + /** Whether a call reports an error: the configuration's fault comes first. */ + [[nodiscard]] bool failed() noexcept { + if (configured_fault_ && !error_) { + error_ = error::invalid_prefix; + } + return static_cast(error_); + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (has_pending_ || position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The bytes `send` accepted. */ + std::span borrowed_; + /** The next borrowed byte to read. */ + std::size_t position_ = 0; + /** The low letter the output had no room for. */ + char pending_ = 0; + /** Whether `pending_` waits. */ + bool has_pending_ = false; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the format's configuration is at fault. */ + bool configured_fault_ = false; + /** The error every call returns until `reset`. */ + boost::system::error_code error_; + }; + + /** + The stream decoder: a byte for each pair of letters, written straight into the caller's span; + the first letter of a pair whose second is not borrowed yet is held. Every letter's verdict + is accumulated, and reported after `flush` by the call that reads the end of the input, which + runs it over everything still borrowed before it writes (B44). + + @tparam Options The stream's options. + */ + template + class decoder { + public: + /** The letters read. */ + using input_type = char; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** A decoder of `format_value` in `needs_input`. */ + explicit decoder(test::letters_t const& format_value) noexcept + : configured_fault_(format_value.configured_fault) {} + + /** A copy of the state, borrowing what `other` borrows. */ + decoder(decoder const&) noexcept = default; + /** A copy of the state, borrowing what `other` borrows. */ + decoder& operator=(decoder const&) noexcept = default; + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + decoder(decoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + held_(other.held_), + has_held_(other.has_held_), + invalid_seen_(other.invalid_seen_), + flushed_(other.flushed_), + verdict_passed_(other.verdict_passed_), + configured_fault_(other.configured_fault_), + error_(other.error_) { + other.reset(); + } + + /** Takes `other`'s state and leaves `other` as `reset` does. */ + decoder& operator=(decoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + held_ = other.held_; + has_held_ = other.has_held_; + invalid_seen_ = other.invalid_seen_; + flushed_ = other.flushed_; + verdict_passed_ = other.verdict_passed_; + configured_fault_ = other.configured_fault_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + ~decoder() = default; + + /** Borrows all of `input` in `needs_input`; a lone letter is held at once. */ + result send(std::span input) noexcept { + if (failed()) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + hold_lone_letter(); + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes a byte for each pair of letters, as `output` has room. After `flush`, the first call + runs the verdict over what is still borrowed and returns its error, writing nothing. + */ + result receive(std::span output) noexcept { + if (failed()) { + return error_; + } + if (flushed_ && !verdict_passed_ && !pass_verdict()) { + return error_; + } + std::size_t written = 0; + while (written < output.size()) { + if (!has_held_) { + if (borrowed_.size() - position_ < 2) { + break; + } + take_held(borrowed_[position_++]); + } + if (position_ == borrowed_.size()) { + break; + } + char const low_letter = borrowed_[position_++]; + invalid_seen_ = invalid_seen_ || !is_letter(low_letter); + output[written++] = + static_cast((half_of(held_) << 4U) | half_of(low_letter)); + has_held_ = false; + } + hold_lone_letter(); + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input; with nothing borrowed, it runs the verdict, and reports its error, itself. + */ + result flush() noexcept { + if (failed()) { + return error_; + } + if (!flushed_) { + flushed_ = true; + if (position_ == borrowed_.size() && !pass_verdict()) { + return error_; + } + } + return state(); + } + + /** Back to `needs_input`, nothing borrowed or held, the verdict and the error forgotten. */ + void reset() noexcept { + borrowed_ = {}; + position_ = 0; + held_ = 0; + has_held_ = false; + invalid_seen_ = false; + flushed_ = false; + verdict_passed_ = false; + error_.clear(); + } + + private: + /** Whether `letter` is one of `a` to `p`, read as an unsigned byte. */ + [[nodiscard]] static bool is_letter(char letter) noexcept { + auto const letter_value = static_cast(letter); + return letter_value >= static_cast('a') && + letter_value <= static_cast('p'); + } + + /** The half a letter stands for; any four bits for a character that is no letter. */ + [[nodiscard]] static unsigned half_of(char letter) noexcept { + return static_cast(static_cast(letter) - + static_cast('a')) & + 15U; + } + + /** Holds `letter`, the first of a pair, its verdict accumulated. */ + void take_held(char letter) noexcept { + invalid_seen_ = invalid_seen_ || !is_letter(letter); + held_ = letter; + has_held_ = true; + } + + /** Holds the last borrowed letter when it is alone, which frees the borrow. */ + void hold_lone_letter() noexcept { + if (!has_held_ && borrowed_.size() - position_ == 1) { + take_held(borrowed_[position_++]); + } + } + + /** + The verdict over the whole input, what is still borrowed included: `invalid_character`, + else `invalid_length` for a letter with no pair (the lowest value wins, B23). + */ + [[nodiscard]] bool pass_verdict() noexcept { + bool invalid = invalid_seen_; + for (char const letter : borrowed_.subspan(position_)) { + invalid = invalid || !is_letter(letter); + } + std::size_t const letter_count = + (has_held_ ? std::size_t{1} : std::size_t{0}) + (borrowed_.size() - position_); + if (invalid) { + error_ = error::invalid_character; + } else if (letter_count % 2 != 0) { + error_ = error::invalid_length; + } + verdict_passed_ = !error_; + return verdict_passed_; + } + + /** Whether a call reports an error: the configuration's fault comes first. */ + [[nodiscard]] bool failed() noexcept { + if (configured_fault_ && !error_) { + error_ = error::invalid_prefix; + } + return static_cast(error_); + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The letters `send` accepted. */ + std::span borrowed_; + /** The next borrowed letter to read. */ + std::size_t position_ = 0; + /** The first letter of a pair whose second is not read yet. */ + char held_ = 0; + /** Whether `held_` waits. */ + bool has_held_ = false; + /** Whether a character that is no letter was read. */ + bool invalid_seen_ = false; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the verdict over the whole input passed. */ + bool verdict_passed_ = false; + /** Whether the format's configuration is at fault. */ + bool configured_fault_ = false; + /** The error every call returns until `reset`. */ + boost::system::error_code error_; + }; +}; + } // namespace webcpp::codecs #endif // WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP From 2f04e2fe86120da97316dc8b1ec252a1aaf499d0 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 18:40:00 -0300 Subject: [PATCH 060/157] codecs: encoder and decoder lint fix, the format taken by value, the stream options named, the moved-from format's copy stated, the test's format of internal linkage, the fixed seeds stated --- .../codecs/detail/core/format_transformer.hpp | 46 ++++++++----- test/format_transformer_test.cpp | 66 +++++++++++-------- test/support/chunkings.hpp | 13 +++- 3 files changed, 77 insertions(+), 48 deletions(-) diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index 8dbf9e3..a2f2399 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -85,6 +85,12 @@ struct stream_codec; namespace detail { +/** The options of a public stream, whose decoder holds its default. */ +inline constexpr stream_options public_stream{}; + +/** The options of a secret stream, whose decoder holds its default. */ +inline constexpr stream_options secret_stream{.secret = true}; + /** Whether `stream_codec` is specialized: the format streams natively. */ template concept has_stream_codec = requires { sizeof(stream_codec); }; @@ -249,12 +255,12 @@ class format_encoder { /** Makes the encoder of `format_value`, in `flow::needs_input`. - @param format_value The format, copied. + @param format_value The format. */ - explicit format_encoder(Format const& format_value) noexcept( - std::is_nothrow_copy_constructible_v && + explicit format_encoder(Format format_value) noexcept( + std::is_nothrow_move_constructible_v && std::is_nothrow_constructible_v) - : format_(format_value), stream_(format_) {} + : format_(std::move(format_value)), stream_(format_) {} /** Copies `other`'s format and stream state, when the stream state is copyable. @@ -277,10 +283,12 @@ class format_encoder { @param other The encoder moved from, which keeps its format. */ // The format is copied, so that the moved-from encoder still converts (Review Focus 5). - // NOLINTNEXTLINE(performance-move-constructor-init) + // NOLINTBEGIN(performance-move-constructor-init,cert-oop11-cpp) format_encoder(format_encoder&& other) noexcept(nothrow_move) : format_(other.format_), stream_(std::move(other.stream_)) {} + // NOLINTEND(performance-move-constructor-init,cert-oop11-cpp) + /** Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. @@ -453,12 +461,12 @@ class format_decoder { /** Makes the decoder of `format_value`, in `flow::needs_input`. - @param format_value The format, copied. + @param format_value The format. */ - explicit format_decoder(Format const& format_value) noexcept( - std::is_nothrow_copy_constructible_v && + explicit format_decoder(Format format_value) noexcept( + std::is_nothrow_move_constructible_v && std::is_nothrow_constructible_v) - : format_(format_value), stream_(format_) {} + : format_(std::move(format_value)), stream_(format_) {} /** Copies `other`'s format and stream state, when the stream state is copyable. @@ -481,10 +489,12 @@ class format_decoder { @param other The decoder moved from, which keeps its format. */ // The format is copied, so that the moved-from decoder still converts (Review Focus 5). - // NOLINTNEXTLINE(performance-move-constructor-init) + // NOLINTBEGIN(performance-move-constructor-init,cert-oop11-cpp) format_decoder(format_decoder&& other) noexcept(nothrow_move) : format_(other.format_), stream_(std::move(other.stream_)) {} + // NOLINTEND(performance-move-constructor-init,cert-oop11-cpp) + /** Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. @@ -757,8 +767,8 @@ template */ template [[nodiscard]] auto encoder(F const& format_value) noexcept( - detail::nothrow_encoder()) { - return detail::make_encoder(format_value); + detail::nothrow_encoder()) { + return detail::make_encoder(format_value); } /** @@ -771,8 +781,8 @@ template */ template [[nodiscard]] auto encoder(F const& format_value, secret_operation_t /*secret*/) noexcept( - detail::nothrow_encoder()) { - return detail::make_encoder(format_value); + detail::nothrow_encoder()) { + return detail::make_encoder(format_value); } /** @@ -789,8 +799,8 @@ template */ template [[nodiscard]] auto decoder(F const& format_value) noexcept( - detail::nothrow_decoder()) { - return detail::make_decoder(format_value); + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); } /** @@ -803,8 +813,8 @@ template */ template [[nodiscard]] auto decoder(F const& format_value, secret_operation_t /*secret*/) noexcept( - detail::nothrow_decoder()) { - return detail::make_decoder(format_value); + detail::nothrow_decoder()) { + return detail::make_decoder(format_value); } /** diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index 6ade5c1..8bb3477 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -35,38 +35,40 @@ #include #include -namespace webcpp::codecs::test { +namespace holding_formats { +namespace { /** The type of the format holding_letters, of this test's own: whole_letters' codec, and a stream decoder that declares that it holds its input and gives what it read, as bech32's and the armor's do; its streams are letters'. */ -struct holding_letters_t : whole_letters_t { +struct holding_letters_t : webcpp::codecs::test::whole_letters_t { /** The format's name. */ static constexpr std::string_view name = "holding_letters"; }; /** The format holding_letters. */ -inline constexpr holding_letters_t holding_letters{}; +constexpr holding_letters_t holding_letters{}; -} // namespace webcpp::codecs::test +} // namespace +} // namespace holding_formats namespace webcpp::codecs { /** The codec of holding_letters: whole_letters', which takes it as its base. */ template <> -struct codec : codec {}; +struct codec : codec {}; /** The stream codec of holding_letters: letters', its decoder holding and giving its parts. */ template <> -struct stream_codec { +struct stream_codec { /** letters' encoder. */ template class encoder : public stream_codec::encoder { public: /** letters' encoder. */ - explicit encoder(test::holding_letters_t const& /*format*/) noexcept + explicit encoder(holding_formats::holding_letters_t const& /*format*/) noexcept : stream_codec::encoder(test::letters) {} }; @@ -80,7 +82,7 @@ struct stream_codec { static constexpr std::size_t hold = Options.capacity == 0 ? 90 : Options.capacity; /** letters' decoder. */ - explicit decoder(test::holding_letters_t const& /*format*/) noexcept + explicit decoder(holding_formats::holding_letters_t const& /*format*/) noexcept : stream_codec::decoder(test::letters) {} /** The human-readable part it read. */ @@ -166,33 +168,39 @@ static_assert( static_assert( std::same_as>); -static_assert(std::same_as)), - codecs::format_decoder>); static_assert( - std::same_as)), - codecs::format_decoder)), + codecs::format_decoder>); +static_assert( + std::same_as)), + codecs::format_decoder>); static_assert( - std::same_as, + std::same_as, codecs::secret_operation)), - codecs::format_decoder>); -static_assert(codecs::stream_codec::decoder::hold == 8); +/** The options of a public stream that holds 8 letters. */ +constexpr codecs::stream_options hold_of_eight{.capacity = 8}; static_assert( - codecs::stream_codec::decoder::hold == 90); + codecs::stream_codec::decoder::hold == 8); +static_assert(codecs::stream_codec::decoder< + codecs::stream_options{}>::hold == 90); // A decoder forwards what its stream decoder gives after flush, where it has it (B39). static_assert(!gives_label); static_assert(!gives_human_readable_part); static_assert(!gives_label); -static_assert(gives_label); -static_assert(gives_human_readable_part); +static_assert(gives_label); +static_assert( + gives_human_readable_part); /** `size` bytes from a generator of a fixed seed. */ std::vector random_bytes(std::size_t size) { + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) std::mt19937_64 generator{20261126}; std::uniform_int_distribution byte_value{0, 255}; std::vector bytes(size); @@ -292,9 +300,11 @@ boost::system::error_code error_after_flush( void invalid_texts_give_the_one_shot_error_after_flush() { auto decoder = codecs::decoder(test::letters); std::string const high_character{'a', 'b', static_cast(0xc1), 'b'}; - for (std::string_view const text : - {std::string_view{"abq"}, std::string_view{"abc"}, std::string_view{"qbc"}, - std::string_view{"abcdeq"}, std::string_view{high_character}}) { + std::array const texts{ + std::string_view{"abq"}, std::string_view{"abc"}, std::string_view{"qbc"}, + std::string_view{"abcdeq"}, std::string_view{high_character}, + }; + for (std::string_view const text : texts) { auto const one_shot = codecs::decode(test::letters, text); BOOST_TEST(!one_shot.has_value()); test::for_each_chunking( @@ -495,8 +505,10 @@ void transform_is_the_buffer_form() { // A format that does not stream natively streams through buffered (D20). auto whole = codecs::buffered(codecs::encoder(test::whole_letters)); - std::array const, 2> const chunks{std::span{bytes}.first(1), - std::span{bytes}.subspan(1)}; + std::array const, 2> const chunks{ + std::span{bytes}.first(1), + std::span{bytes}.subspan(1), + }; auto const streamed = test::stream_whole(whole, std::span{chunks}, 1); BOOST_TEST(streamed.has_value() && std::string_view(streamed->data(), streamed->size()) == "abcdpo"); @@ -646,7 +658,7 @@ void a_secret_transformer_runs_the_secret_arithmetic() { (B39, B47). */ void a_holding_decoder_gives_what_it_read() { - auto decoder = codecs::decoder(test::holding_letters, codecs::capacity<8>); + auto decoder = codecs::decoder(holding_formats::holding_letters, codecs::capacity<8>); std::array const, 1> const chunks{characters_of("abcd")}; auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); diff --git a/test/support/chunkings.hpp b/test/support/chunkings.hpp index c0ee295..a48822c 100644 --- a/test/support/chunkings.hpp +++ b/test/support/chunkings.hpp @@ -82,8 +82,11 @@ void for_each_chunking(std::span input, Callback callback) { if (second_cut < first_cut) { continue; } - chunks = {input.first(first_cut), input.subspan(first_cut, second_cut - first_cut), - input.subspan(second_cut)}; + chunks = { + input.first(first_cut), + input.subspan(first_cut, second_cut - first_cut), + input.subspan(second_cut), + }; call_back(); } } @@ -93,9 +96,13 @@ void for_each_chunking(std::span input, Callback callback) { } call_back(); + // A fixed seed, so that every lane and every run sees the same chunkings. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) std::mt19937_64 generator{20261126}; std::uniform_int_distribution chunk_size{ - 0, std::max(4, input.size() / 8)}; + 0, + std::max(4, input.size() / 8), + }; for (int chunking = 0; chunking < 32; ++chunking) { chunks.clear(); std::size_t position = 0; From f3c46393ac0c22632c1c08d13a0844ead164b761 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:15:58 -0300 Subject: [PATCH 061/157] codecs: a fault of the format's configuration through codec's optional configuration_fault, checked first by every form, a chain's the outer link's else the inner link's, and reported by a stream's first call until it is gone --- .../webcpp/codecs/detail/core/contract.hpp | 100 +++++ .../codecs/detail/core/format_transformer.hpp | 103 +++-- .../webcpp/codecs/detail/core/operations.hpp | 60 ++- include/webcpp/codecs/detail/core/over.hpp | 49 ++- include/webcpp/codecs/detail/core/secrecy.hpp | 12 - include/webcpp/codecs/detail/core/sizes.hpp | 34 +- test/format_transformer_test.cpp | 356 ++++++++++++++++-- test/messages/Jamfile | 1 + .../refused_configuration_fault/Jamfile | 16 + .../refused_configuration_fault.cpp | 79 ++++ .../refused_secret_overload.cpp | 7 +- .../refused_secret_parameters.cpp | 7 +- test/over_test.cpp | 4 +- test/support/letters.hpp | 67 ++-- 14 files changed, 739 insertions(+), 156 deletions(-) create mode 100644 test/messages/refused_configuration_fault/Jamfile create mode 100644 test/messages/refused_configuration_fault/refused_configuration_fault.cpp diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index ca4859b..ddacf70 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,26 @@ namespace webcpp::codecs { refused with @ref error::input_too_long before it is read. When a data error is found, the one with the lowest value of @ref error is reported. + Two kinds of function are optional. A format whose arithmetic differs when the operation is + secret (base58's) also has overloads of `encoded_size`, `decoded_size`, `encode` or `decode` that + take `detail::secret_tag` first, which the core calls in a secret operation (ruling R7). A format + that has a configuration (a human-readable part, a label, an option) also has the function that + checks it: + + @code + // The fault of format_value's configuration, std::nullopt when it has none. + static constexpr std::optional configuration_fault( + formats::bech32_t const& format_value) noexcept; + @endcode + + The core calls it first in every form, before any size check and any data, and returns its + error unchanged, so that a fault of the configuration wins over every data error; a stream + transformer reports it from its first call, whatever it is, and from every call after, and gives + its links nothing. The other functions of the codec are called only for a format whose + configuration has no fault, and check nothing of it. A codec without the function is of a format + that has no configuration. One of another signature (another parameter, another result, not + `noexcept`) stops the build. + Each function takes the parameter types written above, which D3 names: `std::span` for the bytes read, `std::string_view` for the text read, `std::span` and `std::span` for the output, never a deduced template @@ -270,6 +291,85 @@ namespace detail { template concept has_codec = requires { sizeof(codec); }; +/** + An argument that converts to any type, which a probe passes where the core's own argument might + not convert to a parameter: unevaluated, never defined. +*/ +struct any_argument { + /** Converts to any type, a reference to `const` included. */ + template + // The probe's argument converts to anything, which is its purpose. + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + operator T() const noexcept; +}; + +/** + Whether `codec` has a `configuration_fault` of one argument, of any parameter and any result: + one the core's argument does not convert to is found too, so that it cannot be passed over. +*/ +template +concept takes_configuration_fault = requires { codec::configuration_fault(any_argument{}); }; + +/** + Whether `codec` has the `configuration_fault` of the contract: it takes the format, is + `noexcept`, and gives a `std::optional`. +*/ +template +concept has_configuration_fault = requires(F const& format_value) { + { codec::configuration_fault(format_value) } noexcept -> std::same_as>; +}; + +/** + Stops the build when `codec` has a `configuration_fault` of another signature than the + contract's: it would otherwise be passed over, and a fault of the configuration never reported. +*/ +template +constexpr void check_configuration_fault() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(!webcpp::codecs::detail::takes_configuration_fault || + webcpp::codecs::detail::has_configuration_fault, + "webcpp::codecs: a codec's configuration_fault takes the format by reference to " + "const, is noexcept and returns std::optional"); +} + +/** + How the core asks a format for the fault of its configuration: `codec::configuration_fault` + where the codec has it, else none. `over` specializes it for every chain, a chain of a value + codec's link included, as its links' faults (over.hpp). + + @tparam F The format's type. +*/ +template +struct configuration_probe { + /** + The fault of `format_value`'s configuration. + + @param format_value The format. + @return The fault, or `std::nullopt` when the format's configuration has none or the format + has no configuration. + */ + [[nodiscard]] static constexpr std::optional fault( + [[maybe_unused]] F const& format_value) noexcept { + if constexpr (has_codec) { + check_configuration_fault(); + if constexpr (has_configuration_fault) { + return codec::configuration_fault(format_value); + } + } + return std::nullopt; + } +}; + +/** + The fault of `format_value`'s configuration, which every form of the core checks first, before + any size check and any data, so that it wins over every data error (B23). +*/ +template +[[nodiscard]] constexpr std::optional configuration_fault_of( + F const& format_value) noexcept { + return configuration_probe::fault(format_value); +} + /** Whether `T` is a byte result the core builds: a string, a vector or an array of bytes. */ template struct byte_result_type : std::false_type {}; diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index a2f2399..e61ea21 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -63,13 +64,16 @@ struct stream_options { Each is a `stream_transformer` constructed from the format's value (`formats::hex_t const&`), with `input_type` and `output_type` as written above and every call `noexcept`. It keeps the format's minimal pending state and nothing else, and reads the caller's input and writes the - caller's output as the protocol says (D18). The error rules every stream codec keeps (D18, B23, - B44): a fault of the format's configuration is checked before any data and reported by the first - call, whatever it is; a fault of the data is reported once, after `flush`, by the first call that - has processed the whole input (`flush` itself when nothing is still borrowed, otherwise the - `receive` that reaches the end), and it is the error the one-shot form reports for the same whole - input; that call writes nothing, the verdict running over everything still borrowed before the - tail is written; after an error every call returns it until `reset`. A moved-from encoder or + caller's output as the protocol says (D18). A fault of the format's configuration is not the + stream codec's to find: the transformer asks the codec's `configuration_fault` when it is made and + reports the fault from its first call, whatever it is, and from every call after, never calling + the stream codec's encoder or decoder, which may be made from such a format and check nothing of + it. The error rules every stream codec keeps (D18, B23, B44): a fault of the data is reported + once, after `flush`, by the first call that has processed the whole input (`flush` itself when + nothing is still borrowed, otherwise the `receive` that reaches the end), and it is the error the + one-shot form reports for the same whole input; that call writes nothing, the verdict running + over everything still borrowed before the tail is written; after an error every call returns it + until `reset`. A moved-from encoder or decoder is in the state `reset` leaves. A decoder that holds its input until its verdict (bech32's) declares @@ -206,9 +210,13 @@ constexpr void refuse_hold() noexcept { The stream members, `send`, `receive`, `flush` and `reset`, exist when `stream_codec` is specialized and forward to its `encoder`, which keeps the protocol (D18) and its error - rules. A move copies the format and moves the stream state, whose own move leaves the moved-from - state as `reset` does, so that the moved-from encoder converts a new input from the start (Review - Focus 5). It is copyable when the stream state is. + rules. A fault of the format's configuration (its codec's `configuration_fault`, asked when the + encoder is made) comes first in every form: `transform` returns it, `output_size` is 0, and + `send`, `receive` and `flush` return it from the first call, whatever it is, and from every call + after, also after `reset`, giving the stream encoder nothing (B23). A move copies the format and + moves the stream state, whose own move leaves the moved-from state as `reset` does, so that the + moved-from encoder converts a new input from the start (Review Focus 5). It is copyable when the + stream state is. It is constant time when `codec` is, and `noexcept` in every call but the ones that allocate (`over`'s encode with a heap intermediate, owner decision 24). @@ -260,7 +268,9 @@ class format_encoder { explicit format_encoder(Format format_value) noexcept( std::is_nothrow_move_constructible_v && std::is_nothrow_constructible_v) - : format_(std::move(format_value)), stream_(format_) {} + : format_(std::move(format_value)), + configuration_fault_(detail::configuration_fault_of(format_)), + stream_(format_) {} /** Copies `other`'s format and stream state, when the stream state is copyable. @@ -285,7 +295,9 @@ class format_encoder { // The format is copied, so that the moved-from encoder still converts (Review Focus 5). // NOLINTBEGIN(performance-move-constructor-init,cert-oop11-cpp) format_encoder(format_encoder&& other) noexcept(nothrow_move) - : format_(other.format_), stream_(std::move(other.stream_)) {} + : format_(other.format_), + configuration_fault_(other.configuration_fault_), + stream_(std::move(other.stream_)) {} // NOLINTEND(performance-move-constructor-init,cert-oop11-cpp) @@ -298,6 +310,7 @@ class format_encoder { format_encoder& operator=(format_encoder&& other) noexcept(nothrow_move_assignment) { if (this != &other) { format_ = other.format_; + configuration_fault_ = other.configuration_fault_; stream_ = std::move(other.stream_); } return *this; @@ -318,7 +331,8 @@ class format_encoder { /** The exact size of the text `transform` writes for `input`: `codec::encoded_size`, or 0 - for an input whose encoding does not fit, which `transform` refuses. + for an input `transform` refuses before it reads it: a fault of the format's configuration, + or an input whose encoding does not fit. @param input The bytes. @return The characters. @@ -326,7 +340,7 @@ class format_encoder { [[nodiscard]] std::size_t output_size(std::span input) const noexcept(detail::codec_encoded_size_is_noexcept>()) { - if (detail::input_size_fault(format_, input.size())) { + if (configuration_fault_ || detail::input_size_fault(format_, input.size())) { return 0; } return detail::codec_encoded_size(format_, input); @@ -347,7 +361,8 @@ class format_encoder { } /** - Gives `input` to the stream encoder, which borrows it as the protocol says. + Gives `input` to the stream encoder, which borrows it as the protocol says; returns the fault + of the format's configuration instead, when it has one. @param input The bytes to encode. @return The bytes accepted and the state after, or the error. @@ -355,6 +370,9 @@ class format_encoder { [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.send(input); } @@ -367,6 +385,9 @@ class format_encoder { [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.receive(output); } @@ -379,10 +400,16 @@ class format_encoder { [[nodiscard]] result flush() noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.flush(); } - /** Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error. */ + /** + Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error; a + fault of the format's configuration stays, as the format does. + */ void reset() noexcept requires streams { @@ -392,6 +419,8 @@ class format_encoder { private: /** The format. */ Format format_; + /** The fault of the format's configuration, which every stream call returns. */ + std::optional configuration_fault_; /** The stream encoder's state, made from the format. */ stream_type stream_; }; @@ -412,7 +441,10 @@ class format_encoder { The stream members, `send`, `receive`, `flush` and `reset`, exist when `stream_codec` is specialized and forward to its `decoder`, which keeps the protocol (D18) and its error - rules; `human_readable_part()` and `label()` exist when that decoder has them (B39). A move + rules; `human_readable_part()` and `label()` exist when that decoder has them (B39). A fault of + the format's configuration comes first in every form, as for @ref format_encoder: `transform` + returns it, `output_size` is 0, and the stream calls return it from the first, whatever it is, + and from every call after, also after `reset`, giving the stream decoder nothing (B23). A move copies the format and moves the stream state, so that the moved-from decoder converts a new input from the start (Review Focus 5). It is copyable when the stream state is. @@ -466,7 +498,9 @@ class format_decoder { explicit format_decoder(Format format_value) noexcept( std::is_nothrow_move_constructible_v && std::is_nothrow_constructible_v) - : format_(std::move(format_value)), stream_(format_) {} + : format_(std::move(format_value)), + configuration_fault_(detail::configuration_fault_of(format_)), + stream_(format_) {} /** Copies `other`'s format and stream state, when the stream state is copyable. @@ -491,7 +525,9 @@ class format_decoder { // The format is copied, so that the moved-from decoder still converts (Review Focus 5). // NOLINTBEGIN(performance-move-constructor-init,cert-oop11-cpp) format_decoder(format_decoder&& other) noexcept(nothrow_move) - : format_(other.format_), stream_(std::move(other.stream_)) {} + : format_(other.format_), + configuration_fault_(other.configuration_fault_), + stream_(std::move(other.stream_)) {} // NOLINTEND(performance-move-constructor-init,cert-oop11-cpp) @@ -504,6 +540,7 @@ class format_decoder { format_decoder& operator=(format_decoder&& other) noexcept(nothrow_move_assignment) { if (this != &other) { format_ = other.format_; + configuration_fault_ = other.configuration_fault_; stream_ = std::move(other.stream_); } return *this; @@ -524,7 +561,8 @@ class format_decoder { /** The exact size of the bytes `transform` writes for `input`: `codec::decoded_size`, or - 0 for a text `transform` refuses, which writes nothing. + 0 for a text `transform` refuses, which writes nothing: a fault of the format's + configuration, a text whose bytes do not fit, or a text of a data error. @param input The text. @return The bytes. @@ -532,7 +570,7 @@ class format_decoder { [[nodiscard]] std::size_t output_size(std::span input) const noexcept( detail::codec_decoded_size_is_noexcept()) { std::string_view const text_characters{input.data(), input.size()}; - if (detail::text_size_fault(format_, text_characters.size())) { + if (configuration_fault_ || detail::text_size_fault(format_, text_characters.size())) { return 0; } auto const byte_count = @@ -555,7 +593,8 @@ class format_decoder { } /** - Gives `input` to the stream decoder, which borrows it as the protocol says. + Gives `input` to the stream decoder, which borrows it as the protocol says; returns the fault + of the format's configuration instead, when it has one. @param input The characters to decode. @return The characters accepted and the state after, or the error. @@ -563,6 +602,9 @@ class format_decoder { [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.send(input); } @@ -575,6 +617,9 @@ class format_decoder { [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.receive(output); } @@ -587,10 +632,16 @@ class format_decoder { [[nodiscard]] result flush() noexcept(nothrow_stream) requires streams { + if (configuration_fault_) { + return *configuration_fault_; + } return stream_.flush(); } - /** Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error. */ + /** + Returns the stream to `flow::needs_input`, with nothing borrowed or pending and no error; a + fault of the format's configuration stays, as the format does. + */ void reset() noexcept requires streams { @@ -624,6 +675,8 @@ class format_decoder { private: /** The format. */ Format format_; + /** The fault of the format's configuration, which every stream call returns. */ + std::optional configuration_fault_; /** The stream decoder's state, made from the format. */ stream_type stream_; }; @@ -632,7 +685,9 @@ class format_decoder { The stream of `over` when both links stream natively: the encoder is a pipe of the inner link's encoder and then the outer link's, the decoder a pipe of the outer link's decoder and then the inner link's, each with an intermediate in place of the default capacity - (D11, B43). + (D11, B43). A fault of a link's configuration, the outer link's first, is the chain's own (its + codec's `configuration_fault`): the chain's transformer reports it from its first call and never + calls the pipe, so that it comes before any data of either link. The pipe's rules are the stream's: the first error of either link is the chain's, a call that reports it writes nothing, and a move leaves the moved-from stream as `reset` does; the chain's diff --git a/include/webcpp/codecs/detail/core/operations.hpp b/include/webcpp/codecs/detail/core/operations.hpp index 32f7c21..2cba6a9 100644 --- a/include/webcpp/codecs/detail/core/operations.hpp +++ b/include/webcpp/codecs/detail/core/operations.hpp @@ -263,6 +263,9 @@ template F const& format_value, Input const& input_value, Allocators const&... allocator_values) noexcept(is_fixed_result && encode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } auto const input_view = [&] { if constexpr (value_encodable) { return std::span{}; @@ -376,6 +379,9 @@ template F const& format_value, Text const& text_value, Allocators const&... allocator_values) noexcept(decode_is_fixed && decode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } auto const text_characters = bounded_text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; @@ -469,6 +475,9 @@ template F const& format_value, Input const& input_value, Token& token_object) noexcept(token_is_noexcept && encode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } constexpr bool from_value = value_encodable; auto const input_view = [&] { if constexpr (from_value) { @@ -529,6 +538,9 @@ template F const& format_value, Text const& text_value, Token& token_object) noexcept(token_is_noexcept && decode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } auto const text_characters = bounded_text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; @@ -633,6 +645,9 @@ template [[nodiscard]] result encode_value_into_buffer( F const& format_value, Input const& input_value, std::span output_buffer) noexcept(encode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } std::size_t const output_size = value_encoded_size(format_value, input_value); if (output_buffer.size() < output_size) { return error::output_too_small; @@ -687,10 +702,11 @@ constexpr bool decode_token_is_noexcept() { `secret_byte_vector`), holds secure's timing guard for its duration and runs the format's secret arithmetic where it has one. - It is `noexcept` exactly when the result is held in place, which allocates nothing. An - input whose encoding does not fit in `std::size_t` is @ref error::input_too_long, before it is - read. A value codec of `F` and `Input` is used when it encodes, else `codec`. A pair that is - not @ref encodable stops the build with a message that the format does not convert this type. + It is `noexcept` exactly when the result is held in place, which allocates nothing. A fault of + the format's configuration is returned first (its codec's `configuration_fault`); an input whose + encoding does not fit in `std::size_t` is @ref error::input_too_long, before it is read. A value + codec of `F` and `Input` is used when it encodes, else `codec`. A pair that is not + @ref encodable stops the build with a message that the format does not convert this type. @tparam F The format's type. @tparam Input The input's type: a byte input, or a value of a value codec. @@ -718,8 +734,9 @@ template Encodes `input_value`, a value of a value codec of bytes, in `format_value` into the caller's buffer, allocating nothing. - The checks come first, and on every error nothing is written: an `output_buffer` shorter than - the exact size is @ref error::output_too_small. The bytes are then written at the start of + The checks come first, and on every error nothing is written: a fault of the format's + configuration is returned first (its codec's `configuration_fault`); an `output_buffer` shorter + than the exact size is @ref error::output_too_small. The bytes are then written at the start of `output_buffer`, whose other bytes are unchanged. The errors the value codec returns reach the caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds secure's timing guard while the value codec runs, which runs its overloads that take `detail::secret_tag` @@ -753,8 +770,9 @@ template Encodes `input_value`, a value of a value codec of text, in `format_value` into the caller's buffer, allocating nothing. - The checks come first, and on every error nothing is written: an `output_buffer` shorter than - the exact size is @ref error::output_too_small. The text is then written at the start of + The checks come first, and on every error nothing is written: a fault of the format's + configuration is returned first (its codec's `configuration_fault`); an `output_buffer` shorter + than the exact size is @ref error::output_too_small. The text is then written at the start of `output_buffer`, whose other characters are unchanged. The errors the value codec returns reach the caller unchanged. A secret value (`is_secret_v`, or the value codec's `secret`) holds secure's timing guard while the value codec runs, which runs its overloads that take @@ -786,9 +804,10 @@ encode(F const& format_value, Input const& input_value, std::span output_b `bytes` when the text's size is known at compile time (`text`, a `std::array`), `M` being the format's bound, and `std::vector` otherwise. - It is `noexcept` exactly when the result is a `bytes`, which allocates nothing. A text whose - bytes do not fit in `std::size_t` is @ref error::input_too_long, before it is read; the whole text - is then checked, and its data error with the lowest value of @ref error is returned. A format with + It is `noexcept` exactly when the result is a `bytes`, which allocates nothing. A fault of the + format's configuration is returned first (its codec's `configuration_fault`); a text whose bytes + do not fit in `std::size_t` is @ref error::input_too_long, before it is read; the whole text is + then checked, and its data error with the lowest value of @ref error is returned. A format with no `codec` specialization stops the build with a message that the format does not convert bytes (named `webcpp::codecs::detail::decoded_bytes`). @@ -822,8 +841,9 @@ template `bytes` for a value codec of bytes; `secret` and `secret(allocator)`, D9's secret column, in place when the bound is known at compile time and on the heap of the allocator otherwise) or an object of the token contract of Boost.URL's string tokens, used as given. The result is - `result`. The order is that of the buffer form's: every check of the - input (an input whose encoding does not fit in `std::size_t` is @ref error::input_too_long), then + `result`. The order is that of the buffer form's: a fault of the + format's configuration first, every check of the input (an input whose encoding does not fit in + `std::size_t` is @ref error::input_too_long), then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A token is untouched when a check fails, and a token of codecs' also when the @@ -897,8 +917,9 @@ template by reference; `fixed`, a `bytes`; `secret` and `secret(allocator)`, `secret_bytes` for a text of a size known at compile time and `basic_secret_byte_vector` of the allocator otherwise) or an object of the token contract (a byte token), used as given. The result is `result`. The order is that of the buffer form's: a text whose bytes do not fit in - `std::size_t` is @ref error::input_too_long, the whole text is checked and its data error with the + Token::result_type>`. The order is that of the buffer form's: a fault of the format's + configuration first, a text whose bytes do not fit in `std::size_t` is + @ref error::input_too_long, the whole text is checked and its data error with the lowest value of @ref error returned, then the token's `capacity` against the exact size (@ref error::output_too_small), then one `prepare` with the exact size, the conversion, one `result`. A token is untouched when a check fails, and a token of codecs' also when the conversion fails after @@ -960,8 +981,10 @@ template otherwise), `secure::secret` among them; a `bytes` or a `secret_bytes`, which take up to `N` bytes (@ref error::output_too_small otherwise); a `std::string`, a `std::vector`, a `basic_secret_string` or a `basic_secret_byte_vector`, which take - the heap. It is `noexcept` for the fixed byte results, and for a value codec as the value codec's - `decode` is declared; the heap types allocate and are not. The operation is secret (D10) when + the heap. A fault of the format's configuration is returned first, before any data, in every + case (its codec's `configuration_fault`, or a chain's links'). It is `noexcept` for the fixed + byte results, and for a value codec as the value codec's `decode` is declared; the heap types + allocate and are not. The operation is secret (D10) when `Value`'s `is_secret_v` or the value codec's `secret` says so: it then holds secure's timing guard, runs the format's secret arithmetic where it has one, and wipes the temporary it decodes into before it returns, by `secure::erase_secret`. A pair `F` does not convert stops the build with @@ -982,6 +1005,9 @@ template constexpr bool secret = detail::secret_operation_v; if constexpr (detail::value_decodable) { using value_type = value_codec; + if (auto const configuration_error = detail::configuration_fault_of(format_value)) { + return make_error_code(*configuration_error); + } if constexpr (value_type::output == output_kind::bytes && detail::byte_input) { if constexpr (secret) { secure::timing_guard const timing_scope{true}; diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 6dedffc..1712617 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -91,8 +92,10 @@ struct over_name { `decoded_size` run the inner link into the intermediate (ruling R3): with a heap intermediate they allocate, so those, `encode` and `decode` are not `noexcept` and an exception of the allocator reaches the caller, the buffer forms of the core among them (the one allocating buffer form), - and with a bound known at compile time they are `noexcept` and allocate nothing. `over` stays - one-shot: its stream counterpart is `pipe`. + and with a bound known at compile time they are `noexcept` and allocate nothing. A fault of a + link's configuration is the chain's, the outer link's first: every form reports it before it + reads any data, in either link. Its transformers, `encoder(chain)` and `decoder(chain)`, stream + through a pipe of the links' streams when both links stream natively (format_transformer.hpp). An intermediate in place is held for every bound known at compile time, with no cap, so that `over` with a static bound allocates nothing, as the spec's Allocation requirement says. Its cost @@ -214,6 +217,32 @@ over(Outer, Inner, Allocator) -> over; namespace detail { +/** + The fault of a chain's configuration: the outer link's, else the inner link's, a link that is a + chain asked in turn. It is the core's probe of every chain, of a value codec's link too, which + has no `codec` to ask, so that every form of `over` reports it before it reads any data (B23). + + @tparam Outer The outer link's type. + @tparam Inner The inner link's type. + @tparam Allocator The allocator's type. +*/ +template +struct configuration_probe> { + /** + The fault of `chain`'s configuration. + + @param chain The chain. + @return The outer link's fault, else the inner link's, or `std::nullopt` when neither has one. + */ + [[nodiscard]] static constexpr std::optional fault( + over const& chain) noexcept { + if (std::optional const outer_fault = configuration_fault_of(chain.outer)) { + return outer_fault; + } + return configuration_fault_of(chain.inner); + } +}; + /** The most bytes the intermediate of a link's encode holds when its input holds `Bound`. */ template [[nodiscard]] constexpr std::size_t encoded_bound() noexcept { @@ -527,7 +556,9 @@ template > { : codec::max_decoded_size(middle_size); } + /** + The fault of the chain's configuration, which the core checks before any data: the outer + link's, else the inner link's. + + @param chain The chain. + @return The fault, or `std::nullopt` when neither link's configuration has one. + */ + [[nodiscard]] static constexpr std::optional configuration_fault( + format_type const& chain) noexcept { + return detail::configuration_probe::fault(chain); + } + /** The exact size of the text of `input_view`, the inner link run into the intermediate. diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 0ca13ab..03c10e7 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -200,18 +200,6 @@ struct secret_tag { explicit secret_tag() = default; }; -/** - An argument that converts to any type, which a probe passes where the core's own argument might - not convert to a parameter: unevaluated, never defined. -*/ -struct any_argument { - /** Converts to any type, a reference to `const` included. */ - template - // The probe's argument converts to anything, which is its purpose. - // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) - operator T() const noexcept; -}; - /** Whether `codec` has an `encoded_size` of the arity of the core's call that takes `secret_tag` first, of any parameters after it and any result: an overload the core's arguments do not diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index 65e48bc..bf06376 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -139,12 +139,16 @@ template /** Encodes the bytes of `input_value` into `output_buffer`, with the format's secret arithmetic - where `Secret` and the format has one (R7): the buffer form's checks, then the conversion. + where `Secret` and the format has one (R7): the buffer form's checks, the configuration's first, + then the conversion. */ template [[nodiscard]] result encode_into_buffer( F const& format_value, Input const& input_value, std::span output_buffer) noexcept(encode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } auto const input_view = bounded_input_bytes(input_value); if (auto const size_fault = input_size_fault(format_value, input_view.size())) { return *size_fault; @@ -158,12 +162,16 @@ template /** Decodes `text_value` into `output_buffer`, with the format's secret arithmetic where `Secret` and - the format has one (R7): the buffer form's checks, the whole text checked, then the conversion. + the format has one (R7): the buffer form's checks, the configuration's first, the whole text + checked, then the conversion. */ template [[nodiscard]] result decode_into_buffer( F const& format_value, Text const& text_value, std::span output_buffer) noexcept(decode_calls_are_noexcept()) { + if (auto const configuration_error = configuration_fault_of(format_value)) { + return *configuration_error; + } auto const text_characters = bounded_text_view(text_value); if (auto const size_fault = text_size_fault(format_value, text_characters.size())) { return *size_fault; @@ -247,10 +255,11 @@ template /** Encodes `input_value` in `format_value` into the caller's buffer, allocating nothing. - The checks come first, and on every error nothing is written: an input whose encoding does not - fit in `std::size_t` is @ref error::input_too_long, before it is read; an `output_buffer` shorter - than the exact size is @ref error::output_too_small. The text is then written at the start of - `output_buffer`, whose other characters are unchanged. + The checks come first, and on every error nothing is written: a fault of the format's + configuration is returned first, as its codec's `configuration_fault` gives it; an input whose + encoding does not fit in `std::size_t` is @ref error::input_too_long, before it is read; an + `output_buffer` shorter than the exact size is @ref error::output_too_small. The text is then + written at the start of `output_buffer`, whose other characters are unchanged. A secret input (`is_secret_v`, as `secure::secret`) makes the operation secret: it holds secure's timing guard and runs the format's secret arithmetic where it has one (D10). A format @@ -286,12 +295,13 @@ encode(F const& format_value, Input const& input_value, std::span output_b /** Decodes `text_value` in `format_value` into the caller's buffer, allocating nothing. - The checks come first, and on every error nothing is written: a text whose bytes do not fit in - `std::size_t` is @ref error::input_too_long, before it is read; then the whole text is checked, - and its data error with the lowest value of @ref error is returned; then an `output_buffer` - shorter than the exact size is @ref error::output_too_small. The bytes are then written at the - start of `output_buffer`, whose other bytes are unchanged. Where the format's page says so, - `output_buffer` may be the text's own storage. + The checks come first, and on every error nothing is written: a fault of the format's + configuration is returned first, as its codec's `configuration_fault` gives it; a text whose + bytes do not fit in `std::size_t` is @ref error::input_too_long, before it is read; then the + whole text is checked, and its data error with the lowest value of @ref error is returned; then + an `output_buffer` shorter than the exact size is @ref error::output_too_small. The bytes are + then written at the start of `output_buffer`, whose other bytes are unchanged. Where the + format's page says so, `output_buffer` may be the text's own storage. A format with no `codec` specialization stops the build with a message that the format does not convert bytes (named `webcpp::codecs::detail::decoded_bytes`). diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index 8bb3477..ce97ab1 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -14,6 +14,7 @@ // transformer runs the format's secret arithmetic (R7); a decoder that holds takes a capacity and // gives what it read (B39). The refusals are message cases (test/messages). +#include "support/be16.hpp" #include "support/chunkings.hpp" #include "support/letters.hpp" #include "support/tagged_letters.hpp" @@ -27,10 +28,13 @@ #include #include #include +#include +#include #include #include #include #include +#include #include #include #include @@ -410,42 +414,288 @@ void the_call_that_fails_writes_nothing() { BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); } +// A codec's configuration_fault is optional: letters' and every chain's have it, whole_letters' +// has none (D3); the core asks a chain of a value codec's link through its links (B23). +static_assert(codecs::detail::has_configuration_fault); +static_assert(!codecs::detail::takes_configuration_fault); +static_assert(codecs::detail::has_configuration_fault); +static_assert(codecs::detail::has_configuration_fault); +static_assert(!codecs::detail::has_codec>); +static_assert(noexcept(codecs::detail::configuration_fault_of(test::letters))); +static_assert(codecs::detail::configuration_fault_of(test::letters(true)) == + codecs::error::invalid_prefix); +static_assert(!codecs::detail::configuration_fault_of(test::letters).has_value()); +static_assert(!codecs::detail::configuration_fault_of(test::whole_letters).has_value()); +static_assert(codecs::detail::configuration_fault_of(codecs::over{test::letters, test::be16}) == + std::nullopt); +static_assert(codecs::detail::configuration_fault_of(codecs::over{ + test::letters, codecs::over{test::letters(true), test::letters}}) == + codecs::error::invalid_prefix); + +/** The error of a fault of letters' configuration. */ +constexpr codecs::error configured_fault = codecs::error::invalid_prefix; + +/** Whether `outcome` failed with the fault of the configuration. */ +template +bool is_configured_fault(Result const& outcome) { + return !outcome.has_value() && outcome.error() == configured_fault; +} + /** - A fault of the format's configuration is reported by the first call, before any data, whatever - the call, and wins over a data fault, in the stream form and the one-shot form (B23). + Every one-shot form of `format`, a format whose configuration is at fault, returns the fault, and + writes nothing and leaves its token as it was: the encodes of bytes into the default results, a + buffer too small and one large enough, and every token; the decodes of each of `texts`, valid + ones and ones of a data error, into the default result, a buffer, every token and the typed + results whose own checks would fail; and `transform` and `output_size` of its transformers (B23). */ -void a_configuration_fault_comes_first() { - std::array const bytes{1, 2, 3}; - std::array text_buffer{}; - BOOST_TEST(codecs::encode(test::letters(true), bytes).error() == codecs::error::invalid_prefix); - BOOST_TEST(codecs::decode(test::letters(true), std::string_view{"abq"}).error() == - codecs::error::invalid_prefix); - - auto encoder = codecs::encoder(test::letters(true)); - auto const transformed = encoder.transform(bytes, text_buffer); - BOOST_TEST(!transformed.has_value() && transformed.error() == codecs::error::invalid_prefix); - auto const sent = encoder.send(bytes); - BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_prefix); - encoder.reset(); - auto const flushed = encoder.flush(); - BOOST_TEST(!flushed.has_value() && flushed.error() == codecs::error::invalid_prefix); - encoder.reset(); - auto const received = encoder.receive(text_buffer); - BOOST_TEST(!received.has_value() && received.error() == codecs::error::invalid_prefix); - - auto decoder = codecs::decoder(test::letters(true)); - std::array byte_buffer{}; - auto const decoded = decoder.transform(characters_of("abq"), byte_buffer); - BOOST_TEST(!decoded.has_value() && decoded.error() == codecs::error::invalid_prefix); - auto const decoder_sent = decoder.send(characters_of("abq")); - BOOST_TEST(!decoder_sent.has_value() && decoder_sent.error() == codecs::error::invalid_prefix); - auto const decoder_flushed = decoder.flush(); - BOOST_TEST(!decoder_flushed.has_value() && - decoder_flushed.error() == codecs::error::invalid_prefix); - decoder.reset(); - auto const decoder_received = decoder.receive(byte_buffer); - BOOST_TEST(!decoder_received.has_value() && - decoder_received.error() == codecs::error::invalid_prefix); +template +void expect_the_fault_in_every_one_shot_form(Format const& format, + std::span texts) { + std::array const bytes{0x01, 0x23, 0xfe}; + std::vector const heap_bytes(bytes.begin(), bytes.end()); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes))); + BOOST_TEST(is_configured_fault(codecs::encode(format, heap_bytes))); + std::array text_buffer{}; + text_buffer.fill('x'); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, std::span{text_buffer}))); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, std::span{text_buffer}.first(1)))); + BOOST_TEST(std::ranges::all_of(text_buffer, [](char character) { return character == 'x'; })); + std::string appended{"kept"}; + BOOST_TEST( + is_configured_fault(codecs::encode(format, bytes, codecs::tokens::append_to(appended)))); + BOOST_TEST_EQ(appended, "kept"); + std::string assigned{"kept"}; + BOOST_TEST( + is_configured_fault(codecs::encode(format, bytes, codecs::tokens::assign_to(assigned)))); + BOOST_TEST_EQ(assigned, "kept"); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::return_string))); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::fixed<1>{}))); + BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::secret))); + BOOST_TEST(is_configured_fault(codecs::encode(format, heap_bytes, codecs::tokens::secret))); + auto const encoder = codecs::encoder(format); + BOOST_TEST(is_configured_fault(encoder.transform(bytes, text_buffer))); + BOOST_TEST(std::ranges::all_of(text_buffer, [](char character) { return character == 'x'; })); + BOOST_TEST_EQ(encoder.output_size(bytes), 0U); + auto const secret_encoder = codecs::encoder(format, codecs::secret_operation); + BOOST_TEST(is_configured_fault(secret_encoder.transform(bytes, text_buffer))); + + for (std::string_view const text : texts) { + BOOST_TEST(is_configured_fault(codecs::decode(format, text))); + std::array byte_buffer{}; + byte_buffer.fill(0x5a); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}))); + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}.first(0)))); + BOOST_TEST( + std::ranges::all_of(byte_buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector appended_bytes{0x5a}; + BOOST_TEST(is_configured_fault( + codecs::decode(format, text, codecs::tokens::append_to(appended_bytes)))); + BOOST_TEST(appended_bytes == std::vector{0x5a}); + std::vector assigned_bytes{0x5a}; + BOOST_TEST(is_configured_fault( + codecs::decode(format, text, codecs::tokens::assign_to(assigned_bytes)))); + BOOST_TEST(assigned_bytes == std::vector{0x5a}); + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, codecs::tokens::return_string))); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::fixed<1>{}))); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::secret))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, std::allocator{}))); + auto const decoder = codecs::decoder(format); + BOOST_TEST(is_configured_fault(decoder.transform(characters_of(text), byte_buffer))); + BOOST_TEST( + std::ranges::all_of(byte_buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST_EQ(decoder.output_size(characters_of(text)), 0U); + auto const secret_decoder = codecs::decoder(format, codecs::secret_operation); + BOOST_TEST(is_configured_fault(secret_decoder.transform(characters_of(text), byte_buffer))); + } +} + +/** + A fault of the format's configuration is checked first and wins over every data error, in every + one-shot form (B23): of letters(true), of a chain whose outer link's configuration is at fault and + of one whose inner link's is, the texts of the outer link's data error and of the inner link's + included, of a chain of chains, and of a chain of a value codec's link. Each text gives its data + error where no configuration is at fault, which the fault then beats. +*/ +void a_configuration_fault_wins_in_every_one_shot_form() { + std::string const inner_invalid_character = + codecs::encode(test::letters, std::string_view{"abq"}).value(); + std::string const inner_invalid_length = + codecs::encode(test::letters, std::string_view{"abc"}).value(); + std::string const inner_valid = codecs::encode(test::letters, std::string_view{"abcd"}).value(); + letters_over_letters const chain{test::letters, test::letters}; + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abq"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abc"}).error() == + codecs::error::invalid_length); + BOOST_TEST(codecs::decode(chain, std::string_view{"abq"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(chain, inner_invalid_character).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(chain, inner_invalid_length).error() == + codecs::error::invalid_length); + + std::array const letters_texts{"abq", "abc", "abcd"}; + expect_the_fault_in_every_one_shot_form(test::letters(true), letters_texts); + + std::array const chain_texts{ + "abq", + inner_invalid_character, + inner_invalid_length, + inner_valid, + }; + expect_the_fault_in_every_one_shot_form( + letters_over_letters{test::letters(true), test::letters}, chain_texts); + expect_the_fault_in_every_one_shot_form( + letters_over_letters{test::letters, test::letters(true)}, chain_texts); + expect_the_fault_in_every_one_shot_form( + codecs::over{test::letters, letters_over_letters{test::letters, test::letters(true)}}, + chain_texts); + expect_the_fault_in_every_one_shot_form( + codecs::over{letters_over_letters{test::letters, test::letters(true)}, test::letters}, + chain_texts); + + // A chain of a value codec's link, which has no codec: its outer link's fault comes first, in + // the encode of a value into the default result, a buffer and a token, and in its typed decode. + auto const value_chain = codecs::over{test::letters(true), test::be16}; + BOOST_TEST( + codecs::decode(codecs::over{test::letters, test::be16}, "bcdebz").error() == + codecs::error::invalid_character); + BOOST_TEST(is_configured_fault(codecs::encode(value_chain, test::number{0x1234}))); + std::array value_text{}; + value_text.fill('x'); + BOOST_TEST(is_configured_fault( + codecs::encode(value_chain, test::number{0x1234}, std::span{value_text}))); + BOOST_TEST(std::ranges::all_of(value_text, [](char character) { return character == 'x'; })); + std::string value_appended{"kept"}; + BOOST_TEST(is_configured_fault(codecs::encode(value_chain, test::number{0x1234}, + codecs::tokens::append_to(value_appended)))); + BOOST_TEST_EQ(value_appended, "kept"); + BOOST_TEST(is_configured_fault( + codecs::encode(value_chain, test::number{0x1234}, codecs::tokens::secret))); + for (std::string_view const text : {std::string_view{"bcde"}, std::string_view{"bcdebz"}}) { + BOOST_TEST(is_configured_fault(codecs::decode(value_chain, text))); + } +} + +/** + Every stream call of `transformer`, a transformer of a format whose configuration is at fault, + returns the fault and writes nothing, twice over and again after `reset`: `send` of `input`, + `receive` and `flush`, whatever the order (B23). +*/ +template +void expect_the_fault_from_every_stream_call( + Transformer& transformer, std::span input) { + using output_type = Transformer::output_type; + std::array output{}; + output.fill(static_cast(0x5a)); + for (int round = 0; round < 2; ++round) { + BOOST_TEST(is_configured_fault(transformer.send(input))); + BOOST_TEST(is_configured_fault(transformer.receive(output))); + BOOST_TEST(is_configured_fault(transformer.flush())); + BOOST_TEST(is_configured_fault(transformer.receive(output))); + BOOST_TEST(is_configured_fault(transformer.send(input))); + BOOST_TEST(is_configured_fault(transformer.flush())); + transformer.reset(); + } + BOOST_TEST(std::ranges::all_of( + output, [](output_type element) { return element == static_cast(0x5a); })); +} + +/** + The first stream call of a fresh transformer that `make` gives, `send`, `receive`, `flush` or one + after `reset`, returns the fault of the configuration, and so does every call after it, of the + transformer, of the one moved to and of the one moved from, for every chunking of `input` and + through `drain` (B23). +*/ +template +void expect_the_fault_from_the_first_stream_call( + Make make, std::span input) { + using output_type = decltype(make())::output_type; + std::array output{}; + auto by_send = make(); + BOOST_TEST(is_configured_fault(by_send.send(input))); + expect_the_fault_from_every_stream_call(by_send, input); + auto by_receive = make(); + BOOST_TEST(is_configured_fault(by_receive.receive(output))); + expect_the_fault_from_every_stream_call(by_receive, input); + auto by_flush = make(); + BOOST_TEST(is_configured_fault(by_flush.flush())); + expect_the_fault_from_every_stream_call(by_flush, input); + auto by_reset = make(); + by_reset.reset(); + BOOST_TEST(is_configured_fault(by_reset.send(input))); + + // A moved-to transformer and the moved-from one keep the format, and its fault. + auto moved_to{std::move(by_send)}; + expect_the_fault_from_every_stream_call(moved_to, input); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from transformer keeps its format + expect_the_fault_from_every_stream_call(by_send, input); + by_receive = std::move(moved_to); + expect_the_fault_from_every_stream_call(by_receive, input); + + // Every chunking ends in the fault at the first call, and drain reports it. + test::for_each_chunking( + input, [&](std::span const> chunks) { + by_flush.reset(); + auto const streamed = test::stream_whole(by_flush, chunks, 4); + BOOST_TEST(is_configured_fault(streamed)); + }); + auto drained = make(); + BOOST_TEST(is_configured_fault(drained.send(input))); + BOOST_TEST(is_configured_fault(codecs::drain(drained, [](auto /*piece*/) noexcept {}))); +} + +/** + A fault of the format's configuration is reported by a stream's first call, whatever it is, and + by every call until the transformer is gone, `reset` changing nothing, and nothing reaches the + stream codec (B23): of letters(true), and of a chain whose outer link's configuration is at fault + or whose inner link's is, which the pipe of the links would otherwise report later (the inner + link's fault at the first receive, the outer link's data error before the inner link's fault). +*/ +void a_configuration_fault_comes_from_the_first_stream_call() { + std::vector const bytes = random_bytes(40); + std::string const valid = codecs::encode(test::letters, bytes).value(); + std::string const inner_invalid_length = + codecs::encode(test::letters, std::string_view{"abc"}).value(); + std::array const texts{"abq", "abc", valid, inner_invalid_length}; + + auto const formats = std::make_tuple( + test::letters(true), letters_over_letters{test::letters(true), test::letters}, + letters_over_letters{test::letters, test::letters(true)}, + codecs::over{test::letters, letters_over_letters{test::letters, test::letters(true)}}); + std::apply( + [&](auto const&... format) { + (expect_the_fault_from_the_first_stream_call([&] { return codecs::encoder(format); }, + bytes_of(bytes)), + ...); + (expect_the_fault_from_the_first_stream_call( + [&] { return codecs::encoder(format, codecs::secret_operation); }, + bytes_of(bytes)), + ...); + for (std::string_view const text : texts) { + (expect_the_fault_from_the_first_stream_call( + [&] { return codecs::decoder(format); }, characters_of(text)), + ...); + } + }, + formats); + + // The cases a pipe of the links alone got wrong: the inner link's fault surfaced at the first + // receive, after {n, output_pending}; the outer link's data error beat the inner link's fault. + auto encoder = codecs::encoder(letters_over_letters{test::letters(true), test::letters}); + BOOST_TEST(is_configured_fault(encoder.send(bytes_of(bytes)))); + auto decoder = codecs::decoder(letters_over_letters{test::letters, test::letters(true)}); + BOOST_TEST(is_configured_fault(decoder.send(characters_of("abq")))); + BOOST_TEST(is_configured_fault(decoder.flush())); + std::array output{}; + BOOST_TEST(is_configured_fault(decoder.receive(output))); } /** @@ -503,6 +753,26 @@ void transform_is_the_buffer_form() { BOOST_TEST_EQ(decoder.output_size(characters_of("abcdpo")), 3U); BOOST_TEST_EQ(decoder.output_size(characters_of("abq")), 0U); + // Empty spans: transform writes nothing and returns 0, of the encoder and of the decoder, of a + // format and of a chain, public and secret (Review Focus 3). + std::span const no_bytes; + std::span const no_characters; + BOOST_TEST(encoder.transform(no_bytes, std::span{}).value() == 0); + BOOST_TEST(decoder.transform(no_characters, std::span{}).value() == 0); + BOOST_TEST(codecs::encoder(test::letters, codecs::secret_operation) + .transform(no_bytes, std::span{}) + .value() == 0); + BOOST_TEST(codecs::decoder(test::letters, codecs::secret_operation) + .transform(no_characters, std::span{}) + .value() == 0); + letters_over_letters const empty_chain{test::letters, test::letters}; + BOOST_TEST(codecs::encoder(empty_chain).transform(no_bytes, std::span{}).value() == 0); + BOOST_TEST( + codecs::decoder(empty_chain).transform(no_characters, std::span{}).value() == + 0); + BOOST_TEST_EQ(encoder.output_size(no_bytes), 0U); + BOOST_TEST_EQ(decoder.output_size(no_characters), 0U); + // A format that does not stream natively streams through buffered (D20). auto whole = codecs::buffered(codecs::encoder(test::whole_letters)); std::array const, 2> const chunks{ @@ -530,16 +800,21 @@ void over_streams_through_a_pipe() { expect_every_chunking(encoder, bytes_of(bytes), text.value()); expect_every_chunking(decoder, characters_of(text.value()), bytes); } - // The outer link's error, and the inner link's: "abq" is the letters of "abq" over letters. - std::string const inner_fault = codecs::encode(test::letters, std::string_view{"abq"}).value(); - for (std::string_view const text : {std::string_view{"abq"}, std::string_view{inner_fault}}) { + // The outer link's error, invalid_character of "abq", and the inner link's, invalid_length of + // the letters of "abc": the errors differ, so that each shows which link reported it. + std::string const inner_fault = codecs::encode(test::letters, std::string_view{"abc"}).value(); + std::array, 2> const faults{{ + {std::string_view{"abq"}, codecs::error::invalid_character}, + {std::string_view{inner_fault}, codecs::error::invalid_length}, + }}; + for (auto const& [text, expected_error] : faults) { auto const one_shot = codecs::decode(chain, text); - BOOST_TEST(!one_shot.has_value()); + BOOST_TEST(!one_shot.has_value() && one_shot.error() == expected_error); test::for_each_chunking( characters_of(text), [&](std::span const> chunks) { decoder.reset(); auto const streamed = test::stream_whole(decoder, chunks, 3); - BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); + BOOST_TEST(!streamed.has_value() && streamed.error() == expected_error); }); } @@ -675,7 +950,8 @@ int main() { invalid_texts_give_the_one_shot_error_after_flush(); send_while_output_is_pending(); the_call_that_fails_writes_nothing(); - a_configuration_fault_comes_first(); + a_configuration_fault_wins_in_every_one_shot_form(); + a_configuration_fault_comes_from_the_first_stream_call(); an_error_stays_until_reset(); transform_is_the_buffer_form(); over_streams_through_a_pipe(); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 73d5973..0935d40 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -23,6 +23,7 @@ build-project refused_allocator ; build-project refused_secret_overload ; build-project refused_secret_parameters ; build-project refused_secret_value_overload ; +build-project refused_configuration_fault ; build-project pipe_incompatible ; build-project pipe_one_shot ; build-project piped_incompatible ; diff --git a/test/messages/refused_configuration_fault/Jamfile b/test/messages/refused_configuration_fault/Jamfile new file mode 100644 index 0000000..1c3cf57 --- /dev/null +++ b/test/messages/refused_configuration_fault/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_configuration_fault : refused_configuration_fault.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_configuration_fault_refused : refused_configuration_fault.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_configuration_fault/refused_configuration_fault.cpp b/test/messages/refused_configuration_fault/refused_configuration_fault.cpp new file mode 100644 index 0000000..f9bb567 --- /dev/null +++ b/test/messages/refused_configuration_fault/refused_configuration_fault.cpp @@ -0,0 +1,79 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A codec's optional configuration_fault (D3) takes the format, is noexcept and returns +// std::optional: one of another signature would be passed over, and the fault of the +// configuration never reported (B23), so the build stops. Here it returns a bool. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement '!webcpp::codecs::detail::takes_configuration_fault || webcpp::codecs::detail::has_configuration_fault': webcpp::codecs: a codec's configuration_fault takes the format by reference to const, is noexcept and returns std::optional}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include +#include +#include +#include +#include + +/** A format of letters whose configuration_fault returns a bool. */ +struct misconfigured_t { + /** The format's name. */ + static constexpr std::string_view name = "misconfigured"; +}; + +namespace webcpp::codecs { + +/** whole_letters' codec, with a configuration_fault of the wrong return type. */ +template <> +struct codec : codec { + /** The fault of the configuration, as a bool. */ + static constexpr bool configuration_fault(misconfigured_t const& /*format*/) noexcept { + return false; + } + + /** letters' size of the text. */ + static std::size_t encoded_size(misconfigured_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::whole_letters, input_bytes); + } + + /** letters' size of the bytes. */ + static result decoded_size(misconfigured_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::whole_letters, text_characters); + } + + /** letters' encode. */ + static result encode(misconfigured_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::whole_letters, input_bytes, + output_characters); + } + + /** letters' decode. */ + static result decode(misconfigured_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::whole_letters, text_characters, + output_bytes); + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + std::array const bytes{1, 2}; + auto const encoded = codecs::encode(misconfigured_t{}, bytes); + return encoded.has_value() ? 0 : 1; +} diff --git a/test/messages/refused_secret_overload/refused_secret_overload.cpp b/test/messages/refused_secret_overload/refused_secret_overload.cpp index 4f5dad7..58c4d91 100644 --- a/test/messages/refused_secret_overload/refused_secret_overload.cpp +++ b/test/messages/refused_secret_overload/refused_secret_overload.cpp @@ -33,9 +33,12 @@ struct mismatched_t { namespace webcpp::codecs { -/** letters' codec, with a secret encode of the wrong return type. */ +/** + letters' codec (whole_letters', of no configuration, as its base), with a secret encode of the + wrong return type. +*/ template <> -struct codec : codec { +struct codec : codec { /** letters' size of the text. */ static std::size_t encoded_size(mismatched_t const& /*format*/, std::span input_bytes) noexcept { diff --git a/test/messages/refused_secret_parameters/refused_secret_parameters.cpp b/test/messages/refused_secret_parameters/refused_secret_parameters.cpp index cd127e9..e76a9e3 100644 --- a/test/messages/refused_secret_parameters/refused_secret_parameters.cpp +++ b/test/messages/refused_secret_parameters/refused_secret_parameters.cpp @@ -34,9 +34,12 @@ struct parameters_t { namespace webcpp::codecs { -/** letters' codec, with a secret encode of parameters the core's arguments do not convert to. */ +/** + letters' codec (whole_letters', of no configuration, as its base), with a secret encode of + parameters the core's arguments do not convert to. +*/ template <> -struct codec : codec { +struct codec : codec { /** letters' size of the text. */ static std::size_t encoded_size(parameters_t const& /*format*/, std::span input_bytes) noexcept { diff --git a/test/over_test.cpp b/test/over_test.cpp index 182d509..0c43e89 100644 --- a/test/over_test.cpp +++ b/test/over_test.cpp @@ -73,9 +73,9 @@ struct seal_t { namespace webcpp::codecs { -/** steady is letters, and constant time. */ +/** steady is letters (whole_letters' codec, of no configuration), and constant time. */ template <> -struct codec : codec { +struct codec : codec { /** The format is constant time. */ static constexpr bool constant_time = true; }; diff --git a/test/support/letters.hpp b/test/support/letters.hpp index b26a503..d2cdd3c 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -73,6 +74,18 @@ struct codec { return text_size / 2; } + /** + The fault of the format's configuration: `invalid_prefix` for `letters(true)`, which the core + reports before any data; the other functions check nothing of it. + */ + static constexpr std::optional configuration_fault( + test::letters_t const& format_value) noexcept { + if (format_value.configured_fault) { + return error::invalid_prefix; + } + return std::nullopt; + } + /** Two letters a byte. */ static constexpr std::size_t encoded_size(test::letters_t const& /*format*/, std::span input_bytes) noexcept { @@ -80,15 +93,11 @@ struct codec { } /** - The bytes of a text: `invalid_prefix` for a format whose configuration is at fault, else - `invalid_character` for a character outside `a` to `p`, else `invalid_length` for an odd - length (the lowest value wins, B23). + The bytes of a text: `invalid_character` for a character outside `a` to `p`, else + `invalid_length` for an odd length (the lowest value wins, B23). */ - static result decoded_size(test::letters_t const& format_value, + static result decoded_size(test::letters_t const& /*format*/, std::string_view text_characters) noexcept { - if (format_value.configured_fault) { - return error::invalid_prefix; - } for (char const text_character : text_characters) { // Read as an unsigned byte first: a signed char from 0x80 up is negative. auto const character_value = static_cast(text_character); @@ -103,16 +112,10 @@ struct codec { return text_characters.size() / 2; } - /** - Writes two letters a byte into `output_characters`, which must hold them; `invalid_prefix` - first for a format whose configuration is at fault. - */ + /** Writes two letters a byte into `output_characters`, which must hold them. */ static result encode(test::letters_t const& format_value, std::span input_bytes, std::span output_characters) noexcept { - if (format_value.configured_fault) { - return error::invalid_prefix; - } std::size_t const written_size = encoded_size(format_value, input_bytes); if (output_characters.size() < written_size) { return error::output_too_small; @@ -213,9 +216,8 @@ struct stream_codec { /** The letters written. */ using output_type = char; - /** An encoder of `format_value` in `needs_input`. */ - explicit encoder(test::letters_t const& format_value) noexcept - : configured_fault_(format_value.configured_fault) {} + /** An encoder in `needs_input`; letters' stream has nothing of the format to keep. */ + explicit encoder(test::letters_t const& /*format*/) noexcept {} /** A copy of the state, borrowing what `other` borrows. */ encoder(encoder const&) noexcept = default; @@ -229,7 +231,6 @@ struct stream_codec { pending_(other.pending_), has_pending_(other.has_pending_), flushed_(other.flushed_), - configured_fault_(other.configured_fault_), error_(other.error_) { other.reset(); } @@ -242,7 +243,6 @@ struct stream_codec { pending_ = other.pending_; has_pending_ = other.has_pending_; flushed_ = other.flushed_; - configured_fault_ = other.configured_fault_; error_ = other.error_; other.reset(); } @@ -312,13 +312,8 @@ struct stream_codec { } private: - /** Whether a call reports an error: the configuration's fault comes first. */ - [[nodiscard]] bool failed() noexcept { - if (configured_fault_ && !error_) { - error_ = error::invalid_prefix; - } - return static_cast(error_); - } + /** Whether a call reports an error, which stays until `reset`. */ + [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } /** The state the next call sees. */ [[nodiscard]] flow state() const noexcept { @@ -338,8 +333,6 @@ struct stream_codec { bool has_pending_ = false; /** Whether `flush` ended the input. */ bool flushed_ = false; - /** Whether the format's configuration is at fault. */ - bool configured_fault_ = false; /** The error every call returns until `reset`. */ boost::system::error_code error_; }; @@ -360,9 +353,8 @@ struct stream_codec { /** The bytes written. */ using output_type = std::uint8_t; - /** A decoder of `format_value` in `needs_input`. */ - explicit decoder(test::letters_t const& format_value) noexcept - : configured_fault_(format_value.configured_fault) {} + /** A decoder in `needs_input`; letters' stream has nothing of the format to keep. */ + explicit decoder(test::letters_t const& /*format*/) noexcept {} /** A copy of the state, borrowing what `other` borrows. */ decoder(decoder const&) noexcept = default; @@ -378,7 +370,6 @@ struct stream_codec { invalid_seen_(other.invalid_seen_), flushed_(other.flushed_), verdict_passed_(other.verdict_passed_), - configured_fault_(other.configured_fault_), error_(other.error_) { other.reset(); } @@ -393,7 +384,6 @@ struct stream_codec { invalid_seen_ = other.invalid_seen_; flushed_ = other.flushed_; verdict_passed_ = other.verdict_passed_; - configured_fault_ = other.configured_fault_; error_ = other.error_; other.reset(); } @@ -529,13 +519,8 @@ struct stream_codec { return verdict_passed_; } - /** Whether a call reports an error: the configuration's fault comes first. */ - [[nodiscard]] bool failed() noexcept { - if (configured_fault_ && !error_) { - error_ = error::invalid_prefix; - } - return static_cast(error_); - } + /** Whether a call reports an error, which stays until `reset`. */ + [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } /** The state the next call sees. */ [[nodiscard]] flow state() const noexcept { @@ -559,8 +544,6 @@ struct stream_codec { bool flushed_ = false; /** Whether the verdict over the whole input passed. */ bool verdict_passed_ = false; - /** Whether the format's configuration is at fault. */ - bool configured_fault_ = false; /** The error every call returns until `reset`. */ boost::system::error_code error_; }; From 449f92755b1f637bcc686a113780c5c2d1dce869 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:16:05 -0300 Subject: [PATCH 062/157] codecs: decoder(format, capacity<0>) refused, a hold being 1 or more and 0 the default, with its message case on holding_letters, moved to the test support --- .../codecs/detail/core/format_transformer.hpp | 50 +++++++++-- test/format_transformer_test.cpp | 89 +++---------------- test/messages/Jamfile | 1 + test/messages/capacity_of_zero/Jamfile | 16 ++++ .../capacity_of_zero/capacity_of_zero.cpp | 28 ++++++ test/support/letters.hpp | 64 +++++++++++-- 6 files changed, 158 insertions(+), 90 deletions(-) create mode 100644 test/messages/capacity_of_zero/Jamfile create mode 100644 test/messages/capacity_of_zero/capacity_of_zero.cpp diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index e61ea21..3f5473a 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -39,7 +39,8 @@ namespace webcpp::codecs { `encoder(format, codecs::secret_operation)` and `decoder(format, codecs::secret_operation)` set `secret`; `decoder(format, codecs::capacity)` sets `capacity`, the hold of a decoder that holds - its input (bech32's, in characters, B47). + its input (bech32's, in characters, B47), which is 1 or more: `codecs::capacity<0>` stops the + build, as 0 here is the decoder's default. */ struct stream_options { /** Whether the stream is secret: its state wiped, its calls under secure's timing guard. */ @@ -181,6 +182,24 @@ constexpr void refuse_value_format() noexcept { "converted whole by codecs::encode and codecs::decode"); } +/** The requirement of the refusal of a hold of 0: false for the `N` it is asked for, 0. */ +template +inline constexpr bool hold_of_one_or_more = N != 0; + +/** + Stops the build: `codecs::capacity<0>` was given to a decoder, whose hold is 1 or more; 0 in + @ref stream_options is the decoder's default, which `decoder(format)` gives. `Tags` are the tags + of the call, so that each overload that takes a capacity refuses in its own instantiation. +*/ +template +constexpr void refuse_hold_of_zero() noexcept { + // Qualified, so that the compiler's message names the requirement as the core's. + static_assert(webcpp::codecs::detail::hold_of_one_or_more, + "webcpp::codecs: codecs::capacity sets the hold of a decoder that holds its " + "input, and a hold is 1 or more; for the decoder's default hold, call " + "codecs::decoder(format) without a capacity"); +} + /** Stops the build: `codecs::capacity` was given to the decoder of a format whose stream decoder holds nothing (`Decoder`, or @ref no_stream for a format that does not stream natively). @@ -876,17 +895,22 @@ template The transformer of `format`'s decoding whose stream decoder holds `N` elements of its input (bech32's, in characters, B47). - A format whose decoder holds nothing stops the build with a message that says so. + A format whose decoder holds nothing stops the build with a message that says so, and so does + `codecs::capacity<0>`: a hold is 1 or more. @tparam F The format's type. - @tparam N The hold. + @tparam N The hold, 1 or more. @param format_value The format. @return The format's decoder, of the hold `N`. */ template [[nodiscard]] auto decoder(F const& format_value, capacity_t /*hold*/) noexcept( detail::nothrow_decoder()) { - return detail::make_decoder(format_value); + if constexpr (N == 0) { + detail::refuse_hold_of_zero>(); + } else { + return detail::make_decoder(format_value); + } } /** @@ -894,7 +918,7 @@ template input, as `decoder(format, codecs::capacity)` with `codecs::secret_operation`. @tparam F The format's type. - @tparam N The hold. + @tparam N The hold, 1 or more. @param format_value The format. @return The format's secret decoder, of the hold `N`. */ @@ -902,7 +926,12 @@ template [[nodiscard]] auto decoder(F const& format_value, secret_operation_t /*secret*/, capacity_t /*hold*/) noexcept( detail::nothrow_decoder()) { - return detail::make_decoder(format_value); + if constexpr (N == 0) { + detail::refuse_hold_of_zero>(); + } else { + return detail::make_decoder( + format_value); + } } /** @@ -910,7 +939,7 @@ decoder(F const& format_value, secret_operation_t /*secret*/, capacity_t /*ho input: the tags in the other order. @tparam F The format's type. - @tparam N The hold. + @tparam N The hold, 1 or more. @param format_value The format. @return The format's secret decoder, of the hold `N`. */ @@ -918,7 +947,12 @@ template [[nodiscard]] auto decoder(F const& format_value, capacity_t /*hold*/, secret_operation_t /*secret*/) noexcept( detail::nothrow_decoder()) { - return detail::make_decoder(format_value); + if constexpr (N == 0) { + detail::refuse_hold_of_zero, secret_operation_t>(); + } else { + return detail::make_decoder( + format_value); + } } } // namespace webcpp::codecs diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index ce97ab1..bb294f2 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -39,66 +39,6 @@ #include #include -namespace holding_formats { -namespace { - -/** - The type of the format holding_letters, of this test's own: whole_letters' codec, and a stream - decoder that declares that it holds its input and gives what it read, as bech32's and the - armor's do; its streams are letters'. -*/ -struct holding_letters_t : webcpp::codecs::test::whole_letters_t { - /** The format's name. */ - static constexpr std::string_view name = "holding_letters"; -}; - -/** The format holding_letters. */ -constexpr holding_letters_t holding_letters{}; - -} // namespace -} // namespace holding_formats - -namespace webcpp::codecs { - -/** The codec of holding_letters: whole_letters', which takes it as its base. */ -template <> -struct codec : codec {}; - -/** The stream codec of holding_letters: letters', its decoder holding and giving its parts. */ -template <> -struct stream_codec { - /** letters' encoder. */ - template - class encoder : public stream_codec::encoder { - public: - /** letters' encoder. */ - explicit encoder(holding_formats::holding_letters_t const& /*format*/) noexcept - : stream_codec::encoder(test::letters) {} - }; - - /** letters' decoder, which says that it holds `Options.capacity` letters. */ - template - class decoder : public stream_codec::decoder { - public: - /** The decoder holds its input. */ - static constexpr bool holds = true; - /** Its hold: the capacity, or 90 letters. */ - static constexpr std::size_t hold = Options.capacity == 0 ? 90 : Options.capacity; - - /** letters' decoder. */ - explicit decoder(holding_formats::holding_letters_t const& /*format*/) noexcept - : stream_codec::decoder(test::letters) {} - - /** The human-readable part it read. */ - [[nodiscard]] std::string_view human_readable_part() const noexcept { return "hl"; } - - /** The label it read. */ - [[nodiscard]] std::string_view label() const noexcept { return "HOLDING"; } - }; -}; - -} // namespace webcpp::codecs - namespace { namespace codecs = webcpp::codecs; @@ -172,34 +112,31 @@ static_assert( static_assert( std::same_as>); +static_assert(std::same_as)), + codecs::format_decoder>); static_assert( - std::same_as)), - codecs::format_decoder>); -static_assert( - std::same_as)), - codecs::format_decoder)), + codecs::format_decoder>); static_assert( - std::same_as, + std::same_as, codecs::secret_operation)), - codecs::format_decoder>); /** The options of a public stream that holds 8 letters. */ constexpr codecs::stream_options hold_of_eight{.capacity = 8}; +static_assert(codecs::stream_codec::decoder::hold == 8); static_assert( - codecs::stream_codec::decoder::hold == 8); -static_assert(codecs::stream_codec::decoder< - codecs::stream_options{}>::hold == 90); + codecs::stream_codec::decoder::hold == 90); // A decoder forwards what its stream decoder gives after flush, where it has it (B39). static_assert(!gives_label); static_assert(!gives_human_readable_part); static_assert(!gives_label); -static_assert(gives_label); -static_assert( - gives_human_readable_part); +static_assert(gives_label); +static_assert(gives_human_readable_part); /** `size` bytes from a generator of a fixed seed. */ std::vector random_bytes(std::size_t size) { @@ -933,7 +870,7 @@ void a_secret_transformer_runs_the_secret_arithmetic() { (B39, B47). */ void a_holding_decoder_gives_what_it_read() { - auto decoder = codecs::decoder(holding_formats::holding_letters, codecs::capacity<8>); + auto decoder = codecs::decoder(test::holding_letters, codecs::capacity<8>); std::array const, 1> const chunks{characters_of("abcd")}; auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 0935d40..c87098d 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -34,4 +34,5 @@ build-project buffered_bound_not_constant ; build-project encoder_of_value_format ; build-project encoder_of_value_over ; build-project capacity_without_hold ; +build-project capacity_of_zero ; build-project drain_of_one_shot ; diff --git a/test/messages/capacity_of_zero/Jamfile b/test/messages/capacity_of_zero/Jamfile new file mode 100644 index 0000000..f20c299 --- /dev/null +++ b/test/messages/capacity_of_zero/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic capacity_of_zero : capacity_of_zero.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail capacity_of_zero_refused : capacity_of_zero.cpp + : clang:no : native emscripten ; diff --git a/test/messages/capacity_of_zero/capacity_of_zero.cpp b/test/messages/capacity_of_zero/capacity_of_zero.cpp new file mode 100644 index 0000000..ba5f93c --- /dev/null +++ b/test/messages/capacity_of_zero/capacity_of_zero.cpp @@ -0,0 +1,28 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// codecs::capacity sets the hold of a decoder that holds its input, as bech32's (D20, B47), and +// a hold is 1 or more: 0 in stream_options is the decoder's default, so capacity<0> would give the +// default in silence. holding_letters' decoder holds its input, so the build stops with this +// message alone, in each of the three overloads that take a capacity. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/format_transformer.hpp:* 3 {{static assertion failed due to requirement 'webcpp::codecs::detail::hold_of_one_or_more<0>': webcpp::codecs: codecs::capacity sets the hold of a decoder that holds its input, and a hold is 1 or more; for the decoder's default hold, call codecs::decoder(format) without a capacity}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::decoder(codecs::test::holding_letters, codecs::capacity<0>); + codecs::decoder(codecs::test::holding_letters, codecs::secret_operation, codecs::capacity<0>); + codecs::decoder(codecs::test::holding_letters, codecs::capacity<0>, codecs::secret_operation); + return 0; +} diff --git a/test/support/letters.hpp b/test/support/letters.hpp index d2cdd3c..31119f1 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -6,12 +6,15 @@ // letters, a format of the tests' own: every byte is written as two letters `a` to `p`, its high // half then its low half, so that the contract is proven before any real format exists. Its codec -// is the six functions of D3 and nothing else; it is not constant time. `letters(true)` is the -// format with a fault of its configuration, which every form reports as `invalid_prefix` before -// any data (B23). Its stream codec (D20) keeps the protocol's error rules (D18, B44): the encoder -// holds the one letter its output had no room for, the decoder one letter of a pair and the lowest -// data error seen. whole_letters is letters' codec under another name, with no stream codec, so -// that its transformers are one-shot alone. +// is the six functions of D3 and the optional configuration_fault; it is not constant time. +// `letters(true)` is the format with a fault of its configuration, which its codec's +// configuration_fault gives as `invalid_prefix` and nothing else checks: the core reports it first +// in every form (B23). Its stream codec (D20) keeps the protocol's error rules (D18, B44): the +// encoder holds the one letter its output had no room for, the decoder one letter of a pair and the +// lowest data error seen. whole_letters is letters' codec under another name, with no stream codec +// and no configuration, so that its transformers are one-shot alone. holding_letters is +// whole_letters' codec with letters' streams, its decoder declaring that it holds its input and +// giving what it read, as bech32's and the armor's do. #ifndef WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP @@ -54,6 +57,18 @@ struct whole_letters_t { /** The format whole_letters, whose transformers are one-shot alone. */ inline constexpr whole_letters_t whole_letters{}; +/** + The type of the format holding_letters: whole_letters' codec, and a stream decoder that holds its + input and gives what it read. +*/ +struct holding_letters_t : whole_letters_t { + /** The format's name. */ + static constexpr std::string_view name = "holding_letters"; +}; + +/** The format holding_letters. */ +inline constexpr holding_letters_t holding_letters{}; + } // namespace webcpp::codecs::test namespace webcpp::codecs { @@ -549,6 +564,43 @@ struct stream_codec { }; }; +/** The codec of holding_letters: whole_letters', which takes it as its base. */ +template <> +struct codec : codec {}; + +/** The stream codec of holding_letters: letters', its decoder holding and giving its parts. */ +template <> +struct stream_codec { + /** letters' encoder. */ + template + class encoder : public stream_codec::encoder { + public: + /** letters' encoder. */ + explicit encoder(test::holding_letters_t const& /*format*/) noexcept + : stream_codec::encoder(test::letters) {} + }; + + /** letters' decoder, which says that it holds `Options.capacity` letters. */ + template + class decoder : public stream_codec::decoder { + public: + /** The decoder holds its input. */ + static constexpr bool holds = true; + /** Its hold: the capacity, or 90 letters. */ + static constexpr std::size_t hold = Options.capacity == 0 ? 90 : Options.capacity; + + /** letters' decoder. */ + explicit decoder(test::holding_letters_t const& /*format*/) noexcept + : stream_codec::decoder(test::letters) {} + + /** The human-readable part it read. */ + [[nodiscard]] std::string_view human_readable_part() const noexcept { return "hl"; } + + /** The label it read. */ + [[nodiscard]] std::string_view label() const noexcept { return "HOLDING"; } + }; +}; + } // namespace webcpp::codecs #endif // WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP From 8c1ae0a3fd3533948149d102632fb69a00387bdd Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:16:05 -0300 Subject: [PATCH 063/157] codecs: the chunkings' three-chunk splits exhaustive up to 128 elements, BIP-173's and BIP-350's vectors among them, sampled past it --- test/support/chunkings.hpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/test/support/chunkings.hpp b/test/support/chunkings.hpp index a48822c..69b60e7 100644 --- a/test/support/chunkings.hpp +++ b/test/support/chunkings.hpp @@ -7,10 +7,12 @@ // The chunkings a stream test sends an input in (D15, "every chunking equals the one-shot form"): // for_each_chunking calls back with the input whole, every split into two chunks and into three, // chunks of one element, and 32 random chunkings, some of their chunks empty, drawn from -// std::mt19937_64{20261126} so that every lane sees the same. Of an input longer than -// every_cut_limit elements the three-chunk splits are those whose two cuts are each at one of the -// first and last cut_edge positions or on a grid of cut_steps steps between, so that 1000 elements -// give hundreds of splits and not half a million, every boundary near the ends included. +// std::mt19937_64{20261126} so that every lane sees the same. Up to every_cut_limit elements, 128, +// the three-chunk splits are exhaustive, every pair of cuts, so that BIP-173's and BIP-350's +// vectors (up to 90 characters) are split everywhere. Of a longer input they are sampled: the +// splits whose two cuts are each at one of the first and last cut_edge positions or on a grid of +// cut_steps steps between, so that 1000 elements give hundreds of splits and not half a million, +// every boundary near the ends included. // stream_whole sends the chunks to a stream transformer, receiving into spans of a given size after // each, flushes and receives until it finishes, and checks that a call that reports an error wrote // nothing (B44). @@ -30,8 +32,11 @@ namespace webcpp::codecs::test { -/** Up to this many elements, an input is split into three chunks at every pair of cuts. */ -inline constexpr std::size_t every_cut_limit = 64; +/** + Up to this many elements, an input is split into three chunks at every pair of cuts (BIP-173's + and BIP-350's vectors, up to 90 characters, among them); past it, the cuts are sampled. +*/ +inline constexpr std::size_t every_cut_limit = 128; /** Past `every_cut_limit`, the cuts at each end of the input that a three-chunk split takes. */ inline constexpr std::size_t cut_edge = 8; /** Past `every_cut_limit`, the steps of the grid of cuts between the ends. */ From 8f22c9a51d3286070aabae0712d72daff9b3aa76 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:17:07 -0300 Subject: [PATCH 064/157] codecs: the noexcept and allocation tests of a fault of the format's configuration, the probe and the stream calls that report it --- test/allocation_test.cpp | 12 ++++++++++++ test/noexcept_test.cpp | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index c5df5d9..abbf240 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -694,6 +694,18 @@ void check_format_transformers() { decoded_chain->flow == codecs::flow::finished && decoded == bytes; }); BOOST_TEST(verdict); + expect_no_allocation("a fault of the configuration, in every stream call", [&] { + auto encoder = codecs::encoder(codecs::over{test::letters, test::letters(true)}); + bool faulted = !encoder.send(bytes).has_value() && !encoder.receive(text).has_value() && + !encoder.flush().has_value(); + encoder.reset(); + auto decoder = codecs::decoder(test::letters(true)); + faulted = faulted && !decoder.send(std::span{text}).has_value() && + !decoder.receive(decoded).has_value() && !decoder.flush().has_value() && + !decoder.transform(std::span{text}, decoded).has_value(); + verdict = faulted; + }); + BOOST_TEST(verdict); } /** Frames 0 to 4, whose bytes number 2, 3, 4, 2 and 3. */ diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index e77f8b4..8168d64 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -502,4 +502,13 @@ static_assert(!noexcept(std::declval().transform(std::span std::span{}))); static_assert(!noexcept(std::declval().output_size(std::span{}))); +// The fault of a format's configuration is asked by the core in every form, and cannot throw: +// letters' codec's, a chain's (its links'), and the probe of a format with none. +static_assert(noexcept(codecs::codec::configuration_fault(test::letters))); +static_assert(noexcept( + codecs::codec::configuration_fault(std::declval()))); +static_assert(noexcept(codecs::detail::configuration_fault_of(test::be16))); +static_assert(noexcept(codecs::encoder(test::letters(true)))); +static_assert(noexcept(codecs::decoder(test::letters(true)))); + } // namespace From bed0202e4f24b07630ecd3247924b8f3409d683a Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:20:04 -0300 Subject: [PATCH 065/157] codecs: configuration fault doc fix, the over stream's brief one sentence --- include/webcpp/codecs/detail/core/format_transformer.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index 3f5473a..766cbfe 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -704,11 +704,11 @@ class format_decoder { The stream of `over` when both links stream natively: the encoder is a pipe of the inner link's encoder and then the outer link's, the decoder a pipe of the outer link's decoder and then the inner link's, each with an intermediate in place of the default capacity - (D11, B43). A fault of a link's configuration, the outer link's first, is the chain's own (its - codec's `configuration_fault`): the chain's transformer reports it from its first call and never - calls the pipe, so that it comes before any data of either link. + (D11, B43). - The pipe's rules are the stream's: the first error of either link is the chain's, a call that + A fault of a link's configuration, the outer link's first, is the chain's own (its codec's + `configuration_fault`): the chain's transformer reports it from its first call and never calls + the pipe, so that it comes before any data of either link. The pipe's rules are the stream's: the first error of either link is the chain's, a call that reports it writes nothing, and a move leaves the moved-from stream as `reset` does; the chain's stream must not be moved while the second link borrows the intermediate, between a `receive` that reports `flow::output_pending` and the next call that reports `flow::needs_input` or From 25c7ce86ae46df36cb421647f26f42ac11ec8791 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:25:12 -0300 Subject: [PATCH 066/157] codecs: configuration fault lint fix, the one-shot check split into encodes and decodes, the pairs' list of a trailing comma, the over stream's comment formatted, no colon after a reference --- .../codecs/detail/core/format_transformer.hpp | 21 ++-- test/format_transformer_test.cpp | 108 ++++++++++-------- 2 files changed, 71 insertions(+), 58 deletions(-) diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index 766cbfe..e6d12f1 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -461,11 +461,11 @@ class format_encoder { The stream members, `send`, `receive`, `flush` and `reset`, exist when `stream_codec` is specialized and forward to its `decoder`, which keeps the protocol (D18) and its error rules; `human_readable_part()` and `label()` exist when that decoder has them (B39). A fault of - the format's configuration comes first in every form, as for @ref format_encoder: `transform` - returns it, `output_size` is 0, and the stream calls return it from the first, whatever it is, - and from every call after, also after `reset`, giving the stream decoder nothing (B23). A move - copies the format and moves the stream state, so that the moved-from decoder converts a new input - from the start (Review Focus 5). It is copyable when the stream state is. + the format's configuration comes first in every form, as for @ref format_encoder, so that + `transform` returns it, `output_size` is 0, and the stream calls return it from the first, whatever + it is, and from every call after, also after `reset`, giving the stream decoder nothing (B23). A + move copies the format and moves the stream state, so that the moved-from decoder converts a new + input from the start (Review Focus 5). It is copyable when the stream state is. It is constant time when `codec` is, and `noexcept` in every call but the ones that allocate (`over`'s decode with a heap intermediate, owner decision 24). @@ -708,11 +708,12 @@ class format_decoder { A fault of a link's configuration, the outer link's first, is the chain's own (its codec's `configuration_fault`): the chain's transformer reports it from its first call and never calls - the pipe, so that it comes before any data of either link. The pipe's rules are the stream's: the first error of either link is the chain's, a call that - reports it writes nothing, and a move leaves the moved-from stream as `reset` does; the chain's - stream must not be moved while the second link borrows the intermediate, between a `receive` that - reports `flow::output_pending` and the next call that reports `flow::needs_input` or - `flow::finished`, unless it has reported an error (@ref piped). + the pipe, so that it comes before any data of either link. The pipe's rules are the stream's: the + first error of either link is the chain's, a call that reports it writes nothing, and a move + leaves the moved-from stream as `reset` does; the chain's stream must not be moved while the + second link borrows the intermediate, between a `receive` that reports `flow::output_pending` and + the next call that reports `flow::needs_input` or `flow::finished`, unless it has reported an + error (@ref piped). @tparam Outer The outer link's type. @tparam Inner The inner link's type. diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index bb294f2..7f9f50a 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -369,6 +369,11 @@ static_assert(codecs::detail::configuration_fault_of(codecs::over{ test::letters, codecs::over{test::letters(true), test::letters}}) == codecs::error::invalid_prefix); +/** Whether every byte of `buffer` is still 0x5a, which a call that failed must leave. */ +bool untouched_bytes(std::span buffer) { + return std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0x5a; }); +} + /** The error of a fault of letters' configuration. */ constexpr codecs::error configured_fault = codecs::error::invalid_prefix; @@ -379,15 +384,12 @@ bool is_configured_fault(Result const& outcome) { } /** - Every one-shot form of `format`, a format whose configuration is at fault, returns the fault, and - writes nothing and leaves its token as it was: the encodes of bytes into the default results, a - buffer too small and one large enough, and every token; the decodes of each of `texts`, valid - ones and ones of a data error, into the default result, a buffer, every token and the typed - results whose own checks would fail; and `transform` and `output_size` of its transformers (B23). + Every one-shot encode of `format`, a format whose configuration is at fault, returns the fault, + writes nothing and leaves its token as it was: into the default results, a buffer too small and + one large enough, every token, and `transform` and `output_size` of its encoders (B23). */ template -void expect_the_fault_in_every_one_shot_form(Format const& format, - std::span texts) { +void expect_the_fault_in_every_encode(Format const& format) { std::array const bytes{0x01, 0x23, 0xfe}; std::vector const heap_bytes(bytes.begin(), bytes.end()); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes))); @@ -396,60 +398,70 @@ void expect_the_fault_in_every_one_shot_form(Format const& format, text_buffer.fill('x'); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, std::span{text_buffer}))); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, std::span{text_buffer}.first(1)))); - BOOST_TEST(std::ranges::all_of(text_buffer, [](char character) { return character == 'x'; })); std::string appended{"kept"}; BOOST_TEST( is_configured_fault(codecs::encode(format, bytes, codecs::tokens::append_to(appended)))); - BOOST_TEST_EQ(appended, "kept"); std::string assigned{"kept"}; BOOST_TEST( is_configured_fault(codecs::encode(format, bytes, codecs::tokens::assign_to(assigned)))); - BOOST_TEST_EQ(assigned, "kept"); + BOOST_TEST(appended == "kept" && assigned == "kept"); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::return_string))); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::fixed<1>{}))); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, codecs::tokens::secret))); BOOST_TEST(is_configured_fault(codecs::encode(format, heap_bytes, codecs::tokens::secret))); auto const encoder = codecs::encoder(format); BOOST_TEST(is_configured_fault(encoder.transform(bytes, text_buffer))); - BOOST_TEST(std::ranges::all_of(text_buffer, [](char character) { return character == 'x'; })); BOOST_TEST_EQ(encoder.output_size(bytes), 0U); auto const secret_encoder = codecs::encoder(format, codecs::secret_operation); BOOST_TEST(is_configured_fault(secret_encoder.transform(bytes, text_buffer))); + BOOST_TEST(std::ranges::all_of(text_buffer, [](char character) { return character == 'x'; })); +} + +/** + Every one-shot decode of `text` in `format`, a format whose configuration is at fault, returns + the fault, writes nothing and leaves its token as it was: into the default result, a buffer, + every token, the typed results whose own checks would fail, and `transform` and `output_size` of + its decoders (B23). +*/ +template +void expect_the_fault_in_every_decode(Format const& format, std::string_view text) { + BOOST_TEST(is_configured_fault(codecs::decode(format, text))); + std::array byte_buffer{}; + byte_buffer.fill(0x5a); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}))); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}.first(0)))); + std::vector appended{0x5a}; + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, codecs::tokens::append_to(appended)))); + std::vector assigned{0x5a}; + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, codecs::tokens::assign_to(assigned)))); + BOOST_TEST(appended == std::vector{0x5a} && + assigned == std::vector{0x5a}); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::return_string))); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::fixed<1>{}))); + BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::secret))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); + BOOST_TEST( + is_configured_fault(codecs::decode(format, text, std::allocator{}))); + auto const decoder = codecs::decoder(format); + BOOST_TEST(is_configured_fault(decoder.transform(characters_of(text), byte_buffer))); + BOOST_TEST_EQ(decoder.output_size(characters_of(text)), 0U); + auto const secret_decoder = codecs::decoder(format, codecs::secret_operation); + BOOST_TEST(is_configured_fault(secret_decoder.transform(characters_of(text), byte_buffer))); + BOOST_TEST(untouched_bytes(byte_buffer)); +} +/** Every one-shot encode of `format` and every decode of each of `texts` return the fault. */ +template +void expect_the_fault_in_every_one_shot_form(Format const& format, + std::span texts) { + expect_the_fault_in_every_encode(format); for (std::string_view const text : texts) { - BOOST_TEST(is_configured_fault(codecs::decode(format, text))); - std::array byte_buffer{}; - byte_buffer.fill(0x5a); - BOOST_TEST(is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}))); - BOOST_TEST( - is_configured_fault(codecs::decode(format, text, std::span{byte_buffer}.first(0)))); - BOOST_TEST( - std::ranges::all_of(byte_buffer, [](std::uint8_t byte) { return byte == 0x5a; })); - std::vector appended_bytes{0x5a}; - BOOST_TEST(is_configured_fault( - codecs::decode(format, text, codecs::tokens::append_to(appended_bytes)))); - BOOST_TEST(appended_bytes == std::vector{0x5a}); - std::vector assigned_bytes{0x5a}; - BOOST_TEST(is_configured_fault( - codecs::decode(format, text, codecs::tokens::assign_to(assigned_bytes)))); - BOOST_TEST(assigned_bytes == std::vector{0x5a}); - BOOST_TEST( - is_configured_fault(codecs::decode(format, text, codecs::tokens::return_string))); - BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::fixed<1>{}))); - BOOST_TEST(is_configured_fault(codecs::decode(format, text, codecs::tokens::secret))); - BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); - BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); - BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); - BOOST_TEST(is_configured_fault(codecs::decode>(format, text))); - BOOST_TEST( - is_configured_fault(codecs::decode(format, text, std::allocator{}))); - auto const decoder = codecs::decoder(format); - BOOST_TEST(is_configured_fault(decoder.transform(characters_of(text), byte_buffer))); - BOOST_TEST( - std::ranges::all_of(byte_buffer, [](std::uint8_t byte) { return byte == 0x5a; })); - BOOST_TEST_EQ(decoder.output_size(characters_of(text)), 0U); - auto const secret_decoder = codecs::decoder(format, codecs::secret_operation); - BOOST_TEST(is_configured_fault(secret_decoder.transform(characters_of(text), byte_buffer))); + expect_the_fault_in_every_decode(format, text); } } @@ -740,10 +752,10 @@ void over_streams_through_a_pipe() { // The outer link's error, invalid_character of "abq", and the inner link's, invalid_length of // the letters of "abc": the errors differ, so that each shows which link reported it. std::string const inner_fault = codecs::encode(test::letters, std::string_view{"abc"}).value(); - std::array, 2> const faults{{ - {std::string_view{"abq"}, codecs::error::invalid_character}, - {std::string_view{inner_fault}, codecs::error::invalid_length}, - }}; + std::array, 2> const faults{ + std::pair{std::string_view{"abq"}, codecs::error::invalid_character}, + std::pair{std::string_view{inner_fault}, codecs::error::invalid_length}, + }; for (auto const& [text, expected_error] : faults) { auto const one_shot = codecs::decode(chain, text); BOOST_TEST(!one_shot.has_value() && one_shot.error() == expected_error); From edfd6164a2bcf6e18d1dfc4c364f9646bfc73752 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 19:49:42 -0300 Subject: [PATCH 067/157] codecs: Task 11's minors, encoded_size 0 for a format whose configuration is at fault and over's encoded_size probing it before any link runs, a non-static configuration_fault refused with its message case, stream_codec's comment reflowed --- .../webcpp/codecs/detail/core/contract.hpp | 27 ++++-- .../codecs/detail/core/format_transformer.hpp | 3 +- include/webcpp/codecs/detail/core/over.hpp | 22 ++++- include/webcpp/codecs/detail/core/sizes.hpp | 23 +++-- test/format_transformer_test.cpp | 33 ++++++++ test/messages/Jamfile | 1 + .../Jamfile | 16 ++++ .../refused_member_configuration_fault.cpp | 83 +++++++++++++++++++ 8 files changed, 190 insertions(+), 18 deletions(-) create mode 100644 test/messages/refused_member_configuration_fault/Jamfile create mode 100644 test/messages/refused_member_configuration_fault/refused_member_configuration_fault.cpp diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index ddacf70..6f36e42 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -85,7 +85,7 @@ namespace webcpp::codecs { its links nothing. The other functions of the codec are called only for a format whose configuration has no fault, and check nothing of it. A codec without the function is of a format that has no configuration. One of another signature (another parameter, another result, not - `noexcept`) stops the build. + `noexcept`, not `static`) stops the build. Each function takes the parameter types written above, which D3 names: `std::span` for the bytes read, `std::string_view` for the text read, @@ -304,8 +304,19 @@ struct any_argument { }; /** - Whether `codec` has a `configuration_fault` of one argument, of any parameter and any result: - one the core's argument does not convert to is found too, so that it cannot be passed over. + Whether `codec` names a `configuration_fault` of one argument that an object of the codec + calls, static or not, of any parameter and any result: a non-static one, which the core's call + `codec::configuration_fault(format_value)` cannot reach, is found too, so that it cannot be + passed over. +*/ +template +concept names_configuration_fault = + requires(codec& codec_object) { codec_object.configuration_fault(any_argument{}); }; + +/** + Whether `codec` has a static `configuration_fault` of one argument, of any parameter and any + result: one the core's argument does not convert to is found too, so that it cannot be passed + over. */ template concept takes_configuration_fault = requires { codec::configuration_fault(any_argument{}); }; @@ -321,11 +332,17 @@ concept has_configuration_fault = requires(F const& format_value) { /** Stops the build when `codec` has a `configuration_fault` of another signature than the - contract's: it would otherwise be passed over, and a fault of the configuration never reported. + contract's, or one that is not static: it would otherwise be passed over, and a fault of the + configuration never reported. */ template constexpr void check_configuration_fault() noexcept { - // Qualified, so that the compiler's message names the requirement as the core's. + // Qualified, so that the compiler's message names the requirement as the core's. A non-static + // hook is refused by the first check alone: the second asks for the static form only. + static_assert(!webcpp::codecs::detail::names_configuration_fault || + webcpp::codecs::detail::takes_configuration_fault, + "webcpp::codecs: a codec's configuration_fault is a static member function, " + "called as codec::configuration_fault(format_value)"); static_assert(!webcpp::codecs::detail::takes_configuration_fault || webcpp::codecs::detail::has_configuration_fault, "webcpp::codecs: a codec's configuration_fault takes the format by reference to " diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index e6d12f1..f175018 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -74,8 +74,7 @@ struct stream_options { nothing is still borrowed, otherwise the `receive` that reaches the end), and it is the error the one-shot form reports for the same whole input; that call writes nothing, the verdict running over everything still borrowed before the tail is written; after an error every call returns it - until `reset`. A moved-from encoder or - decoder is in the state `reset` leaves. + until `reset`. A moved-from encoder or decoder is in the state `reset` leaves. A decoder that holds its input until its verdict (bech32's) declares `static constexpr bool holds = true` and holds `Options.capacity` elements, or its default when it diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 1712617..11d0f95 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -448,12 +448,17 @@ template /** The exact size of the text `chain` encodes `input_view` to: the inner link runs into the intermediate (ruling R3), then the outer link sizes what it holds. When the inner link fails, the - outer link's bound on the intermediate's size is returned, so that `encode` finds the error. + outer link's bound on the intermediate's size is returned, so that `encode` finds the error. A + chain whose configuration is at fault is 0, as the core's `encoded_size` is, and no link runs. */ template [[nodiscard]] std::size_t over_encoded_size( over const& chain, View input_view) noexcept(over_encode_is_noexcept()) { + if (configuration_fault_of(chain)) { + // A link's functions are called only for a configuration without a fault (D3). + return 0; + } constexpr std::size_t middle_bound = encoded_bound>(); std::size_t const middle_size = codec_encoded_size(chain.inner, input_view); if (past_bound(middle_size)) { @@ -620,7 +625,8 @@ struct codec> { @tparam View A `std::span` of the bytes, or a `detail::bounded_bytes` of them. @param chain The chain. @param input_view The bytes. - @return The size, a bound when the inner link fails, so that `encode` finds the error. + @return The size, a bound when the inner link fails, so that `encode` finds the error, 0 for a + chain whose configuration is at fault, which no link then sees. */ template [[nodiscard]] static std::size_t encoded_size( @@ -816,12 +822,19 @@ template } } -/** The exact size of the text of `held_value`: its value codec runs into the intermediate (R3). */ +/** + The exact size of the text of `held_value`: its value codec runs into the intermediate (R3). A + chain whose configuration is at fault is 0, and no link runs. +*/ template [[nodiscard]] std::size_t over_value_encoded_size( over const& chain, Value const& held_value) noexcept(over_value_encode_is_noexcept()) { + if (configuration_fault_of(chain)) { + // A link's functions are called only for a configuration without a fault (D3). + return 0; + } constexpr std::size_t middle_bound = inner_value_bound(); std::size_t const middle_size = value_encoded_size(chain.inner, held_value); if (past_bound(middle_size)) { @@ -915,7 +928,8 @@ struct over_value_encoding {}; template requires value_encodable struct over_value_encoding { - /** The exact size of the text of `held_value`. */ + /** The exact size of the text of `held_value`, 0 for a chain whose configuration is at fault. + */ [[nodiscard]] static std::size_t encoded_size(over const& chain, Value const& held_value) noexcept( over_value_encode_is_noexcept, Outer, Inner, Value>()) { diff --git a/include/webcpp/codecs/detail/core/sizes.hpp b/include/webcpp/codecs/detail/core/sizes.hpp index bf06376..bac2e71 100644 --- a/include/webcpp/codecs/detail/core/sizes.hpp +++ b/include/webcpp/codecs/detail/core/sizes.hpp @@ -199,7 +199,9 @@ template `std::uint8_t` or `unsigned char` (or the input is a value of a value codec whose `encoded_size` is `constexpr`), and the input is not secret. A value codec of `F` and `Input` is used when it encodes, else `codec`. Of a secret input (`is_secret_v`, or a value codec's `secret`) it holds - secure's timing guard and runs the format's secret arithmetic where it has one (D10). + secure's timing guard and runs the format's secret arithmetic where it has one (D10). It has no + error channel: for a format whose configuration is at fault, which every `encode` refuses, it is + 0, as a transformer's `output_size` is, and the format's functions are not called (B23). A pair that is not @ref encodable stops the build with a message that the format does not convert this type. @@ -208,7 +210,8 @@ template @tparam Input The input's type: a byte input, or a value of a value codec. @param format_value The format. @param input_value The bytes, or the value, to encode. - @return The size, `SIZE_MAX` when it does not fit in `std::size_t`. + @return The size, `SIZE_MAX` when it does not fit in `std::size_t`, 0 for a format whose + configuration is at fault. */ template [[nodiscard]] constexpr std::size_t @@ -217,12 +220,18 @@ encoded_size(F const& format_value, Input const& input_value) noexcept( if constexpr (!encodable) { detail::refuse(); return 0; - } else if constexpr (detail::secret_operation_v) { - return detail::secret_encoded_size(format_value, input_value); - } else if constexpr (detail::value_encodable) { - return detail::value_encoded_size(format_value, input_value); } else { - return codec::encoded_size(format_value, detail::bounded_input_bytes(input_value)); + if (detail::configuration_fault_of(format_value)) { + // The format's functions are called only for a configuration without a fault (D3). + return 0; + } + if constexpr (detail::secret_operation_v) { + return detail::secret_encoded_size(format_value, input_value); + } else if constexpr (detail::value_encodable) { + return detail::value_encoded_size(format_value, input_value); + } else { + return codec::encoded_size(format_value, detail::bounded_input_bytes(input_value)); + } } } diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index 7f9f50a..033e123 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -355,6 +355,8 @@ void the_call_that_fails_writes_nothing() { // has none (D3); the core asks a chain of a value codec's link through its links (B23). static_assert(codecs::detail::has_configuration_fault); static_assert(!codecs::detail::takes_configuration_fault); +static_assert(codecs::detail::names_configuration_fault); +static_assert(!codecs::detail::names_configuration_fault); static_assert(codecs::detail::has_configuration_fault); static_assert(codecs::detail::has_configuration_fault); static_assert(!codecs::detail::has_codec>); @@ -368,6 +370,10 @@ static_assert(codecs::detail::configuration_fault_of(codecs::over{test::letters, static_assert(codecs::detail::configuration_fault_of(codecs::over{ test::letters, codecs::over{test::letters(true), test::letters}}) == codecs::error::invalid_prefix); +// encoded_size, which has no error channel, is 0 for a format whose configuration is at fault, as +// output_size is, also as a constant expression, and the format's functions are not called (D3). +static_assert(codecs::encoded_size(test::letters(true), std::array{}) == 0); +static_assert(codecs::encoded_size(test::letters, std::array{}) == 6); /** Whether every byte of `buffer` is still 0x5a, which a call that failed must leave. */ bool untouched_bytes(std::span buffer) { @@ -394,6 +400,9 @@ void expect_the_fault_in_every_encode(Format const& format) { std::vector const heap_bytes(bytes.begin(), bytes.end()); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes))); BOOST_TEST(is_configured_fault(codecs::encode(format, heap_bytes))); + BOOST_TEST_EQ(codecs::encoded_size(format, bytes), 0U); + BOOST_TEST_EQ(codecs::encoded_size(format, heap_bytes), 0U); + BOOST_TEST_EQ(codecs::encoded_size(format, webcpp::secure::secret<3>{}), 0U); std::array text_buffer{}; text_buffer.fill('x'); BOOST_TEST(is_configured_fault(codecs::encode(format, bytes, std::span{text_buffer}))); @@ -510,9 +519,33 @@ void a_configuration_fault_wins_in_every_one_shot_form() { codecs::over{letters_over_letters{test::letters, test::letters(true)}, test::letters}, chain_texts); + // over's own encoded_size probes the chain's configuration before it runs the inner link, as + // the core's does: 0, where the links, which check nothing of it, would give a size. + std::array const chain_bytes{0x01, 0x23, 0xfe}; + for (letters_over_letters const faulted_chain : + {letters_over_letters{test::letters(true), test::letters}, + letters_over_letters{test::letters, test::letters(true)}}) { + BOOST_TEST_EQ(codecs::codec::encoded_size( + faulted_chain, std::span{chain_bytes}), + 0U); + BOOST_TEST_EQ(codecs::codec::encoded_size( + codecs::detail::secret_tag{}, faulted_chain, + std::span{chain_bytes}), + 0U); + } + BOOST_TEST_EQ(codecs::codec::encoded_size( + chain, std::span{chain_bytes}), + 12U); + // A chain of a value codec's link, which has no codec: its outer link's fault comes first, in // the encode of a value into the default result, a buffer and a token, and in its typed decode. auto const value_chain = codecs::over{test::letters(true), test::be16}; + using value_chain_codec = + codecs::value_codec, test::number>; + BOOST_TEST_EQ(codecs::encoded_size(value_chain, test::number{0x1234}), 0U); + BOOST_TEST_EQ(value_chain_codec::encoded_size(value_chain, test::number{0x1234}), 0U); + BOOST_TEST_EQ( + codecs::encoded_size(codecs::over{test::letters, test::be16}, test::number{0x1234}), 4U); BOOST_TEST( codecs::decode(codecs::over{test::letters, test::be16}, "bcdebz").error() == codecs::error::invalid_character); diff --git a/test/messages/Jamfile b/test/messages/Jamfile index c87098d..f1a71b5 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -24,6 +24,7 @@ build-project refused_secret_overload ; build-project refused_secret_parameters ; build-project refused_secret_value_overload ; build-project refused_configuration_fault ; +build-project refused_member_configuration_fault ; build-project pipe_incompatible ; build-project pipe_one_shot ; build-project piped_incompatible ; diff --git a/test/messages/refused_member_configuration_fault/Jamfile b/test/messages/refused_member_configuration_fault/Jamfile new file mode 100644 index 0000000..946dffa --- /dev/null +++ b/test/messages/refused_member_configuration_fault/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_member_configuration_fault : refused_member_configuration_fault.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_member_configuration_fault_refused : refused_member_configuration_fault.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_member_configuration_fault/refused_member_configuration_fault.cpp b/test/messages/refused_member_configuration_fault/refused_member_configuration_fault.cpp new file mode 100644 index 0000000..2965bc7 --- /dev/null +++ b/test/messages/refused_member_configuration_fault/refused_member_configuration_fault.cpp @@ -0,0 +1,83 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A codec's optional configuration_fault (D3) is a static member function, which the core calls +// as codec::configuration_fault(format_value): a non-static one, of the contract's +// signature otherwise, would be passed over, and the fault of the configuration never reported +// (B23), so the build stops. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement '!webcpp::codecs::detail::names_configuration_fault || webcpp::codecs::detail::takes_configuration_fault': webcpp::codecs: a codec's configuration_fault is a static member function, called as codec::configuration_fault(format_value)}} +// clang-format on + +#include "../../support/letters.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +/** A format of letters whose configuration_fault is a non-static member function. */ +struct member_hook_t { + /** The format's name. */ + static constexpr std::string_view name = "member_hook"; +}; + +namespace webcpp::codecs { + +/** whole_letters' codec, with a non-static configuration_fault. */ +template <> +struct codec : codec { + /** The fault of the configuration, of the contract's signature but not static. */ + // NOLINTNEXTLINE(readability-convert-member-functions-to-static): the refused form + [[nodiscard]] std::optional configuration_fault( + member_hook_t const& /*format*/) const noexcept { + return error::invalid_prefix; + } + + /** letters' size of the text. */ + static std::size_t encoded_size(member_hook_t const& /*format*/, + std::span input_bytes) noexcept { + return codec::encoded_size(test::whole_letters, input_bytes); + } + + /** letters' size of the bytes. */ + static result decoded_size(member_hook_t const& /*format*/, + std::string_view text_characters) noexcept { + return codec::decoded_size(test::whole_letters, text_characters); + } + + /** letters' encode. */ + static result encode(member_hook_t const& /*format*/, + std::span input_bytes, + std::span output_characters) noexcept { + return codec::encode(test::whole_letters, input_bytes, + output_characters); + } + + /** letters' decode. */ + static result decode(member_hook_t const& /*format*/, + std::string_view text_characters, + std::span output_bytes) noexcept { + return codec::decode(test::whole_letters, text_characters, + output_bytes); + } +}; + +} // namespace webcpp::codecs + +int main() { + namespace codecs = webcpp::codecs; + std::array const bytes{1, 2}; + auto const encoded = codecs::encode(member_hook_t{}, bytes); + return encoded.has_value() ? 0 : 1; +} From 2d9500e4969f5855b266d547b37e057c8c967bc9 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:01:58 -0300 Subject: [PATCH 068/157] codecs: Task 11's minors gcc fix, the faulted chains' loop by reference (range-loop-construct) --- test/format_transformer_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index 033e123..0c19de5 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -522,7 +522,7 @@ void a_configuration_fault_wins_in_every_one_shot_form() { // over's own encoded_size probes the chain's configuration before it runs the inner link, as // the core's does: 0, where the links, which check nothing of it, would give a size. std::array const chain_bytes{0x01, 0x23, 0xfe}; - for (letters_over_letters const faulted_chain : + for (letters_over_letters const& faulted_chain : {letters_over_letters{test::letters(true), test::letters}, letters_over_letters{test::letters, test::letters(true)}}) { BOOST_TEST_EQ(codecs::codec::encoded_size( From d8a1a947a1a7dfa2bd1839af7c87bc1578592136 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:06:54 -0300 Subject: [PATCH 069/157] codecs: secret streams, move-only, a guard in every call nesting with their parts', their pending state wiped on reset, move and destruction --- .../webcpp/codecs/detail/core/adapters.hpp | 173 +++- .../codecs/detail/core/format_transformer.hpp | 88 +- include/webcpp/codecs/detail/core/pipe.hpp | 70 +- include/webcpp/codecs/detail/core/secrecy.hpp | 8 + test/Jamfile | 7 + test/allocation_test.cpp | 69 ++ test/secret_stream_test.cpp | 834 ++++++++++++++++++ test/support/allocators.hpp | 25 +- test/support/letters.hpp | 69 +- 9 files changed, 1279 insertions(+), 64 deletions(-) create mode 100644 test/secret_stream_test.cpp diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index 652f8fd..d740bfc 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -7,7 +7,8 @@ /** A one-shot transformer as a stream (D19, D22): `each`, which converts each input element on its own, as a whole unit, and `buffered`, which accumulates the whole input and converts it at - `flush`; each in place, with `codecs::capacity`, or with an allocator. + `flush`; each in place, with `codecs::capacity`, or with an allocator; each secret, guarded and + wiped, when its transformer is (D21). */ #ifndef WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP #define WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP @@ -15,8 +16,11 @@ #include #include +#include #include #include +#include +#include #include @@ -114,6 +118,9 @@ class in_place_output { /** The output's elements. */ [[nodiscard]] std::span elements() const noexcept { return elements_; } + /** Wipes every element by `secure::erase_secret`: a secret stream's storage (D21). */ + void wipe() noexcept { secure::erase_secret(elements_); } + private: /** The elements. */ std::array elements_{}; @@ -123,9 +130,11 @@ class in_place_output { An output from `Allocator`, rebound to `Element`, which grows for each conversion as D19 says: to the transformer's exact size when it states one, else to its static bound, else to the input's size, and then doubles while `transform` reports `output_too_small`. It never shrinks, so that a - later conversion reuses its memory. + later conversion reuses its memory. When `Wiped`, a secret stream's (D21), its elements are wiped + by `secure::erase_secret` before it grows, so that the memory the allocator gets back holds none + of them. */ -template +template class heap_output { /** The allocator of the elements. */ using element_allocator = std::allocator_traits::template rebind_alloc; @@ -153,6 +162,10 @@ class heap_output { if (wanted > largest) { return error::input_too_long; } + if constexpr (Wiped) { + // The old memory goes back wiped; the elements it moves over are zero. + secure::erase_secret(elements_); + } elements_.resize(wanted); } auto const written = transformer.transform(input, std::span{elements_}); @@ -172,6 +185,12 @@ class heap_output { /** The output's elements, as many as it has grown to. */ [[nodiscard]] std::span elements() const noexcept { return elements_; } + /** + Wipes every element it has grown to by `secure::erase_secret`, keeping the memory; past them + the memory holds nothing written. + */ + void wipe() noexcept { secure::erase_secret(elements_); } + /** The allocator, as given. */ [[nodiscard]] Allocator get_allocator() const noexcept { return Allocator(elements_.get_allocator()); @@ -219,6 +238,9 @@ class in_place_input { too_long_ = false; } + /** Wipes every element by `secure::erase_secret`: a secret stream's storage (D21). */ + void wipe() noexcept { secure::erase_secret(elements_); } + private: /** The elements. */ std::array elements_{}; @@ -270,9 +292,11 @@ class truncation_guard { /** An input from `Allocator`, rebound to `Element`, grown geometrically as it is appended to; it - records an input past what the allocator can hold. A failed append keeps what it held. + records an input past what the allocator can hold. A failed append keeps what it held. When + `Wiped`, a secret stream's (D21), it grows by copying its elements into new memory and wiping the + old by `secure::erase_secret` before the allocator gets it back. */ -template +template class heap_input { /** The allocator of the elements. */ using element_allocator = std::allocator_traits::template rebind_alloc; @@ -299,7 +323,18 @@ class heap_input { // times; reserve keeps the elements as they were when it throws. std::size_t const doubled = std::min(saturating_multiply(elements_.capacity(), 2), elements_.max_size()); - elements_.reserve(std::max(kept + input.size(), doubled)); + std::size_t const grown_capacity = std::max(kept + input.size(), doubled); + if constexpr (Wiped) { + // The elements are copied into the new memory, and the old memory goes back + // wiped; when the allocation throws, the elements are as they were. + std::vector grown(elements_.get_allocator()); + grown.reserve(grown_capacity); + grown.insert(grown.end(), elements_.begin(), elements_.end()); + secure::erase_secret(elements_); + elements_.swap(grown); + } else { + elements_.reserve(grown_capacity); + } } truncation_guard> guard{elements_, kept}; elements_.insert(elements_.end(), input.begin(), input.end()); @@ -318,6 +353,12 @@ class heap_input { too_long_ = false; } + /** + Wipes the elements appended by `secure::erase_secret`, keeping them and the memory; past them + the memory holds nothing appended since it was last wiped. + */ + void wipe() noexcept { secure::erase_secret(elements_); } + /** The allocator, as given. */ [[nodiscard]] Allocator get_allocator() const noexcept { return Allocator(elements_.get_allocator()); @@ -333,8 +374,8 @@ class heap_input { /** The item storage of `each`: one item's output from the allocator `Storage`. */ template struct each_storage { - /** The output of one item. */ - using output = heap_output; + /** The output of one item, wiped as it grows when `T` is secret. */ + using output = heap_output>; }; /** The item storage of `each>`: one item's output, `N` elements in place. */ @@ -354,10 +395,10 @@ struct each_storage> { /** The storage of `buffered`: the input and the output from the allocator `Storage`. */ template struct buffered_storage { - /** The input accumulated. */ - using input = heap_input; - /** The output of the whole input. */ - using output = heap_output; + /** The input accumulated, wiped as it grows when `T` is secret. */ + using input = heap_input>; + /** The output of the whole input, wiped as it grows when `T` is secret. */ + using output = heap_output>; }; /** @@ -417,6 +458,12 @@ struct buffered_storage> { stream still calls its `T`, which the move left as `T`'s own move leaves it, so it converts anew only when a moved-from `T` still transforms (a requirement of @ref one_shot_transformer). + It is secret when `T` is (`codecs::is_secret_v`, D21): then it is move-only, each of its calls, + `reset` included, holds an engaged `secure::timing_guard`, which nests with `T`'s own, and its item + storage, whose elements must then be trivially copyable, is wiped by `secure::erase_secret` on + `reset`, on destruction, in the moved-from stream on a move, in the stream a move assigns to + before it takes the other's, and, from an allocator, before the memory it outgrows goes back. + @tparam T The one-shot transformer. @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. */ @@ -428,6 +475,14 @@ class each { /** One item's output. */ using output_storage = detail::each_storage::output; + /** Whether the stream is secret: `T` is. */ + static constexpr bool secret = is_secret_v; + + // After the alias, as each_storage's check. + static_assert(detail::wipeable_elements_v, + "webcpp::codecs: a secret each wipes its item storage with secure::erase_secret, " + "so T's output_type is trivially copyable"); + /** Whether making the storage from `Storage` cannot throw: an allocator is only copied. */ static constexpr bool nothrow_construction = std::is_nothrow_move_constructible_v && @@ -466,19 +521,23 @@ class each { : transformer_(std::move(transformer)), output_(storage) {} /** - A copy borrows the item `other` borrows. + A copy borrows the item `other` borrows; a secret stream is not copyable (D21). @param other The stream copied. */ - each(each const& other) = default; + each(each const& other) + requires(!secret) + = default; /** - A copy borrows the item `other` borrows. + A copy borrows the item `other` borrows; a secret stream is not copyable (D21). @param other The stream copied. @return This stream. */ - each& operator=(each const& other) = default; + each& operator=(each const& other) + requires(!secret) + = default; /** Takes `other`'s transformer, item, output and state, and leaves `other` as `reset` does. @@ -508,6 +567,8 @@ class each { each& operator=(each&& other) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v) { if (this != &other) { + // The output this stream held goes before it takes the other's. + wipe_storage(); transformer_ = std::move(other.transformer_); output_ = std::move(other.output_); item_ = other.item_; @@ -522,8 +583,8 @@ class each { return *this; } - /** Destroys the transformer and the storage. */ - ~each() = default; + /** Destroys the transformer and the storage, wiped first when the stream is secret. */ + ~each() { wipe_storage(); } /** Accepts the first element of `input` as the item in `flow::needs_input`; accepts nothing in @@ -533,6 +594,7 @@ class each { @return `{1, flow::output_pending}`, `{0, state}`, or the stream's error. */ [[nodiscard]] result send(std::span input) noexcept { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -552,6 +614,7 @@ class each { that transforms the item reports, writing nothing. */ [[nodiscard]] result receive(std::span output) noexcept(nothrow_receive) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -597,6 +660,7 @@ class each { stream's error. */ [[nodiscard]] result flush() noexcept { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -606,9 +670,11 @@ class each { /** Returns to `flow::needs_input` with no item, no error and a count of zero; the allocated - storage is kept for the next stream. + storage is kept for the next stream, wiped when the stream is secret. */ void reset() noexcept { + secure::timing_guard const timing_scope{secret}; + wipe_storage(); item_ = {}; stored_ = 0; delivered_ = 0; @@ -645,6 +711,13 @@ class each { return flushed_ ? flow::finished : flow::needs_input; } + /** Wipes the item storage when the stream is secret (D21). */ + void wipe_storage() noexcept { + if constexpr (secret) { + output_.wipe(); + } + } + /** The item is delivered: the caller's input is free, and the count grows. */ void complete_item() noexcept { item_ = {}; @@ -702,6 +775,14 @@ each(T, capacity_t) -> each>; template each(T, Allocator) -> each; +// The reference's check (tools/doc/doc_comments.py) keys the partial specializations of one +// template by its name, so that every @tparam of them must name a parameter of the first: these +// state their parameters in their text. + +/** `each` is secret when its transformer `T` is (D21), whatever its storage. */ +template +struct is_secret> : std::bool_constant> {}; + /** A stream transformer that accumulates its whole input and converts it at `flush` through the one-shot transformer `T` (D19): a conversion that cannot stream, as base58's, has the whole input @@ -737,6 +818,14 @@ each(T, Allocator) -> each; provided that a moved-from `T` still transforms (a requirement of @ref one_shot_transformer), since it keeps calling the `T` the move left it. + It is secret when `T` is (`codecs::is_secret_v`, D21): then it is move-only, each of its calls, + `reset` included, holds an engaged `secure::timing_guard`, which nests with `T`'s own, and its + storage, the input and the output, whose elements must then be trivially copyable, is wiped by + `secure::erase_secret` on `reset`, on destruction, in the moved-from stream on a move, in the + stream a move assigns to before it takes the other's, and, from an allocator, before the memory + it outgrows goes back. Over a secret format's encoder, its `flush` runs the format's secret + arithmetic (base58's, ruling R7). + @tparam T The one-shot transformer. @tparam Storage `codecs::capacity_t`, the storage in place, or an allocator. */ @@ -750,6 +839,15 @@ class buffered { /** The output of the whole input. */ using output_storage = detail::buffered_storage::output; + /** Whether the stream is secret: `T` is. */ + static constexpr bool secret = is_secret_v; + + // After the aliases, as buffered_storage's check. + static_assert(detail::wipeable_elements_v && + detail::wipeable_elements_v, + "webcpp::codecs: a secret buffered wipes its storage with secure::erase_secret, " + "so T's input_type and output_type are trivially copyable"); + /** Whether making the storage from `Storage` cannot throw: an allocator is only copied. */ static constexpr bool nothrow_construction = std::is_nothrow_move_constructible_v && @@ -795,19 +893,23 @@ class buffered { : transformer_(std::move(transformer)), input_(storage), output_(storage) {} /** - A copy holds what `other` holds. + A copy holds what `other` holds; a secret stream is not copyable (D21). @param other The stream copied. */ - buffered(buffered const& other) = default; + buffered(buffered const& other) + requires(!secret) + = default; /** - A copy holds what `other` holds. + A copy holds what `other` holds; a secret stream is not copyable (D21). @param other The stream copied. @return This stream. */ - buffered& operator=(buffered const& other) = default; + buffered& operator=(buffered const& other) + requires(!secret) + = default; /** Takes `other`'s transformer, input, output and state, and leaves `other` as `reset` does. @@ -837,6 +939,8 @@ class buffered { std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v) { if (this != &other) { + // The storage this stream held goes before it takes the other's. + wipe_storage(); transformer_ = std::move(other.transformer_); input_ = std::move(other.input_); output_ = std::move(other.output_); @@ -849,8 +953,8 @@ class buffered { return *this; } - /** Destroys the transformer and the storage. */ - ~buffered() = default; + /** Destroys the transformer and the storage, wiped first when the stream is secret. */ + ~buffered() { wipe_storage(); } /** Copies all of `input` into the storage in `flow::needs_input`, and accepts nothing in another @@ -862,6 +966,7 @@ class buffered { @return The elements accepted and `flow::needs_input`, `{0, state}`, or the stream's error. */ [[nodiscard]] result send(std::span input) noexcept(nothrow_send) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -879,6 +984,7 @@ class buffered { @return The elements written and the state after, or the stream's error. */ [[nodiscard]] result receive(std::span output) noexcept(nothrow_receive) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -900,6 +1006,7 @@ class buffered { stream's error: `T`'s, or `error::input_too_long` for an input past the storage's capacity. */ [[nodiscard]] result flush() noexcept(nothrow_flush) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -923,9 +1030,11 @@ class buffered { /** Returns to `flow::needs_input` with nothing held, pending or in error; the allocated storage is - kept for the next stream. + kept for the next stream, wiped when the stream is secret. */ void reset() noexcept { + secure::timing_guard const timing_scope{secret}; + wipe_storage(); input_.clear(); stored_ = 0; delivered_ = 0; @@ -953,6 +1062,14 @@ class buffered { return delivered_ < stored_ ? flow::output_pending : flow::finished; } + /** Wipes the input and the output when the stream is secret (D21). */ + void wipe_storage() noexcept { + if constexpr (secret) { + input_.wipe(); + output_.wipe(); + } + } + /** The one-shot transformer. */ T transformer_; /** The input accumulated. */ @@ -997,6 +1114,10 @@ buffered(T, capacity_t) -> buffered>; template buffered(T, Allocator) -> buffered; +/** `buffered` is secret when its transformer `T` is (D21), whatever its storage. */ +template +struct is_secret> : std::bool_constant> {}; + } // namespace webcpp::codecs #endif // WEBCPP_CODECS_DETAIL_CORE_ADAPTERS_HPP diff --git a/include/webcpp/codecs/detail/core/format_transformer.hpp b/include/webcpp/codecs/detail/core/format_transformer.hpp index f175018..ce8b312 100644 --- a/include/webcpp/codecs/detail/core/format_transformer.hpp +++ b/include/webcpp/codecs/detail/core/format_transformer.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -76,6 +77,12 @@ struct stream_options { over everything still borrowed before the tail is written; after an error every call returns it until `reset`. A moved-from encoder or decoder is in the state `reset` leaves. + With `Options.secret` (D21) the stream codec's encoder and decoder wipe their own pending state + (the carries, the error mask, a hold) by `secure::erase_secret` on `reset`, on destruction and in + the moved-from object on a move, and need not be copyable; the core's class holds the engaged + `secure::timing_guard` around each of their calls, is move-only, and runs the format's secret + arithmetic in its one-shot form (ruling R7). + A decoder that holds its input until its verdict (bech32's) declares `static constexpr bool holds = true` and holds `Options.capacity` elements, or its default when it is 0; `decoder(format, codecs::capacity)` of any other format stops the build. A decoder that @@ -234,7 +241,13 @@ constexpr void refuse_hold() noexcept { after, also after `reset`, giving the stream encoder nothing (B23). A move copies the format and moves the stream state, whose own move leaves the moved-from state as `reset` does, so that the moved-from encoder converts a new input from the start (Review Focus 5). It is copyable when the - stream state is. + stream state is and the encoder is public. + + With `Options.secret`, made by `codecs::encoder(format, codecs::secret_operation)`, it is secret + (`codecs::is_secret_v`, D21): it is move-only, each of its calls, `transform`, `output_size` and + the four stream calls, holds an engaged `secure::timing_guard`, which nests with the guards of a + composition that holds it, and the stream encoder wipes its own pending state on `reset`, on + destruction and in the moved-from encoder. It is constant time when `codec` is, and `noexcept` in every call but the ones that allocate (`over`'s encode with a heap intermediate, owner decision 24). @@ -269,6 +282,9 @@ class format_encoder { static constexpr bool nothrow_move_assignment = std::is_nothrow_copy_assignable_v && std::is_nothrow_move_assignable_v; + /** Whether the transformer is secret (D21). */ + static constexpr bool secret = Options.secret; + public: /** The bytes the encoder reads. */ using input_type = std::uint8_t; @@ -291,19 +307,25 @@ class format_encoder { stream_(format_) {} /** - Copies `other`'s format and stream state, when the stream state is copyable. + Copies `other`'s format and stream state, when the stream state is copyable; a secret encoder + is not copyable (D21). @param other The encoder copied. */ - format_encoder(format_encoder const& other) = default; + format_encoder(format_encoder const& other) + requires(!secret) + = default; /** - Copies `other`'s format and stream state, when the stream state is copyable. + Copies `other`'s format and stream state, when the stream state is copyable; a secret encoder + is not copyable (D21). @param other The encoder copied. @return This encoder. */ - format_encoder& operator=(format_encoder const& other) = default; + format_encoder& operator=(format_encoder const& other) + requires(!secret) + = default; /** Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. @@ -358,6 +380,7 @@ class format_encoder { [[nodiscard]] std::size_t output_size(std::span input) const noexcept(detail::codec_encoded_size_is_noexcept>()) { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_ || detail::input_size_fault(format_, input.size())) { return 0; } @@ -375,6 +398,7 @@ class format_encoder { std::span output) const noexcept(detail::encode_calls_are_noexcept, Options.secret>()) { + secure::timing_guard const timing_scope{secret}; return detail::encode_into_buffer(format_, input, output); } @@ -388,6 +412,7 @@ class format_encoder { [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -403,6 +428,7 @@ class format_encoder { [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -418,6 +444,7 @@ class format_encoder { [[nodiscard]] result flush() noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -431,6 +458,7 @@ class format_encoder { void reset() noexcept requires streams { + secure::timing_guard const timing_scope{secret}; stream_.reset(); } @@ -464,7 +492,14 @@ class format_encoder { `transform` returns it, `output_size` is 0, and the stream calls return it from the first, whatever it is, and from every call after, also after `reset`, giving the stream decoder nothing (B23). A move copies the format and moves the stream state, so that the moved-from decoder converts a new - input from the start (Review Focus 5). It is copyable when the stream state is. + input from the start (Review Focus 5). It is copyable when the stream state is and the decoder is + public. + + With `Options.secret`, made by `codecs::decoder(format, codecs::secret_operation)`, it is secret + (`codecs::is_secret_v`, D21): it is move-only, each of its calls, `transform`, `output_size` and + the four stream calls, holds an engaged `secure::timing_guard`, which nests with the guards of a + composition that holds it, and the stream decoder wipes its own pending state (its carries, its + error mask, its hold) on `reset`, on destruction and in the moved-from decoder. It is constant time when `codec` is, and `noexcept` in every call but the ones that allocate (`over`'s decode with a heap intermediate, owner decision 24). @@ -499,6 +534,9 @@ class format_decoder { static constexpr bool nothrow_move_assignment = std::is_nothrow_copy_assignable_v && std::is_nothrow_move_assignable_v; + /** Whether the transformer is secret (D21). */ + static constexpr bool secret = Options.secret; + public: /** The characters the decoder reads. */ using input_type = char; @@ -521,19 +559,25 @@ class format_decoder { stream_(format_) {} /** - Copies `other`'s format and stream state, when the stream state is copyable. + Copies `other`'s format and stream state, when the stream state is copyable; a secret decoder + is not copyable (D21). @param other The decoder copied. */ - format_decoder(format_decoder const& other) = default; + format_decoder(format_decoder const& other) + requires(!secret) + = default; /** - Copies `other`'s format and stream state, when the stream state is copyable. + Copies `other`'s format and stream state, when the stream state is copyable; a secret decoder + is not copyable (D21). @param other The decoder copied. @return This decoder. */ - format_decoder& operator=(format_decoder const& other) = default; + format_decoder& operator=(format_decoder const& other) + requires(!secret) + = default; /** Copies `other`'s format and takes its stream state, which leaves `other` as `reset` does. @@ -587,6 +631,7 @@ class format_decoder { */ [[nodiscard]] std::size_t output_size(std::span input) const noexcept( detail::codec_decoded_size_is_noexcept()) { + secure::timing_guard const timing_scope{secret}; std::string_view const text_characters{input.data(), input.size()}; if (configuration_fault_ || detail::text_size_fault(format_, text_characters.size())) { return 0; @@ -606,6 +651,7 @@ class format_decoder { [[nodiscard]] result transform(std::span input, std::span output) const noexcept(detail::decode_calls_are_noexcept()) { + secure::timing_guard const timing_scope{secret}; return detail::decode_into_buffer( format_, std::string_view{input.data(), input.size()}, output); } @@ -620,6 +666,7 @@ class format_decoder { [[nodiscard]] result send(std::span input) noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -635,6 +682,7 @@ class format_decoder { [[nodiscard]] result receive(std::span output) noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -650,6 +698,7 @@ class format_decoder { [[nodiscard]] result flush() noexcept(nothrow_stream) requires streams { + secure::timing_guard const timing_scope{secret}; if (configuration_fault_) { return *configuration_fault_; } @@ -663,6 +712,7 @@ class format_decoder { void reset() noexcept requires streams { + secure::timing_guard const timing_scope{secret}; stream_.reset(); } @@ -699,6 +749,24 @@ class format_decoder { stream_type stream_; }; +// The reference's check (tools/doc/doc_comments.py) keys the partial specializations of one +// template by its name, so that every @tparam of them must name a parameter of the first: these +// state their parameters in their text. + +/** + A format's encoder is secret when its options say so, `Options.secret`, as + `codecs::encoder(format, codecs::secret_operation)` makes it (D21). +*/ +template +struct is_secret> : std::bool_constant {}; + +/** + A format's decoder is secret when its options say so, `Options.secret`, as + `codecs::decoder(format, codecs::secret_operation)` makes it (D21). +*/ +template +struct is_secret> : std::bool_constant {}; + /** The stream of `over` when both links stream natively: the encoder is a pipe of the inner link's encoder and then the outer link's, the decoder a pipe of the outer link's diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index 295cd15..c11bfde 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -6,7 +6,8 @@ /** The composition of stream transformers (D19): `pipe`, which joins two by their element types - alone through an intermediate in place, and `drain`, which receives from one into a sink. + alone through an intermediate in place, and `drain`, which receives from one into a sink; a pipe + of a secret part is secret, and a drain of a secret transformer wipes its buffer (D21). */ #ifndef WEBCPP_CODECS_DETAIL_CORE_PIPE_HPP #define WEBCPP_CODECS_DETAIL_CORE_PIPE_HPP @@ -14,7 +15,10 @@ #include #include +#include #include +#include +#include #include #include @@ -120,6 +124,13 @@ inline constexpr bool nothrow_movable_v = (std::is_nothrow_move_constructible_v< from it: the pipe must not be moved in that window, unless the pipe has reported an error (it calls `Second` no more until `reset`). + The pipe is secret when either part is (`codecs::is_secret_v`, D21): then each of its calls, + `reset` included, holds an engaged `secure::timing_guard`, which nests with its parts' own, and + its intermediate, whose elements must then be trivially copyable, is wiped by + `secure::erase_secret` on `reset`, on destruction, in the moved-from pipe on a move (after the + check that `Second` does not borrow it) and in the pipe a move assigns to before it takes the + other's elements; each part wipes its own state. + @tparam First The first transformer, whose input is the pipe's. @tparam Second The second transformer, whose output is the pipe's. @tparam Capacity The intermediate's elements, at least one. @@ -140,6 +151,13 @@ class piped { /** The elements `Second` reads. */ using second_input_type = Second::input_type; + /** Whether the pipe is secret: either part is. */ + static constexpr bool secret = is_secret_v || is_secret_v; + + static_assert(detail::wipeable_elements_v, + "webcpp::codecs: a secret pipe wipes its intermediate with secure::erase_secret, " + "so the first transformer's output_type is trivially copyable"); + /** Whether every call of both parts is `noexcept`. */ static constexpr bool nothrow_calls = detail::nothrow_stream_calls && detail::nothrow_stream_calls; @@ -203,13 +221,15 @@ class piped { if (this != &other) { first_ = std::move(other.first_); second_ = std::move(other.second_); + // The elements this pipe held go before it takes the other's. + wipe_intermediate(); take_state(other); } return *this; } - /** Destroys both parts. */ - ~piped() = default; + /** Destroys both parts, the intermediate wiped first when the pipe is secret. */ + ~piped() { wipe_intermediate(); } /** Gives `input` to `First` in `flow::needs_input`; accepts nothing in another state. @@ -218,6 +238,7 @@ class piped { @return The elements accepted and the state after, or the pipe's error. */ [[nodiscard]] result send(std::span input) noexcept(nothrow_calls) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -242,6 +263,7 @@ class piped { @return The elements written and the state after, or the pipe's error. */ [[nodiscard]] result receive(std::span output) noexcept(nothrow_calls) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -269,6 +291,7 @@ class piped { pipe's error. */ [[nodiscard]] result flush() noexcept(nothrow_calls) { + secure::timing_guard const timing_scope{secret}; if (error_) { return error_; } @@ -285,10 +308,15 @@ class piped { return state(); } - /** Resets both parts and returns to `flow::needs_input`, with nothing pending and no error. */ + /** + Resets both parts and returns to `flow::needs_input`, with nothing pending and no error; the + intermediate is wiped when the pipe is secret. + */ void reset() noexcept { + secure::timing_guard const timing_scope{secret}; first_.reset(); second_.reset(); + wipe_intermediate(); first_flow_ = flow::needs_input; second_flow_ = flow::needs_input; sent_ = 0; @@ -421,7 +449,8 @@ class piped { */ void take_state(piped& other) noexcept(nothrow_moves) { // Second's borrow of the intermediate cannot follow it to another object; a pipe that has - // reported an error never calls Second again before reset, which ends the borrow. + // reported an error never calls Second again before reset, which ends the borrow. Checked + // before other.reset() wipes the intermediate a borrowing Second would still read. BOOST_ASSERT(!other.lent_ || other.error_); std::span const unsent_elements = std::span{other.intermediate_}.subspan(other.sent_, other.size_ - other.sent_); @@ -435,6 +464,13 @@ class piped { other.reset(); } + /** Wipes the intermediate when the pipe is secret (D21); a public pipe's is left as it is. */ + void wipe_intermediate() noexcept { + if constexpr (secret) { + secure::erase_secret(intermediate_); + } + } + /** The first transformer. */ First first_; /** The second transformer. */ @@ -455,6 +491,18 @@ class piped { boost::system::error_code error_; }; +// The reference's check (tools/doc/doc_comments.py) keys the partial specializations of one +// template by its name, so that every @tparam of them must name a parameter of the first: this one +// states its parameters in its text. + +/** + A pipe is secret when either of its parts, `First` or `Second`, is (D21), whatever the capacity of + its intermediate. +*/ +template +struct is_secret> + : std::bool_constant || is_secret_v> {}; + /** A stream transformer of `first` and then `second`, with an intermediate in place of `N` elements of `first`'s output (D19). @@ -616,7 +664,9 @@ template The sink is called directly, as a template parameter, and returns `void` or `codecs::result`, whose error stops the drain. When output is pending and the transformer - writes none of it into the buffer, the drain stops with `error::output_too_small`. + writes none of it into the buffer, the drain stops with `error::output_too_small`. Of a secret + transformer (`codecs::is_secret_v`, D21), the buffer is wiped by `secure::erase_secret` before the + drain returns, by every path. @tparam T The transformer's type. @tparam Sink The sink's type. @@ -631,6 +681,7 @@ template if constexpr (stream_transformer) { using output_type = T::output_type; std::array> buffer{}; + detail::temporary_wipe, output_type> const buffer_wipe{std::span{buffer}}; return detail::drain_through(transformer, sink, std::span{buffer}); } else { static_assert(stream_transformer, @@ -643,7 +694,7 @@ template /** Receives from `transformer` into `sink` as @ref drain does, through a buffer in place of `N` - elements. + elements, wiped before the drain returns when the transformer is secret. @tparam T The transformer's type. @tparam Sink The sink's type. @@ -657,6 +708,8 @@ template detail::nothrow_drain()) { if constexpr (stream_transformer) { std::array buffer{}; + detail::temporary_wipe, typename T::output_type> const buffer_wipe{ + std::span{buffer}}; return detail::drain_through(transformer, sink, std::span{buffer}); } else { static_assert(stream_transformer, @@ -671,6 +724,9 @@ template Receives from `transformer` into `sink` as @ref drain does, through the caller's `buffer`: each piece is a view of its first elements. + The buffer stays the caller's, who wipes it as the caller's own secret buffers are wiped: the + drain does not, also of a secret transformer. + @tparam T The transformer's type. @tparam Sink The sink's type. @param transformer A stream transformer. diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 03c10e7..45efe66 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -577,6 +577,14 @@ template } } +/** + Whether the elements a secret transformer holds in its own storage are wiped by + `secure::erase_secret`, which writes them as bytes: trivially copyable ones (D21). A public + transformer wipes nothing, and holds elements of any type. +*/ +template +inline constexpr bool wipeable_elements_v = !Secret || std::is_trivially_copyable_v; + /** Wipes `wiped` by `secure::erase_secret` when it goes, when `Engaged`: the scope guard of a secret operation's temporary, which wipes it also when the operation returns early or an allocation diff --git a/test/Jamfile b/test/Jamfile index a0e13f9..fd8d633 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -100,6 +100,13 @@ codecs-run buffered : buffered_test.cpp ; # one-shot form; the protocol's error rules (D18, B23, B44); over's stream # through a pipe of its links; a moved-from transformer restarts. codecs-run format_transformer : format_transformer_test.cpp ; +# Secret streams (D21): a transformer made with secret_operation, or of a secret +# part (pipe, each, buffered), is move-only, enters a guard of codecs' in each +# call, as secure's timing seam records it, with DIT set inside where the CPU has +# it, and wipes its pending state on reset, on destruction and on a move, as +# secure's wipe seam records it; a drain of one wipes its buffer. +codecs-run secret_stream : secret_stream_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index abbf240..ae7ab28 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -775,6 +775,74 @@ void check_each_and_buffered() { BOOST_TEST(verdict); } +/** + A secret stream allocates nothing either (D21): its guard and its wipes are in place. A secret + encoder and decoder of letters, sent, received into short spans, drained, moved, reset and + destroyed; a pipe of two secret encoders and over's secret stream; each and buffered in place + over a secret encoder. +*/ +void check_secret_streams() { + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + bool volatile verdict = false; + expect_no_allocation("encoder(letters, secret_operation) and its decoder", [&] { + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{text}.first(3)).has_value(); + auto moved{std::move(encoder)}; + std::size_t written = 3; + auto sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + streamed = streamed && moved.flush().has_value() && + codecs::drain(moved, sink, codecs::capacity<5>).has_value() && written == 12; + moved.reset(); + auto decoder = codecs::decoder(test::letters, codecs::secret_operation); + streamed = streamed && decoder.send(std::span{text}.first(12)).has_value() && + decoder.flush().has_value() && decoder.receive(decoded).has_value(); + auto moved_decoder{std::move(decoder)}; + moved_decoder.reset(); + verdict = streamed && decoded == bytes; + }); + BOOST_TEST(verdict); + expect_no_allocation("pipe of two secret encoders, and over's secret stream", [&] { + auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + bool streamed = piped.send(bytes).has_value() && piped.flush().has_value(); + auto const received = piped.receive(text); + auto moved{std::move(piped)}; + moved.reset(); + auto chain = + codecs::encoder(codecs::over{test::letters, test::letters}, codecs::secret_operation); + std::array chain_text{}; + streamed = streamed && received.has_value() && received->count == text.size() && + chain.send(bytes).has_value() && chain.flush().has_value() && + chain.receive(chain_text).has_value(); + chain.reset(); + verdict = streamed && chain_text == text; + }); + BOOST_TEST(verdict); + expect_no_allocation("each and buffered in place over a secret encoder", [&] { + auto each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{text}.first(1)).has_value() && + each.receive(std::span{text}.subspan(1, 1)).has_value(); + auto moved_each{std::move(each)}; + moved_each.reset(); + auto buffered = codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<6>); + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text[0] == 'a' && text[11] == 'l'; + }); + BOOST_TEST(verdict); +} + /** A pipe of packets_to_frames into each(frame_to_image, capacity<1>) allocates nothing (D21). */ void check_pipe_of_packets_into_each() { std::array images{}; @@ -855,6 +923,7 @@ int main() { check_pipe_and_drain(); check_format_transformers(); check_each_and_buffered(); + check_secret_streams(); check_pipe_of_packets_into_each(); check_saturating_refusals(); return boost::report_errors(); diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp new file mode 100644 index 0000000..db57d7b --- /dev/null +++ b/test/secret_stream_test.cpp @@ -0,0 +1,834 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Secret streams (D21), through both of secure's seams: support/timing_seam.hpp counts the timing +// guards codecs enters, and support/wipe_recorder.hpp records every wipe. A transformer is secret +// when it was made with secret_operation (format_encoder and format_decoder) or a part of it is +// (piped, each, buffered): it is move-only, each of its calls enters a guard of codecs', which +// nests with its parts' own, and its pending state (letters' carries, the pipe's intermediate, the +// storage of each and buffered) is wiped on reset, on destruction and in the moved-from object; a +// drain of a secret transformer wipes its own buffer. Where the guard acts +// (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, dit_probe, a secret transformer of the +// test's own, finds DIT set in each conversion call of a pipe, an each and a buffered of it, and +// DIT is clear after each call (D15, ruling R4). The spec's scenario "A secret stream's state is +// wiped", here on letters (Task 16 adds base64's); every moved-from secret transformer converts a +// new input from the start (Review Focus 5). + +#include "support/timing_seam.hpp" + +#include "support/wipe_recorder.hpp" + +#include "support/timing_dit.hpp" + +#include "support/allocators.hpp" +#include "support/letters.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; + +namespace secret_stream { +namespace { + +/** The calls of every dit_probe, and those that found DIT set. */ +struct dit_record { + /** The conversion calls. */ + std::size_t calls = 0; + /** The conversion calls that found DIT set. */ + std::size_t calls_with_dit = 0; +}; + +/** The calls of every dit_probe since the test last cleared them. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +dit_record dit_seen; + +/** Counts a conversion call of a dit_probe, and whether it found DIT set. */ +void record_dit() noexcept { + ++dit_seen.calls; + if (secure::dit_is_set()) { + ++dit_seen.calls_with_dit; + } +} + +/** + A secret transformer of the test's own, std::uint8_t to std::uint8_t, one-shot and stream, that + copies its input and records whether DIT is set in each conversion call (`transform`, `send`, + `receive`, `flush`); it holds no guard of its own, so that DIT is set only by the composition + that holds it. It borrows what `send` accepts and copies it during `receive`. +*/ +class dit_probe { +public: + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** As many bytes out as in. */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Copies `input` into `output`. */ + [[nodiscard]] codecs::result transform(std::span input, + std::span output) noexcept { + record_dit(); + if (output.size() < input.size()) { + return codecs::error::output_too_small; + } + std::ranges::copy(input, output.begin()); + return input.size(); + } + + /** Borrows all of `input` in `needs_input`. */ + [[nodiscard]] codecs::result send(std::span input) noexcept { + record_dit(); + if (state() != codecs::flow::needs_input) { + return codecs::step{.count = 0, .flow = state()}; + } + borrowed_ = input; + return codecs::step{.count = input.size(), .flow = state()}; + } + + /** Copies what it borrows into `output`, as it has room. */ + [[nodiscard]] codecs::result receive(std::span output) noexcept { + record_dit(); + std::size_t const count = std::min(borrowed_.size(), output.size()); + std::ranges::copy(borrowed_.first(count), output.begin()); + borrowed_ = borrowed_.subspan(count); + return codecs::step{.count = count, .flow = state()}; + } + + /** Ends the input. */ + [[nodiscard]] codecs::result flush() noexcept { + record_dit(); + flushed_ = true; + return state(); + } + + /** Back to `needs_input`, nothing borrowed. */ + void reset() noexcept { + borrowed_ = {}; + flushed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] codecs::flow state() const noexcept { + if (!borrowed_.empty()) { + return codecs::flow::output_pending; + } + return flushed_ ? codecs::flow::finished : codecs::flow::needs_input; + } + + /** The bytes `send` accepted and `receive` has not copied. */ + std::span borrowed_; + /** Whether `flush` ended the input. */ + bool flushed_ = false; +}; + +} // namespace +} // namespace secret_stream + +/** dit_probe is secret. */ +template <> +struct webcpp::codecs::is_secret : std::true_type {}; + +namespace secret_stream { +namespace { + +using secret_encoder = decltype(codecs::encoder(test::letters, codecs::secret_operation)); +using secret_decoder = decltype(codecs::decoder(test::letters, codecs::secret_operation)); +using public_encoder = decltype(codecs::encoder(test::letters)); +using public_decoder = decltype(codecs::decoder(test::letters)); +using secret_pipe = codecs::piped>; +using mixed_pipe = codecs::piped>; +using public_pipe = codecs::piped>; +using secret_each = codecs::each>; +using public_each = codecs::each>; +using secret_buffered = codecs::buffered>; +using public_buffered = codecs::buffered>; + +// A transformer is secret when it was made with secret_operation, or a part of it is (D21). +static_assert(codecs::is_secret_v && codecs::is_secret_v); +static_assert(!codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v && codecs::is_secret_v); +static_assert(codecs::is_secret_v< + codecs::piped>>); +static_assert(!codecs::is_secret_v); +static_assert(codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v>>); +static_assert(std::same_as>); +static_assert(codecs::is_secret_v>); + +/** Whether `T` is move-only: movable without throwing, and neither copy constructible nor + * assignable. */ +template +inline constexpr bool move_only_v = + std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v && + !std::is_copy_constructible_v && !std::is_copy_assignable_v; + +// A secret transformer is move-only (D21); its public twin keeps its copy. +static_assert(move_only_v && move_only_v); +static_assert(move_only_v && move_only_v); +static_assert(move_only_v && move_only_v); +static_assert(move_only_v>>); +static_assert(move_only_v>>); +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v && + std::is_copy_assignable_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v && + std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); + +// A secret transformer keeps its concepts and its noexcept calls. +static_assert(codecs::stream_transformer && + codecs::one_shot_transformer); +static_assert(codecs::stream_transformer && codecs::stream_transformer && + codecs::stream_transformer); +static_assert(noexcept(std::declval().receive(std::declval>()))); +static_assert(noexcept(std::declval().receive(std::declval>()))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +/** The 31 secret bytes every check converts: 0x00, 0x11, ... with 0xf7 and 0x08 among them. */ +std::array thirty_one_bytes() { + std::array bytes{}; + for (std::size_t index = 0; index < bytes.size(); ++index) { + bytes[index] = static_cast((index * 0x11U) + (index / 16U)); + } + return bytes; +} + +/** The letters of `bytes`, by the one-shot form. */ +std::string letters_of(std::span bytes) { + return codecs::encode(test::letters, bytes, codecs::tokens::return_string).value(); +} + +/** The letters of the letters of `bytes`: a pipe of two letters encoders, as over's one-shot. */ +std::string letters_of_letters(std::span bytes) { + return codecs::encode(codecs::over{test::letters, test::letters}, bytes, + codecs::tokens::return_string) + .value(); +} + +/** Whether DIT reads set inside a guard here: the guard acts and the CPU has DIT. */ +bool dit_applies() { +#ifdef WEBCPP_SECURE_TIMING_COVERED + return secure::cpu_has_dit(); +#else + return false; +#endif +} + +/** + Checks the guards a call entered, from `before`: at least one of codecs' for a call of a secret + transformer (`Secret`), none at all for a public one; and DIT clear after it, the guards having + restored it. +*/ +template +void check_guards(std::size_t before, std::size_t all_before) { + if constexpr (Secret) { + BOOST_TEST_GT(test::timing_entries, before); + } else { + BOOST_TEST_EQ(test::timing_all_entries, all_before); + } + BOOST_TEST(!secure::dit_is_set()); +} + +/** + Runs `call`, one call of a transformer, and checks its guards as @ref check_guards does: at least + one of codecs' when `Secret`, the default, none otherwise. + + @return What the call returned. +*/ +template +auto guarded(Call call) { + std::size_t const before = test::timing_entries; + std::size_t const all_before = test::timing_all_entries; + if constexpr (std::is_void_v) { + call(); + check_guards(before, all_before); + } else { + auto const outcome = call(); + check_guards(before, all_before); + return outcome; + } +} + +/** + Streams `input` through `stream` from the state it is in: sends what it accepts, receives into + spans of `span_size` elements, flushes once the input is sent, until it is finished; every call + is checked by @ref guarded, a guard of codecs' entered when the stream is secret and none when it + is public, and the output appended to `output`. + + @return Whether every call succeeded and the stream finished. +*/ +template +bool stream_guarded(Stream& stream, std::span input, + std::size_t span_size, Output& output) { + using output_type = Stream::output_type; + constexpr bool secret = codecs::is_secret_v; + std::array buffer{}; + std::size_t sent = 0; + bool flushed = false; + codecs::flow state = codecs::flow::needs_input; + for (std::size_t calls = 0; calls < 100000; ++calls) { + if (state == codecs::flow::finished) { + return true; + } + if (state == codecs::flow::needs_input && sent < input.size()) { + auto const accepted = guarded([&] { return stream.send(input.subspan(sent)); }); + if (!accepted.has_value()) { + return false; + } + sent += accepted->count; + state = accepted->flow; + } else if (state == codecs::flow::needs_input && !flushed) { + auto const ended = guarded([&] { return stream.flush(); }); + if (!ended.has_value()) { + return false; + } + flushed = true; + state = *ended; + } else { + auto const received = + guarded([&] { return stream.receive(std::span{buffer}.first(span_size)); }); + if (!received.has_value()) { + return false; + } + output.insert(output.end(), buffer.begin(), + buffer.begin() + static_cast(received->count)); + state = received->flow; + if (state == codecs::flow::needs_input && flushed) { + return false; + } + } + } + return false; +} + +/** The text a stream of characters gives for `input`, through @ref stream_guarded. */ +template +std::string text_of(Stream& stream, std::span input, std::size_t span_size) { + std::string output; + BOOST_TEST(stream_guarded(stream, input, span_size, output)); + return output; +} + +/** The bytes a stream of bytes gives for `input`, through @ref stream_guarded. */ +template +std::vector bytes_of(Stream& stream, std::span input, + std::size_t span_size) { + std::vector output; + BOOST_TEST(stream_guarded(stream, input, span_size, output)); + return output; +} + +/** The characters of `text`, as a decoder reads them. */ +std::span characters_of(std::string_view text) { + return {text.data(), text.size()}; +} + +/** + The wipes of `size` bytes, every byte zero when reported, whose first byte is inside the + `object_size` bytes at `object`: an object's own storage, alive or destroyed. +*/ +std::size_t wipes_inside(void const* object, std::size_t object_size, std::size_t size) { + auto const* const first = static_cast(object); + auto const* const end = first + object_size; + std::less const before; + std::size_t found = 0; + for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); + ++index) { + test::wipe_entry const& entry = test::wipes.entries[index]; + if (entry.size == size && entry.zero && !before(entry.address, first) && + before(entry.address, end)) { + ++found; + } + } + return found; +} + +/** The wipes of `size` bytes, every byte zero when reported, wherever they were. */ +std::size_t wipes_of_size(std::size_t size) { + std::size_t found = 0; + for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); + ++index) { + test::wipe_entry const& entry = test::wipes.entries[index]; + if (entry.size == size && entry.zero) { + ++found; + } + } + return found; +} + +/** The wipes of `size` bytes inside `object`, as @ref wipes_inside counts them. */ +template +std::size_t wipes_in(T const& object, std::size_t size) { + return wipes_inside(&object, sizeof(T), size); +} + +/** + Destroys the object `holder` holds and returns the wipes of `size` bytes inside the storage it + had, as @ref wipes_inside counts them. +*/ +template +std::size_t wipes_at_destruction(std::optional& holder, std::size_t size) { + void const* const storage = &*holder; + test::clear_wipes(); + holder.reset(); + return wipes_inside(storage, sizeof(T), size); +} + +/** + Every call of a secret pipe of two secret letters encoders over 31 bytes enters a guard of + codecs' and leaves DIT clear, `reset` included, and the pipe is move-only; each and buffered over + a secret encoder the same; the output is the one-shot form's. +*/ +void every_call_of_a_secret_composition_is_guarded() { + std::array const input = thirty_one_bytes(); + test::force_dit(false); + for (std::size_t span_size : {std::size_t{1}, std::size_t{3}, std::size_t{64}}) { + auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + static_assert(std::same_as); + BOOST_TEST_EQ(text_of(piped, input, span_size), letters_of_letters(input)); + guarded([&] { piped.reset(); }); + BOOST_TEST_EQ(text_of(piped, input, span_size), letters_of_letters(input)); + + // One secret part makes the pipe secret: its own guard covers the public part's calls. + auto mixed = codecs::pipe(codecs::encoder(test::letters), + codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(mixed, input, span_size), letters_of_letters(input)); + + auto each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>); + BOOST_TEST_EQ(text_of(each, input, span_size), letters_of(input)); + guarded([&] { each.reset(); }); + auto heap_each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(heap_each, input, span_size), letters_of(input)); + + auto buffered = codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>); + BOOST_TEST_EQ(text_of(buffered, input, span_size), letters_of(input)); + guarded([&] { buffered.reset(); }); + auto heap_buffered = + codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(heap_buffered, input, span_size), letters_of(input)); + } +} + +/** + Every call of a secret format transformer enters a guard of codecs': the four stream calls and + `transform` and `output_size`, of the encoder and of the decoder; a public one enters none. +*/ +void every_call_of_a_secret_format_transformer_is_guarded() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + test::force_dit(false); + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + BOOST_TEST_EQ(text_of(encoder, input, 5), text); + guarded([&] { encoder.reset(); }); + std::array text_buffer{}; + BOOST_TEST(guarded([&] { return encoder.transform(input, text_buffer); }).has_value()); + BOOST_TEST_EQ(guarded([&] { return encoder.output_size(input); }), 62U); + auto decoder = codecs::decoder(test::letters, codecs::secret_operation); + std::vector decoded; + BOOST_TEST(stream_guarded(decoder, characters_of(text), 7, decoded)); + BOOST_TEST(std::ranges::equal(decoded, input)); + guarded([&] { decoder.reset(); }); + std::array byte_buffer{}; + BOOST_TEST( + guarded([&] { return decoder.transform(characters_of(text), byte_buffer); }).has_value()); + BOOST_TEST_EQ(guarded([&] { return decoder.output_size(characters_of(text)); }), 31U); + + // A public transformer enters no guard. + std::size_t const before = test::timing_all_entries; + auto public_letters = codecs::encoder(test::letters); + BOOST_TEST(public_letters.send(input).has_value()); + BOOST_TEST(public_letters.receive(text_buffer).has_value()); + BOOST_TEST(public_letters.flush().has_value()); + public_letters.reset(); + BOOST_TEST(public_letters.transform(input, text_buffer).has_value()); + auto public_pipe_of_letters = + codecs::pipe(codecs::encoder(test::letters), codecs::encoder(test::letters)); + BOOST_TEST(public_pipe_of_letters.send(input).has_value()); + public_pipe_of_letters.reset(); + BOOST_TEST_EQ(test::timing_all_entries, before); +} + +/** + Where the guard acts and the CPU has DIT, a dit_probe finds DIT set in each conversion call of a + pipe of two, of an each and of a buffered of one, which hold the guard, and DIT is clear after + each call; elsewhere it never finds DIT set (D15, ruling R4: the guards nest, and the count of + engaged guards returns to zero after each call). +*/ +void dit_is_set_in_every_call_of_a_secret_composition() { + std::array const input = thirty_one_bytes(); + std::vector const expected(input.begin(), input.end()); + bool const applies = dit_applies(); + test::force_dit(false); + BOOST_TEST(!secure::dit_is_set()); + + dit_seen = dit_record{}; + auto piped = codecs::pipe(dit_probe{}, dit_probe{}, codecs::capacity<4>); + BOOST_TEST(bytes_of(piped, input, 3) == expected); + auto each = codecs::each(dit_probe{}, codecs::capacity<1>); + BOOST_TEST(bytes_of(each, input, 2) == expected); + auto buffered = codecs::buffered(dit_probe{}, codecs::capacity<31>); + BOOST_TEST(bytes_of(buffered, input, 5) == expected); + auto heap_buffered = codecs::buffered(dit_probe{}); + BOOST_TEST(bytes_of(heap_buffered, input, 64) == expected); + + BOOST_TEST_GT(dit_seen.calls, 40U); + BOOST_TEST_EQ(dit_seen.calls_with_dit, applies ? dit_seen.calls : 0U); + BOOST_TEST(!secure::dit_is_set()); + + // A probe called outside any guard finds DIT clear: the check above is not vacuous. + dit_seen = dit_record{}; + dit_probe alone; + std::array copied{}; + BOOST_TEST(alone.transform(input, copied).has_value()); + BOOST_TEST_EQ(dit_seen.calls, 1U); + BOOST_TEST_EQ(dit_seen.calls_with_dit, 0U); +} + +/** + The spec's scenario "A secret stream's state is wiped", on letters: 31 secret bytes into a secret + encoder, received into spans of one letter, so that one letter waits; the wipe seam records the + waiting letter's wipe in the source after a move, at reset and at the destruction of each; the + moved-to encoder delivers the rest, and the moved-from one converts a new input from the start + (Review Focus 5). +*/ +void a_secret_encoders_pending_state_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + std::optional source; + source.emplace(test::letters); + auto const sent = source->send(input); + BOOST_TEST(sent.has_value() && sent->count == input.size()); + std::array letter{}; + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + BOOST_TEST_EQ(letter[0], text[0]); + + // The move takes the waiting letter, and wipes it in the source. + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(wipes_in(*source, 1), 1U); + std::string rest; + BOOST_TEST(stream_guarded(*target, std::span{}, 1, rest)); + BOOST_TEST_EQ(text.substr(0, 1) + rest, text); + + // The moved-from encoder converts a new input from the start. + BOOST_TEST_EQ(text_of(*source, input, 1), text); + + // reset wipes; the reset encoder converts again. + BOOST_TEST(target->send(input).has_value()); + BOOST_TEST(target->receive(letter).has_value()); + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(wipes_in(*target, 1), 1U); + BOOST_TEST_EQ(text_of(*target, input, 2), text); + + // The destruction of each wipes. + BOOST_TEST(target->send(input).has_value()); + BOOST_TEST(target->receive(letter).has_value()); + BOOST_TEST_EQ(wipes_at_destruction(target, 1), 1U); + BOOST_TEST_EQ(wipes_at_destruction(source, 1), 1U); + + // A move assignment wipes the source as the move does. + secret_encoder assigned{test::letters}; + secret_encoder moved{test::letters}; + BOOST_TEST(moved.send(input).has_value()); + BOOST_TEST(moved.receive(letter).has_value()); + test::clear_wipes(); + assigned = std::move(moved); + BOOST_TEST_EQ(wipes_in(moved, 1), 1U); + BOOST_TEST_EQ(text_of(moved, input, 3), text); +} + +/** + A secret decoder's held letter and error mask are wiped likewise: a byte each, in the source after + a move, at reset and at destruction; the moved-to decoder delivers the rest and the moved-from one + decodes a new text from the start (Review Focus 5). +*/ +void a_secret_decoders_pending_state_is_wiped() { + std::array const input = thirty_one_bytes(); + std::vector const expected(input.begin(), input.end()); + std::string const text = letters_of(input); + std::optional source; + source.emplace(test::letters); + // Three letters: a byte of the first two, the third held. + BOOST_TEST(source->send(characters_of(text).first(3)).has_value()); + std::array byte{}; + auto const first = source->receive(byte); + BOOST_TEST(first.has_value() && first->count == 1 && first->flow == codecs::flow::needs_input); + BOOST_TEST_EQ(byte[0], input[0]); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(wipes_in(*source, 1), 2U); + std::vector rest{input[0]}; + BOOST_TEST(stream_guarded(*target, characters_of(text).subspan(3), 1, rest)); + BOOST_TEST(rest == expected); + + std::vector again; + BOOST_TEST(stream_guarded(*source, characters_of(text), 1, again)); + BOOST_TEST(again == expected); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(wipes_in(*target, 1), 2U); + BOOST_TEST_EQ(wipes_at_destruction(target, 1), 2U); + BOOST_TEST_EQ(wipes_at_destruction(source, 1), 2U); +} + +/** + A secret pipe's intermediate is wiped whole (512 characters) in the source after a move, at reset + and at destruction; the move is made where the second part borrows nothing, after a receive that + took everything, with the intermediate holding what the second part read; the moved-from pipe + converts a new input from the start (Review Focus 5). +*/ +void a_secret_pipes_intermediate_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of_letters(input); + constexpr std::size_t intermediate_size = codecs::default_capacity_v; + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST(source->send(input).has_value()); + std::array output{}; + auto const received = source->receive(output); + BOOST_TEST(received.has_value() && received->count == output.size() && + received->flow == codecs::flow::needs_input); + BOOST_TEST_EQ(std::string_view(output.data(), output.size()), text); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(wipes_in(*source, intermediate_size), 1U); + std::string rest; + BOOST_TEST(stream_guarded(*target, std::span{}, 8, rest)); + BOOST_TEST(rest.empty()); + + BOOST_TEST_EQ(text_of(*source, input, 7), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(wipes_in(*target, intermediate_size), 1U); + BOOST_TEST_EQ(text_of(*target, input, 64), text); + BOOST_TEST_EQ(wipes_at_destruction(target, intermediate_size), 1U); + BOOST_TEST_EQ(wipes_at_destruction(source, intermediate_size), 1U); + + // A public pipe wipes nothing of its own. + std::optional public_holder; + public_holder.emplace(codecs::encoder(test::letters), codecs::encoder(test::letters)); + BOOST_TEST_EQ(text_of(*public_holder, input, 64).size(), text.size()); + BOOST_TEST_EQ(wipes_at_destruction(public_holder, intermediate_size), 0U); +} + +/** + A secret buffered's storage in place, 31 bytes of input and 62 letters of output, is wiped in the + source after a move, at reset and at destruction, with output pending at the move; the moved-to + stream delivers the rest and the moved-from one converts a new input from the start (Review Focus + 5). +*/ +void a_secret_buffereds_storage_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), codecs::capacity<31>); + BOOST_TEST(source->send(input).has_value()); + BOOST_TEST(source->flush().has_value()); + std::array letter{}; + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(wipes_in(*source, 31), 1U); + BOOST_TEST_EQ(wipes_in(*source, 62), 1U); + std::string rest{letter[0]}; + BOOST_TEST(stream_guarded(*target, std::span{}, 4, rest)); + BOOST_TEST_EQ(rest, text); + + BOOST_TEST_EQ(text_of(*source, input, 9), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(wipes_in(*target, 31), 1U); + BOOST_TEST_EQ(wipes_in(*target, 62), 1U); + BOOST_TEST_EQ(text_of(*target, input, 64), text); + BOOST_TEST_EQ(wipes_at_destruction(target, 62), 1U); + BOOST_TEST_EQ(wipes_at_destruction(source, 31), 1U); +} + +/** + A secret each's item storage in place, the two letters of one byte, is wiped in the source after a + move made while a letter of the item waits in it, at reset and at destruction; the moved-to stream + delivers the rest and the moved-from one converts a new input from the start (Review Focus 5). +*/ +void a_secret_eachs_storage_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), codecs::capacity<2>); + auto const sent = source->send(input); + BOOST_TEST(sent.has_value() && sent->count == 1); + std::array letter{}; + // A span shorter than the item's two letters: the item goes through the storage. + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(wipes_in(*source, 2), 1U); + std::string rest{letter[0]}; + BOOST_TEST(stream_guarded(*target, std::span{input}.subspan(1), 1, rest)); + BOOST_TEST_EQ(rest, text); + + BOOST_TEST_EQ(text_of(*source, input, 1), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(wipes_in(*target, 2), 1U); + BOOST_TEST_EQ(wipes_at_destruction(target, 2), 1U); + BOOST_TEST_EQ(wipes_at_destruction(source, 2), 1U); +} + +/** + From an allocator, the storage of a secret buffered and of a secret each goes back to it wiped, + every block: the blocks the input outgrows as many small sends grow it, and the last at + destruction; a public buffered gives its blocks back as they are, so that the count is not + vacuous. +*/ +void a_secret_streams_heap_storage_goes_back_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + test::wipe_checking_allocator const allocator; + { + auto buffered = + codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), allocator); + for (std::size_t index = 0; index < input.size(); ++index) { + BOOST_TEST(buffered.send(std::span{input}.subspan(index, 1)).has_value()); + } + std::string output; + BOOST_TEST(stream_guarded(buffered, std::span{}, 4, output)); + BOOST_TEST_EQ(output, text); + buffered.reset(); + BOOST_TEST_EQ(text_of(buffered, input, 64), text); + } + test::wipe_checking_allocator const each_allocator; + { + auto each = + codecs::each(codecs::encoder(test::letters, codecs::secret_operation), each_allocator); + BOOST_TEST_EQ(text_of(each, input, 1), text); + } + BOOST_TEST_GT(allocator.state()->deallocations, 4U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.state()->allocations); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); + BOOST_TEST_GT(each_allocator.state()->deallocations, 0U); + BOOST_TEST_EQ(each_allocator.state()->wiped_deallocations, + each_allocator.state()->deallocations); + + test::wipe_checking_allocator const public_allocator; + { + auto buffered = codecs::buffered(codecs::encoder(test::letters), public_allocator); + BOOST_TEST_EQ(text_of(buffered, input, 64), text); + } + BOOST_TEST_GT(public_allocator.state()->deallocations, 0U); + BOOST_TEST_LT(public_allocator.state()->wiped_deallocations, + public_allocator.state()->deallocations); +} + +/** + A drain of a secret transformer wipes its own buffer before it returns, of the default capacity + and of a capacity named; a drain of a public one does not. +*/ +void a_drain_of_a_secret_stream_wipes_its_buffer() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + std::string drained; + auto sink = [&](std::span piece) { drained.append(piece.begin(), piece.end()); }; + + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + BOOST_TEST(encoder.send(input).has_value()); + test::clear_wipes(); + auto const named = codecs::drain(encoder, sink, codecs::capacity<37>); + BOOST_TEST(named.has_value() && named.value() == codecs::flow::needs_input); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(wipes_of_size(37), 1U); + + drained.clear(); + encoder.reset(); + BOOST_TEST(encoder.send(input).has_value()); + BOOST_TEST(encoder.flush().has_value()); + test::clear_wipes(); + auto const by_default = codecs::drain(encoder, sink); + BOOST_TEST(by_default.has_value() && by_default.value() == codecs::flow::finished); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(wipes_of_size(codecs::default_capacity_v), 1U); + + drained.clear(); + auto public_letters = codecs::encoder(test::letters); + BOOST_TEST(public_letters.send(input).has_value()); + test::clear_wipes(); + BOOST_TEST(codecs::drain(public_letters, sink, codecs::capacity<37>).has_value()); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace +} // namespace secret_stream + +int main() { + secret_stream::every_call_of_a_secret_composition_is_guarded(); + secret_stream::every_call_of_a_secret_format_transformer_is_guarded(); + secret_stream::dit_is_set_in_every_call_of_a_secret_composition(); + secret_stream::a_secret_encoders_pending_state_is_wiped(); + secret_stream::a_secret_decoders_pending_state_is_wiped(); + secret_stream::a_secret_pipes_intermediate_is_wiped(); + secret_stream::a_secret_buffereds_storage_is_wiped(); + secret_stream::a_secret_eachs_storage_is_wiped(); + secret_stream::a_secret_streams_heap_storage_goes_back_wiped(); + secret_stream::a_drain_of_a_secret_stream_wipes_its_buffer(); + return boost::report_errors(); +} diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp index 499a6ff..55c4551 100644 --- a/test/support/allocators.hpp +++ b/test/support/allocators.hpp @@ -18,7 +18,10 @@ // (support/bookkeeping.hpp), which holds no byte of a value, is not counted. // // A move of throwing_allocator or wipe_checking_allocator is a copy: the source keeps the shared -// count and stays equal to what it was, as the allocator requirements ask. +// count and stays equal to what it was, as the allocator requirements ask. Both give out blocks +// that read zero, so that a byte that does not read zero when its block is given back was written +// and not wiped, on every target: an allocator that reuses memory (Emscripten's dlmalloc) would +// otherwise hand out bytes nobody wrote, past the elements a container holds. #ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP @@ -29,6 +32,7 @@ #include #include +#include #include #include #include @@ -42,6 +46,17 @@ inline bool reads_zero(void const* block, std::size_t count) noexcept { [](unsigned char byte_value) { return byte_value == 0; }); } +/** + A block of `count` elements from `std::allocator`, every byte zero, raw storage in which no + element is constructed yet. +*/ +template +[[nodiscard]] T* allocate_zeroed(std::size_t count) { + T* const block = std::allocator{}.allocate(count); + std::memset(static_cast(block), 0, count * sizeof(T)); + return block; +} + #ifndef WEBCPP_CODECS_NO_EXCEPTIONS /** The count a throwing_allocator and its copies share. */ @@ -96,7 +111,7 @@ class throwing_allocator { // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) throwing_allocator(throwing_allocator const& other) noexcept : state_(other.state()) {} - /** Allocates `count` elements, or throws on the allocation that is to fail. */ + /** Allocates `count` elements, every byte zero, or throws on the allocation that is to fail. */ [[nodiscard]] T* allocate(std::size_t count) { // A standard container's own block (the MSVC STL's debug proxy) is neither counted nor // failed: it is allocated in noexcept constructors, where a throw ends the program. @@ -106,7 +121,7 @@ class throwing_allocator { throw std::bad_alloc(); } } - return std::allocator{}.allocate(count); + return allocate_zeroed(count); } /** Counts the block, and whether a byte of it was not zero, and returns it. */ @@ -240,12 +255,12 @@ class wipe_checking_allocator { wipe_checking_allocator(wipe_checking_allocator const& other) noexcept : state_(other.state()) {} - /** Allocates `count` elements. */ + /** Allocates `count` elements, every byte zero. */ [[nodiscard]] T* allocate(std::size_t count) { if (!is_bookkeeping(count * sizeof(T), alignof(T))) { ++state_->allocations; } - return std::allocator{}.allocate(count); + return allocate_zeroed(count); } /** Counts the block, whether it is all zero, and returns it. */ diff --git a/test/support/letters.hpp b/test/support/letters.hpp index 31119f1..f2bc909 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -11,15 +11,19 @@ // configuration_fault gives as `invalid_prefix` and nothing else checks: the core reports it first // in every form (B23). Its stream codec (D20) keeps the protocol's error rules (D18, B44): the // encoder holds the one letter its output had no room for, the decoder one letter of a pair and the -// lowest data error seen. whole_letters is letters' codec under another name, with no stream codec -// and no configuration, so that its transformers are one-shot alone. holding_letters is -// whole_letters' codec with letters' streams, its decoder declaring that it holds its input and -// giving what it read, as bech32's and the armor's do. +// lowest data error seen; with Options.secret (D21) each is move-only and wipes its pending state +// (the encoder's waiting letter, the decoder's held letter and its error mask) by +// secure::erase_secret on reset, on destruction and in the moved-from object, one byte a wipe. +// whole_letters is letters' codec under another name, with no stream codec and no configuration, so +// that its transformers are one-shot alone. holding_letters is whole_letters' codec with letters' +// streams, its decoder declaring that it holds its input and giving what it read, as bech32's and +// the armor's do. #ifndef WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_LETTERS_HPP #include +#include #include @@ -234,10 +238,14 @@ struct stream_codec { /** An encoder in `needs_input`; letters' stream has nothing of the format to keep. */ explicit encoder(test::letters_t const& /*format*/) noexcept {} - /** A copy of the state, borrowing what `other` borrows. */ - encoder(encoder const&) noexcept = default; - /** A copy of the state, borrowing what `other` borrows. */ - encoder& operator=(encoder const&) noexcept = default; + /** A copy of the state, borrowing what `other` borrows; a secret stream has none. */ + encoder(encoder const&) noexcept + requires(!Options.secret) + = default; + /** A copy of the state, borrowing what `other` borrows; a secret stream has none. */ + encoder& operator=(encoder const&) noexcept + requires(!Options.secret) + = default; /** Takes `other`'s state and leaves `other` as `reset` does. */ encoder(encoder&& other) noexcept @@ -264,7 +272,8 @@ struct stream_codec { return *this; } - ~encoder() = default; + /** Wipes the waiting letter of a secret stream. */ + ~encoder() { wipe_pending(); } /** Borrows all of `input` in `needs_input`. */ result send(std::span input) noexcept { @@ -316,8 +325,12 @@ struct stream_codec { return state(); } - /** Back to `needs_input`, nothing borrowed or pending, the error forgotten. */ + /** + Back to `needs_input`, nothing borrowed or pending, the error forgotten; the waiting + letter of a secret stream wiped. + */ void reset() noexcept { + wipe_pending(); borrowed_ = {}; position_ = 0; pending_ = 0; @@ -327,6 +340,13 @@ struct stream_codec { } private: + /** Wipes the waiting letter, a byte, when the stream is secret. */ + void wipe_pending() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&pending_, 1}); + } + } + /** Whether a call reports an error, which stays until `reset`. */ [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } @@ -371,10 +391,14 @@ struct stream_codec { /** A decoder in `needs_input`; letters' stream has nothing of the format to keep. */ explicit decoder(test::letters_t const& /*format*/) noexcept {} - /** A copy of the state, borrowing what `other` borrows. */ - decoder(decoder const&) noexcept = default; - /** A copy of the state, borrowing what `other` borrows. */ - decoder& operator=(decoder const&) noexcept = default; + /** A copy of the state, borrowing what `other` borrows; a secret stream has none. */ + decoder(decoder const&) noexcept + requires(!Options.secret) + = default; + /** A copy of the state, borrowing what `other` borrows; a secret stream has none. */ + decoder& operator=(decoder const&) noexcept + requires(!Options.secret) + = default; /** Takes `other`'s state and leaves `other` as `reset` does. */ decoder(decoder&& other) noexcept @@ -405,7 +429,8 @@ struct stream_codec { return *this; } - ~decoder() = default; + /** Wipes the held letter and the error mask of a secret stream. */ + ~decoder() { wipe_held(); } /** Borrows all of `input` in `needs_input`; a lone letter is held at once. */ result send(std::span input) noexcept { @@ -473,8 +498,12 @@ struct stream_codec { return state(); } - /** Back to `needs_input`, nothing borrowed or held, the verdict and the error forgotten. */ + /** + Back to `needs_input`, nothing borrowed or held, the verdict and the error forgotten; the + held letter and the error mask of a secret stream wiped. + */ void reset() noexcept { + wipe_held(); borrowed_ = {}; position_ = 0; held_ = 0; @@ -486,6 +515,14 @@ struct stream_codec { } private: + /** Wipes the held letter and the error mask, a byte each, when the stream is secret. */ + void wipe_held() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&held_, 1}); + secure::erase_secret(std::span{&invalid_seen_, 1}); + } + } + /** Whether `letter` is one of `a` to `p`, read as an unsigned byte. */ [[nodiscard]] static bool is_letter(char letter) noexcept { auto const letter_value = static_cast(letter); From 7b12736f1efec60a166d9a45df8b93dfe08dcd69 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:07:28 -0300 Subject: [PATCH 070/157] codecs: secret streams doc fix, is_secret's Doc Comment names the transformers it is specialized for --- include/webcpp/codecs/detail/core/secrecy.hpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/include/webcpp/codecs/detail/core/secrecy.hpp b/include/webcpp/codecs/detail/core/secrecy.hpp index 45efe66..33a23a0 100644 --- a/include/webcpp/codecs/detail/core/secrecy.hpp +++ b/include/webcpp/codecs/detail/core/secrecy.hpp @@ -46,8 +46,10 @@ class basic_secret_byte_vector; Whether values of `T` are secret: false unless a library specializes it for its secret types, which makes every operation on such a value secret (D10). - codecs specializes it for `secure::secret` and for its own secret results. A specialization - derives from `std::true_type`. + codecs specializes it for `secure::secret`, for its own secret results, and for its + transformers, which are secret when made with `codecs::secret_operation` or of a secret part + (D21). A specialization derives from `std::true_type`, or from `std::bool_constant` where the + type is secret by its parameters, as a pipe is by its parts. @tparam T The type, cv-unqualified and not a reference. */ From 7a8cc440a3e54ce27f9241dfe37afd4772010bb9 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:11:52 -0300 Subject: [PATCH 071/157] codecs: secret streams lint fix, the trailing commas of two lists, the probe's transform static, the transparent less, a Jamfile comment in 80 columns, the use after a move under test --- include/webcpp/codecs/detail/core/pipe.hpp | 6 +++--- test/Jamfile | 6 +++--- test/format_transformer_test.cpp | 7 ++++--- test/secret_stream_test.cpp | 12 ++++++------ 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index c11bfde..b69c04d 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -707,9 +707,9 @@ template [[nodiscard]] result drain(T& transformer, Sink&& sink, capacity_t /*capacity*/) noexcept( detail::nothrow_drain()) { if constexpr (stream_transformer) { - std::array buffer{}; - detail::temporary_wipe, typename T::output_type> const buffer_wipe{ - std::span{buffer}}; + using output_type = T::output_type; + std::array buffer{}; + detail::temporary_wipe, output_type> const buffer_wipe{std::span{buffer}}; return detail::drain_through(transformer, sink, std::span{buffer}); } else { static_assert(stream_transformer, diff --git a/test/Jamfile b/test/Jamfile index fd8d633..a0d1d69 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -102,9 +102,9 @@ codecs-run buffered : buffered_test.cpp ; codecs-run format_transformer : format_transformer_test.cpp ; # Secret streams (D21): a transformer made with secret_operation, or of a secret # part (pipe, each, buffered), is move-only, enters a guard of codecs' in each -# call, as secure's timing seam records it, with DIT set inside where the CPU has -# it, and wipes its pending state on reset, on destruction and on a move, as -# secure's wipe seam records it; a drain of one wipes its buffer. +# call, as secure's timing seam records it, with DIT set inside where the CPU +# has it, and wipes its pending state on reset, on destruction and on a move, +# as secure's wipe seam records it; a drain of one wipes its buffer. codecs-run secret_stream : secret_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The default result of encode and decode without a token (D9). diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index 0c19de5..d86ff45 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -522,9 +522,10 @@ void a_configuration_fault_wins_in_every_one_shot_form() { // over's own encoded_size probes the chain's configuration before it runs the inner link, as // the core's does: 0, where the links, which check nothing of it, would give a size. std::array const chain_bytes{0x01, 0x23, 0xfe}; - for (letters_over_letters const& faulted_chain : - {letters_over_letters{test::letters(true), test::letters}, - letters_over_letters{test::letters, test::letters(true)}}) { + for (letters_over_letters const& faulted_chain : { + letters_over_letters{test::letters(true), test::letters}, + letters_over_letters{test::letters, test::letters(true)}, + }) { BOOST_TEST_EQ(codecs::codec::encoded_size( faulted_chain, std::span{chain_bytes}), 0U); diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp index db57d7b..587fde0 100644 --- a/test/secret_stream_test.cpp +++ b/test/secret_stream_test.cpp @@ -91,8 +91,8 @@ class dit_probe { } /** Copies `input` into `output`. */ - [[nodiscard]] codecs::result transform(std::span input, - std::span output) noexcept { + [[nodiscard]] static codecs::result transform( + std::span input, std::span output) noexcept { record_dit(); if (output.size() < input.size()) { return codecs::error::output_too_small; @@ -366,7 +366,7 @@ std::span characters_of(std::string_view text) { std::size_t wipes_inside(void const* object, std::size_t object_size, std::size_t size) { auto const* const first = static_cast(object); auto const* const end = first + object_size; - std::less const before; + std::less<> const before; std::size_t found = 0; for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); ++index) { @@ -418,7 +418,7 @@ std::size_t wipes_at_destruction(std::optional& holder, std::size_t size) { void every_call_of_a_secret_composition_is_guarded() { std::array const input = thirty_one_bytes(); test::force_dit(false); - for (std::size_t span_size : {std::size_t{1}, std::size_t{3}, std::size_t{64}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{3}, std::size_t{64}}) { auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), codecs::encoder(test::letters, codecs::secret_operation)); static_assert(std::same_as); @@ -516,9 +516,8 @@ void dit_is_set_in_every_call_of_a_secret_composition() { // A probe called outside any guard finds DIT clear: the check above is not vacuous. dit_seen = dit_record{}; - dit_probe alone; std::array copied{}; - BOOST_TEST(alone.transform(input, copied).has_value()); + BOOST_TEST(dit_probe::transform(input, copied).has_value()); BOOST_TEST_EQ(dit_seen.calls, 1U); BOOST_TEST_EQ(dit_seen.calls_with_dit, 0U); } @@ -576,6 +575,7 @@ void a_secret_encoders_pending_state_is_wiped() { BOOST_TEST(moved.receive(letter).has_value()); test::clear_wipes(); assigned = std::move(moved); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test BOOST_TEST_EQ(wipes_in(moved, 1), 1U); BOOST_TEST_EQ(text_of(moved, input, 3), text); } From 72504290d7f60177421289105193222c9dcaf28b Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:27:27 -0300 Subject: [PATCH 072/157] codecs: MSVC fix, configuration_probe's fault one return a branch (C4702 at /W4) --- include/webcpp/codecs/detail/core/contract.hpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/include/webcpp/codecs/detail/core/contract.hpp b/include/webcpp/codecs/detail/core/contract.hpp index 6f36e42..6266ccd 100644 --- a/include/webcpp/codecs/detail/core/contract.hpp +++ b/include/webcpp/codecs/detail/core/contract.hpp @@ -367,13 +367,17 @@ struct configuration_probe { */ [[nodiscard]] static constexpr std::optional fault( [[maybe_unused]] F const& format_value) noexcept { + // One return a branch, so that no return is unreachable (MSVC's C4702 at /W4). if constexpr (has_codec) { check_configuration_fault(); if constexpr (has_configuration_fault) { return codec::configuration_fault(format_value); + } else { + return std::nullopt; } + } else { + return std::nullopt; } - return std::nullopt; } }; From f816f4ce7e5451a7685442905add81d2e4fc4d37 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:32:12 -0300 Subject: [PATCH 073/157] codecs: secret streams test prints whether DIT applies, so that a lane's log shows the DIT checks ran --- test/secret_stream_test.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp index 587fde0..a7b7f08 100644 --- a/test/secret_stream_test.cpp +++ b/test/secret_stream_test.cpp @@ -13,9 +13,9 @@ // drain of a secret transformer wipes its own buffer. Where the guard acts // (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, dit_probe, a secret transformer of the // test's own, finds DIT set in each conversion call of a pipe, an each and a buffered of it, and -// DIT is clear after each call (D15, ruling R4). The spec's scenario "A secret stream's state is -// wiped", here on letters (Task 16 adds base64's); every moved-from secret transformer converts a -// new input from the start (Review Focus 5). +// DIT is clear after each call (D15, ruling R4); the program prints whether DIT applies. The spec's +// scenario "A secret stream's state is wiped", here on letters (Task 16 adds base64's); every +// moved-from secret transformer converts a new input from the start (Review Focus 5). #include "support/timing_seam.hpp" @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -510,6 +511,9 @@ void dit_is_set_in_every_call_of_a_secret_composition() { auto heap_buffered = codecs::buffered(dit_probe{}); BOOST_TEST(bytes_of(heap_buffered, input, 64) == expected); + // Printed, so that a lane's log shows whether the DIT checks ran on its target. + std::printf("secret_stream: DIT %s; dit_probe calls %zu, with DIT set %zu\n", + applies ? "applies" : "does not apply", dit_seen.calls, dit_seen.calls_with_dit); BOOST_TEST_GT(dit_seen.calls, 40U); BOOST_TEST_EQ(dit_seen.calls_with_dit, applies ? dit_seen.calls : 0U); BOOST_TEST(!secure::dit_is_set()); From d818c57c2f98f7174e304f0b69d8ebf48de659c9 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:56:25 -0300 Subject: [PATCH 074/157] codecs: Task 12 fix round 1, the heap output's wipe before it outgrows a block under test, the move assignments' pre-wipe under test, the three secret refusals' message cases, a constrained destructor pair so that a public stream stays trivially destructible, two Doc Comments in the repository style --- .../webcpp/codecs/detail/core/adapters.hpp | 22 ++- include/webcpp/codecs/detail/core/over.hpp | 5 +- include/webcpp/codecs/detail/core/pipe.hpp | 12 +- test/messages/Jamfile | 3 + .../secret_buffered_not_wipeable/Jamfile | 16 ++ .../secret_buffered_not_wipeable.cpp | 25 +++ .../messages/secret_each_not_wipeable/Jamfile | 16 ++ .../secret_each_not_wipeable.cpp | 25 +++ .../messages/secret_pipe_not_wipeable/Jamfile | 16 ++ .../secret_pipe_not_wipeable.cpp | 26 ++++ test/secret_stream_test.cpp | 147 +++++++++++++++++- test/support/letters.hpp | 18 ++- test/support/secret_wide.hpp | 90 +++++++++++ 13 files changed, 409 insertions(+), 12 deletions(-) create mode 100644 test/messages/secret_buffered_not_wipeable/Jamfile create mode 100644 test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp create mode 100644 test/messages/secret_each_not_wipeable/Jamfile create mode 100644 test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp create mode 100644 test/messages/secret_pipe_not_wipeable/Jamfile create mode 100644 test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp create mode 100644 test/support/secret_wide.hpp diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index d740bfc..8f860a0 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -583,8 +583,15 @@ class each { return *this; } - /** Destroys the transformer and the storage, wiped first when the stream is secret. */ - ~each() { wipe_storage(); } + /** Destroys the transformer and the storage, wiped first: a secret stream's. */ + ~each() + requires(secret) + { + wipe_storage(); + } + + /** Destroys the transformer and the storage; a public stream wipes nothing. */ + ~each() = default; /** Accepts the first element of `input` as the item in `flow::needs_input`; accepts nothing in @@ -953,8 +960,15 @@ class buffered { return *this; } - /** Destroys the transformer and the storage, wiped first when the stream is secret. */ - ~buffered() { wipe_storage(); } + /** Destroys the transformer and the storage, wiped first: a secret stream's. */ + ~buffered() + requires(secret) + { + wipe_storage(); + } + + /** Destroys the transformer and the storage; a public stream wipes nothing. */ + ~buffered() = default; /** Copies all of `input` into the storage in `flow::needs_input`, and accepts nothing in another diff --git a/include/webcpp/codecs/detail/core/over.hpp b/include/webcpp/codecs/detail/core/over.hpp index 11d0f95..145e03a 100644 --- a/include/webcpp/codecs/detail/core/over.hpp +++ b/include/webcpp/codecs/detail/core/over.hpp @@ -928,8 +928,9 @@ struct over_value_encoding {}; template requires value_encodable struct over_value_encoding { - /** The exact size of the text of `held_value`, 0 for a chain whose configuration is at fault. - */ + /** + The exact size of the text of `held_value`, 0 for a chain whose configuration is at fault. + */ [[nodiscard]] static std::size_t encoded_size(over const& chain, Value const& held_value) noexcept( over_value_encode_is_noexcept, Outer, Inner, Value>()) { diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index b69c04d..6f8d7a5 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -228,8 +228,16 @@ class piped { return *this; } - /** Destroys both parts, the intermediate wiped first when the pipe is secret. */ - ~piped() { wipe_intermediate(); } + /** Destroys both parts, the intermediate wiped first: a secret pipe's. */ + ~piped() + requires(secret) + { + wipe_intermediate(); + } + + /** Destroys both parts; a public pipe wipes nothing, and is trivially destructible when they + * are. */ + ~piped() = default; /** Gives `input` to `First` in `flow::needs_input`; accepts nothing in another state. diff --git a/test/messages/Jamfile b/test/messages/Jamfile index f1a71b5..55b9126 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -25,6 +25,9 @@ build-project refused_secret_parameters ; build-project refused_secret_value_overload ; build-project refused_configuration_fault ; build-project refused_member_configuration_fault ; +build-project secret_each_not_wipeable ; +build-project secret_buffered_not_wipeable ; +build-project secret_pipe_not_wipeable ; build-project pipe_incompatible ; build-project pipe_one_shot ; build-project piped_incompatible ; diff --git a/test/messages/secret_buffered_not_wipeable/Jamfile b/test/messages/secret_buffered_not_wipeable/Jamfile new file mode 100644 index 0000000..feeadc5 --- /dev/null +++ b/test/messages/secret_buffered_not_wipeable/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic secret_buffered_not_wipeable : secret_buffered_not_wipeable.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail secret_buffered_not_wipeable_refused : secret_buffered_not_wipeable.cpp + : clang:no : native emscripten ; diff --git a/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp b/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp new file mode 100644 index 0000000..8282da4 --- /dev/null +++ b/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A secret buffered wipes its storage with secure::erase_secret, which writes bytes: elements that +// are not trivially copyable stop the build with buffered's message. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: a secret buffered wipes its storage with secure::erase_secret, so T's input_type and output_type are trivially copyable}} +// clang-format on + +#include "../../support/secret_wide.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::buffered(codecs::test::secret_wide{}, codecs::capacity<8>); + static_cast(adapter); + return 0; +} diff --git a/test/messages/secret_each_not_wipeable/Jamfile b/test/messages/secret_each_not_wipeable/Jamfile new file mode 100644 index 0000000..9243241 --- /dev/null +++ b/test/messages/secret_each_not_wipeable/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic secret_each_not_wipeable : secret_each_not_wipeable.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail secret_each_not_wipeable_refused : secret_each_not_wipeable.cpp + : clang:no : native emscripten ; diff --git a/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp b/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp new file mode 100644 index 0000000..b2ae49d --- /dev/null +++ b/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A secret each wipes its item storage with secure::erase_secret, which writes bytes: elements that +// are not trivially copyable stop the build with each's message. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: a secret each wipes its item storage with secure::erase_secret, so T's output_type is trivially copyable}} +// clang-format on + +#include "../../support/secret_wide.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + auto const adapter = codecs::each(codecs::test::secret_wide{}, codecs::capacity<2>); + static_cast(adapter); + return 0; +} diff --git a/test/messages/secret_pipe_not_wipeable/Jamfile b/test/messages/secret_pipe_not_wipeable/Jamfile new file mode 100644 index 0000000..4596ac8 --- /dev/null +++ b/test/messages/secret_pipe_not_wipeable/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic secret_pipe_not_wipeable : secret_pipe_not_wipeable.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail secret_pipe_not_wipeable_refused : secret_pipe_not_wipeable.cpp + : clang:no : native emscripten ; diff --git a/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp b/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp new file mode 100644 index 0000000..8752907 --- /dev/null +++ b/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp @@ -0,0 +1,26 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A secret pipe wipes its intermediate with secure::erase_secret, which writes bytes: elements that +// are not trivially copyable stop the build with the pipe's message. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: a secret pipe wipes its intermediate with secure::erase_secret, so the first transformer's output_type is trivially copyable}} +// clang-format on + +#include "../../support/secret_wide.hpp" + +#include + +int main() { + namespace codecs = webcpp::codecs; + codecs::piped const piped{ + codecs::test::secret_wide{}, codecs::test::secret_wide{}}; + static_cast(piped); + return 0; +} diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp index a7b7f08..e63866d 100644 --- a/test/secret_stream_test.cpp +++ b/test/secret_stream_test.cpp @@ -149,6 +149,35 @@ class dit_probe { bool flushed_ = false; }; +/** + A one-shot transformer of the test's own, `std::uint8_t` to `std::uint8_t`, that states no output + size, so that a heap output starts at the input's size and doubles: it writes every byte of its + input twice, as many as fit, and reports `output_too_small` after writing a part. Secret when + `Secret`. +*/ +template +class doubling_probe { +public: + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** Writes each byte of `input` twice into `output`, as many as fit. */ + [[nodiscard]] static codecs::result transform( + std::span input, std::span output) noexcept { + std::size_t written = 0; + for (std::uint8_t const byte : input) { + if (output.size() - written < 2) { + return codecs::error::output_too_small; + } + output[written++] = byte; + output[written++] = byte; + } + return written; + } +}; + } // namespace } // namespace secret_stream @@ -156,6 +185,10 @@ class dit_probe { template <> struct webcpp::codecs::is_secret : std::true_type {}; +/** A secret doubling_probe is secret. */ +template <> +struct webcpp::codecs::is_secret> : std::true_type {}; + namespace secret_stream { namespace { @@ -187,8 +220,10 @@ static_assert(std::same_as>); static_assert(codecs::is_secret_v>); -/** Whether `T` is move-only: movable without throwing, and neither copy constructible nor - * assignable. */ +/** + Whether `T` is move-only: movable without throwing, and neither copy constructible nor + assignable. +*/ template inline constexpr bool move_only_v = std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v && @@ -211,6 +246,15 @@ static_assert(std::is_copy_constructible_v && std::is_copy_constructible_v); static_assert(std::is_copy_constructible_v); +// A public stream over trivially destructible parts stays trivially destructible: only a secret +// one has a destructor that wipes. +static_assert(std::is_trivially_destructible_v && + std::is_trivially_destructible_v && + std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v && + !std::is_trivially_destructible_v && + !std::is_trivially_destructible_v); + // A secret transformer keeps its concepts and its noexcept calls. static_assert(codecs::stream_transformer && codecs::one_shot_transformer); @@ -783,6 +827,103 @@ void a_secret_streams_heap_storage_goes_back_wiped() { public_allocator.state()->deallocations); } +/** + A move assignment wipes what the target held before it takes the source's: the whole intermediate + of a pipe (which takes only the elements the source's second part has not read, so that the + rest would stay), the storage of a buffered and of an each, each of the target populated by a + conversion that leaves its storage holding secret elements; the target then converts a new input + as a new stream does. +*/ +void a_move_assignment_wipes_what_the_target_held() { + std::array const input = thirty_one_bytes(); + std::string const text = letters_of(input); + { + constexpr std::size_t intermediate_size = codecs::default_capacity_v; + secret_pipe source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)}; + secret_pipe target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)}; + BOOST_TEST(target.send(input).has_value()); + std::array output{}; + auto const received = target.receive(output); + BOOST_TEST(received.has_value() && received->flow == codecs::flow::needs_input); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(wipes_in(target, intermediate_size), 1U); + BOOST_TEST_EQ(text_of(target, input, 64), letters_of_letters(input)); + } + { + secret_buffered source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>}; + secret_buffered target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>}; + BOOST_TEST(target.send(input).has_value()); + BOOST_TEST(target.flush().has_value()); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(wipes_in(target, 31), 1U); + BOOST_TEST_EQ(wipes_in(target, 62), 1U); + BOOST_TEST_EQ(text_of(target, input, 64), text); + } + { + secret_each source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>}; + secret_each target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>}; + BOOST_TEST(target.send(input).has_value()); + std::array letter{}; + auto const first = target.receive(letter); + BOOST_TEST(first.has_value() && first->flow == codecs::flow::output_pending); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(wipes_in(target, 2), 1U); + BOOST_TEST_EQ(text_of(target, input, 1), text); + } +} + +/** + A heap output that outgrows a block holding secret bytes gives that block back wiped: a + transformer that states no output size starts the output at the input's size, writes part of the + output into it and reports `output_too_small`, and the output doubles over the secret bytes it + holds; a short input first and a longer one after a reset, as a reused stream does. A public + twin's blocks go back as they are, so that the count is not vacuous. +*/ +void a_secret_heap_output_wipes_the_block_it_outgrows() { + std::array const input = thirty_one_bytes(); + auto const convert = [&input](auto& stream, std::size_t size) { + BOOST_TEST(stream.send(std::span{input}.first(size)).has_value()); + BOOST_TEST(stream.flush().has_value()); + std::vector output(size * 2); + auto const received = stream.receive(output); + BOOST_TEST(received.has_value() && received->count == output.size()); + for (std::size_t index = 0; index < size; ++index) { + BOOST_TEST_EQ(output[2 * index], input[index]); + BOOST_TEST_EQ(output[(2 * index) + 1], input[index]); + } + }; + test::wipe_checking_allocator const allocator; + { + auto stream = codecs::buffered(doubling_probe{}, allocator); + convert(stream, 3); + stream.reset(); + convert(stream, 31); + } + BOOST_TEST_GT(allocator.state()->deallocations, 2U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.state()->allocations); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); + + test::wipe_checking_allocator const public_allocator; + { + auto stream = codecs::buffered(doubling_probe{}, public_allocator); + convert(stream, 3); + stream.reset(); + convert(stream, 31); + } + BOOST_TEST_GT(public_allocator.state()->deallocations, 2U); + BOOST_TEST_LT(public_allocator.state()->wiped_deallocations, + public_allocator.state()->deallocations); +} + /** A drain of a secret transformer wipes its own buffer before it returns, of the default capacity and of a capacity named; a drain of a public one does not. @@ -833,6 +974,8 @@ int main() { secret_stream::a_secret_buffereds_storage_is_wiped(); secret_stream::a_secret_eachs_storage_is_wiped(); secret_stream::a_secret_streams_heap_storage_goes_back_wiped(); + secret_stream::a_move_assignment_wipes_what_the_target_held(); + secret_stream::a_secret_heap_output_wipes_the_block_it_outgrows(); secret_stream::a_drain_of_a_secret_stream_wipes_its_buffer(); return boost::report_errors(); } diff --git a/test/support/letters.hpp b/test/support/letters.hpp index f2bc909..5f56ccf 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -273,7 +273,14 @@ struct stream_codec { } /** Wipes the waiting letter of a secret stream. */ - ~encoder() { wipe_pending(); } + ~encoder() + requires(Options.secret) + { + wipe_pending(); + } + + /** A public stream wipes nothing. */ + ~encoder() = default; /** Borrows all of `input` in `needs_input`. */ result send(std::span input) noexcept { @@ -430,7 +437,14 @@ struct stream_codec { } /** Wipes the held letter and the error mask of a secret stream. */ - ~decoder() { wipe_held(); } + ~decoder() + requires(Options.secret) + { + wipe_held(); + } + + /** A public stream wipes nothing. */ + ~decoder() = default; /** Borrows all of `input` in `needs_input`; a lone letter is held at once. */ result send(std::span input) noexcept { diff --git a/test/support/secret_wide.hpp b/test/support/secret_wide.hpp new file mode 100644 index 0000000..e581224 --- /dev/null +++ b/test/support/secret_wide.hpp @@ -0,0 +1,90 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secret_wide, a secret transformer of the tests' own whose elements are not trivially copyable, +// for the message cases that refuse a secret stream whose storage secure::erase_secret could not +// wipe: `wide` to `wide`, one-shot and stream, copying its input. It is not for conversion; its +// calls do the least that satisfies the concepts. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_SECRET_WIDE_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_SECRET_WIDE_HPP + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** An element with a copy constructor of its own: not trivially copyable. */ +struct wide { + /** The value. */ + int value = 0; + + /** A default element. */ + wide() = default; + + /** A copy, user-provided. */ + wide(wide const& other) noexcept : value(other.value) {} + + /** A copy assignment, user-provided. */ + wide& operator=(wide const& other) noexcept { + value = other.value; + return *this; + } + + ~wide() = default; +}; + +/** Copies `wide` elements, as a one-shot and a stream transformer. */ +class secret_wide { +public: + /** The elements read. */ + using input_type = wide; + /** The elements written. */ + using output_type = wide; + + /** As many elements out as in. */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Copies `input` into `output`. */ + [[nodiscard]] static result transform(std::span input, + std::span output) noexcept { + if (output.size() < input.size()) { + return error::output_too_small; + } + std::ranges::copy(input, output.begin()); + return input.size(); + } + + /** Accepts nothing. */ + [[nodiscard]] static result send(std::span /*input*/) noexcept { + return step{.count = 0, .flow = flow::needs_input}; + } + + /** Writes nothing. */ + [[nodiscard]] static result receive(std::span /*output*/) noexcept { + return step{.count = 0, .flow = flow::needs_input}; + } + + /** Ends the input. */ + [[nodiscard]] static result flush() noexcept { return flow::finished; } + + /** Nothing is held. */ + static void reset() noexcept {} +}; + +} // namespace webcpp::codecs::test + +/** secret_wide is secret. */ +template <> +struct webcpp::codecs::is_secret : std::true_type {}; + +#endif From 725a2211d0801f9166d5968976b302325454765d Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 20:57:30 -0300 Subject: [PATCH 075/157] codecs: Task 12 fix round 1, the new message cases name the requirement clang prints --- .../secret_buffered_not_wipeable.cpp | 2 +- .../secret_each_not_wipeable/secret_each_not_wipeable.cpp | 2 +- .../secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp b/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp index 8282da4..3b64420 100644 --- a/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp +++ b/test/messages/secret_buffered_not_wipeable/secret_buffered_not_wipeable.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: a secret buffered wipes its storage with secure::erase_secret, so T's input_type and output_type are trivially copyable}} +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed due to requirement 'detail::wipeable_elements_v': webcpp::codecs: a secret buffered wipes its storage with secure::erase_secret, so T's input_type and output_type are trivially copyable}} // clang-format on #include "../../support/secret_wide.hpp" diff --git a/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp b/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp index b2ae49d..e2a1a67 100644 --- a/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp +++ b/test/messages/secret_each_not_wipeable/secret_each_not_wipeable.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed: webcpp::codecs: a secret each wipes its item storage with secure::erase_secret, so T's output_type is trivially copyable}} +// expected-error@webcpp/codecs/detail/core/adapters.hpp:* {{static assertion failed due to requirement 'detail::wipeable_elements_v': webcpp::codecs: a secret each wipes its item storage with secure::erase_secret, so T's output_type is trivially copyable}} // clang-format on #include "../../support/secret_wide.hpp" diff --git a/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp b/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp index 8752907..1f9e958 100644 --- a/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp +++ b/test/messages/secret_pipe_not_wipeable/secret_pipe_not_wipeable.cpp @@ -10,7 +10,7 @@ // clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the // whole text stays on one line. // clang-format off -// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: a secret pipe wipes its intermediate with secure::erase_secret, so the first transformer's output_type is trivially copyable}} +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed due to requirement 'detail::wipeable_elements_v': webcpp::codecs: a secret pipe wipes its intermediate with secure::erase_secret, so the first transformer's output_type is trivially copyable}} // clang-format on #include "../../support/secret_wide.hpp" From 9aad042176b33c7d2b874abc939f00ed694bd851 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 21:04:10 -0300 Subject: [PATCH 076/157] codecs: Task 12 fix round 1 lint fix, requires without redundant parentheses in the constrained destructors --- include/webcpp/codecs/detail/core/adapters.hpp | 4 ++-- include/webcpp/codecs/detail/core/pipe.hpp | 2 +- test/support/letters.hpp | 10 ++++++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/include/webcpp/codecs/detail/core/adapters.hpp b/include/webcpp/codecs/detail/core/adapters.hpp index 8f860a0..5991aae 100644 --- a/include/webcpp/codecs/detail/core/adapters.hpp +++ b/include/webcpp/codecs/detail/core/adapters.hpp @@ -585,7 +585,7 @@ class each { /** Destroys the transformer and the storage, wiped first: a secret stream's. */ ~each() - requires(secret) + requires secret { wipe_storage(); } @@ -962,7 +962,7 @@ class buffered { /** Destroys the transformer and the storage, wiped first: a secret stream's. */ ~buffered() - requires(secret) + requires secret { wipe_storage(); } diff --git a/include/webcpp/codecs/detail/core/pipe.hpp b/include/webcpp/codecs/detail/core/pipe.hpp index 6f8d7a5..1dd2e8b 100644 --- a/include/webcpp/codecs/detail/core/pipe.hpp +++ b/include/webcpp/codecs/detail/core/pipe.hpp @@ -230,7 +230,7 @@ class piped { /** Destroys both parts, the intermediate wiped first: a secret pipe's. */ ~piped() - requires(secret) + requires secret { wipe_intermediate(); } diff --git a/test/support/letters.hpp b/test/support/letters.hpp index 5f56ccf..7008764 100644 --- a/test/support/letters.hpp +++ b/test/support/letters.hpp @@ -230,6 +230,9 @@ struct stream_codec { template class encoder { public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + /** The bytes read. */ using input_type = std::uint8_t; /** The letters written. */ @@ -274,7 +277,7 @@ struct stream_codec { /** Wipes the waiting letter of a secret stream. */ ~encoder() - requires(Options.secret) + requires wipes { wipe_pending(); } @@ -390,6 +393,9 @@ struct stream_codec { template class decoder { public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + /** The letters read. */ using input_type = char; /** The bytes written. */ @@ -438,7 +444,7 @@ struct stream_codec { /** Wipes the held letter and the error mask of a secret stream. */ ~decoder() - requires(Options.secret) + requires wipes { wipe_held(); } From 0662312f5fe45128b33ee967a697dd214676aeb3 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 21:43:47 -0300 Subject: [PATCH 077/157] codecs: hex, constant time, its stream, RFC 4648's base16 vectors --- include/webcpp/codecs/detail/formats/hex.hpp | 158 +++++ include/webcpp/codecs/hex.hpp | 648 ++++++++++++++++++ meta/include-boundaries.json | 11 +- test/Jamfile | 12 +- test/allocation_test.cpp | 165 +++++ test/format_transformer_test.cpp | 71 +- test/hex_stream_test.cpp | 543 +++++++++++++++ test/hex_test.cpp | 538 +++++++++++++++ test/messages/Jamfile | 2 + test/messages/pipe_char_to_packet/Jamfile | 16 + .../pipe_char_to_packet.cpp | 30 + test/messages/refused_pair_hex/Jamfile | 16 + .../refused_pair_hex/refused_pair_hex.cpp | 29 + test/noexcept_test.cpp | 58 ++ test/secret_heap_test.cpp | 64 +- test/secret_operation_test.cpp | 67 +- test/support/chunkings.hpp | 65 +- test/timing_test.cpp | 39 +- test/tokens_boost_url_test.cpp | 33 +- test/toy_media_test.cpp | 100 ++- 20 files changed, 2584 insertions(+), 81 deletions(-) create mode 100644 include/webcpp/codecs/detail/formats/hex.hpp create mode 100644 include/webcpp/codecs/hex.hpp create mode 100644 test/hex_stream_test.cpp create mode 100644 test/hex_test.cpp create mode 100644 test/messages/pipe_char_to_packet/Jamfile create mode 100644 test/messages/pipe_char_to_packet/pipe_char_to_packet.cpp create mode 100644 test/messages/refused_pair_hex/Jamfile create mode 100644 test/messages/refused_pair_hex/refused_pair_hex.cpp diff --git a/include/webcpp/codecs/detail/formats/hex.hpp b/include/webcpp/codecs/detail/formats/hex.hpp new file mode 100644 index 0000000..d1011ac --- /dev/null +++ b/include/webcpp/codecs/detail/formats/hex.hpp @@ -0,0 +1,158 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of hex, which its codec and its stream codec share (``): a + nibble to its character and a character to its nibble by webcpp::secure's constant-time blocks, + with no table indexed by a data byte and no branch on one, and the verdict over a text, which + passes through `secure::declassify` before its one branch (D12). libsodium's `sodium_bin2hex` and + `sodium_hex2bin` are the reference for the method, written here over secure's masks. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** + The character of a nibble: `0` to `9` for 0 to 9, then the letters from `letter_base`, chosen by + a mask with no branch. + + @param nibble A value of 0 to 15, which may be secret. + @param letter_base `a` or `A`, the format's case, which is public. + @return The character. +*/ +[[nodiscard]] constexpr char hex_character(std::uint8_t nibble, char letter_base) noexcept { + std::uint8_t const digit_mask = secure::constant_time::is_less_mask(nibble, 10); + auto const digit = static_cast('0' + nibble); + auto const letter = + static_cast(static_cast(letter_base) + nibble - 10); + return static_cast(secure::constant_time::select(digit_mask, digit, letter)); +} + +/** What a character reads as: its nibble, and the mask of whether it is no hex digit. */ +struct hex_reading { + /** The nibble, 0 for a character that is no hex digit. */ + std::uint8_t value; + /** All ones when the character is no hex digit, else zero. */ + std::uint8_t invalid_mask; +}; + +/** + Reads a character as a hex digit, either case: three range masks over its byte value, read as an + unsigned byte first, since a `char` from 0x80 up is negative where `char` is signed. + + @param character The character, which may be secret. + @return Its nibble and the mask of whether it is no hex digit. +*/ +[[nodiscard]] constexpr hex_reading hex_nibble(char character) noexcept { + auto const code = static_cast(character); + std::uint8_t const digit_mask = + secure::constant_time::is_in_range_mask(code, '0', '9'); + std::uint8_t const lower_mask = + secure::constant_time::is_in_range_mask(code, 'a', 'f'); + std::uint8_t const upper_mask = + secure::constant_time::is_in_range_mask(code, 'A', 'F'); + auto const digit_value = static_cast(code - '0'); + auto const lower_value = static_cast(code - ('a' - 10)); + auto const upper_value = static_cast(code - ('A' - 10)); + return hex_reading{ + .value = static_cast((digit_mask & digit_value) | (lower_mask & lower_value) | + (upper_mask & upper_value)), + .invalid_mask = static_cast(~(digit_mask | lower_mask | upper_mask)), + }; +} + +/** + Writes the two characters of each byte of `input_bytes`, its high nibble first. + + @param input_bytes The bytes. + @param output_characters Their characters, two a byte: exactly `2 * input_bytes.size()`. + @param letter_base `a` or `A`, the format's case. +*/ +constexpr void hex_encode_bytes(std::span input_bytes, + std::span output_characters, char letter_base) noexcept { + std::size_t character_index = 0; + for (std::uint8_t const input_byte : input_bytes) { + output_characters[character_index] = + hex_character(static_cast(input_byte >> 4U), letter_base); + output_characters[character_index + 1] = + hex_character(static_cast(input_byte & 15U), letter_base); + character_index += 2; + } +} + +/** + The mask of a text's characters that are no hex digit, accumulated over every character with no + early exit. + + @param text_characters The text. + @return Zero when every character is a hex digit, else all ones. +*/ +[[nodiscard]] constexpr std::uint8_t hex_invalid_mask(std::string_view text_characters) noexcept { + std::uint8_t invalid_mask = 0; + for (char const text_character : text_characters) { + invalid_mask |= hex_nibble(text_character).invalid_mask; + } + return invalid_mask; +} + +/** + Writes the byte of each pair of digits of a text found valid. + + Byte `i` is written after characters `2i` and `2i + 1` are read, so that `output_bytes` may be the + text's own storage. + + @param text_characters The digits, `2 * output_bytes.size()` of them at least. + @param output_bytes The bytes. +*/ +constexpr void hex_decode_pairs(std::string_view text_characters, + std::span output_bytes) noexcept { + for (std::size_t byte_index = 0; byte_index < output_bytes.size(); ++byte_index) { + std::uint8_t const high_nibble = hex_nibble(text_characters[2 * byte_index]).value; + std::uint8_t const low_nibble = hex_nibble(text_characters[(2 * byte_index) + 1]).value; + output_bytes[byte_index] = static_cast((high_nibble << 4U) | low_nibble); + } +} + +/** + The verdict over a whole text: @ref error::invalid_character when a character is no hex digit, + else @ref error::invalid_length for an odd count of characters (the lowest value wins, B23). + + The mask passes through `secure::declassify` before the one branch on it: the result's success is + public, the place of a bad character is not. + + @param invalid_mask The mask accumulated over the text, which is secret. + @param character_count The text's characters, which is public. + @return The fault, or `std::nullopt` for a valid text. +*/ +[[nodiscard]] inline std::optional hex_verdict(std::uint8_t invalid_mask, + std::size_t character_count) noexcept { + std::uint8_t verdict = invalid_mask; + secure::declassify(verdict); + if (verdict != 0) { + return error::invalid_character; + } + if (character_count % 2 != 0) { + return error::invalid_length; + } + return std::nullopt; +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP diff --git a/include/webcpp/codecs/hex.hpp b/include/webcpp/codecs/hex.hpp new file mode 100644 index 0000000..d49ae6f --- /dev/null +++ b/include/webcpp/codecs/hex.hpp @@ -0,0 +1,648 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + hex, base16 (RFC 4648 section 8): each byte as two hex digits, its high nibble first. The format + `formats::hex` writes lower case, and `formats::hex(formats::letter_case::upper)` upper case, as + RFC 4648 does; decode takes either case, mixed included. It is constant time on every call, and + streams natively. +*/ +#ifndef WEBCPP_CODECS_HEX_HPP +#define WEBCPP_CODECS_HEX_HPP + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::formats { + +/** The case of the letters `a` to `f` a format writes. */ +enum class letter_case : unsigned char { + /** `a` to `f`. */ + lower = 1, + /** `A` to `F`. */ + upper = 2, +}; + +/** + The type of the format hex: base16, each byte as two hex digits, its high nibble first. + + Encode writes `written_case`; decode takes either case, mixed included, and refuses a text of an + odd length with @ref error::invalid_length and any character that is no hex digit with + @ref error::invalid_character, which wins when both are found. A text may be decoded into its own + storage: byte `i` is written after characters `2i` and `2i + 1` are read. Encode and decode, + one-shot and streamed, index no table by a data byte and branch on none (D12); the text's length + and the result's success are public. +*/ +struct hex_t { + /** The format's name. */ + static constexpr std::string_view name = "hex"; + + /** The case of the letters encode writes. */ + letter_case written_case = letter_case::lower; + + /** + The format writing letters in `chosen` case. + + @param chosen The case. + @return The configured format. + */ + [[nodiscard]] constexpr hex_t operator()(letter_case chosen) const noexcept { + return hex_t{.written_case = chosen}; + } +}; + +/** The format hex, writing lower case: `codecs::encode(formats::hex, digest)`. */ +inline constexpr hex_t hex{}; + +} // namespace webcpp::codecs::formats + +namespace webcpp::codecs { + +namespace detail { + +/** + The first letter hex writes in its format's case: `A` for upper case, else `a`. + + @param format_value The format, whose case is public. + @return `a` or `A`. +*/ +[[nodiscard]] constexpr char hex_letter_base(formats::hex_t const& format_value) noexcept { + return format_value.written_case == formats::letter_case::upper ? 'A' : 'a'; +} + +} // namespace detail + +/** The codec of hex: two digits a byte, in constant time. */ +template <> +struct codec { + /** hex indexes no table by a data byte and branches on none. */ + static constexpr bool constant_time = true; + + /** + Two characters a byte. + + @param input_size The bytes. + @return The characters, `SIZE_MAX` when they do not fit. + */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return detail::saturating_multiply(input_size, 2); + } + + /** + One byte every two characters. + + @param text_size The characters. + @return The most bytes. + */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return text_size / 2; + } + + /** + The exact size of the text of `input_bytes`: two characters a byte. + + @param format_value The format. + @param input_bytes The bytes. + @return The characters. + */ + static constexpr std::size_t encoded_size(formats::hex_t const& format_value, + std::span input_bytes) noexcept { + static_cast(format_value); + return max_encoded_size(input_bytes.size()); + } + + /** + The exact size of the bytes of `text_characters`, every character checked. + + @param format_value The format. + @param text_characters The text. + @return The bytes, or @ref error::invalid_character for a character that is no hex digit, + else @ref error::invalid_length for an odd length. + */ + static result decoded_size(formats::hex_t const& format_value, + std::string_view text_characters) noexcept { + static_cast(format_value); + if (auto const fault = detail::hex_verdict(detail::hex_invalid_mask(text_characters), + text_characters.size())) { + return *fault; + } + return text_characters.size() / 2; + } + + /** + Writes the two digits of each byte of `input_bytes` at the start of `output_characters`. + + @param format_value The format, whose case the letters are written in. + @param input_bytes The bytes. + @param output_characters The buffer. + @return The characters written, or @ref error::output_too_small, with nothing written, when + `output_characters` cannot hold them. + */ + static result encode(formats::hex_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { + std::size_t const written_size = encoded_size(format_value, input_bytes); + if (output_characters.size() < written_size) { + return error::output_too_small; + } + detail::hex_encode_bytes(input_bytes, output_characters.first(written_size), + detail::hex_letter_base(format_value)); + return written_size; + } + + /** + Writes the bytes of `text_characters` at the start of `output_bytes`, after the whole text is + found valid; `output_bytes` may be the text's own storage. + + @param format_value The format. + @param text_characters The text. + @param output_bytes The buffer. + @return The bytes written, or the text's error as `decoded_size` gives it, else + @ref error::output_too_small, with nothing written. + */ + static result decode(formats::hex_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { + result const decoded_count = decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count; + } + // Read unchecked: the error was returned above. + std::size_t const byte_count = decoded_count.unsafe_value(); + if (output_bytes.size() < byte_count) { + return error::output_too_small; + } + detail::hex_decode_pairs(text_characters, output_bytes.first(byte_count)); + return byte_count; + } +}; + +/** + The stream codec of hex (D20): an encoder that holds one character of a pair its output had no + room for, and a decoder that holds one digit of a pair and the error mask, each in constant time. +*/ +template <> +struct stream_codec { + /** + The stream encoder: two digits a borrowed byte, written straight into the caller's span. + + The low digit of a byte whose high digit filled the span waits for the next `receive`. It + never fails. With `Options.secret` it is move-only and wipes the waiting digit by + `secure::erase_secret` on `reset`, on destruction and in the moved-from encoder. + + @tparam Options The stream's options. + */ + template + class encoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The bytes read. */ + using input_type = std::uint8_t; + /** The digits written. */ + using output_type = char; + + /** + An encoder in `flow::needs_input`, writing the case of `format_value`. + + @param format_value The format. + */ + explicit encoder(formats::hex_t const& format_value) noexcept + : letter_base_(detail::hex_letter_base(format_value)) {} + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + encoder(encoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This encoder. + */ + encoder& operator=(encoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + */ + encoder(encoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + pending_(other.pending_), + has_pending_(other.has_pending_), + flushed_(other.flushed_), + letter_base_(other.letter_base_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + @return This encoder. + */ + encoder& operator=(encoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + pending_ = other.pending_; + has_pending_ = other.has_pending_; + flushed_ = other.flushed_; + letter_base_ = other.letter_base_; + other.reset(); + } + return *this; + } + + /** Wipes the waiting digit of a secret stream. */ + ~encoder() + requires wipes + { + wipe_pending(); + } + + /** A public stream wipes nothing. */ + ~encoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state. + + @param input The bytes to encode. + @return The bytes accepted and the state after. + */ + result send(std::span input) noexcept { + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes the waiting digit, then two digits a borrowed byte, as `output` has room. + + @param output The span to write into. + @return The digits written and the state after. + */ + result receive(std::span output) noexcept { + std::size_t written = 0; + if (has_pending_ && written < output.size()) { + output[written++] = pending_; + has_pending_ = false; + } + while (position_ < borrowed_.size() && written < output.size()) { + std::uint8_t const input_byte = borrowed_[position_++]; + output[written++] = detail::hex_character( + static_cast(input_byte >> 4U), letter_base_); + char const low_digit = detail::hex_character( + static_cast(input_byte & 15U), letter_base_); + if (written < output.size()) { + output[written++] = low_digit; + } else { + pending_ = low_digit; + has_pending_ = true; + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input: hex has no fault of the data to find in bytes. + + @return `flow::output_pending` while digits remain, else `flow::finished`. + */ + result flush() noexcept { + flushed_ = true; + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or pending; the waiting digit of a secret + stream wiped. + */ + void reset() noexcept { + wipe_pending(); + borrowed_ = {}; + position_ = 0; + pending_ = 0; + has_pending_ = false; + flushed_ = false; + } + + private: + /** Wipes the waiting digit, a byte, when the stream is secret. */ + void wipe_pending() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&pending_, 1}); + } + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (has_pending_ || position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The bytes `send` accepted. */ + std::span borrowed_; + /** The next borrowed byte to read. */ + std::size_t position_ = 0; + /** The low digit the output had no room for. */ + char pending_ = 0; + /** Whether `pending_` waits. */ + bool has_pending_ = false; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** `a` or `A`: the format's case, which stays across `reset`. */ + char letter_base_; + }; + + /** + The stream decoder: a byte for each pair of digits, written straight into the caller's span. + + The first digit of a pair whose second is not borrowed yet is held. Every digit's verdict is + accumulated in a mask, and reported after `flush` by the call that reads the end of the input, + which runs it over everything still borrowed before it writes, as the one-shot form reports + it (B44): @ref error::invalid_character, else @ref error::invalid_length. With + `Options.secret` it is move-only and wipes the held digit and the error mask by + `secure::erase_secret` on `reset`, on destruction and in the moved-from decoder. + + @tparam Options The stream's options. + */ + template + class decoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The digits read. */ + using input_type = char; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** + A decoder in `flow::needs_input`; it reads either case, whatever the format's. + + @param format_value The format. + */ + explicit decoder(formats::hex_t const& format_value) noexcept { + static_cast(format_value); + } + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + decoder(decoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This decoder. + */ + decoder& operator=(decoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + */ + decoder(decoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + held_(other.held_), + has_held_(other.has_held_), + invalid_mask_(other.invalid_mask_), + flushed_(other.flushed_), + verdict_passed_(other.verdict_passed_), + error_(other.error_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + @return This decoder. + */ + decoder& operator=(decoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + held_ = other.held_; + has_held_ = other.has_held_; + invalid_mask_ = other.invalid_mask_; + flushed_ = other.flushed_; + verdict_passed_ = other.verdict_passed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Wipes the held digit and the error mask of a secret stream. */ + ~decoder() + requires wipes + { + wipe_held(); + } + + /** A public stream wipes nothing. */ + ~decoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state; a lone + digit is held at once, which frees the input. + + @param input The digits to decode. + @return The digits accepted and the state after, or the error found after `flush`. + */ + result send(std::span input) noexcept { + if (failed()) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + hold_lone_digit(); + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes a byte for each pair of digits, as `output` has room. + + After `flush`, the first call runs the verdict over what is still borrowed and returns its + error, writing nothing. + + @param output The span to write into. + @return The bytes written and the state after, or the error. + */ + result receive(std::span output) noexcept { + if (failed()) { + return error_; + } + if (flushed_ && !verdict_passed_ && !pass_verdict()) { + return error_; + } + std::size_t written = 0; + while (written < output.size()) { + if (!has_held_) { + if (borrowed_.size() - position_ < 2) { + break; + } + take_held(borrowed_[position_++]); + } + if (position_ == borrowed_.size()) { + break; + } + detail::hex_reading const low_digit = detail::hex_nibble(borrowed_[position_++]); + invalid_mask_ |= low_digit.invalid_mask; + output[written++] = static_cast((held_ << 4U) | low_digit.value); + has_held_ = false; + } + hold_lone_digit(); + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input; with nothing borrowed, it runs the verdict and reports its error itself. + + @return `flow::output_pending` while bytes remain, else `flow::finished`, or the error. + */ + result flush() noexcept { + if (failed()) { + return error_; + } + if (!flushed_) { + flushed_ = true; + if (position_ == borrowed_.size() && !pass_verdict()) { + return error_; + } + } + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or held, the verdict and the error + forgotten; the held digit and the error mask of a secret stream wiped. + */ + void reset() noexcept { + wipe_held(); + borrowed_ = {}; + position_ = 0; + held_ = 0; + has_held_ = false; + invalid_mask_ = 0; + flushed_ = false; + verdict_passed_ = false; + error_.clear(); + } + + private: + /** Wipes the held digit and the error mask, a byte each, when the stream is secret. */ + void wipe_held() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&held_, 1}); + secure::erase_secret(std::span{&invalid_mask_, 1}); + } + } + + /** Holds the nibble of `digit`, the first of a pair, its verdict accumulated. */ + void take_held(char digit) noexcept { + detail::hex_reading const reading = detail::hex_nibble(digit); + invalid_mask_ |= reading.invalid_mask; + held_ = reading.value; + has_held_ = true; + } + + /** Holds the last borrowed digit when it is alone, which frees the borrow. */ + void hold_lone_digit() noexcept { + if (!has_held_ && borrowed_.size() - position_ == 1) { + take_held(borrowed_[position_++]); + } + } + + /** + The verdict over the whole input, what is still borrowed included, as `decoded_size` + gives it for the whole text: a digit read in pairs before counts in the mask, and the + held digit in the length. + + @return Whether the input is valid; the error is set when it is not. + */ + [[nodiscard]] bool pass_verdict() noexcept { + std::span const unread = borrowed_.subspan(position_); + auto const invalid_mask = + static_cast(invalid_mask_ | detail::hex_invalid_mask(std::string_view{ + unread.data(), unread.size()})); + std::size_t const character_count = + (has_held_ ? std::size_t{1} : std::size_t{0}) + unread.size(); + if (auto const fault = detail::hex_verdict(invalid_mask, character_count)) { + error_ = *fault; + } + verdict_passed_ = !error_; + return verdict_passed_; + } + + /** Whether a call reports an error, which stays until `reset`. */ + [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The digits `send` accepted. */ + std::span borrowed_; + /** The next borrowed digit to read. */ + std::size_t position_ = 0; + /** The nibble of the first digit of a pair whose second is not read yet. */ + std::uint8_t held_ = 0; + /** Whether `held_` waits. */ + bool has_held_ = false; + /** All ones once a character that is no hex digit was read, else zero. */ + std::uint8_t invalid_mask_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the verdict over the whole input passed. */ + bool verdict_passed_ = false; + /** The error every call returns until `reset`. */ + boost::system::error_code error_; + }; +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_HEX_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 53b2b5b..32f3f50 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -3,7 +3,8 @@ { "headers": [ "include/webcpp/codecs.hpp", - "include/webcpp/codecs/detail/core/*.hpp" + "include/webcpp/codecs/detail/core/*.hpp", + "include/webcpp/codecs/detail/formats/*.hpp" ], "must-not-include": [ "webcpp/codecs/hex", @@ -16,13 +17,14 @@ "webcpp/codecs/detail/formats", "boost/url" ], - "why": "the core registers no format and needs no Boost.URL" + "why": "the core registers no format and needs no Boost.URL, and a format's arithmetic includes no format's header" }, { "headers": [ "include/webcpp/codecs.hpp", "include/webcpp/codecs/*.hpp", - "include/webcpp/codecs/detail/core/*.hpp" + "include/webcpp/codecs/detail/core/*.hpp", + "include/webcpp/codecs/detail/formats/*.hpp" ], "must-not-include": [ "boost/url" @@ -33,7 +35,8 @@ "headers": [ "include/webcpp/codecs.hpp", "include/webcpp/codecs/*.hpp", - "include/webcpp/codecs/detail/core/*.hpp" + "include/webcpp/codecs/detail/core/*.hpp", + "include/webcpp/codecs/detail/formats/*.hpp" ], "must-not-include": [ "webcpp/asio", diff --git a/test/Jamfile b/test/Jamfile index a0d1d69..ce6aa5e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -27,7 +27,8 @@ rule codecs-compile ( name : sources + : requirements * : targets * ) } webcpp.headers-alone codecs : ../include : - codecs.hpp codecs/config.hpp codecs/detail/core/*.hpp ; + codecs.hpp codecs/config.hpp codecs/detail/core/*.hpp + codecs/hex.hpp codecs/detail/formats/*.hpp ; # config.hpp defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when webcpp has no # exceptions, keeps it when a developer defines it, and defines it when @@ -107,6 +108,15 @@ codecs-run format_transformer : format_transformer_test.cpp ; # as secure's wipe seam records it; a drain of one wipes its buffer. codecs-run secret_stream : secret_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# hex (D13): RFC 4648's base16 vectors in either case, the spec's scenarios on +# hex, every byte value as a character at each place of a pair, the bounds at +# SIZE_MAX, empty input in every form and a text decoded into its own storage. +codecs-run hex : hex_test.cpp ; +# hex as a stream (D20): every chunking equals the one-shot form, its errors +# included; the protocol's states; a file in fixed chunks with no heap; a +# moved-from stream restarts; a secret stream's carries wiped, as secure's wipe +# seam records it. +codecs-run hex_stream : hex_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # The default result of encode and decode without a token (D9). codecs-run default_result : default_result_test.cpp ; # The typed decode into fixed byte types, the heap and a value codec's value. diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index ae7ab28..0cd047d 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -20,6 +20,7 @@ #include "support/toy_media.hpp" #include +#include #include #include @@ -31,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -907,6 +909,167 @@ void check_saturating_refusals() { codecs::error::input_too_long); } +/** 32 bytes of every digit. */ +std::array digest_bytes() { + std::array digest{}; + for (std::size_t index = 0; index < digest.size(); ++index) { + digest[index] = static_cast((index * 8U) ^ (index >> 1U)); + } + return digest; +} + +/** hex's buffer forms, fixed results, typed decodes into fixed types and secret fixed results + (Task 13) allocate nothing, on every path. */ +void check_hex_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = digest_bytes(); + webcpp::secure::secret<32> const key; + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::hex, digest); // built before the windows + std::size_t volatile sink = 0; + bool volatile verdict = false; + expect_no_allocation("hex's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::hex, digest); + sink = codecs::max_decoded_size(formats::hex, fixed_text.value().view()); + verdict = + codecs::encode(formats::hex, digest, text).has_value() && + codecs::decode(formats::hex, std::string_view{text.data(), text.size()}, decoded) + .has_value() && + codecs::encode(formats::hex(formats::letter_case::upper), digest, text).has_value() && + codecs::decode(formats::hex, std::string_view{text.data(), text.size()}, decoded) + .has_value() && + decoded == digest; + }); + BOOST_TEST(verdict); + expect_no_allocation("hex's refused buffer forms", [&] { + verdict = + codecs::encode(formats::hex, digest, std::span{text}.first(63)).has_value() || + codecs::decode(formats::hex, std::string_view{"abc"}, decoded).has_value() || + codecs::decode(formats::hex, std::string_view{"ag"}, decoded).has_value() || + codecs::decode(formats::hex, std::string_view{"abcd"}, std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + expect_no_allocation("hex's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::hex, digest); + auto const back = codecs::decode(formats::hex, encoded.value()); + auto const into_array = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_key = codecs::decode(formats::hex, "abcd"); + auto const through_fixed = + codecs::encode(formats::hex, digest, codecs::tokens::fixed<64>{}); + auto const fixed_back = + codecs::decode(formats::hex, fixed_text.value(), codecs::tokens::fixed<32>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && + fixed_back.has_value() && back.value().view().size() == 32; + }); + BOOST_TEST(verdict); + expect_no_allocation("hex's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::hex, key); + auto const through_token = codecs::encode(formats::hex, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_secret_bytes = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::hex, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::hex, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(formats::hex, key) == 64; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + hex's streams allocate nothing once made (the spec's "Streams allocate nothing", on hex): 1 MiB of + random bytes in random chunks through encoder(hex) piped into decoder(hex), drained into a fixed + span and compared as it goes; encoder(hex) and decoder(hex), public and secret, streamed, moved + and reset; and each and buffered in place over encoder(hex). +*/ +void check_hex_streams() { + namespace formats = codecs::formats; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + bool volatile verdict = false; + expect_no_allocation("1 MiB through pipe(encoder(hex), decoder(hex)) in random chunks", [&] { + auto piped = codecs::pipe(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); + std::uniform_int_distribution chunk_size{0, 3000}; + std::size_t compared = 0; + bool same = true; + auto const sink = [&](std::span piece) noexcept { + same = same && compared + piece.size() <= input.size() && + std::ranges::equal(piece, std::span{input}.subspan(compared, piece.size())); + compared += piece.size(); + }; + bool streamed = true; + std::array fixed_span{}; + for (std::size_t position = 0; position < input.size() && streamed;) { + std::size_t const size = std::min(chunk_size(generator), input.size() - position); + auto const sent = piped.send(std::span{input}.subspan(position, size)); + streamed = + sent.has_value() && codecs::drain(piped, sink, std::span{fixed_span}).has_value(); + position += sent.has_value() ? sent->count : 0; + } + streamed = streamed && piped.flush().has_value() && + codecs::drain(piped, sink, std::span{fixed_span}).has_value(); + verdict = streamed && same && compared == input.size(); + }); + BOOST_TEST(verdict); + + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + expect_no_allocation("encoder(hex) and decoder(hex), public and secret", [&] { + auto encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{text}.first(3)).has_value() && + encoder.receive(std::span{text}.subspan(3)).has_value() && + encoder.flush().has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); + streamed = streamed && + secret_decoder.send(std::span{text}.first(5)).has_value() && + secret_decoder.receive(decoded).has_value() && + secret_decoder.send(std::span{text}.subspan(5)).has_value() && + secret_decoder.flush().has_value() && + secret_decoder.receive(std::span{decoded}.subspan(2)).has_value(); + auto moved_decoder{std::move(secret_decoder)}; + moved_decoder.reset(); + auto secret_encoder = codecs::encoder(formats::hex, codecs::secret_operation); + streamed = streamed && secret_encoder.send(bytes).has_value() && + secret_encoder.receive(std::span{text}.first(1)).has_value(); + auto moved_secret{std::move(secret_encoder)}; + moved_secret.reset(); + verdict = streamed && decoded == bytes && text[0] == '0' && text[11] == 'B'; + }); + BOOST_TEST(verdict); + expect_no_allocation("each and buffered in place over encoder(hex)", [&] { + auto each = codecs::each(codecs::encoder(formats::hex), codecs::capacity<2>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{text}.first(1)).has_value() && + each.receive(std::span{text}.subspan(1, 1)).has_value(); + auto buffered = codecs::buffered(codecs::encoder(formats::hex, codecs::secret_operation), + codecs::capacity<6>); + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text[0] == '0' && text[11] == 'b'; + }); + BOOST_TEST(verdict); +} + } // namespace int main() { @@ -926,5 +1089,7 @@ int main() { check_secret_streams(); check_pipe_of_packets_into_each(); check_saturating_refusals(); + check_hex_one_shot_forms(); + check_hex_streams(); return boost::report_errors(); } diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index d86ff45..ab49fa7 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -22,7 +22,6 @@ #include #include -#include #include #include @@ -161,28 +160,6 @@ std::span bytes_of(std::span bytes) { return bytes; } -/** - Streams every chunking of `input` through `transformer`, reset before each, with output spans of - one element and of 1024, and checks that each gives `expected`. -*/ -template -void expect_every_chunking(Transformer& transformer, std::span input, - Output const& expected) { - std::size_t chunkings = 0; - test::for_each_chunking(input, [&](std::span const> chunks) { - for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { - transformer.reset(); - auto const streamed = test::stream_whole(transformer, chunks, span_size); - BOOST_TEST(streamed.has_value()); - if (streamed) { - BOOST_TEST(std::ranges::equal(streamed.value(), expected)); - } - } - ++chunkings; - }); - BOOST_TEST(chunkings > 0); -} - /** encoder(letters) and decoder(letters) over every chunking equal the one-shot forms. */ void every_chunking_equals_the_one_shot_form() { auto encoder = codecs::encoder(test::letters); @@ -191,46 +168,9 @@ void every_chunking_equals_the_one_shot_form() { std::vector const bytes = random_bytes(size); auto const text = codecs::encode(test::letters, bytes); BOOST_TEST_EQ(text.value().size(), 2 * size); - expect_every_chunking(encoder, bytes_of(bytes), text.value()); - expect_every_chunking(decoder, characters_of(text.value()), bytes); - } -} - -/** - Sends `chunks` to `transformer`, receiving into spans of `span_size` after each but the last, and - checks that no call fails before flush; then returns the error of flush, or of the receive after - it when the last chunk is still borrowed, which must write nothing (B44). -*/ -template -boost::system::error_code error_after_flush( - Transformer& transformer, - std::span const> chunks, - std::size_t span_size) { - using output_type = Transformer::output_type; - std::vector span_buffer(span_size); - for (std::size_t index = 0; index < chunks.size(); ++index) { - auto const sent = transformer.send(chunks[index]); - BOOST_TEST(sent.has_value() && sent->count == chunks[index].size()); - while (index + 1 < chunks.size()) { - auto const received = transformer.receive(std::span{span_buffer}); - BOOST_TEST(received.has_value()); - if (!received || received->flow != codecs::flow::output_pending) { - break; - } - } - } - auto const flushed = transformer.flush(); - if (!flushed) { - return flushed.error(); + test::expect_every_chunking(encoder, bytes_of(bytes), text.value()); + test::expect_every_chunking(decoder, characters_of(text.value()), bytes); } - BOOST_TEST(flushed.value() == codecs::flow::output_pending); - std::ranges::fill(span_buffer, static_cast(0x5a)); - auto const received = transformer.receive(std::span{span_buffer}); - BOOST_TEST(!received.has_value()); - BOOST_TEST(std::ranges::all_of(span_buffer, [](output_type element) { - return element == static_cast(0x5a); - })); - return received ? boost::system::error_code{} : received.error(); } /** @@ -252,7 +192,8 @@ void invalid_texts_give_the_one_shot_error_after_flush() { characters_of(text), [&](std::span const> chunks) { for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { decoder.reset(); - BOOST_TEST(error_after_flush(decoder, chunks, span_size) == one_shot.error()); + BOOST_TEST(test::error_after_flush(decoder, chunks, span_size) == + one_shot.error()); decoder.reset(); auto const streamed = test::stream_whole(decoder, chunks, span_size); BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); @@ -780,8 +721,8 @@ void over_streams_through_a_pipe() { std::vector const bytes = random_bytes(size); auto const text = codecs::encode(chain, bytes); BOOST_TEST_EQ(text.value().size(), 4 * size); - expect_every_chunking(encoder, bytes_of(bytes), text.value()); - expect_every_chunking(decoder, characters_of(text.value()), bytes); + test::expect_every_chunking(encoder, bytes_of(bytes), text.value()); + test::expect_every_chunking(decoder, characters_of(text.value()), bytes); } // The outer link's error, invalid_character of "abq", and the inner link's, invalid_length of // the letters of "abc": the errors differ, so that each shows which link reported it. diff --git a/test/hex_stream_test.cpp b/test/hex_stream_test.cpp new file mode 100644 index 0000000..4ae5b11 --- /dev/null +++ b/test/hex_stream_test.cpp @@ -0,0 +1,543 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// hex as a stream (D20): encoder(hex) and decoder(hex) are its one-shot transformers always and its +// stream transformers through stream_codec, whose encoder holds one character of a +// pair the output had no room for and whose decoder one digit of a pair and the error mask (D20's +// table). RFC 4648's vectors and 1000 random bytes, in either case, equal the one-shot forms for +// every chunking (support/chunkings.hpp), and every invalid text gives the one-shot form's error +// after flush, every byte value as a character at each place of a pair among them (Review Focus +// 1); the spec's "Send while output is pending", "After the end and after an error" and "A file +// ... with no heap" (on hex); empty input (Review Focus 3); a moved-from stream converts from the +// start (Review Focus 5); a secret stream wipes its carries, as secure's wipe seam records it. + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/chunkings.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using hex_encoder = decltype(codecs::encoder(formats::hex)); +using hex_decoder = decltype(codecs::decoder(formats::hex)); +using secret_hex_encoder = decltype(codecs::encoder(formats::hex, codecs::secret_operation)); +using secret_hex_decoder = decltype(codecs::decoder(formats::hex, codecs::secret_operation)); +using stream_encoder = codecs::stream_codec::encoder; +using stream_decoder = codecs::stream_codec::decoder; +using secret_stream_encoder = + codecs::stream_codec::encoder; +using secret_stream_decoder = + codecs::stream_codec::decoder; + +// hex streams natively: its transformers are one-shot and stream transformers, of bytes to +// characters and back, constant time as its codec is. +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(hex_encoder::max_output_size(3) == 6); +static_assert(hex_decoder::max_output_size(7) == 3); +// The stream codec's own streams: a public one is copyable and trivially destructible, a secret +// one move-only, with a destructor that wipes (D21). +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(codecs::is_secret_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); + +/** `size` bytes from a generator of a fixed seed. */ +std::vector random_bytes(std::size_t size) { + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::uniform_int_distribution byte_value{0, 255}; + std::vector bytes(size); + for (std::uint8_t& byte : bytes) { + byte = static_cast(byte_value(generator)); + } + return bytes; +} + +/** The characters of `text` as the span a decoder reads. */ +std::span characters_of(std::string_view text) { + return {text.data(), text.size()}; +} + +/** The bytes of `characters` as the span an encoder reads. */ +std::span bytes_of(std::string_view characters) { + // A char is read through an unsigned char, which may alias any object. + return {reinterpret_cast(characters.data()), characters.size()}; +} + +/** `text` with every other letter's case changed: mixed case. */ +std::string mixed_case(std::string_view text) { + std::string mixed{text}; + for (std::size_t index = 0; index < mixed.size(); index += 2) { + char const character = mixed[index]; + if (character >= 'a' && character <= 'f') { + mixed[index] = static_cast(character - 'a' + 'A'); + } else if (character >= 'A' && character <= 'F') { + mixed[index] = static_cast(character - 'A' + 'a'); + } + } + return mixed; +} + +/** + The encoders, in either case, and the decoder of the lower, upper and mixed-case texts, public and + secret, over every chunking of `bytes`, equal the one-shot forms. +*/ +void expect_every_chunking_of(std::span bytes) { + std::string const lower = codecs::encode(formats::hex, bytes).value(); + std::string const upper = + codecs::encode(formats::hex(formats::letter_case::upper), bytes).value(); + std::string const mixed = mixed_case(upper); + auto lower_encoder = codecs::encoder(formats::hex); + auto upper_encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); + auto decoder = codecs::decoder(formats::hex); + test::expect_every_chunking(lower_encoder, bytes, lower); + test::expect_every_chunking(upper_encoder, bytes, upper); + test::expect_every_chunking(decoder, characters_of(lower), bytes); + test::expect_every_chunking(decoder, characters_of(upper), bytes); + test::expect_every_chunking(decoder, characters_of(mixed), bytes); + auto secret_encoder = codecs::encoder(formats::hex, codecs::secret_operation); + auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); + test::expect_every_chunking(secret_encoder, bytes, lower); + test::expect_every_chunking(secret_decoder, characters_of(mixed), bytes); +} + +/** RFC 4648 section 10's inputs and random bytes of 0 to 1000 bytes, over every chunking. */ +void every_chunking_equals_the_one_shot_form() { + for (std::string_view const input : {"", "f", "fo", "foo", "foob", "fooba", "foobar"}) { + expect_every_chunking_of(bytes_of(input)); + } + for (std::size_t const size : std::array{0, 1, 31, 32, 33, 1000}) { + std::vector const bytes = random_bytes(size); + expect_every_chunking_of(bytes); + } + // RFC 4648's upper-case text through the upper-case encoder, as the RFC writes it. + auto upper_encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); + test::expect_every_chunking(upper_encoder, bytes_of("foobar"), + std::string_view{"666F6F626172"}); +} + +/** + Every chunking of `text` decodes as the one-shot form does: the same bytes, or the same error, + reported after flush by the call that reads the end, which writes nothing (B44). +*/ +void expect_the_one_shot_verdict(std::string_view text) { + auto const one_shot = codecs::decode(formats::hex, text); + auto decoder = codecs::decoder(formats::hex); + if (one_shot.has_value()) { + test::expect_every_chunking(decoder, characters_of(text), one_shot.value()); + return; + } + auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); + test::for_each_chunking( + characters_of(text), [&](std::span const> chunks) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + decoder.reset(); + BOOST_TEST(test::error_after_flush(decoder, chunks, span_size) == one_shot.error()); + decoder.reset(); + auto const streamed = test::stream_whole(decoder, chunks, span_size); + BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); + secret_decoder.reset(); + BOOST_TEST(test::error_after_flush(secret_decoder, chunks, span_size) == + one_shot.error()); + } + }); +} + +/** + Invalid texts give the one-shot form's error after flush, for every chunking: a character that is + no digit is invalid_character wherever it is, an odd length invalid_length, and both + invalid_character (B23). Every byte value as a character, `char` signed, at the first and the + second place of a pair and as a lone last character, gives the one-shot form's verdict (Review + Focus 1). +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + std::string const high_character{'a', 'b', static_cast(0xc1), 'b'}; + for (std::string_view const text : + {std::string_view{"abq"}, std::string_view{"abc"}, std::string_view{"qbc"}, + std::string_view{"abcdeq"}, std::string_view{"abc\n"}, std::string_view{"0g"}, + std::string_view{"g0"}, std::string_view{high_character}}) { + BOOST_TEST(!codecs::decode(formats::hex, text).has_value()); + expect_the_one_shot_verdict(text); + } + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::array const first{character, '0'}; + std::array const second{'0', character}; + std::array const lone{'a', 'B', character}; + expect_the_one_shot_verdict(std::string_view{first.data(), first.size()}); + expect_the_one_shot_verdict(std::string_view{second.data(), second.size()}); + expect_the_one_shot_verdict(std::string_view{lone.data(), lone.size()}); + } +} + +/** Receives from `transformer` into `span_size` spans until it needs input or finishes. */ +template +std::size_t receive_until_done(Transformer& transformer, std::size_t span_size) { + std::vector span_buffer(span_size); + std::size_t total = 0; + for (;;) { + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(received.has_value()); + if (!received) { + return total; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return total; + } + } +} + +/** Whether `actual` is a step of `count` elements and `flow`. */ +bool is_step(codecs::result const& actual, std::size_t count, codecs::flow flow) { + return actual.has_value() && actual->count == count && actual->flow == flow; +} + +/** + The spec's "Send while output is pending": 64 bytes then 4 more before any receive give {64, + output_pending} then {0, output_pending}, and the second send is accepted once the output is + received until needs_input. +*/ +void send_while_output_is_pending() { + std::vector const bytes = random_bytes(68); + auto encoder = codecs::encoder(formats::hex); + BOOST_TEST(is_step(encoder.send(std::span{bytes}.first(64)), 64, codecs::flow::output_pending)); + BOOST_TEST( + is_step(encoder.send(std::span{bytes}.subspan(64)), 0, codecs::flow::output_pending)); + BOOST_TEST_EQ(receive_until_done(encoder, 100), 128U); + BOOST_TEST( + is_step(encoder.send(std::span{bytes}.subspan(64)), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ(receive_until_done(encoder, 3), 8U); + // A send of nothing is accepted whole and absorbed. + BOOST_TEST(is_step(encoder.send({}), 0, codecs::flow::needs_input)); + // A lone digit is absorbed into the decoder's state, which frees the input at once. + auto decoder = codecs::decoder(formats::hex); + BOOST_TEST(is_step(decoder.send(characters_of("a")), 1, codecs::flow::needs_input)); + BOOST_TEST(is_step(decoder.send(characters_of("bcd")), 3, codecs::flow::output_pending)); + std::array decoded{}; + BOOST_TEST(is_step(decoder.receive(decoded), 2, codecs::flow::needs_input)); + BOOST_TEST((decoded == std::array{0xab, 0xcd})); +} + +/** + The spec's "After the end and after an error": a finished hex encoder's send is {0, finished}; + a decoder whose flush reported invalid_character returns it from both receives after, and from + every call, and decodes a valid text after reset. +*/ +void after_the_end_and_after_an_error() { + std::array const bytes{0x12, 0x34}; + auto encoder = codecs::encoder(formats::hex); + BOOST_TEST(encoder.send(bytes).has_value()); + BOOST_TEST_EQ(receive_until_done(encoder, 16), 4U); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + BOOST_TEST(is_step(encoder.send(bytes), 0, codecs::flow::finished)); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(is_step(encoder.receive(text), 0, codecs::flow::finished)); + + auto decoder = codecs::decoder(formats::hex); + BOOST_TEST(decoder.send(characters_of("0g12")).has_value()); + std::array decoded{}; + BOOST_TEST(is_step(decoder.receive(decoded), 2, codecs::flow::needs_input)); + auto const failed = decoder.flush(); + BOOST_TEST(!failed.has_value() && failed.error() == codecs::error::invalid_character); + decoded.fill(0x5a); + auto const first = decoder.receive(decoded); + auto const second = decoder.receive(decoded); + BOOST_TEST(!first.has_value() && first.error() == codecs::error::invalid_character); + BOOST_TEST(!second.has_value() && second.error() == codecs::error::invalid_character); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); + auto const sent = decoder.send(characters_of("12")); + BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_character); + auto const flushed_again = decoder.flush(); + BOOST_TEST(!flushed_again.has_value() && + flushed_again.error() == codecs::error::invalid_character); + decoder.reset(); + BOOST_TEST(is_step(decoder.send(characters_of("C0fFeE")), 6, codecs::flow::output_pending)); + BOOST_TEST(decoder.flush().has_value()); + BOOST_TEST(is_step(decoder.receive(decoded), 3, codecs::flow::finished)); + BOOST_TEST(decoded[0] == 0xc0 && decoded[1] == 0xff && decoded[2] == 0xee); + + // An odd length after flush: invalid_length, from flush when nothing is still borrowed. + decoder.reset(); + BOOST_TEST(decoder.send(characters_of("abc")).has_value()); + BOOST_TEST(is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + auto const odd = decoder.flush(); + BOOST_TEST(!odd.has_value() && odd.error() == codecs::error::invalid_length); +} + +/** + Review Focus 3: a stream flushed with nothing sent finishes at once with nothing written, and + transform of empty spans writes nothing and returns 0. +*/ +void empty_input() { + auto encoder = codecs::encoder(formats::hex); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(is_step(encoder.receive(text), 0, codecs::flow::finished)); + auto decoder = codecs::decoder(formats::hex); + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(decoder_flushed.has_value() && decoder_flushed.value() == codecs::flow::finished); + std::array decoded{}; + BOOST_TEST(is_step(decoder.receive(decoded), 0, codecs::flow::finished)); + auto const encoded_nothing = + encoder.transform(std::span{}, std::span{}); + BOOST_TEST(encoded_nothing.has_value() && encoded_nothing.value() == 0); + auto const decoded_nothing = + decoder.transform(std::span{}, std::span{}); + BOOST_TEST(decoded_nothing.has_value() && decoded_nothing.value() == 0); +} + +/** + Review Focus 5: a moved-from encoder and decoder, public and secret, convert an input from the + start, and the moved-to one finishes what the source had begun. +*/ +template +void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { + std::vector const bytes = random_bytes(31); + std::string const text = codecs::encode(formats::hex, bytes).value(); + BOOST_TEST(encoder.send(bytes).has_value()); + std::array one_character{}; + BOOST_TEST(is_step(encoder.receive(one_character), 1, codecs::flow::output_pending)); + Encoder moved_encoder{std::move(encoder)}; + std::vector> const no_chunk; + auto const rest = test::stream_whole(moved_encoder, no_chunk, 5); + BOOST_TEST(rest.has_value() && + std::string(1, one_character[0]) + std::string(rest->begin(), rest->end()) == text); + std::vector> const whole{bytes}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const again = test::stream_whole(encoder, whole, 7); + BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); + + BOOST_TEST(decoder.send(characters_of(text).first(3)).has_value()); + std::array one_byte{}; + BOOST_TEST(is_step(decoder.receive(one_byte), 1, codecs::flow::needs_input)); + Decoder moved_decoder{std::move(decoder)}; + std::vector> const tail{characters_of(text).subspan(3)}; + auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); + BOOST_TEST(decoded_rest.has_value() && one_byte[0] == bytes[0] && + std::ranges::equal(*decoded_rest, std::span{bytes}.subspan(1))); + std::vector> const whole_text{characters_of(text)}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const decoded_again = test::stream_whole(decoder, whole_text, 3); + BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); +} + +/** Runs `body` and checks that the counting operator new saw nothing of it. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const before = test::allocations(); + body(); + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(allocated, 0U); +} + +/** + The spec's "A file in base64 with no heap", on hex: a file of 64 KiB is read in 4096-byte chunks + into one buffer, each sent to encoder(hex) and drained into a fixed span before the next chunk is + read; the text equals the one-shot encoding of the whole file, and decodes back the same way, with + no allocation counted. +*/ +void a_file_with_no_heap() { + std::vector const file = random_bytes(std::size_t{64} * 1024); + std::string const expected = codecs::encode(formats::hex, file).value(); + std::string text(expected.size(), ' '); // the output, made before the window + std::vector decoded(file.size()); + bool volatile verdict = false; + expect_no_allocation("a file through encoder(hex) and decoder(hex)", [&] { + std::array chunk{}; + std::array fixed_span{}; + std::size_t written = 0; + auto const text_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + auto encoder = codecs::encoder(formats::hex); + bool streamed = true; + for (std::size_t offset = 0; offset < file.size(); offset += chunk.size()) { + // The "read": the next chunk of the file into the one buffer. + std::ranges::copy(std::span{file}.subspan(offset, chunk.size()), chunk.begin()); + streamed = streamed && encoder.send(chunk).has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + } + streamed = streamed && encoder.flush().has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + + std::array fixed_bytes{}; + std::size_t decoded_count = 0; + auto const byte_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, decoded.begin() + static_cast(decoded_count)); + decoded_count += piece.size(); + }; + auto decoder = codecs::decoder(formats::hex); + std::array text_chunk{}; + for (std::size_t offset = 0; offset < text.size(); offset += text_chunk.size()) { + std::ranges::copy(std::string_view{text}.substr(offset, text_chunk.size()), + text_chunk.begin()); + streamed = streamed && decoder.send(text_chunk).has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + } + streamed = streamed && decoder.flush().has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + verdict = streamed && written == expected.size() && decoded_count == file.size(); + }); + BOOST_TEST(verdict); + BOOST_TEST(text == expected); + BOOST_TEST(decoded == file); +} + +/** + The wipes of `size` bytes, every byte zero when reported, whose first byte is inside the + `object_size` bytes at `object`: an object's own storage, alive or destroyed. +*/ +std::size_t wipes_inside(void const* object, std::size_t object_size, std::size_t size) { + auto const* const first = static_cast(object); + auto const* const end = first + object_size; + std::less<> const before; + std::size_t found = 0; + for (std::size_t index = 0; index < test::wipes.count && index < test::wipes.entries.size(); + ++index) { + test::wipe_entry const& entry = test::wipes.entries[index]; + if (entry.size == size && entry.zero && !before(entry.address, first) && + before(entry.address, end)) { + ++found; + } + } + return found; +} + +/** The wipes of one byte inside `object`, as @ref wipes_inside counts them. */ +template +std::size_t byte_wipes_in(T const& object) { + return wipes_inside(&object, sizeof(T), 1); +} + +/** The wipes of one byte inside `held` at its destruction, which it is reset to. */ +template +std::size_t byte_wipes_at_destruction(std::optional& held) { + void const* const object = &*held; + test::clear_wipes(); + held.reset(); + return wipes_inside(object, sizeof(T), 1); +} + +/** + A secret stream wipes its carries (D21): the encoder's waiting character, a byte, and the decoder's + held digit and error mask, a byte each, in the source after a move, at reset and at destruction; + a public stream wipes nothing. +*/ +void a_secret_streams_carries_are_wiped() { + std::array const bytes{0xab, 0xcd}; + std::array one_character{}; + std::optional encoder; + encoder.emplace(formats::hex); + BOOST_TEST(encoder->send(bytes).has_value()); + BOOST_TEST(is_step(encoder->receive(one_character), 1, codecs::flow::output_pending)); + test::clear_wipes(); + secret_stream_encoder moved_encoder{std::move(*encoder)}; + BOOST_TEST_EQ(byte_wipes_in(*encoder), 1U); + test::clear_wipes(); + moved_encoder.reset(); + BOOST_TEST_EQ(byte_wipes_in(moved_encoder), 1U); + BOOST_TEST_EQ(byte_wipes_at_destruction(encoder), 1U); + + std::optional decoder; + decoder.emplace(formats::hex); + BOOST_TEST(decoder->send(characters_of("abc")).has_value()); + std::array one_byte{}; + BOOST_TEST(is_step(decoder->receive(one_byte), 1, codecs::flow::needs_input)); + test::clear_wipes(); + secret_stream_decoder moved_decoder{std::move(*decoder)}; + BOOST_TEST_EQ(byte_wipes_in(*decoder), 2U); + test::clear_wipes(); + moved_decoder.reset(); + BOOST_TEST_EQ(byte_wipes_in(moved_decoder), 2U); + BOOST_TEST_EQ(byte_wipes_at_destruction(decoder), 2U); + + // A public stream wipes nothing. + test::clear_wipes(); + { + stream_encoder public_encoder{formats::hex}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(one_character).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::hex}; + BOOST_TEST(public_decoder.send(characters_of("abc")).has_value()); + public_decoder.reset(); + } + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace + +int main() { + every_chunking_equals_the_one_shot_form(); + invalid_texts_give_the_one_shot_error_after_flush(); + send_while_output_is_pending(); + after_the_end_and_after_an_error(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::hex), + codecs::decoder(formats::hex)); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::hex, codecs::secret_operation), + codecs::decoder(formats::hex, codecs::secret_operation)); + a_file_with_no_heap(); + a_secret_streams_carries_are_wiped(); + return boost::report_errors(); +} diff --git a/test/hex_test.cpp b/test/hex_test.cpp new file mode 100644 index 0000000..8a49474 --- /dev/null +++ b/test/hex_test.cpp @@ -0,0 +1,538 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// hex, the format (D13, the spec's "Format: hex"): RFC 4648 section 10's base16 vectors, written in +// upper case by hex(letter_case::upper) and in lower case by default, each decoding back from +// either case and from mixed case; a short buffer refused with nothing written; a digest's hex in +// place, with no heap; a typed decode into a fixed array of exactly 32 bytes; a pmr string token +// over an arena; every byte value as a character at the first and the second place of a pair and +// as a lone last character, the verdict equal to a plain table's, with `char` signed (Review Focus +// 1); the bounds saturating at SIZE_MAX and an input of SIZE_MAX / 2 + 1 bytes refused (Review +// Focus 2); empty input in every form (Review Focus 3); a text decoded into its own storage (Review +// Focus 4). Boost.URL's token on hex is in tokens_boost_url_test, so that this program links no +// compiled library. + +#include "support/counting.hpp" + +#include "support/arena.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using hex_codec = codecs::codec; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The format: a value whose call configures the case it writes (D2), lower case by default. +static_assert(codecs::format); +static_assert(formats::hex_t::name == "hex"); +static_assert(formats::hex.written_case == formats::letter_case::lower); +static_assert(formats::hex(formats::letter_case::upper).written_case == + formats::letter_case::upper); +static_assert(formats::hex(formats::letter_case::lower).written_case == + formats::letter_case::lower); +static_assert(static_cast(formats::letter_case::lower) == 1U); +static_assert(static_cast(formats::letter_case::upper) == 2U); +static_assert(std::is_same_v, unsigned char>); + +// Its codec: constant time; two characters a byte, saturated at SIZE_MAX, and a byte every two +// characters (Review Focus 2: on a 32-bit std::size_t too, the bound never wraps). +static_assert(hex_codec::constant_time); +static_assert(hex_codec::max_encoded_size(0) == 0); +static_assert(hex_codec::max_encoded_size(32) == 64); +static_assert(hex_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(hex_codec::max_encoded_size(size_maximum / 2) == size_maximum - 1); +static_assert(hex_codec::max_encoded_size((size_maximum / 2) + 1) == size_maximum); +static_assert(hex_codec::max_decoded_size(0) == 0); +static_assert(hex_codec::max_decoded_size(63) == 31); +static_assert(hex_codec::max_decoded_size(64) == 32); +static_assert(hex_codec::max_decoded_size(size_maximum) == size_maximum / 2); +// The core refuses an input whose bound saturates, SIZE_MAX / 2 + 1 bytes, before it reads it; a +// text's bound never saturates. +static_assert(codecs::detail::input_size_fault(formats::hex, (size_maximum / 2) + 1) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::hex, size_maximum) == + codecs::error::input_too_long); +static_assert(!codecs::detail::input_size_fault(formats::hex, size_maximum / 2).has_value()); +static_assert(!codecs::detail::text_size_fault(formats::hex, size_maximum).has_value()); +// The sizes are constant expressions. +static_assert(codecs::encoded_size(formats::hex, std::array{}) == 6); +static_assert(codecs::encoded_size(formats::hex(formats::letter_case::upper), + std::array{}) == 0); +static_assert(codecs::max_decoded_size(formats::hex, std::string_view{"abcde"}) == 2); +// hex has no configuration to be at fault. +static_assert(!codecs::detail::takes_configuration_fault); +static_assert(!codecs::detail::configuration_fault_of(formats::hex).has_value()); + +// The default results (D9): in place for a size known at compile time, the heap otherwise. +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v const&>())), + codecs::result>); +static_assert(std::is_same_v>>); + +// The arithmetic, as constant expressions: a nibble's character in either case, and a character's +// nibble and verdict. +static_assert(codecs::detail::hex_character(0, 'a') == '0'); +static_assert(codecs::detail::hex_character(9, 'a') == '9'); +static_assert(codecs::detail::hex_character(10, 'a') == 'a'); +static_assert(codecs::detail::hex_character(15, 'A') == 'F'); +static_assert(codecs::detail::hex_nibble('7').value == 7); +static_assert(codecs::detail::hex_nibble('7').invalid_mask == 0); +static_assert(codecs::detail::hex_nibble('c').value == 12); +static_assert(codecs::detail::hex_nibble('C').value == 12); +static_assert(codecs::detail::hex_nibble('g').invalid_mask == 0xff); +static_assert(codecs::detail::hex_nibble(static_cast(0xc1)).invalid_mask == 0xff); + +/** The upper-case digits, a plain table for the test's own reference encoder. */ +constexpr std::string_view upper_digits = "0123456789ABCDEF"; +/** The lower-case digits. */ +constexpr std::string_view lower_digits = "0123456789abcdef"; + +/** The test's reference: the hex of `input`, by a plain table. */ +std::string reference_hex(std::span input, formats::letter_case written) { + std::string_view const digits = + written == formats::letter_case::upper ? upper_digits : lower_digits; + std::string text; + for (std::uint8_t const input_byte : input) { + text += digits[input_byte >> 4U]; + text += digits[input_byte & 15U]; + } + return text; +} + +/** The bytes of a text read as bytes. */ +std::span bytes_of(std::string_view characters) { + // A char is read through an unsigned char, which may alias any object. + return {reinterpret_cast(characters.data()), characters.size()}; +} + +/** `text` with every other letter's case changed: mixed case. */ +std::string mixed_case(std::string_view text) { + std::string mixed{text}; + for (std::size_t index = 0; index < mixed.size(); index += 2) { + char const character = mixed[index]; + if (character >= 'a' && character <= 'f') { + mixed[index] = static_cast(character - 'a' + 'A'); + } else if (character >= 'A' && character <= 'F') { + mixed[index] = static_cast(character - 'A' + 'a'); + } + } + return mixed; +} + +/** `text` in lower case. */ +std::string lower_case(std::string_view text) { + std::string lowered{text}; + for (char& character : lowered) { + if (character >= 'A' && character <= 'F') { + character = static_cast(character - 'A' + 'a'); + } + } + return lowered; +} + +/** A vector of RFC 4648 section 10: the input and its base16, in upper case. */ +struct base16_vector { + /** The input. */ + std::string_view input; + /** Its base16. */ + std::string_view upper; +}; + +/** RFC 4648 section 10's base16 vectors. */ +constexpr std::array rfc4648_base16{{ + {.input = "", .upper = ""}, + {.input = "f", .upper = "66"}, + {.input = "fo", .upper = "666F"}, + {.input = "foo", .upper = "666F6F"}, + {.input = "foob", .upper = "666F6F62"}, + {.input = "fooba", .upper = "666F6F6261"}, + {.input = "foobar", .upper = "666F6F626172"}, +}}; + +/** Whether `decoded` holds the bytes of `expected`. */ +bool decodes_to(codecs::result> const& decoded, + std::string_view expected) { + return decoded.has_value() && std::ranges::equal(decoded.value(), bytes_of(expected)); +} + +/** + The spec's "RFC 4648's base16": each input in upper case is the RFC's text, in lower case by + default, and each text decodes back from upper, lower and mixed case. +*/ +void rfc4648_base16_vectors() { + for (base16_vector const& vector : rfc4648_base16) { + auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), vector.input); + BOOST_TEST(upper.has_value() && upper.value() == vector.upper); + std::string const lower = lower_case(vector.upper); + auto const defaulted = codecs::encode(formats::hex, vector.input); + BOOST_TEST(defaulted.has_value() && defaulted.value() == lower); + auto const chosen_lower = + codecs::encode(formats::hex(formats::letter_case::lower), vector.input); + BOOST_TEST(chosen_lower.has_value() && chosen_lower.value() == lower); + BOOST_TEST(decodes_to(codecs::decode(formats::hex, vector.upper), vector.input)); + BOOST_TEST(decodes_to(codecs::decode(formats::hex, lower), vector.input)); + BOOST_TEST( + decodes_to(codecs::decode(formats::hex, mixed_case(vector.upper)), vector.input)); + // The case of the format is what it writes: either decodes any case. + BOOST_TEST(decodes_to(codecs::decode(formats::hex(formats::letter_case::upper), lower), + vector.input)); + BOOST_TEST_EQ(codecs::encoded_size(formats::hex, vector.input), vector.upper.size()); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::hex, vector.upper), vector.input.size()); + } + // Mixed case within a pair, too. + BOOST_TEST( + decodes_to(codecs::decode(formats::hex, std::string_view{"DeAdbEeF"}), "\xde\xad\xbe\xef")); + BOOST_TEST(decodes_to(codecs::decode(formats::hex, std::string_view{"0123456789abcdefABCDEF"}), + "\x01\x23\x45\x67\x89\xab\xcd\xef\xab\xcd\xef")); +} + +/** 32 bytes, 0x00 to 0xf8 by steps of 8, then turned so that every digit appears. */ +std::array digest_bytes() { + std::array digest{}; + for (std::size_t index = 0; index < digest.size(); ++index) { + digest[index] = static_cast((index * 8U) ^ (index >> 1U)); + } + return digest; +} + +/** The spec's "A short buffer": 32 bytes in 63 characters are refused, the buffer unchanged. */ +void a_short_buffer() { + std::array const digest = digest_bytes(); + std::array buffer{}; + buffer.fill('x'); + auto const refused = codecs::encode(formats::hex, digest, std::span{buffer}.first(63)); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(buffer, [](char character) { return character == 'x'; })); + auto const written = codecs::encode(formats::hex, digest, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == 64); + BOOST_TEST(std::string_view(buffer.data(), buffer.size()) == + reference_hex(digest, formats::letter_case::lower)); + + // A decode into a short buffer likewise, after the text is found valid. + std::array bytes{}; + bytes.fill(0x5a); + auto const short_decode = + codecs::decode(formats::hex, std::string_view{"a1b2c3"}, std::span{bytes}.first(2)); + BOOST_TEST(!short_decode.has_value() && + short_decode.error() == codecs::error::output_too_small); + // The text's data error comes first (B23). + auto const invalid_first = + codecs::decode(formats::hex, std::string_view{"a1b2cx"}, std::span{bytes}.first(2)); + BOOST_TEST(!invalid_first.has_value() && + invalid_first.error() == codecs::error::invalid_character); + BOOST_TEST(std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** Runs `body` and checks that the counting operator new saw nothing of it. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const before = test::allocations(); + body(); + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(allocated, 0U); +} + +/** + The spec's "A digest's hex with no heap": a std::array of 32 bytes encodes to text<64> and decodes + back to bytes<32>, equal to the digest, with nothing allocated; upper case likewise. +*/ +void a_digests_hex_with_no_heap() { + std::array const digest = digest_bytes(); + bool volatile verdict = false; + expect_no_allocation("a digest's hex", [&] { + codecs::result> const encoded = codecs::encode(formats::hex, digest); + codecs::result> const decoded = + codecs::decode(formats::hex, encoded.value()); + auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), digest); + auto const upper_decoded = codecs::decode(formats::hex, upper.value()); + verdict = encoded.has_value() && decoded.has_value() && + std::ranges::equal(decoded.value().view(), digest) && upper.has_value() && + upper_decoded.has_value() && + std::ranges::equal(upper_decoded.value().view(), digest); + }); + BOOST_TEST(verdict); + auto const encoded = codecs::encode(formats::hex, digest); + BOOST_TEST(encoded.value().view() == reference_hex(digest, formats::letter_case::lower)); + auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), digest); + BOOST_TEST(upper.value().view() == reference_hex(digest, formats::letter_case::upper)); +} + +/** + The spec's "A key from hex into a fixed array": 64 digits give the 32 bytes, 62 give + invalid_length; with nothing allocated. +*/ +void a_key_from_hex_into_a_fixed_array() { + std::array const digest = digest_bytes(); + std::string const text = reference_hex(digest, formats::letter_case::lower); + std::string_view const short_text = std::string_view{text}.substr(0, 62); + bool volatile verdict = false; + expect_no_allocation("decode>", [&] { + auto const key = codecs::decode>(formats::hex, text); + auto const short_key = + codecs::decode>(formats::hex, short_text); + verdict = key.has_value() && key.value() == digest && !short_key.has_value() && + short_key.error() == codecs::error::invalid_length; + }); + BOOST_TEST(verdict); +} + +/** + The spec's "A pmr string token": 32 bytes in hex appended to a std::pmr::string over an arena and + returned as a std::pmr::string from the arena's allocator; both are the hex, the arena records + every allocation and the global operator new counts none. +*/ +void a_pmr_string_token() { + std::array const digest = digest_bytes(); + std::string const expected = reference_hex(digest, formats::letter_case::lower); + test::recording_resource arena; + std::pmr::string appended{&arena}; + std::optional> returned; + expect_no_allocation("hex into pmr string tokens", [&] { + auto const appended_result = + codecs::encode(formats::hex, digest, tokens::append_to(appended)); + BOOST_TEST(appended_result.has_value()); + returned.emplace( + codecs::encode(formats::hex, digest, + tokens::return_string(std::pmr::polymorphic_allocator{&arena}))); + }); + static_assert( + std::is_same_v{&arena}))), + codecs::result>); + BOOST_TEST(std::string_view{appended} == expected); + BOOST_TEST(returned.has_value() && returned->has_value() && + std::string_view{returned->value()} == expected); + BOOST_TEST(arena.owns(appended.data())); + BOOST_TEST(returned->has_value() && arena.owns(returned->value().data())); + BOOST_TEST(returned->value().get_allocator().resource() == &arena); + BOOST_TEST_EQ(arena.allocation_count(), 2U); +} + +/** The nibble of each byte value as a character, by a plain table: -1 for no hex digit. */ +std::array plain_table() { + std::array table{}; + table.fill(-1); + for (std::size_t digit = 0; digit < 16; ++digit) { + table[static_cast(lower_digits[digit])] = static_cast(digit); + table[static_cast(upper_digits[digit])] = static_cast(digit); + } + return table; +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at the first and the + second place of a pair, and as the lone last character of a text of an odd length: the verdict and + the byte equal a plain table's. NUL, 0x80 to 0xff and the characters one past each range (`/`, + `:`, `@`, `G`, `` ` ``, `g`) are invalid_character; a lone valid digit is invalid_length, and a + lone invalid one invalid_character, the lowest value (B23). +*/ +void every_byte_value_as_a_character() { + std::array const table = plain_table(); + for (unsigned value = 0; value < 256; ++value) { + int const expected = table[value]; + auto const character = static_cast(static_cast(value)); + for (std::size_t const place : {std::size_t{0}, std::size_t{1}}) { + std::array text{'0', '0'}; + text[place] = character; + std::string_view const view{text.data(), text.size()}; + std::array decoded{0x5a}; + auto const written = codecs::decode(formats::hex, view, std::span{decoded}); + auto const size = hex_codec::decoded_size(formats::hex, view); + if (expected < 0) { + BOOST_TEST(!written.has_value() && + written.error() == codecs::error::invalid_character); + BOOST_TEST(!size.has_value() && size.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(decoded[0], 0x5aU); + } else { + BOOST_TEST(written.has_value() && written.value() == 1); + BOOST_TEST(size.has_value() && size.value() == 1); + unsigned const shift = place == 0 ? 4U : 0U; + BOOST_TEST_EQ(decoded[0], static_cast(expected) << shift); + } + } + std::array odd{'a', 'B', character}; + auto const odd_size = + hex_codec::decoded_size(formats::hex, std::string_view{odd.data(), odd.size()}); + BOOST_TEST(!odd_size.has_value()); + BOOST_TEST(odd_size.error() == (expected < 0 ? codecs::error::invalid_character + : codecs::error::invalid_length)); + } +} + +/** + The spec's "Format: hex" refusals: an odd length is invalid_length, any other character + invalid_character, and the lowest value wins when both are found (B23); "abc\n" is + invalid_character. +*/ +void the_refusals() { + BOOST_TEST(codecs::decode(formats::hex, std::string_view{"abc\n"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::hex, std::string_view{"abc"}).error() == + codecs::error::invalid_length); + BOOST_TEST(codecs::decode(formats::hex, std::string_view{"ab\n"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::hex, std::string_view{"0x12"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::hex, std::string_view{" 12"}).error() == + codecs::error::invalid_character); + // A NUL inside a text is a character, as the view holds it. + BOOST_TEST(codecs::decode(formats::hex, std::string_view{"1\0", 2}).error() == + codecs::error::invalid_character); + // Every form gives the error, and a token is left as it was. + std::vector appended{0x5a}; + BOOST_TEST(codecs::decode(formats::hex, "abc", tokens::append_to(appended)).error() == + codecs::error::invalid_length); + BOOST_TEST(appended == std::vector{0x5a}); + BOOST_TEST(codecs::decode>(formats::hex, "zz").error() == + codecs::error::invalid_character); +} + +/** + Review Focus 4: a text decoded into its own storage gives the right bytes, byte `i` written after + characters `2i` and `2i + 1` are read; an invalid one leaves the storage as it was. +*/ +void decoding_in_place() { + std::string_view const text = "00ff7F80DeadBEEF0123456789abcdef"; + std::array buffer{}; + std::ranges::copy(text, buffer.begin()); + // The bytes are written over the characters, through an unsigned char, which may alias them. + std::span const bytes{reinterpret_cast(buffer.data()), + buffer.size()}; + auto const written = + codecs::decode(formats::hex, std::string_view{buffer.data(), buffer.size()}, bytes); + BOOST_TEST(written.has_value() && written.value() == 16); + std::array const expected{0x00, 0xff, 0x7f, 0x80, 0xde, 0xad, 0xbe, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; + BOOST_TEST(std::ranges::equal(bytes.first(16), expected)); + // The characters past the bytes are untouched. + BOOST_TEST(std::string_view(buffer.data() + 16, 16) == text.substr(16)); + + // The codec's own decode, likewise. + std::ranges::copy(text, buffer.begin()); + auto const codec_written = + hex_codec::decode(formats::hex, std::string_view{buffer.data(), buffer.size()}, bytes); + BOOST_TEST(codec_written.has_value() && codec_written.value() == 16); + BOOST_TEST(std::ranges::equal(bytes.first(16), expected)); + + // An invalid last character: nothing is written. + std::ranges::copy(text, buffer.begin()); + buffer.back() = 'g'; + auto const refused = + codecs::decode(formats::hex, std::string_view{buffer.data(), buffer.size()}, bytes); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::invalid_character); + BOOST_TEST(std::string_view(buffer.data(), 31) == text.substr(0, 31)); +} + +/** + Review Focus 3: empty input in every form gives an empty result: the default results in place and + on the heap, the buffer forms (0 written), the tokens, the typed decodes and the sizes. +*/ +void empty_input_in_every_form() { + std::array const nothing{}; + auto const fixed = codecs::encode(formats::hex, nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed.value().view().empty()); + auto const heap = codecs::encode(formats::hex, std::vector{}); + BOOST_TEST(heap.has_value() && heap.value().empty()); + auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), std::string{}); + BOOST_TEST(upper.has_value() && upper.value().empty()); + auto const buffer_written = + codecs::encode(formats::hex, std::span{}, std::span{}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 0); + auto const returned = codecs::encode(formats::hex, nothing, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value().empty()); + std::string kept{"kept"}; + BOOST_TEST(codecs::encode(formats::hex, nothing, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "kept"); + BOOST_TEST_EQ(codecs::encoded_size(formats::hex, std::vector{}), 0U); + + auto const decoded = codecs::decode(formats::hex, std::string_view{}); + BOOST_TEST(decoded.has_value() && decoded.value().empty()); + auto const fixed_decoded = codecs::decode(formats::hex, fixed.value()); + BOOST_TEST(fixed_decoded.has_value() && fixed_decoded.value().view().empty()); + auto const literal_decoded = codecs::decode(formats::hex, ""); + BOOST_TEST(literal_decoded.has_value() && literal_decoded.value().empty()); + auto const buffer_decoded = + codecs::decode(formats::hex, std::string_view{}, std::span{}); + BOOST_TEST(buffer_decoded.has_value() && buffer_decoded.value() == 0); + auto const typed = codecs::decode>(formats::hex, std::string{}); + BOOST_TEST(typed.has_value() && typed.value().empty()); + auto const typed_array = codecs::decode>(formats::hex, ""); + BOOST_TEST(typed_array.has_value()); + auto const into_secret = codecs::decode(formats::hex, std::string_view{}, tokens::secret); + BOOST_TEST(into_secret.has_value() && into_secret.value().view().empty()); + auto const size = hex_codec::decoded_size(formats::hex, std::string_view{}); + BOOST_TEST(size.has_value() && size.value() == 0); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::hex, std::string_view{}), 0U); +} + +/** Every byte value at every place: 256 bytes, then each turned, round trip in either case. */ +void every_byte_round_trips() { + std::vector all_bytes(256); + for (std::size_t index = 0; index < all_bytes.size(); ++index) { + all_bytes[index] = static_cast(index); + } + for (formats::letter_case const written : + {formats::letter_case::lower, formats::letter_case::upper}) { + auto const text = codecs::encode(formats::hex(written), all_bytes); + BOOST_TEST(text.has_value() && text.value() == reference_hex(all_bytes, written)); + auto const back = codecs::decode(formats::hex, text.value()); + BOOST_TEST(back.has_value() && back.value() == all_bytes); + } +} + +} // namespace + +int main() { + rfc4648_base16_vectors(); + a_short_buffer(); + a_digests_hex_with_no_heap(); + a_key_from_hex_into_a_fixed_array(); + a_pmr_string_token(); + every_byte_value_as_a_character(); + the_refusals(); + decoding_in_place(); + empty_input_in_every_form(); + every_byte_round_trips(); + return boost::report_errors(); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile index 55b9126..01390d3 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -40,3 +40,5 @@ build-project encoder_of_value_over ; build-project capacity_without_hold ; build-project capacity_of_zero ; build-project drain_of_one_shot ; +build-project refused_pair_hex ; +build-project pipe_char_to_packet ; diff --git a/test/messages/pipe_char_to_packet/Jamfile b/test/messages/pipe_char_to_packet/Jamfile new file mode 100644 index 0000000..564604d --- /dev/null +++ b/test/messages/pipe_char_to_packet/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic pipe_char_to_packet : pipe_char_to_packet.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail pipe_char_to_packet_refused : pipe_char_to_packet.cpp + : clang:no : native emscripten ; diff --git a/test/messages/pipe_char_to_packet/pipe_char_to_packet.cpp b/test/messages/pipe_char_to_packet/pipe_char_to_packet.cpp new file mode 100644 index 0000000..3cb1f74 --- /dev/null +++ b/test/messages/pipe_char_to_packet/pipe_char_to_packet.cpp @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The spec's scenario "Types refuse a wrong pipe": hex's encoder writes characters and +// packets_to_frames reads packets, so a pipe of the two stops in pipe's refusal, whose requirement +// names both element types, char and webcpp::codecs::test::packet (ruling R2). The requirement is +// a concept, which clang prints in the note that follows the error rather than in the error's own +// line. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/codecs/detail/core/pipe.hpp:* {{static assertion failed: webcpp::codecs: the first transformer's output_type is not the second's input_type}} +// expected-note@webcpp/codecs/detail/core/pipe.hpp:* {{because 'detail::compatible_elements' evaluated to false}} +// clang-format on + +#include "../../support/toy_media.hpp" + +#include +#include + +int main() { + namespace codecs = webcpp::codecs; + static_cast( + codecs::pipe(codecs::encoder(codecs::formats::hex), codecs::test::packets_to_frames{})); + return 0; +} diff --git a/test/messages/refused_pair_hex/Jamfile b/test/messages/refused_pair_hex/Jamfile new file mode 100644 index 0000000..d7309ac --- /dev/null +++ b/test/messages/refused_pair_hex/Jamfile @@ -0,0 +1,16 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic refused_pair_hex : refused_pair_hex.cpp + : : native wasip2 wasip3 : alone ; +webcpp.compile-fail refused_pair_hex_refused : refused_pair_hex.cpp + : clang:no : native emscripten ; diff --git a/test/messages/refused_pair_hex/refused_pair_hex.cpp b/test/messages/refused_pair_hex/refused_pair_hex.cpp new file mode 100644 index 0000000..b00804b --- /dev/null +++ b/test/messages/refused_pair_hex/refused_pair_hex.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The spec's scenario "A pair that does not exist": a program that decodes hex into a type the +// format does not convert stops in the core's refusal, whose requirement names the type and the +// format's type, webcpp::codecs::formats::hex_t (ruling R2). The type is printed differently by +// libc++ and libstdc++, so the directive matches both. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so the +// whole text stays on one line. +// clang-format off +// expected-error-re@webcpp/codecs/detail/core/contract.hpp:* {{static assertion failed due to requirement 'webcpp::codecs::detail::converts>, webcpp::codecs::formats::hex_t>': webcpp::codecs: this format does not convert this type; include the format's header, or specialize webcpp::codecs::value_codec for the format and the type}} +// clang-format on + +#include +#include + +#include +#include + +int main() { + namespace codecs = webcpp::codecs; + std::string_view const text{"0123"}; + auto const decoded = codecs::decode(codecs::formats::hex, text); + return decoded.has_value() ? 0 : 1; +} diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 8168d64..c2c8510 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -14,6 +14,7 @@ #include "support/toy_media.hpp" #include +#include #include #include @@ -511,4 +512,61 @@ static_assert(noexcept(codecs::detail::configuration_fault_of(test::be16))); static_assert(noexcept(codecs::encoder(test::letters(true)))); static_assert(noexcept(codecs::decoder(test::letters(true)))); +// hex (Task 13): its codec's six functions and its configuring call are noexcept, as are its +// buffer forms, its fixed and secret fixed results and every call of its streams, public and +// secret; a heap result is not. +namespace formats = webcpp::codecs::formats; +using hex_codec = codecs::codec; +static_assert(noexcept(hex_codec::max_encoded_size(0))); +static_assert(noexcept(hex_codec::max_decoded_size(0))); +static_assert(noexcept(hex_codec::encoded_size(formats::hex, std::span{}))); +static_assert(noexcept(hex_codec::decoded_size(formats::hex, std::string_view{}))); +static_assert(noexcept(hex_codec::encode(formats::hex, std::span{}, + std::span{}))); +static_assert(noexcept(hex_codec::decode(formats::hex, std::string_view{}, + std::span{}))); +static_assert(noexcept(formats::hex(formats::letter_case::upper))); +static_assert(noexcept(codecs::encode(formats::hex, std::span{}, + std::span{}))); +static_assert(noexcept(codecs::decode(formats::hex, std::string_view{}, + std::span{}))); +static_assert(noexcept(codecs::encoded_size(formats::hex, std::array{}))); +static_assert(noexcept(codecs::encode(formats::hex, std::array{}))); +static_assert(noexcept(codecs::decode(formats::hex, codecs::text<64>{}))); +static_assert(noexcept(codecs::decode>(formats::hex, "ab"))); +static_assert(noexcept(codecs::decode>(formats::hex, "ab"))); +static_assert(noexcept(codecs::encode(formats::hex, std::array{}, + tokens::fixed<8>{}))); +static_assert(noexcept(codecs::encode(formats::hex, std::declval>()))); +static_assert(noexcept(codecs::decode>(formats::hex, "ab"))); +static_assert(noexcept(codecs::decode>(formats::hex, "ab"))); +static_assert(!noexcept(codecs::encode(formats::hex, std::vector{}))); +static_assert(!noexcept(codecs::decode(formats::hex, std::string_view{}))); +static_assert(!noexcept(codecs::decode(formats::hex, "ab", tokens::return_string))); +using hex_encoder = decltype(codecs::encoder(formats::hex)); +using hex_decoder = decltype(codecs::decoder(formats::hex)); +using secret_hex_encoder = decltype(codecs::encoder(formats::hex, codecs::secret_operation)); +using secret_hex_decoder = decltype(codecs::decoder(formats::hex, codecs::secret_operation)); +static_assert(noexcept(codecs::encoder(formats::hex))); +static_assert(noexcept(codecs::decoder(formats::hex, codecs::secret_operation))); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(noexcept(std::declval().transform(std::span{}, + std::span{}))); +static_assert(noexcept(std::declval().transform(std::span{}, + std::span{}))); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); + } // namespace diff --git a/test/secret_heap_test.cpp b/test/secret_heap_test.cpp index 4798e6d..c8890c1 100644 --- a/test/secret_heap_test.cpp +++ b/test/secret_heap_test.cpp @@ -9,8 +9,8 @@ // allocator gets it back: on destruction, on shrink_to_fit, and the old buffer when they grow, // one allocation for each growth past the capacity. A wipe-checking counting allocator sees every // buffer zero at deallocate (the spec's scenario "A secret type's buffers are wiped before -// deallocate, also on growth", here given 32 bytes; Task 13 adds the one decoded from 64 hex -// digits), and secure's test seam (support/wipe_recorder.hpp) sees the wipes the allocator cannot: +// deallocate, also on growth", given 32 bytes and decoded from 64 hex digits, as the spec writes +// it), and secure's test seam (support/wipe_recorder.hpp) sees the wipes the allocator cannot: // clear(), a cut, and the source's buffer of a move between unequal allocators that do not // propagate, which copies the bytes into the target's memory. The propagation follows // std::allocator_traits, and the approved spellings are the std::allocator aliases. @@ -20,6 +20,7 @@ #include "support/allocators.hpp" #include +#include #include @@ -39,6 +40,7 @@ namespace { namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; namespace test = webcpp::codecs::test; using checked_bytes = codecs::basic_secret_byte_vector>; @@ -230,6 +232,63 @@ void the_buffers_of_a_string_are_wiped_on_growth_and_destruction() { BOOST_TEST_EQ(counts.wiped_deallocations, 3U); } +/** + The spec's scenario, as it writes it: a basic_secret_byte_vector decoded from 64 hex digits with + a wipe-checking allocator, then appended to past its capacity twice, then destroyed, gives back + three buffers, each read zero at deallocate; a basic_secret_string decoded likewise. +*/ +void a_vector_decoded_from_hex_is_wiped_on_growth_and_destruction() { + std::vector expected = byte_run(32, 1); + std::string const text = codecs::encode(formats::hex, expected).value(); + BOOST_TEST_EQ(text.size(), 64U); + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + { + auto decoded = codecs::decode(formats::hex, text, allocator); + BOOST_TEST(decoded.has_value()); + checked_bytes& secret = decoded.value(); + BOOST_TEST_EQ(counts.allocations, 1U); + BOOST_TEST(holds(secret, expected)); + auto const one_more = byte_run(secret.capacity() - secret.size() + 1, 0xa0); + secret.append(one_more); + expected.insert(expected.end(), one_more.begin(), one_more.end()); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + auto const many_more = byte_run(secret.capacity() - secret.size() + 1, 0x40); + secret.append(many_more); + expected.insert(expected.end(), many_more.begin(), many_more.end()); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, expected)); + } + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); + + std::string expected_text = letter_run(32, 'a'); + std::string const letters_hex = codecs::encode(formats::hex, expected_text).value(); + test::wipe_checking_allocator const character_allocator; + auto const& character_counts = *character_allocator.state(); + { + auto decoded = + codecs::decode(formats::hex, letters_hex, character_allocator); + BOOST_TEST(decoded.has_value()); + checked_string& secret = decoded.value(); + BOOST_TEST_EQ(character_counts.allocations, 1U); + BOOST_TEST(secret.view() == expected_text); + std::string const one_more = letter_run(secret.capacity() - secret.size() + 1, 'k'); + secret.append(one_more); + expected_text += one_more; + BOOST_TEST_EQ(character_counts.allocations, 2U); + std::string const many_more = letter_run(secret.capacity() - secret.size() + 1, 'q'); + secret.append(many_more); + expected_text += many_more; + BOOST_TEST_EQ(character_counts.allocations, 3U); + BOOST_TEST(secret.view() == expected_text); + } + BOOST_TEST_EQ(character_counts.deallocations, 3U); + BOOST_TEST_EQ(character_counts.wiped_deallocations, 3U); +} + void every_wipe_covers_the_whole_capacity() { test::wipe_checking_allocator const allocator; checked_bytes secret{allocator}; @@ -550,6 +609,7 @@ void the_default_allocator() { int main() { the_buffers_of_a_byte_vector_are_wiped_on_growth_and_destruction(); the_buffers_of_a_string_are_wiped_on_growth_and_destruction(); + a_vector_decoded_from_hex_is_wiped_on_growth_and_destruction(); every_wipe_covers_the_whole_capacity(); reserve_and_shrink_to_fit_wipe_the_old_buffer(); clear_and_a_cut_wipe_the_bytes(); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index 13c4af2..cc36870 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -11,10 +11,11 @@ // (support/wipe_recorder.hpp) records it. The fixed secret forms allocate nothing, as // support/counting.hpp's operator new sees. The spec's scenarios // "A secret type encodes to a wiped text", "secure's secret is secret" and "A secret result type -// is secret", here on the format letters (Task 13 adds hex's). A token of the program's own whose -// secret is true makes the operation secret and keeps its result type; every token the core makes -// (return_string's, fixed's, and append_to's and assign_to's in a secret operation) wipes what -// it wrote and does not give, on a failure and in the tail a shrink cuts. +// is secret", on the format letters, and the first two and "Decode follows the requested type" on +// hex. A token of the program's own whose secret is true makes the operation secret and keeps its +// result type; every token the core makes (return_string's, fixed's, and append_to's and +// assign_to's in a secret operation) wipes what it wrote and does not give, on a failure and in +// the tail a shrink cuts. #include "support/wipe_recorder.hpp" @@ -27,6 +28,7 @@ #include "support/tagged_letters.hpp" #include +#include #include #include @@ -46,6 +48,7 @@ #include namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; namespace secure = webcpp::secure; namespace test = webcpp::codecs::test; namespace tokens = webcpp::codecs::tokens; @@ -1017,6 +1020,61 @@ void the_fixed_secret_forms_allocate_nothing() { BOOST_TEST(verdict); } +/** + The spec's scenarios on hex: "A secret type encodes to a wiped text", key32 to secret_text<64>, + whose storage reads zero through the wipe seam after its destruction; "secure's secret is + secret", secure::secret<32> to secret_text<64> and back by decode>, both + secret, with no heap; and "Decode follows the requested type", decode>, secret, + its temporary wiped, with no heap. +*/ +void the_spec_scenarios_on_hex() { + std::string const expected = + codecs::encode(formats::hex, key_bytes(), tokens::return_string).value(); + key32 const key = make_key32(); + void const* storage = nullptr; + { + auto const encoded = codecs::encode(formats::hex, key); + static_assert( + std::is_same_v> const>); + BOOST_TEST(encoded.has_value() && encoded.value().view() == expected); + storage = encoded.value().data(); + test::clear_wipes(); + } + BOOST_TEST(test::wiped(storage, 64)); + + secure::secret<32> const secret_key = make_secret(); + static_assert(std::is_same_v>>); + static_assert( + std::is_same_v>(formats::hex, expected)), + codecs::result>>); + bool volatile verdict = false; + expect_no_allocation("hex of secure's secret and back", [&] { + auto const encoded = codecs::encode(formats::hex, secret_key); + test::clear_wipes(); + auto const decoded = + codecs::decode>(formats::hex, encoded.value().view()); + verdict = encoded.has_value() && encoded.value().view() == expected && + decoded.has_value() && std::ranges::equal(decoded.value().bytes(), key_bytes()) && + wiped_elsewhere(decoded.value().bytes().data(), 32); + }); + BOOST_TEST(verdict); + + verdict = false; + expect_no_allocation("decode> of hex", [&] { + test::clear_wipes(); + auto const decoded = codecs::decode>(formats::hex, expected); + verdict = decoded.has_value() && std::ranges::equal(decoded.value().view(), key_bytes()) && + wiped_elsewhere(decoded.value().data(), 32); + }); + BOOST_TEST(verdict); + // The errors reach the caller, from a secret operation too. + BOOST_TEST(codecs::decode>(formats::hex, "abc").error() == + codecs::error::invalid_length); + BOOST_TEST(codecs::decode>(formats::hex, "zz").error() == + codecs::error::invalid_character); +} + } // namespace } // namespace secret_operation @@ -1036,5 +1094,6 @@ int main() { secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); secret_operation::a_value_codecs_secret_arithmetic_runs_in_a_secret_operation(); secret_operation::the_fixed_secret_forms_allocate_nothing(); + secret_operation::the_spec_scenarios_on_hex(); return boost::report_errors(); } diff --git a/test/support/chunkings.hpp b/test/support/chunkings.hpp index 69b60e7..3563734 100644 --- a/test/support/chunkings.hpp +++ b/test/support/chunkings.hpp @@ -15,7 +15,10 @@ // every boundary near the ends included. // stream_whole sends the chunks to a stream transformer, receiving into spans of a given size after // each, flushes and receives until it finishes, and checks that a call that reports an error wrote -// nothing (B44). +// nothing (B44). expect_every_chunking streams every chunking through a transformer, reset before +// each, and compares the output with the one-shot form's; error_after_flush sends a chunking of an +// invalid input and returns the error that flush, or the receive after it, reports, which writes +// nothing (B44): the helpers every format's stream test runs. #ifndef WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP #define WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP @@ -23,6 +26,7 @@ #include #include +#include #include #include @@ -199,6 +203,65 @@ result> stream_whole( return output; } +/** + Streams every chunking of `input` through `transformer`, reset before each, with output spans of + one element and of 1024, and checks that each gives `expected`. +*/ +template +void expect_every_chunking(Transformer& transformer, std::span input, + Output const& expected) { + std::size_t chunkings = 0; + for_each_chunking(input, [&](std::span const> chunks) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + transformer.reset(); + auto const streamed = stream_whole(transformer, chunks, span_size); + BOOST_TEST(streamed.has_value()); + if (streamed) { + BOOST_TEST(std::ranges::equal(streamed.value(), expected)); + } + } + ++chunkings; + }); + BOOST_TEST(chunkings > 0); +} + +/** + Sends `chunks` to `transformer`, receiving into spans of `span_size` after each but the last, and + checks that no call fails before flush; then returns the error of flush, or of the receive after + it when the last chunk is still borrowed, which must write nothing (B44). +*/ +template +boost::system::error_code error_after_flush( + Transformer& transformer, + std::span const> chunks, + std::size_t span_size) { + using output_type = Transformer::output_type; + std::vector span_buffer(span_size); + for (std::size_t index = 0; index < chunks.size(); ++index) { + auto const sent = transformer.send(chunks[index]); + BOOST_TEST(sent.has_value() && sent->count == chunks[index].size()); + while (index + 1 < chunks.size()) { + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(received.has_value()); + if (!received || received->flow != flow::output_pending) { + break; + } + } + } + auto const flushed = transformer.flush(); + if (!flushed) { + return flushed.error(); + } + BOOST_TEST(flushed.value() == flow::output_pending); + std::ranges::fill(span_buffer, static_cast(0x5a)); + auto const received = transformer.receive(std::span{span_buffer}); + BOOST_TEST(!received.has_value()); + BOOST_TEST(std::ranges::all_of(span_buffer, [](output_type element) { + return element == static_cast(0x5a); + })); + return received ? boost::system::error_code{} : received.error(); +} + } // namespace webcpp::codecs::test #endif // WEBCPP_CODECS_TEST_SUPPORT_CHUNKINGS_HPP diff --git a/test/timing_test.cpp b/test/timing_test.cpp index 37d1905..d645e30 100644 --- a/test/timing_test.cpp +++ b/test/timing_test.cpp @@ -7,8 +7,9 @@ // The timing guard of a secret operation (D10, D12, B11): secure's seam, recorded by // support/timing_seam.hpp, counts one engaged guard of codecs' for each secret operation, held by // the core's function that runs it, named exactly, and none for a public operation (the spec's -// scenario "A secret operation sets DIT through secure", here on the format letters; Task 13 adds -// hex's). A token of the program's own whose secret is true makes its operation secret. +// scenario "A secret operation sets DIT through secure", on the format letters and on hex, whose +// own functions hold no guard). A token of the program's own whose secret is true makes its +// operation secret. // Where the guard acts (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, a value codec of the // test's own reads DIT set while it encodes a secret, and clear after. @@ -20,6 +21,7 @@ #include "support/secret_tokens.hpp" #include +#include #include #include @@ -36,6 +38,7 @@ #include namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; namespace secure = webcpp::secure; namespace test = webcpp::codecs::test; namespace tokens = webcpp::codecs::tokens; @@ -236,6 +239,37 @@ void a_secret_decode_enters_one_guard() { }); } +/** + The spec's scenario on hex: a secret type encoded in hex enters one guard, held by codecs' + function, and public bytes none; so does a secret decode, and a public one none. hex's codec + holds no guard of its own: the one counted is the core's. +*/ +void the_scenario_on_hex() { + key32 const key{}; + std::array const public_bytes{}; + expect_one_guard("webcpp::codecs::encode", + [&] { BOOST_TEST(codecs::encode(formats::hex, key).has_value()); }); + expect_no_guard([&] { BOOST_TEST(codecs::encode(formats::hex, public_bytes).has_value()); }); + std::string const text_value(64, 'a'); + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST(codecs::decode>(formats::hex, text_value).has_value()); + }); + expect_one_guard("webcpp::codecs::decode", [&] { + BOOST_TEST(codecs::decode>(formats::hex, text_value).has_value()); + }); + expect_no_guard([&] { + BOOST_TEST(codecs::decode(formats::hex, text_value).has_value()); + BOOST_TEST( + (codecs::decode>(formats::hex, text_value).has_value())); + }); + // hex's codec called directly, as the core calls it, holds none. + std::array buffer{}; + expect_no_guard([&] { + BOOST_TEST( + codecs::codec::encode(formats::hex, public_bytes, buffer).has_value()); + }); +} + /** Whether the guard acts here (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT. */ bool dit_applies() { #ifdef WEBCPP_SECURE_TIMING_COVERED @@ -264,6 +298,7 @@ void dit_is_set_while_a_secret_encodes() { int main() { timing::a_secret_operation_enters_one_guard(); timing::a_secret_decode_enters_one_guard(); + timing::the_scenario_on_hex(); timing::dit_is_set_while_a_secret_encodes(); return boost::report_errors(); } diff --git a/test/tokens_boost_url_test.cpp b/test/tokens_boost_url_test.cpp index c3e5d80..46e5503 100644 --- a/test/tokens_boost_url_test.cpp +++ b/test/tokens_boost_url_test.cpp @@ -7,11 +7,13 @@ // Boost.URL's three string tokens, as given, in both directions (D8): `return_string`, // `append_to` and `assign_to` of a `std::string`. The bytes of a decode arrive as a `std::string`, // Boost.URL's model for every result. A text that does not decode leaves the string unchanged. -// This program links Boost.URL's compiled library, as percent's does. +// The spec's scenario "Boost.URL's token", on hex. This program links Boost.URL's compiled +// library, as percent's does. #include "support/letters.hpp" #include +#include #include #include @@ -90,9 +92,38 @@ void an_invalid_decode_leaves_the_string() { BOOST_TEST(assigned == "kept"); } +/** + The spec's scenario "Boost.URL's token": hex appended to a string through + boost::urls::string_token::append_to, and the same call with an invalid decode leaves the string + unchanged. +*/ +void hex_through_boost_url_tokens() { + namespace formats = webcpp::codecs::formats; + std::array const bytes{0xde, 0xad, 0xbe, 0xef}; + std::string text = "kept:"; + auto const appended = codecs::encode(formats::hex, bytes, url_token::append_to(text)); + BOOST_TEST(appended.has_value()); + BOOST_TEST(text == "kept:deadbeef"); + auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), bytes, + url_token::return_string{}); + BOOST_TEST(upper.has_value() && upper.value() == "DEADBEEF"); + std::string decoded = "kept"; + auto const refused = codecs::decode(formats::hex, "deadbeeg", url_token::append_to(decoded)); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::invalid_character); + BOOST_TEST(decoded == "kept"); + auto const odd = codecs::decode(formats::hex, "deadbee", url_token::assign_to(decoded)); + BOOST_TEST(!odd.has_value() && odd.error() == codecs::error::invalid_length); + BOOST_TEST(decoded == "kept"); + BOOST_TEST(codecs::decode(formats::hex, "DeadBeef", url_token::append_to(decoded)).has_value()); + BOOST_TEST_EQ(decoded.size(), 8U); + BOOST_TEST_EQ(static_cast(decoded[4]), 0xdeU); + BOOST_TEST_EQ(static_cast(decoded[7]), 0xefU); +} + } // namespace int main() { + hex_through_boost_url_tokens(); encode_with_boost_url_tokens(); decode_with_boost_url_tokens(); an_invalid_decode_leaves_the_string(); diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index 64a3bb5..e771f25 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -9,13 +9,17 @@ // decoder is a stream transformer whose frames come out in index order, the frame held back // until the next packet or flush; the frame encoders are one-shot transformers whose outputs are // checked for frame 4, and which write nothing into a short output. Through a pipe and each, the -// packet decoder and the frame-to-image encoder turn packets into images, allocating nothing. +// packet decoder and the frame-to-image encoder turn packets into images, allocating nothing; and +// the spec's pipeline, the packet decoder piped into each frame's bytes, from its allocator and in +// place, piped into encoder(hex), gives the hex of the frames' bytes in order, the one in place +// allocating nothing. #include "support/counting.hpp" #include "support/toy_media.hpp" #include +#include #include @@ -24,7 +28,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -318,6 +325,96 @@ void packets_to_images() { } } +/** + Streams the five packets through `piped`, one a send, receiving into spans of at most 5 + characters of `text` until the pipe stops reporting output_pending, then flushes and receives + until it finishes. + + @return The characters written, or nothing when a call failed or `text` was too short. +*/ +template +std::optional stream_packets_into(Pipe& piped, std::span text) { + std::size_t written = 0; + auto const receive_all = [&]() -> std::optional { + for (;;) { + std::span const span = + text.subspan(written, std::min(5, text.size() - written)); + auto const received = piped.receive(span); + if (!received.has_value()) { + return std::nullopt; + } + written += received->count; + if (received->flow != codecs::flow::output_pending) { + return received->flow; + } + if (received->count == 0) { + return std::nullopt; + } + } + }; + for (test::packet const& input_packet : packets) { + auto const sent = piped.send(std::span{&input_packet, 1}); + if (!sent.has_value() || sent->count != 1 || !receive_all().has_value()) { + return std::nullopt; + } + } + if (!piped.flush().has_value() || receive_all() != codecs::flow::finished) { + return std::nullopt; + } + return written; +} + +/** + The spec's scenario "A toy media transformer satisfies the contract": five packets through + pipe(pipe(packets_to_frames, each(frame_to_bytes)), encoder(hex)), each frame's bytes from the + allocator, and through the same pipeline with each(frame_to_bytes_bounded, capacity<16>) in + place, give the hex of the bytes of frames 0, 4, 5, 6, 8 and 9 in order; the one in place + allocates nothing once it is made. +*/ +void packets_to_hex() { + std::vector bytes; + for (std::uint32_t const index : {0U, 4U, 5U, 6U, 8U, 9U}) { + std::array frame_bytes{}; + auto const written = test::frame_to_bytes::transform( + std::array{test::make_frame(index)}, frame_bytes); + BOOST_TEST(written.has_value()); + bytes.insert(bytes.end(), frame_bytes.begin(), + frame_bytes.begin() + static_cast(written.value())); + } + std::string const expected = codecs::encode(codecs::formats::hex, bytes).value(); + // Frames 0, 4, 5, 6, 8 and 9 have 2, 3, 4, 2, 4 and 2 bytes: 17 bytes, 34 digits. + BOOST_TEST_EQ(expected.size(), 34U); + std::array text{}; + + auto heap_pipeline = + codecs::pipe(codecs::pipe(test::packets_to_frames{}, codecs::each(test::frame_to_bytes{})), + codecs::encoder(codecs::formats::hex)); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + std::optional const from_heap = stream_packets_into(heap_pipeline, text); + BOOST_TEST(from_heap.has_value() && + std::string_view(text.data(), from_heap.value_or(0)) == expected); + + text.fill(0); + auto bounded_pipeline = codecs::pipe( + codecs::pipe(test::packets_to_frames{}, + codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<16>)), + codecs::encoder(codecs::formats::hex)); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + std::size_t const before = test::allocations(); + std::optional const in_place = stream_packets_into(bounded_pipeline, text); + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf( + "allocated: pipe(pipe(packets_to_frames, each(frame_to_bytes_bounded, " + "capacity<16>)), encoder(hex))\n"); + } + BOOST_TEST_EQ(allocated, 0U); + BOOST_TEST(in_place.has_value() && + std::string_view(text.data(), in_place.value_or(0)) == expected); +} + } // namespace int main() { @@ -326,5 +423,6 @@ int main() { check_packets_to_frames_empty_and_moved(); check_one_shot_outputs(); packets_to_images(); + packets_to_hex(); return boost::report_errors(); } From 878e1b54a6941df9af017fd84d955d349bba74e9 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 21:50:07 -0300 Subject: [PATCH 078/157] codecs: hex lint fix, the masks in unsigned words, the results nodiscard, the tests' long functions split, the lists' trailing commas --- include/webcpp/codecs/detail/formats/hex.hpp | 35 ++++--- include/webcpp/codecs/hex.hpp | 31 +++--- test/hex_stream_test.cpp | 60 ++++++----- test/hex_test.cpp | 100 +++++++++++-------- test/toy_media_test.cpp | 2 +- 5 files changed, 127 insertions(+), 101 deletions(-) diff --git a/include/webcpp/codecs/detail/formats/hex.hpp b/include/webcpp/codecs/detail/formats/hex.hpp index d1011ac..2d4ca3d 100644 --- a/include/webcpp/codecs/detail/formats/hex.hpp +++ b/include/webcpp/codecs/detail/formats/hex.hpp @@ -37,10 +37,12 @@ namespace webcpp::codecs::detail { @return The character. */ [[nodiscard]] constexpr char hex_character(std::uint8_t nibble, char letter_base) noexcept { - std::uint8_t const digit_mask = secure::constant_time::is_less_mask(nibble, 10); - auto const digit = static_cast('0' + nibble); - auto const letter = - static_cast(static_cast(letter_base) + nibble - 10); + // In unsigned, a mask word of secure's that no promotion turns signed. + auto const value = static_cast(nibble); + auto const digit_mask = secure::constant_time::is_less_mask(value, 10U); + unsigned const digit = '0' + value; + unsigned const letter = + static_cast(static_cast(letter_base)) + value - 10U; return static_cast(secure::constant_time::select(digit_mask, digit, letter)); } @@ -60,16 +62,17 @@ struct hex_reading { @return Its nibble and the mask of whether it is no hex digit. */ [[nodiscard]] constexpr hex_reading hex_nibble(char character) noexcept { - auto const code = static_cast(character); - std::uint8_t const digit_mask = - secure::constant_time::is_in_range_mask(code, '0', '9'); - std::uint8_t const lower_mask = - secure::constant_time::is_in_range_mask(code, 'a', 'f'); - std::uint8_t const upper_mask = - secure::constant_time::is_in_range_mask(code, 'A', 'F'); - auto const digit_value = static_cast(code - '0'); - auto const lower_value = static_cast(code - ('a' - 10)); - auto const upper_value = static_cast(code - ('A' - 10)); + // The byte value first, then the unsigned mask word of secure's. + auto const code = static_cast(static_cast(character)); + auto const digit_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'0'}, unsigned{'9'}); + auto const lower_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'a'}, unsigned{'f'}); + auto const upper_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'A'}, unsigned{'F'}); + unsigned const digit_value = code - unsigned{'0'}; + unsigned const lower_value = code - (unsigned{'a'} - 10U); + unsigned const upper_value = code - (unsigned{'A'} - 10U); return hex_reading{ .value = static_cast((digit_mask & digit_value) | (lower_mask & lower_value) | (upper_mask & upper_value)), @@ -123,8 +126,8 @@ constexpr void hex_encode_bytes(std::span input_bytes, constexpr void hex_decode_pairs(std::string_view text_characters, std::span output_bytes) noexcept { for (std::size_t byte_index = 0; byte_index < output_bytes.size(); ++byte_index) { - std::uint8_t const high_nibble = hex_nibble(text_characters[2 * byte_index]).value; - std::uint8_t const low_nibble = hex_nibble(text_characters[(2 * byte_index) + 1]).value; + unsigned const high_nibble = hex_nibble(text_characters[2 * byte_index]).value; + unsigned const low_nibble = hex_nibble(text_characters[(2 * byte_index) + 1]).value; output_bytes[byte_index] = static_cast((high_nibble << 4U) | low_nibble); } } diff --git a/include/webcpp/codecs/hex.hpp b/include/webcpp/codecs/hex.hpp index d49ae6f..e623c7b 100644 --- a/include/webcpp/codecs/hex.hpp +++ b/include/webcpp/codecs/hex.hpp @@ -132,8 +132,8 @@ struct codec { @return The bytes, or @ref error::invalid_character for a character that is no hex digit, else @ref error::invalid_length for an odd length. */ - static result decoded_size(formats::hex_t const& format_value, - std::string_view text_characters) noexcept { + [[nodiscard]] static result decoded_size( + formats::hex_t const& format_value, std::string_view text_characters) noexcept { static_cast(format_value); if (auto const fault = detail::hex_verdict(detail::hex_invalid_mask(text_characters), text_characters.size())) { @@ -151,9 +151,9 @@ struct codec { @return The characters written, or @ref error::output_too_small, with nothing written, when `output_characters` cannot hold them. */ - static result encode(formats::hex_t const& format_value, - std::span input_bytes, - std::span output_characters) noexcept { + [[nodiscard]] static result encode(formats::hex_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { std::size_t const written_size = encoded_size(format_value, input_bytes); if (output_characters.size() < written_size) { return error::output_too_small; @@ -173,9 +173,9 @@ struct codec { @return The bytes written, or the text's error as `decoded_size` gives it, else @ref error::output_too_small, with nothing written. */ - static result decode(formats::hex_t const& format_value, - std::string_view text_characters, - std::span output_bytes) noexcept { + [[nodiscard]] static result decode(formats::hex_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { result const decoded_count = decoded_size(format_value, text_characters); if (!decoded_count) { return decoded_count; @@ -287,7 +287,7 @@ struct stream_codec { @param input The bytes to encode. @return The bytes accepted and the state after. */ - result send(std::span input) noexcept { + [[nodiscard]] result send(std::span input) noexcept { if (state() != flow::needs_input) { return step{.count = 0, .flow = state()}; } @@ -302,7 +302,7 @@ struct stream_codec { @param output The span to write into. @return The digits written and the state after. */ - result receive(std::span output) noexcept { + [[nodiscard]] result receive(std::span output) noexcept { std::size_t written = 0; if (has_pending_ && written < output.size()) { output[written++] = pending_; @@ -333,7 +333,7 @@ struct stream_codec { @return `flow::output_pending` while digits remain, else `flow::finished`. */ - result flush() noexcept { + [[nodiscard]] result flush() noexcept { flushed_ = true; return state(); } @@ -481,7 +481,7 @@ struct stream_codec { @param input The digits to decode. @return The digits accepted and the state after, or the error found after `flush`. */ - result send(std::span input) noexcept { + [[nodiscard]] result send(std::span input) noexcept { if (failed()) { return error_; } @@ -503,7 +503,7 @@ struct stream_codec { @param output The span to write into. @return The bytes written and the state after, or the error. */ - result receive(std::span output) noexcept { + [[nodiscard]] result receive(std::span output) noexcept { if (failed()) { return error_; } @@ -523,7 +523,8 @@ struct stream_codec { } detail::hex_reading const low_digit = detail::hex_nibble(borrowed_[position_++]); invalid_mask_ |= low_digit.invalid_mask; - output[written++] = static_cast((held_ << 4U) | low_digit.value); + output[written++] = static_cast((static_cast(held_) << 4U) | + low_digit.value); has_held_ = false; } hold_lone_digit(); @@ -539,7 +540,7 @@ struct stream_codec { @return `flow::output_pending` while bytes remain, else `flow::finished`, or the error. */ - result flush() noexcept { + [[nodiscard]] result flush() noexcept { if (failed()) { return error_; } diff --git a/test/hex_stream_test.cpp b/test/hex_stream_test.cpp index 4ae5b11..3e5f276 100644 --- a/test/hex_stream_test.cpp +++ b/test/hex_stream_test.cpp @@ -202,10 +202,16 @@ void expect_the_one_shot_verdict(std::string_view text) { */ void invalid_texts_give_the_one_shot_error_after_flush() { std::string const high_character{'a', 'b', static_cast(0xc1), 'b'}; - for (std::string_view const text : - {std::string_view{"abq"}, std::string_view{"abc"}, std::string_view{"qbc"}, - std::string_view{"abcdeq"}, std::string_view{"abc\n"}, std::string_view{"0g"}, - std::string_view{"g0"}, std::string_view{high_character}}) { + for (std::string_view const text : { + std::string_view{"abq"}, + std::string_view{"abc"}, + std::string_view{"qbc"}, + std::string_view{"abcdeq"}, + std::string_view{"abc\n"}, + std::string_view{"0g"}, + std::string_view{"g0"}, + std::string_view{high_character}, + }) { BOOST_TEST(!codecs::decode(formats::hex, text).has_value()); expect_the_one_shot_verdict(text); } @@ -269,12 +275,9 @@ void send_while_output_is_pending() { BOOST_TEST((decoded == std::array{0xab, 0xcd})); } -/** - The spec's "After the end and after an error": a finished hex encoder's send is {0, finished}; - a decoder whose flush reported invalid_character returns it from both receives after, and from - every call, and decodes a valid text after reset. -*/ -void after_the_end_and_after_an_error() { +/** The spec's "After the end and after an error", its first half: a finished hex encoder's send is + {0, finished}, and so is every call after. */ +void after_the_end() { std::array const bytes{0x12, 0x34}; auto encoder = codecs::encoder(formats::hex); BOOST_TEST(encoder.send(bytes).has_value()); @@ -286,36 +289,42 @@ void after_the_end_and_after_an_error() { BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); std::array text{}; BOOST_TEST(is_step(encoder.receive(text), 0, codecs::flow::finished)); +} +/** Whether `actual` failed with `expected`. */ +template +bool failed_with(Result const& actual, codecs::error expected) { + return !actual.has_value() && actual.error() == expected; +} + +/** + The spec's "After the end and after an error", its second half: a decoder whose flush reported + invalid_character returns it from both receives after, writing nothing, and from every call, and + decodes a valid text after reset; an odd length is invalid_length, from flush when nothing is + still borrowed. +*/ +void after_an_error() { auto decoder = codecs::decoder(formats::hex); BOOST_TEST(decoder.send(characters_of("0g12")).has_value()); std::array decoded{}; BOOST_TEST(is_step(decoder.receive(decoded), 2, codecs::flow::needs_input)); - auto const failed = decoder.flush(); - BOOST_TEST(!failed.has_value() && failed.error() == codecs::error::invalid_character); + BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_character)); decoded.fill(0x5a); - auto const first = decoder.receive(decoded); - auto const second = decoder.receive(decoded); - BOOST_TEST(!first.has_value() && first.error() == codecs::error::invalid_character); - BOOST_TEST(!second.has_value() && second.error() == codecs::error::invalid_character); + BOOST_TEST(failed_with(decoder.receive(decoded), codecs::error::invalid_character)); + BOOST_TEST(failed_with(decoder.receive(decoded), codecs::error::invalid_character)); BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); - auto const sent = decoder.send(characters_of("12")); - BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_character); - auto const flushed_again = decoder.flush(); - BOOST_TEST(!flushed_again.has_value() && - flushed_again.error() == codecs::error::invalid_character); + BOOST_TEST(failed_with(decoder.send(characters_of("12")), codecs::error::invalid_character)); + BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_character)); decoder.reset(); BOOST_TEST(is_step(decoder.send(characters_of("C0fFeE")), 6, codecs::flow::output_pending)); BOOST_TEST(decoder.flush().has_value()); BOOST_TEST(is_step(decoder.receive(decoded), 3, codecs::flow::finished)); BOOST_TEST(decoded[0] == 0xc0 && decoded[1] == 0xff && decoded[2] == 0xee); - // An odd length after flush: invalid_length, from flush when nothing is still borrowed. decoder.reset(); BOOST_TEST(decoder.send(characters_of("abc")).has_value()); BOOST_TEST(is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); - auto const odd = decoder.flush(); - BOOST_TEST(!odd.has_value() && odd.error() == codecs::error::invalid_length); + BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_length)); } /** @@ -530,7 +539,8 @@ int main() { every_chunking_equals_the_one_shot_form(); invalid_texts_give_the_one_shot_error_after_flush(); send_while_output_is_pending(); - after_the_end_and_after_an_error(); + after_the_end(); + after_an_error(); empty_input(); a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); diff --git a/test/hex_test.cpp b/test/hex_test.cpp index 8a49474..284eebd 100644 --- a/test/hex_test.cpp +++ b/test/hex_test.cpp @@ -175,15 +175,15 @@ struct base16_vector { }; /** RFC 4648 section 10's base16 vectors. */ -constexpr std::array rfc4648_base16{{ - {.input = "", .upper = ""}, - {.input = "f", .upper = "66"}, - {.input = "fo", .upper = "666F"}, - {.input = "foo", .upper = "666F6F"}, - {.input = "foob", .upper = "666F6F62"}, - {.input = "fooba", .upper = "666F6F6261"}, - {.input = "foobar", .upper = "666F6F626172"}, -}}; +constexpr std::array rfc4648_base16{ + base16_vector{.input = "", .upper = ""}, + base16_vector{.input = "f", .upper = "66"}, + base16_vector{.input = "fo", .upper = "666F"}, + base16_vector{.input = "foo", .upper = "666F6F"}, + base16_vector{.input = "foob", .upper = "666F6F62"}, + base16_vector{.input = "fooba", .upper = "666F6F6261"}, + base16_vector{.input = "foobar", .upper = "666F6F626172"}, +}; /** Whether `decoded` holds the bytes of `expected`. */ bool decodes_to(codecs::result> const& decoded, @@ -359,50 +359,56 @@ std::array plain_table() { return table; } +/** + Decodes the pair `first` and `second` into one byte and checks the verdict against `expected`, the + plain table's: the byte `expected_byte`, or invalid_character with nothing written. +*/ +void expect_pair_verdict(char first, char second, bool expected_valid, unsigned expected_byte) { + std::array const text{first, second}; + std::string_view const view{text.data(), text.size()}; + std::array decoded{0x5a}; + auto const written = codecs::decode(formats::hex, view, std::span{decoded}); + auto const size = hex_codec::decoded_size(formats::hex, view); + if (!expected_valid) { + BOOST_TEST(!written.has_value() && written.error() == codecs::error::invalid_character); + BOOST_TEST(!size.has_value() && size.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(decoded[0], 0x5aU); + return; + } + BOOST_TEST(written.has_value() && written.value() == 1); + BOOST_TEST(size.has_value() && size.value() == 1); + BOOST_TEST_EQ(decoded[0], expected_byte); +} + /** Review Focus 1: each of the 256 byte values as a character, `char` signed, at the first and the second place of a pair, and as the lone last character of a text of an odd length: the verdict and - the byte equal a plain table's. NUL, 0x80 to 0xff and the characters one past each range (`/`, - `:`, `@`, `G`, `` ` ``, `g`) are invalid_character; a lone valid digit is invalid_length, and a - lone invalid one invalid_character, the lowest value (B23). + the byte equal a plain table's. NUL, 0x80 to 0xff and the characters one past each range (the + slash, the colon, the at sign, `G`, the backquote and `g`) are invalid_character; a lone valid + digit is invalid_length, and a lone invalid one invalid_character, the lowest value (B23). */ void every_byte_value_as_a_character() { std::array const table = plain_table(); for (unsigned value = 0; value < 256; ++value) { int const expected = table[value]; + bool const valid = expected >= 0; + auto const nibble = static_cast(valid ? expected : 0); auto const character = static_cast(static_cast(value)); - for (std::size_t const place : {std::size_t{0}, std::size_t{1}}) { - std::array text{'0', '0'}; - text[place] = character; - std::string_view const view{text.data(), text.size()}; - std::array decoded{0x5a}; - auto const written = codecs::decode(formats::hex, view, std::span{decoded}); - auto const size = hex_codec::decoded_size(formats::hex, view); - if (expected < 0) { - BOOST_TEST(!written.has_value() && - written.error() == codecs::error::invalid_character); - BOOST_TEST(!size.has_value() && size.error() == codecs::error::invalid_character); - BOOST_TEST_EQ(decoded[0], 0x5aU); - } else { - BOOST_TEST(written.has_value() && written.value() == 1); - BOOST_TEST(size.has_value() && size.value() == 1); - unsigned const shift = place == 0 ? 4U : 0U; - BOOST_TEST_EQ(decoded[0], static_cast(expected) << shift); - } - } - std::array odd{'a', 'B', character}; + expect_pair_verdict(character, '0', valid, nibble << 4U); + expect_pair_verdict('0', character, valid, nibble); + std::array const odd{'a', 'B', character}; auto const odd_size = hex_codec::decoded_size(formats::hex, std::string_view{odd.data(), odd.size()}); - BOOST_TEST(!odd_size.has_value()); - BOOST_TEST(odd_size.error() == (expected < 0 ? codecs::error::invalid_character - : codecs::error::invalid_length)); + BOOST_TEST(!odd_size.has_value() && + odd_size.error() == + (valid ? codecs::error::invalid_length : codecs::error::invalid_character)); } } /** The spec's "Format: hex" refusals: an odd length is invalid_length, any other character - invalid_character, and the lowest value wins when both are found (B23); "abc\n" is - invalid_character. + invalid_character, and the lowest value wins when both are found (B23); "abc" and a line + feed is invalid_character. */ void the_refusals() { BOOST_TEST(codecs::decode(formats::hex, std::string_view{"abc\n"}).error() == @@ -441,8 +447,10 @@ void decoding_in_place() { auto const written = codecs::decode(formats::hex, std::string_view{buffer.data(), buffer.size()}, bytes); BOOST_TEST(written.has_value() && written.value() == 16); - std::array const expected{0x00, 0xff, 0x7f, 0x80, 0xde, 0xad, 0xbe, 0xef, - 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; + std::array const expected{ + 0x00, 0xff, 0x7f, 0x80, 0xde, 0xad, 0xbe, 0xef, + 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, + }; BOOST_TEST(std::ranges::equal(bytes.first(16), expected)); // The characters past the bytes are untouched. BOOST_TEST(std::string_view(buffer.data() + 16, 16) == text.substr(16)); @@ -464,10 +472,10 @@ void decoding_in_place() { } /** - Review Focus 3: empty input in every form gives an empty result: the default results in place and - on the heap, the buffer forms (0 written), the tokens, the typed decodes and the sizes. + Review Focus 3, the encodes: empty input in every form gives an empty result: the default results + in place and on the heap, the buffer form (0 written), the tokens and the size. */ -void empty_input_in_every_form() { +void empty_input_in_every_encode() { std::array const nothing{}; auto const fixed = codecs::encode(formats::hex, nothing); static_assert(std::is_same_v> const>); @@ -485,10 +493,13 @@ void empty_input_in_every_form() { BOOST_TEST(codecs::encode(formats::hex, nothing, tokens::append_to(kept)).has_value()); BOOST_TEST(kept == "kept"); BOOST_TEST_EQ(codecs::encoded_size(formats::hex, std::vector{}), 0U); +} +/** Review Focus 3, the decodes: an empty text gives an empty result in every form. */ +void empty_text_in_every_decode() { auto const decoded = codecs::decode(formats::hex, std::string_view{}); BOOST_TEST(decoded.has_value() && decoded.value().empty()); - auto const fixed_decoded = codecs::decode(formats::hex, fixed.value()); + auto const fixed_decoded = codecs::decode(formats::hex, codecs::text<0>{}); BOOST_TEST(fixed_decoded.has_value() && fixed_decoded.value().view().empty()); auto const literal_decoded = codecs::decode(formats::hex, ""); BOOST_TEST(literal_decoded.has_value() && literal_decoded.value().empty()); @@ -532,7 +543,8 @@ int main() { every_byte_value_as_a_character(); the_refusals(); decoding_in_place(); - empty_input_in_every_form(); + empty_input_in_every_encode(); + empty_text_in_every_decode(); every_byte_round_trips(); return boost::report_errors(); } diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index e771f25..9aaa687 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -398,7 +398,7 @@ void packets_to_hex() { text.fill(0); auto bounded_pipeline = codecs::pipe( codecs::pipe(test::packets_to_frames{}, - codecs::each(test::frame_to_bytes_bounded{}, codecs::capacity<16>)), + codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<16>)), codecs::encoder(codecs::formats::hex)); static_assert(std::is_same_v); static_assert(std::is_same_v); From 93ac1c608a44966f43381e6ce78896a4c6b9a389 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 22:03:22 -0300 Subject: [PATCH 079/157] codecs: hex lint fix, the fluent chains of the tests bound to names, the toy pipeline's hex pinned as a literal --- test/allocation_test.cpp | 2 +- test/hex_test.cpp | 6 +++--- test/secret_operation_test.cpp | 6 ++++-- test/toy_media_test.cpp | 5 +++-- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 0cd047d..27a3ee2 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -965,7 +965,7 @@ void check_hex_one_shot_forms() { codecs::decode(formats::hex, fixed_text.value(), codecs::tokens::fixed<32>{}); verdict = encoded.has_value() && back.has_value() && into_array.has_value() && into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && - fixed_back.has_value() && back.value().view().size() == 32; + fixed_back.has_value() && back.value().size() == 32; }); BOOST_TEST(verdict); expect_no_allocation("hex's secret fixed results", [&] { diff --git a/test/hex_test.cpp b/test/hex_test.cpp index 284eebd..7f9fa44 100644 --- a/test/hex_test.cpp +++ b/test/hex_test.cpp @@ -479,7 +479,7 @@ void empty_input_in_every_encode() { std::array const nothing{}; auto const fixed = codecs::encode(formats::hex, nothing); static_assert(std::is_same_v> const>); - BOOST_TEST(fixed.has_value() && fixed.value().view().empty()); + BOOST_TEST(fixed.has_value() && fixed.value().size() == 0); auto const heap = codecs::encode(formats::hex, std::vector{}); BOOST_TEST(heap.has_value() && heap.value().empty()); auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), std::string{}); @@ -500,7 +500,7 @@ void empty_text_in_every_decode() { auto const decoded = codecs::decode(formats::hex, std::string_view{}); BOOST_TEST(decoded.has_value() && decoded.value().empty()); auto const fixed_decoded = codecs::decode(formats::hex, codecs::text<0>{}); - BOOST_TEST(fixed_decoded.has_value() && fixed_decoded.value().view().empty()); + BOOST_TEST(fixed_decoded.has_value() && fixed_decoded.value().size() == 0); auto const literal_decoded = codecs::decode(formats::hex, ""); BOOST_TEST(literal_decoded.has_value() && literal_decoded.value().empty()); auto const buffer_decoded = @@ -511,7 +511,7 @@ void empty_text_in_every_decode() { auto const typed_array = codecs::decode>(formats::hex, ""); BOOST_TEST(typed_array.has_value()); auto const into_secret = codecs::decode(formats::hex, std::string_view{}, tokens::secret); - BOOST_TEST(into_secret.has_value() && into_secret.value().view().empty()); + BOOST_TEST(into_secret.has_value() && into_secret.value().size() == 0); auto const size = hex_codec::decoded_size(formats::hex, std::string_view{}); BOOST_TEST(size.has_value() && size.value() == 0); BOOST_TEST_EQ(codecs::max_decoded_size(formats::hex, std::string_view{}), 0U); diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index cc36870..e8c635c 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -1054,9 +1054,11 @@ void the_spec_scenarios_on_hex() { test::clear_wipes(); auto const decoded = codecs::decode>(formats::hex, encoded.value().view()); + std::span const decoded_bytes = + decoded.has_value() ? decoded.value().bytes() : std::span{}; verdict = encoded.has_value() && encoded.value().view() == expected && - decoded.has_value() && std::ranges::equal(decoded.value().bytes(), key_bytes()) && - wiped_elsewhere(decoded.value().bytes().data(), 32); + std::ranges::equal(decoded_bytes, key_bytes()) && + wiped_elsewhere(decoded_bytes.data(), 32); }); BOOST_TEST(verdict); diff --git a/test/toy_media_test.cpp b/test/toy_media_test.cpp index 9aaa687..6eb0f6e 100644 --- a/test/toy_media_test.cpp +++ b/test/toy_media_test.cpp @@ -382,8 +382,9 @@ void packets_to_hex() { frame_bytes.begin() + static_cast(written.value())); } std::string const expected = codecs::encode(codecs::formats::hex, bytes).value(); - // Frames 0, 4, 5, 6, 8 and 9 have 2, 3, 4, 2, 4 and 2 bytes: 17 bytes, 34 digits. - BOOST_TEST_EQ(expected.size(), 34U); + // Frames 0, 4, 5, 6, 8 and 9 have 2, 3, 4, 2, 4 and 2 bytes: each index's low byte, then its + // pixels' low bytes. + BOOST_TEST_EQ(expected, std::string{"00000404050505060706060808090a0909"}); std::array text{}; auto heap_pipeline = From 42c92efc7a0022c9e0869316f6a0d2944d24c425 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 22:04:17 -0300 Subject: [PATCH 080/157] codecs: hex lint fix, an empty secret result read by empty() --- test/hex_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/hex_test.cpp b/test/hex_test.cpp index 7f9fa44..943e0da 100644 --- a/test/hex_test.cpp +++ b/test/hex_test.cpp @@ -511,7 +511,7 @@ void empty_text_in_every_decode() { auto const typed_array = codecs::decode>(formats::hex, ""); BOOST_TEST(typed_array.has_value()); auto const into_secret = codecs::decode(formats::hex, std::string_view{}, tokens::secret); - BOOST_TEST(into_secret.has_value() && into_secret.value().size() == 0); + BOOST_TEST(into_secret.has_value() && into_secret.value().empty()); auto const size = hex_codec::decoded_size(formats::hex, std::string_view{}); BOOST_TEST(size.has_value() && size.value() == 0); BOOST_TEST_EQ(codecs::max_decoded_size(formats::hex, std::string_view{}), 0U); From b94c06769084be10b9f51dbf91e35f8df064ce71 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 22:19:37 -0300 Subject: [PATCH 081/157] codecs: the tests' shared helpers in test/support once, the include boundaries narrowed, hex's decoder delivery documented --- include/webcpp/codecs/hex.hpp | 6 +- meta/include-boundaries.json | 21 +++- test/allocation_test.cpp | 194 ++++++++++++++----------------- test/buffered_test.cpp | 14 +-- test/each_test.cpp | 20 +--- test/format_transformer_test.cpp | 88 ++++++-------- test/hex_stream_test.cpp | 105 +++++------------ test/hex_test.cpp | 78 +++---------- test/secret_operation_test.cpp | 21 +--- test/secret_stream_test.cpp | 21 ++-- test/support/counting.hpp | 14 +++ test/support/letter_cases.hpp | 47 ++++++++ test/support/samples.hpp | 60 ++++++++++ 13 files changed, 328 insertions(+), 361 deletions(-) create mode 100644 test/support/letter_cases.hpp create mode 100644 test/support/samples.hpp diff --git a/include/webcpp/codecs/hex.hpp b/include/webcpp/codecs/hex.hpp index e623c7b..dfe15ec 100644 --- a/include/webcpp/codecs/hex.hpp +++ b/include/webcpp/codecs/hex.hpp @@ -387,7 +387,11 @@ struct stream_codec { The first digit of a pair whose second is not borrowed yet is held. Every digit's verdict is accumulated in a mask, and reported after `flush` by the call that reads the end of the input, which runs it over everything still borrowed before it writes, as the one-shot form reports - it (B44): @ref error::invalid_character, else @ref error::invalid_length. With + it (B44): @ref error::invalid_character, else @ref error::invalid_length. The bytes delivered + before `flush` may come from pairs that later fail that verdict (the error is reported after + `flush` so that the time does not depend on where the text is invalid): a caller discards what + was delivered when the stream reports an error. For "0g12", two bytes are delivered and + `flush` then reports @ref error::invalid_character. With `Options.secret` it is move-only and wipes the held digit and the error mask by `secure::erase_secret` on `reset`, on destruction and in the moved-from decoder. diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index 32f3f50..d0b647a 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -3,8 +3,7 @@ { "headers": [ "include/webcpp/codecs.hpp", - "include/webcpp/codecs/detail/core/*.hpp", - "include/webcpp/codecs/detail/formats/*.hpp" + "include/webcpp/codecs/detail/core/*.hpp" ], "must-not-include": [ "webcpp/codecs/hex", @@ -17,7 +16,23 @@ "webcpp/codecs/detail/formats", "boost/url" ], - "why": "the core registers no format and needs no Boost.URL, and a format's arithmetic includes no format's header" + "why": "the core (codecs.hpp and detail/core) includes no format, no format's arithmetic and no Boost.URL" + }, + { + "headers": [ + "include/webcpp/codecs/detail/formats/*.hpp" + ], + "must-not-include": [ + "webcpp/codecs/hex", + "webcpp/codecs/base32", + "webcpp/codecs/base58", + "webcpp/codecs/base64", + "webcpp/codecs/bech32", + "webcpp/codecs/percent", + "webcpp/codecs/armor", + "boost/url" + ], + "why": "a format's arithmetic includes no public format header and no Boost.URL, but may include another format's arithmetic (armor reuses base64's, D20)" }, { "headers": [ diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 27a3ee2..792b579 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -16,6 +16,7 @@ #include "support/bookkeeping.hpp" #include "support/doubler.hpp" #include "support/letters.hpp" +#include "support/samples.hpp" #include "support/saturating.hpp" #include "support/toy_media.hpp" @@ -72,21 +73,6 @@ namespace { constexpr std::size_t big = 64; constexpr std::align_val_t aligned{big}; -/** Runs `body` and checks that it moved neither counter. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const new_before = test::counted_new.load(); - std::size_t const c_before = test::counted_c.load(); - body(); - std::size_t const new_after = test::counted_new.load(); - std::size_t const c_after = test::counted_c.load(); - if (new_after != new_before || c_after != c_before) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(new_after - new_before, 0U); - BOOST_TEST_EQ(c_after - c_before, 0U); -} - /** Runs `body`, one allocation of operator new's form, and checks that the counter saw it. */ template void expect_counted(char const* form, Body body) { @@ -168,38 +154,38 @@ void check_buffer_forms() { std::array decoded{}; std::size_t volatile sink = 0; bool volatile verdict = false; - expect_no_allocation("encoded_size", [&] { + test::expect_no_allocation("encoded_size", [&] { sink = codecs::encoded_size(test::letters, input); sink = codecs::encoded_size(test::letters, heap_input); }); - expect_no_allocation("max_decoded_size", [&] { + test::expect_no_allocation("max_decoded_size", [&] { sink = codecs::max_decoded_size(test::letters, std::string_view{"abpp"}); sink = codecs::max_decoded_size(test::letters, "abpp"); }); - expect_no_allocation("encode into a buffer", [&] { + test::expect_no_allocation("encode into a buffer", [&] { verdict = codecs::encode(test::letters, input, output).has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("decode into a buffer", [&] { + test::expect_no_allocation("decode into a buffer", [&] { verdict = codecs::decode(test::letters, std::string_view{"abpp"}, decoded).has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("encode into a short buffer", [&] { + test::expect_no_allocation("encode into a short buffer", [&] { verdict = codecs::encode(test::letters, wide_input, std::span{output}.first(63)) .has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("decode into a short buffer", [&] { + test::expect_no_allocation("decode into a short buffer", [&] { verdict = codecs::decode(test::letters, std::string_view{"abab"}, std::span{decoded}.first(1)) .has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("decode of a refused text", [&] { + test::expect_no_allocation("decode of a refused text", [&] { verdict = codecs::decode(test::letters, std::string_view{"abq"}, decoded).has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("empty inputs", [&] { + test::expect_no_allocation("empty inputs", [&] { verdict = codecs::encode(test::letters, std::span{}, std::span{}) .has_value() && codecs::decode(test::letters, std::string_view{}, std::span{}) @@ -209,14 +195,14 @@ void check_buffer_forms() { std::array const long_input{}; std::array long_text{}; long_text.fill('a'); - expect_no_allocation("an input whose bound saturates", [&] { + test::expect_no_allocation("an input whose bound saturates", [&] { sink = codecs::encoded_size(test::saturating, long_input); sink = codecs::max_decoded_size(test::saturating, long_text); verdict = codecs::encode(test::saturating, long_input, output).has_value() || codecs::decode(test::saturating, long_text, decoded).has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("input_size_fault", [&] { + test::expect_no_allocation("input_size_fault", [&] { verdict = codecs::detail::input_size_fault(test::letters, SIZE_MAX).has_value(); }); BOOST_TEST(verdict); @@ -231,13 +217,13 @@ void check_fixed_results() { std::array output_bytes{}; std::size_t volatile sink = 0; bool volatile verdict = false; - expect_no_allocation("encode to a fixed text", [&] { + test::expect_no_allocation("encode to a fixed text", [&] { auto const encoded = codecs::encode(test::letters, wide_input); verdict = encoded.has_value(); sink = encoded.value().size(); }); BOOST_TEST(verdict); - expect_no_allocation("the fixed results", [&] { + test::expect_no_allocation("the fixed results", [&] { codecs::text<8> const first_text; codecs::text<8> const second_text = first_text; codecs::bytes<4> const first_bytes; @@ -247,31 +233,31 @@ void check_fixed_results() { BOOST_TEST(verdict); auto const fixed_text = codecs::encode(test::letters, input); // built before the window BOOST_TEST(fixed_text.has_value()); - expect_no_allocation("decode of a fixed text", [&] { + test::expect_no_allocation("decode of a fixed text", [&] { auto const decoded = codecs::decode(test::letters, fixed_text.value()); verdict = decoded.has_value(); sink = decoded.value().size(); }); BOOST_TEST(verdict); - expect_no_allocation("typed decode into an array", [&] { + test::expect_no_allocation("typed decode into an array", [&] { verdict = codecs::decode>(test::letters, "abpp").has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("typed decode into fixed bytes", [&] { + test::expect_no_allocation("typed decode into fixed bytes", [&] { verdict = codecs::decode>(test::letters, "abpp").has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("typed decode into a library's fixed type", [&] { + test::expect_no_allocation("typed decode into a library's fixed type", [&] { verdict = codecs::decode(test::letters, "abpp").has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("typed decodes that are refused", [&] { + test::expect_no_allocation("typed decodes that are refused", [&] { verdict = codecs::decode>(test::letters, "ab").has_value() || codecs::decode>(test::letters, "abpp").has_value() || codecs::decode(test::letters, "abpq").has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("a value codec's default result and buffer forms", [&] { + test::expect_no_allocation("a value codec's default result and buffer forms", [&] { auto const encoded = codecs::encode(test::be16, test::number{0x1234}); verdict = encoded.has_value() && codecs::encode(test::be16, test::number{0x1234}, output_bytes).has_value() && @@ -279,7 +265,7 @@ void check_fixed_results() { sink = encoded.value().size(); }); BOOST_TEST(verdict); - expect_no_allocation("a value codec's refused buffer", [&] { + test::expect_no_allocation("a value codec's refused buffer", [&] { verdict = codecs::encode(test::be16, test::number{0x1234}, std::span{output_bytes}.first(1)) @@ -289,12 +275,12 @@ void check_fixed_results() { BOOST_TEST(!verdict); // The buffer form of a value codec of text (F16): characters, nothing allocated. std::array output_characters{}; - expect_no_allocation("a value codec of text's buffer form", [&] { + test::expect_no_allocation("a value codec of text's buffer form", [&] { verdict = codecs::encode(test::be16, test::hex_number{0x1234}, output_characters).has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("a value codec of text's refused buffer", [&] { + test::expect_no_allocation("a value codec of text's refused buffer", [&] { verdict = codecs::encode(test::be16, test::hex_number{0x1234}, std::span{output_characters}.first(3)) .has_value(); @@ -309,7 +295,7 @@ void check_fixed_tokens() { std::array const input{0x01, 0xff}; std::vector const heap_input{0x01, 0xff}; // built before the window bool volatile verdict = false; - expect_no_allocation("encode into fixed", [&] { + test::expect_no_allocation("encode into fixed", [&] { auto const from_array = codecs::encode(test::letters, input, codecs::tokens::fixed<8>{}); auto const from_heap = codecs::encode(test::letters, heap_input, codecs::tokens::fixed<8>{}); @@ -317,12 +303,12 @@ void check_fixed_tokens() { from_array.value() == from_heap.value(); }); BOOST_TEST(verdict); - expect_no_allocation("decode into fixed", [&] { + test::expect_no_allocation("decode into fixed", [&] { auto const decoded = codecs::decode(test::letters, "abpp", codecs::tokens::fixed<8>{}); verdict = decoded.has_value() && decoded.value().size() == 2; }); BOOST_TEST(verdict); - expect_no_allocation("a value codec into fixed", [&] { + test::expect_no_allocation("a value codec into fixed", [&] { auto const encoded = codecs::encode(test::be16, test::number{0x1234}, codecs::tokens::fixed<2>{}); auto const text_encoded = @@ -330,13 +316,13 @@ void check_fixed_tokens() { verdict = encoded.has_value() && text_encoded.has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("fixed too small, and refused", [&] { + test::expect_no_allocation("fixed too small, and refused", [&] { verdict = codecs::encode(test::letters, input, codecs::tokens::fixed<3>{}).has_value() || codecs::decode(test::letters, "abpp", codecs::tokens::fixed<1>{}).has_value() || codecs::decode(test::letters, "abpq", codecs::tokens::fixed<8>{}).has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("the default token of a fixed result", [&] { + test::expect_no_allocation("the default token of a fixed result", [&] { verdict = codecs::encode(test::letters, input, codecs::tokens::automatic{}).has_value() && codecs::decode(test::letters, codecs::text<4>{}, codecs::tokens::automatic{}) .has_value(); @@ -348,7 +334,7 @@ void check_fixed_tokens() { */ void check_secret_results() { bool volatile verdict = false; - expect_no_allocation("the fixed secret results", [&] { + test::expect_no_allocation("the fixed secret results", [&] { codecs::secret_text<64> held_text; codecs::detail::fixed_access::writable(held_text)[0] = 's'; codecs::detail::fixed_access::resize(held_text, 1); @@ -363,7 +349,7 @@ void check_secret_results() { verdict = cloned_text.view() == "s" && cloned_bytes.view()[0] == 0x5a; }); BOOST_TEST(verdict); - expect_no_allocation("an empty secret on the heap", [&] { + test::expect_no_allocation("an empty secret on the heap", [&] { codecs::secret_byte_vector empty_bytes; empty_bytes.append(std::span{}); codecs::secret_string empty_text; @@ -380,7 +366,7 @@ void check_secret_operations() { webcpp::secure::secret<2> const key; std::array const input{0x01, 0xff}; bool volatile verdict = false; - expect_no_allocation("the fixed secret operations", [&] { + test::expect_no_allocation("the fixed secret operations", [&] { auto const encoded = codecs::encode(test::letters, key); auto const through_token = codecs::encode(test::letters, input, codecs::tokens::secret); auto const decoded = codecs::decode>(test::letters, "abpp"); @@ -425,7 +411,7 @@ void check_assign_to_scratch() { // the standard library allocates one: the MSVC STL's debug proxy. std::size_t const one_scratch = test::bookkeeping().bytes != 0 ? 2U : 1U; bool volatile verdict = false; - expect_no_allocation("assign_to of a static bound of 4096, in place", [&] { + test::expect_no_allocation("assign_to of a static bound of 4096, in place", [&] { verdict = codecs::encode(test::letters, at_the_limit, codecs::tokens::assign_to(text_target)) .has_value() && @@ -479,18 +465,18 @@ void check_over() { std::array decoded{}; std::size_t volatile sink = 0; bool volatile verdict = false; - expect_no_allocation("over, the default results", [&] { + test::expect_no_allocation("over, the default results", [&] { auto const encoded = codecs::encode(chain, input); auto const bytes_back = codecs::decode(chain, encoded.value()); verdict = encoded.has_value() && bytes_back.has_value() && std::ranges::equal(bytes_back.value().view(), input); }); BOOST_TEST(verdict); - expect_no_allocation("over, the sizes", [&] { + test::expect_no_allocation("over, the sizes", [&] { sink = codecs::encoded_size(chain, input); sink = codecs::encoded_size(chain, key); }); - expect_no_allocation("over, the buffer forms", [&] { + test::expect_no_allocation("over, the buffer forms", [&] { // The decode reads the 64 letters of the input, a text<64>: its intermediate is in place. auto const written = codecs::decode(chain, codecs::encode(chain, input).value(), decoded); verdict = codecs::encode(chain, input, output).has_value() && written.has_value() && @@ -498,7 +484,7 @@ void check_over() { std::ranges::equal(std::span{decoded}.first(input.size()), input); }); BOOST_TEST(verdict); - expect_no_allocation("over, a typed decode and the tokens", [&] { + test::expect_no_allocation("over, a typed decode and the tokens", [&] { auto const text_value = codecs::encode(chain, input); auto const as_array = codecs::decode>(chain, text_value.value()); @@ -506,7 +492,7 @@ void check_over() { verdict = as_array.has_value() && fixed.has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("over, a secret chain", [&] { + test::expect_no_allocation("over, a secret chain", [&] { auto const secret_text = codecs::encode(chain, key); // The text's size is known at compile time: a text of 128 characters in an array. std::array text_array{}; @@ -515,7 +501,7 @@ void check_over() { verdict = secret_text.has_value() && secret_back.has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("over, a value codec", [&] { + test::expect_no_allocation("over, a value codec", [&] { auto const encoded = codecs::encode(value_chain, test::number{0x1234}); auto const number_back = codecs::decode(value_chain, encoded.value()); // Made secret by its token: the intermediate in place, wiped, the result a secret_text<4>. @@ -524,7 +510,7 @@ void check_over() { verdict = encoded.has_value() && number_back.has_value() && secret_text.has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("over, an input whose bound saturates and the empty input", [&] { + test::expect_no_allocation("over, an input whose bound saturates and the empty input", [&] { constexpr codecs::over saturating_chain{test::letters, test::saturating}; std::array const long_input{}; verdict = codecs::encode(saturating_chain, long_input).has_value() || @@ -562,7 +548,7 @@ void check_transformers() { std::array doubled{}; std::size_t volatile sink = 0; bool volatile verdict = false; - expect_no_allocation("doubler, a stream", [&] { + test::expect_no_allocation("doubler, a stream", [&] { test::doubler transformer; bool streamed = transformer.send(std::string_view{"abc"}).has_value(); auto const received = transformer.receive(doubled); @@ -573,7 +559,7 @@ void check_transformers() { verdict = streamed && std::string_view{doubled.data(), 6} == "aabbcc"; }); BOOST_TEST(verdict); - expect_no_allocation("packets_to_frames, a stream", [&] { + test::expect_no_allocation("packets_to_frames, a stream", [&] { test::packets_to_frames decoder; std::size_t received_count = 0; for (test::packet const& input_packet : packets) { @@ -590,7 +576,7 @@ void check_transformers() { frames[2].index == 3; }); BOOST_TEST(verdict); - expect_no_allocation("frame_to_bytes and frame_to_image, one-shot", [&] { + test::expect_no_allocation("frame_to_bytes and frame_to_image, one-shot", [&] { auto const written = test::frame_to_bytes::transform(std::span{frames}.first(3), frame_bytes); auto const bounded = @@ -612,7 +598,7 @@ void check_pipe_and_drain() { std::array piped_output{}; std::array drain_buffer{}; bool volatile verdict = false; - expect_no_allocation("pipe of two doublers", [&] { + test::expect_no_allocation("pipe of two doublers", [&] { auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); bool streamed = piped.send(std::string_view{"abc"}).has_value(); auto const received = piped.receive(piped_output); @@ -623,7 +609,7 @@ void check_pipe_and_drain() { verdict = streamed && std::string_view{piped_output.data(), 12} == "aaaabbbbcccc"; }); BOOST_TEST(verdict); - expect_no_allocation("drain of a pipe of three doublers", [&] { + test::expect_no_allocation("drain of a pipe of three doublers", [&] { auto piped = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}); std::size_t total = 0; auto sink = [&total](std::span piece) noexcept { total += piece.size(); }; @@ -650,7 +636,7 @@ void check_format_transformers() { std::array text{}; std::array decoded{}; bool volatile verdict = false; - expect_no_allocation("encoder(letters) and decoder(letters)", [&] { + test::expect_no_allocation("encoder(letters) and decoder(letters)", [&] { auto encoder = codecs::encoder(test::letters); bool streamed = encoder.send(std::span{bytes}.first(2)).has_value(); auto const first = encoder.receive(std::span{text}.first(3)); @@ -680,7 +666,7 @@ void check_format_transformers() { decoded == bytes && transformed.has_value(); }); BOOST_TEST(verdict); - expect_no_allocation("encoder(over{letters, letters}) as a stream", [&] { + test::expect_no_allocation("encoder(over{letters, letters}) as a stream", [&] { std::array chain_text{}; auto encoder = codecs::encoder(codecs::over{test::letters, test::letters}); bool streamed = encoder.send(bytes).has_value() && encoder.flush().has_value(); @@ -696,7 +682,7 @@ void check_format_transformers() { decoded_chain->flow == codecs::flow::finished && decoded == bytes; }); BOOST_TEST(verdict); - expect_no_allocation("a fault of the configuration, in every stream call", [&] { + test::expect_no_allocation("a fault of the configuration, in every stream call", [&] { auto encoder = codecs::encoder(codecs::over{test::letters, test::letters(true)}); bool faulted = !encoder.send(bytes).has_value() && !encoder.receive(text).has_value() && !encoder.flush().has_value(); @@ -748,7 +734,7 @@ void check_each_and_buffered() { std::array frame_bytes{}; std::array images{}; bool volatile verdict = false; - expect_no_allocation("each(frame_to_bytes_bounded, capacity<4>)", [&] { + test::expect_no_allocation("each(frame_to_bytes_bounded, capacity<4>)", [&] { auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<4>); std::size_t total = 0; bool streamed = true; @@ -763,7 +749,7 @@ void check_each_and_buffered() { verdict = streamed && total == 14 && moved.completed_items() == 0; }); BOOST_TEST(verdict); - expect_no_allocation("buffered(frame_to_image, capacity<8>)", [&] { + test::expect_no_allocation("buffered(frame_to_image, capacity<8>)", [&] { auto adapter = codecs::buffered(test::frame_to_image{}, codecs::capacity<8>); bool streamed = adapter.send(std::span{frames}.first(2)).has_value() && adapter.send(std::span{frames}.subspan(2)).has_value() && @@ -788,7 +774,7 @@ void check_secret_streams() { std::array text{}; std::array decoded{}; bool volatile verdict = false; - expect_no_allocation("encoder(letters, secret_operation) and its decoder", [&] { + test::expect_no_allocation("encoder(letters, secret_operation) and its decoder", [&] { auto encoder = codecs::encoder(test::letters, codecs::secret_operation); bool streamed = encoder.send(bytes).has_value() && encoder.receive(std::span{text}.first(3)).has_value(); @@ -809,7 +795,7 @@ void check_secret_streams() { verdict = streamed && decoded == bytes; }); BOOST_TEST(verdict); - expect_no_allocation("pipe of two secret encoders, and over's secret stream", [&] { + test::expect_no_allocation("pipe of two secret encoders, and over's secret stream", [&] { auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), codecs::encoder(test::letters, codecs::secret_operation)); bool streamed = piped.send(bytes).has_value() && piped.flush().has_value(); @@ -826,7 +812,7 @@ void check_secret_streams() { verdict = streamed && chain_text == text; }); BOOST_TEST(verdict); - expect_no_allocation("each and buffered in place over a secret encoder", [&] { + test::expect_no_allocation("each and buffered in place over a secret encoder", [&] { auto each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation), codecs::capacity<2>); bool streamed = each.send(bytes).has_value() && @@ -853,7 +839,7 @@ void check_pipe_of_packets_into_each() { test::packet{.index = 0, .frames = 1}, test::packet{.index = 1, .frames = 2}, }; - expect_no_allocation("pipe(packets_to_frames, each(frame_to_image, capacity<1>))", [&] { + test::expect_no_allocation("pipe(packets_to_frames, each(frame_to_image, capacity<1>))", [&] { auto piped = codecs::pipe(test::packets_to_frames{}, codecs::each(test::frame_to_image{}, codecs::capacity<1>)); std::size_t total = 0; @@ -881,17 +867,17 @@ void check_saturating_refusals() { std::array long_characters{}; long_characters.fill('a'); bool volatile verdict = true; - expect_no_allocation("default encode of an input whose bound saturates", [&] { + test::expect_no_allocation("default encode of an input whose bound saturates", [&] { verdict = codecs::encode(test::saturating, long_bytes).has_value() || codecs::encode(test::saturating, long_array).has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("default decode of a text whose bound saturates", [&] { + test::expect_no_allocation("default decode of a text whose bound saturates", [&] { verdict = codecs::decode(test::saturating, long_text).has_value() || codecs::decode(test::saturating, long_characters).has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("typed decode of a text whose bound saturates", [&] { + test::expect_no_allocation("typed decode of a text whose bound saturates", [&] { verdict = codecs::decode>(test::saturating, long_text).has_value() || codecs::decode(test::saturating, long_text).has_value() || @@ -909,27 +895,18 @@ void check_saturating_refusals() { codecs::error::input_too_long); } -/** 32 bytes of every digit. */ -std::array digest_bytes() { - std::array digest{}; - for (std::size_t index = 0; index < digest.size(); ++index) { - digest[index] = static_cast((index * 8U) ^ (index >> 1U)); - } - return digest; -} - /** hex's buffer forms, fixed results, typed decodes into fixed types and secret fixed results (Task 13) allocate nothing, on every path. */ void check_hex_one_shot_forms() { namespace formats = codecs::formats; - std::array const digest = digest_bytes(); + std::array const digest = test::digest_bytes(); webcpp::secure::secret<32> const key; std::array text{}; std::array decoded{}; auto const fixed_text = codecs::encode(formats::hex, digest); // built before the windows std::size_t volatile sink = 0; bool volatile verdict = false; - expect_no_allocation("hex's buffer forms and sizes", [&] { + test::expect_no_allocation("hex's buffer forms and sizes", [&] { sink = codecs::encoded_size(formats::hex, digest); sink = codecs::max_decoded_size(formats::hex, fixed_text.value().view()); verdict = @@ -942,7 +919,7 @@ void check_hex_one_shot_forms() { decoded == digest; }); BOOST_TEST(verdict); - expect_no_allocation("hex's refused buffer forms", [&] { + test::expect_no_allocation("hex's refused buffer forms", [&] { verdict = codecs::encode(formats::hex, digest, std::span{text}.first(63)).has_value() || codecs::decode(formats::hex, std::string_view{"abc"}, decoded).has_value() || @@ -951,7 +928,7 @@ void check_hex_one_shot_forms() { .has_value(); }); BOOST_TEST(!verdict); - expect_no_allocation("hex's fixed results and tokens", [&] { + test::expect_no_allocation("hex's fixed results and tokens", [&] { auto const encoded = codecs::encode(formats::hex, digest); auto const back = codecs::decode(formats::hex, encoded.value()); auto const into_array = @@ -968,7 +945,7 @@ void check_hex_one_shot_forms() { fixed_back.has_value() && back.value().size() == 32; }); BOOST_TEST(verdict); - expect_no_allocation("hex's secret fixed results", [&] { + test::expect_no_allocation("hex's secret fixed results", [&] { auto const from_key = codecs::encode(formats::hex, key); auto const through_token = codecs::encode(formats::hex, digest, codecs::tokens::secret); auto const into_secret = @@ -1001,35 +978,36 @@ void check_hex_streams() { std::mt19937_64 generator{20261126}; std::ranges::generate(input, [&] { return static_cast(generator()); }); bool volatile verdict = false; - expect_no_allocation("1 MiB through pipe(encoder(hex), decoder(hex)) in random chunks", [&] { - auto piped = codecs::pipe(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); - std::uniform_int_distribution chunk_size{0, 3000}; - std::size_t compared = 0; - bool same = true; - auto const sink = [&](std::span piece) noexcept { - same = same && compared + piece.size() <= input.size() && - std::ranges::equal(piece, std::span{input}.subspan(compared, piece.size())); - compared += piece.size(); - }; - bool streamed = true; - std::array fixed_span{}; - for (std::size_t position = 0; position < input.size() && streamed;) { - std::size_t const size = std::min(chunk_size(generator), input.size() - position); - auto const sent = piped.send(std::span{input}.subspan(position, size)); - streamed = - sent.has_value() && codecs::drain(piped, sink, std::span{fixed_span}).has_value(); - position += sent.has_value() ? sent->count : 0; - } - streamed = streamed && piped.flush().has_value() && - codecs::drain(piped, sink, std::span{fixed_span}).has_value(); - verdict = streamed && same && compared == input.size(); - }); + test::expect_no_allocation( + "1 MiB through pipe(encoder(hex), decoder(hex)) in random chunks", [&] { + auto piped = codecs::pipe(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); + std::uniform_int_distribution chunk_size{0, 3000}; + std::size_t compared = 0; + bool same = true; + auto const sink = [&](std::span piece) noexcept { + same = same && compared + piece.size() <= input.size() && + std::ranges::equal(piece, std::span{input}.subspan(compared, piece.size())); + compared += piece.size(); + }; + bool streamed = true; + std::array fixed_span{}; + for (std::size_t position = 0; position < input.size() && streamed;) { + std::size_t const size = std::min(chunk_size(generator), input.size() - position); + auto const sent = piped.send(std::span{input}.subspan(position, size)); + streamed = sent.has_value() && + codecs::drain(piped, sink, std::span{fixed_span}).has_value(); + position += sent.has_value() ? sent->count : 0; + } + streamed = streamed && piped.flush().has_value() && + codecs::drain(piped, sink, std::span{fixed_span}).has_value(); + verdict = streamed && same && compared == input.size(); + }); BOOST_TEST(verdict); std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; std::array text{}; std::array decoded{}; - expect_no_allocation("encoder(hex) and decoder(hex), public and secret", [&] { + test::expect_no_allocation("encoder(hex) and decoder(hex), public and secret", [&] { auto encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); bool streamed = encoder.send(bytes).has_value() && encoder.receive(std::span{text}.first(3)).has_value() && @@ -1054,7 +1032,7 @@ void check_hex_streams() { verdict = streamed && decoded == bytes && text[0] == '0' && text[11] == 'B'; }); BOOST_TEST(verdict); - expect_no_allocation("each and buffered in place over encoder(hex)", [&] { + test::expect_no_allocation("each and buffered in place over encoder(hex)", [&] { auto each = codecs::each(codecs::encoder(formats::hex), codecs::capacity<2>); bool streamed = each.send(bytes).has_value() && each.receive(std::span{text}.first(1)).has_value() && diff --git a/test/buffered_test.cpp b/test/buffered_test.cpp index 22f8e28..d386ec9 100644 --- a/test/buffered_test.cpp +++ b/test/buffered_test.cpp @@ -423,18 +423,6 @@ void heap_growth() { } } -/** Runs `body` and checks that it allocated nothing, through operator new or the C library. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const before = test::allocations(); - body(); - std::size_t const after = test::allocations(); - if (after != before) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(after - before, 0U); -} - /** The heap form's limits (Review Focus 2): an output wanted past what the allocator holds is input_too_long at flush, with nothing allocated for it, and a doubling that reaches the most the @@ -447,7 +435,7 @@ void heap_limits() { // A static bound saturated past 4 input elements: wanted exceeds max_size(). auto adapter = codecs::buffered(test::saturated_bound<4>{}); BOOST_TEST(is_step(adapter.send(input), 5, codecs::flow::needs_input)); - expect_no_allocation("a flush past max_size", [&] { + test::expect_no_allocation("a flush past max_size", [&] { BOOST_TEST(is_error(adapter.flush(), codecs::error::input_too_long)); BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); }); diff --git a/test/each_test.cpp b/test/each_test.cpp index cc2c736..85ceb36 100644 --- a/test/each_test.cpp +++ b/test/each_test.cpp @@ -246,18 +246,6 @@ void types() { static_assert(codecs::is_constant_time_v>); } -/** Runs `body` and checks that it allocated nothing, through operator new or the C library. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const before = test::allocations(); - body(); - std::size_t const after = test::allocations(); - if (after != before) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(after - before, 0U); -} - /** The spec's scenario "Per item", first part: five frames streamed through each(frame_to_image) into a span of one image at a time give five images in order, each receive giving one, and flush after @@ -289,8 +277,8 @@ void per_item_images() { // The heap form is made outside the count: a container may allocate when it is constructed // (the MSVC STL's debug proxy), and its calls allocate nothing here. auto heap_adapter = codecs::each(test::frame_to_image{}); - expect_no_allocation("each(frame_to_image)", [&] { images_one_a_receive(heap_adapter); }); - expect_no_allocation("each(frame_to_image, capacity<1>)", [] { + test::expect_no_allocation("each(frame_to_image)", [&] { images_one_a_receive(heap_adapter); }); + test::expect_no_allocation("each(frame_to_image, capacity<1>)", [] { auto adapter = codecs::each(test::frame_to_image{}, codecs::capacity<1>); images_one_a_receive(adapter); }); @@ -308,7 +296,7 @@ void per_item_bytes() { auto const expected = expected_items(frames); for (std::size_t const span_size : {std::size_t{3}, std::size_t{1}, std::size_t{4}, std::size_t{64}}) { - expect_no_allocation("each(frame_to_bytes_bounded, capacity<64>)", [&] { + test::expect_no_allocation("each(frame_to_bytes_bounded, capacity<64>)", [&] { auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<64>); BOOST_TEST(items_through(adapter, frames, span_size) == expected); BOOST_TEST_EQ(adapter.completed_items(), 5U); @@ -435,7 +423,7 @@ void heap_limits() { // A static bound saturated for any item: wanted exceeds max_size(). auto adapter = codecs::each(test::saturated_bound<0>{}); BOOST_TEST(is_step(adapter.send(item), 1, codecs::flow::output_pending)); - expect_no_allocation("a receive past max_size", [&] { + test::expect_no_allocation("a receive past max_size", [&] { BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); BOOST_TEST(is_error(adapter.receive(output), codecs::error::input_too_long)); }); diff --git a/test/format_transformer_test.cpp b/test/format_transformer_test.cpp index ab49fa7..a6f2cc7 100644 --- a/test/format_transformer_test.cpp +++ b/test/format_transformer_test.cpp @@ -17,6 +17,7 @@ #include "support/be16.hpp" #include "support/chunkings.hpp" #include "support/letters.hpp" +#include "support/samples.hpp" #include "support/tagged_letters.hpp" #include @@ -29,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -137,24 +137,6 @@ static_assert(!gives_label); static_assert(gives_label); static_assert(gives_human_readable_part); -/** `size` bytes from a generator of a fixed seed. */ -std::vector random_bytes(std::size_t size) { - // A fixed seed, so that every lane and every run sees the same bytes. - // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) - std::mt19937_64 generator{20261126}; - std::uniform_int_distribution byte_value{0, 255}; - std::vector bytes(size); - for (std::uint8_t& byte : bytes) { - byte = static_cast(byte_value(generator)); - } - return bytes; -} - -/** The characters of `text` as the span a decoder reads. */ -std::span characters_of(std::string_view text) { - return {text.data(), text.size()}; -} - /** The bytes of `text` as the span an encoder reads. */ std::span bytes_of(std::span bytes) { return bytes; @@ -165,11 +147,11 @@ void every_chunking_equals_the_one_shot_form() { auto encoder = codecs::encoder(test::letters); auto decoder = codecs::decoder(test::letters); for (std::size_t const size : std::array{0, 1, 31, 32, 33, 1000}) { - std::vector const bytes = random_bytes(size); + std::vector const bytes = test::random_bytes(size); auto const text = codecs::encode(test::letters, bytes); BOOST_TEST_EQ(text.value().size(), 2 * size); test::expect_every_chunking(encoder, bytes_of(bytes), text.value()); - test::expect_every_chunking(decoder, characters_of(text.value()), bytes); + test::expect_every_chunking(decoder, test::characters_of(text.value()), bytes); } } @@ -189,7 +171,7 @@ void invalid_texts_give_the_one_shot_error_after_flush() { auto const one_shot = codecs::decode(test::letters, text); BOOST_TEST(!one_shot.has_value()); test::for_each_chunking( - characters_of(text), [&](std::span const> chunks) { + test::characters_of(text), [&](std::span const> chunks) { for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { decoder.reset(); BOOST_TEST(test::error_after_flush(decoder, chunks, span_size) == @@ -230,7 +212,7 @@ std::size_t receive_until_done(Transformer& transformer, std::size_t span_size) output is received. A finished encoder accepts nothing: {0, finished}. */ void send_while_output_is_pending() { - std::vector const bytes = random_bytes(68); + std::vector const bytes = test::random_bytes(68); auto encoder = codecs::encoder(test::letters); auto const first = encoder.send(std::span{bytes}.first(64)); BOOST_TEST(first.has_value() && first->count == 64 && @@ -258,7 +240,7 @@ void send_while_output_is_pending() { nothing->flow == codecs::flow::needs_input); // A lone letter is absorbed into the decoder's state, which frees the input at once. auto decoder = codecs::decoder(test::letters); - auto const lone = decoder.send(characters_of("a")); + auto const lone = decoder.send(test::characters_of("a")); BOOST_TEST(lone.has_value() && lone->count == 1 && lone->flow == codecs::flow::needs_input); } @@ -268,21 +250,22 @@ void send_while_output_is_pending() { that reports invalid_character leaves unchanged. */ void the_call_that_fails_writes_nothing() { - std::vector const bytes = random_bytes(2048); + std::vector const bytes = test::random_bytes(2048); std::string const text = codecs::encode(test::letters, bytes).value(); auto decoder = codecs::decoder(test::letters); std::vector delivered; auto sink = [&delivered](std::span piece) { delivered.insert(delivered.end(), piece.begin(), piece.end()); }; - BOOST_TEST(decoder.send(characters_of(std::string_view{text}.substr(0, 4000))).has_value()); + BOOST_TEST( + decoder.send(test::characters_of(std::string_view{text}.substr(0, 4000))).has_value()); auto const drained = codecs::drain(decoder, sink); BOOST_TEST(drained.has_value() && drained.value() == codecs::flow::needs_input); BOOST_TEST(std::ranges::equal(delivered, std::span{bytes}.first(2000))); std::string tail = text.substr(4000, 96); tail.back() = 'z'; - BOOST_TEST(decoder.send(characters_of(tail)).has_value()); + BOOST_TEST(decoder.send(test::characters_of(tail)).has_value()); auto const flushed = decoder.flush(); BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); std::array span{}; @@ -398,10 +381,11 @@ void expect_the_fault_in_every_decode(Format const& format, std::string_view tex BOOST_TEST( is_configured_fault(codecs::decode(format, text, std::allocator{}))); auto const decoder = codecs::decoder(format); - BOOST_TEST(is_configured_fault(decoder.transform(characters_of(text), byte_buffer))); - BOOST_TEST_EQ(decoder.output_size(characters_of(text)), 0U); + BOOST_TEST(is_configured_fault(decoder.transform(test::characters_of(text), byte_buffer))); + BOOST_TEST_EQ(decoder.output_size(test::characters_of(text)), 0U); auto const secret_decoder = codecs::decoder(format, codecs::secret_operation); - BOOST_TEST(is_configured_fault(secret_decoder.transform(characters_of(text), byte_buffer))); + BOOST_TEST( + is_configured_fault(secret_decoder.transform(test::characters_of(text), byte_buffer))); BOOST_TEST(untouched_bytes(byte_buffer)); } @@ -584,7 +568,7 @@ void expect_the_fault_from_the_first_stream_call( link's fault at the first receive, the outer link's data error before the inner link's fault). */ void a_configuration_fault_comes_from_the_first_stream_call() { - std::vector const bytes = random_bytes(40); + std::vector const bytes = test::random_bytes(40); std::string const valid = codecs::encode(test::letters, bytes).value(); std::string const inner_invalid_length = codecs::encode(test::letters, std::string_view{"abc"}).value(); @@ -605,7 +589,7 @@ void a_configuration_fault_comes_from_the_first_stream_call() { ...); for (std::string_view const text : texts) { (expect_the_fault_from_the_first_stream_call( - [&] { return codecs::decoder(format); }, characters_of(text)), + [&] { return codecs::decoder(format); }, test::characters_of(text)), ...); } }, @@ -616,7 +600,7 @@ void a_configuration_fault_comes_from_the_first_stream_call() { auto encoder = codecs::encoder(letters_over_letters{test::letters(true), test::letters}); BOOST_TEST(is_configured_fault(encoder.send(bytes_of(bytes)))); auto decoder = codecs::decoder(letters_over_letters{test::letters, test::letters(true)}); - BOOST_TEST(is_configured_fault(decoder.send(characters_of("abq")))); + BOOST_TEST(is_configured_fault(decoder.send(test::characters_of("abq")))); BOOST_TEST(is_configured_fault(decoder.flush())); std::array output{}; BOOST_TEST(is_configured_fault(decoder.receive(output))); @@ -629,7 +613,7 @@ void a_configuration_fault_comes_from_the_first_stream_call() { */ void an_error_stays_until_reset() { auto decoder = codecs::decoder(test::letters); - BOOST_TEST(decoder.send(characters_of("abq")).has_value()); + BOOST_TEST(decoder.send(test::characters_of("abq")).has_value()); BOOST_TEST_EQ(receive_until_done(decoder, 8), 1U); auto const flushed = decoder.flush(); BOOST_TEST(!flushed.has_value() && flushed.error() == codecs::error::invalid_character); @@ -638,14 +622,14 @@ void an_error_stays_until_reset() { auto const received = decoder.receive(output); BOOST_TEST(!received.has_value() && received.error() == codecs::error::invalid_character); } - auto const sent = decoder.send(characters_of("ab")); + auto const sent = decoder.send(test::characters_of("ab")); BOOST_TEST(!sent.has_value() && sent.error() == codecs::error::invalid_character); auto const flushed_again = decoder.flush(); BOOST_TEST(!flushed_again.has_value() && flushed_again.error() == codecs::error::invalid_character); decoder.reset(); - std::array const, 1> const chunks{characters_of("abcd")}; + std::array const, 1> const chunks{test::characters_of("abcd")}; auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); } @@ -668,14 +652,14 @@ void transform_is_the_buffer_form() { auto const decoder = codecs::decoder(test::letters); std::array decoded{}; decoded.fill(0x5a); - auto const invalid = decoder.transform(characters_of("abq"), decoded); + auto const invalid = decoder.transform(test::characters_of("abq"), decoded); BOOST_TEST(!invalid.has_value() && invalid.error() == codecs::error::invalid_character); BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); - auto const read = decoder.transform(characters_of("abcdpo"), decoded); + auto const read = decoder.transform(test::characters_of("abcdpo"), decoded); BOOST_TEST(read.has_value() && read.value() == 3); BOOST_TEST(std::ranges::equal(std::span{decoded}.first(3), bytes)); - BOOST_TEST_EQ(decoder.output_size(characters_of("abcdpo")), 3U); - BOOST_TEST_EQ(decoder.output_size(characters_of("abq")), 0U); + BOOST_TEST_EQ(decoder.output_size(test::characters_of("abcdpo")), 3U); + BOOST_TEST_EQ(decoder.output_size(test::characters_of("abq")), 0U); // Empty spans: transform writes nothing and returns 0, of the encoder and of the decoder, of a // format and of a chain, public and secret (Review Focus 3). @@ -718,11 +702,11 @@ void over_streams_through_a_pipe() { auto encoder = codecs::encoder(chain); auto decoder = codecs::decoder(chain); for (std::size_t const size : std::array{0, 1, 33, 1000}) { - std::vector const bytes = random_bytes(size); + std::vector const bytes = test::random_bytes(size); auto const text = codecs::encode(chain, bytes); BOOST_TEST_EQ(text.value().size(), 4 * size); test::expect_every_chunking(encoder, bytes_of(bytes), text.value()); - test::expect_every_chunking(decoder, characters_of(text.value()), bytes); + test::expect_every_chunking(decoder, test::characters_of(text.value()), bytes); } // The outer link's error, invalid_character of "abq", and the inner link's, invalid_length of // the letters of "abc": the errors differ, so that each shows which link reported it. @@ -735,7 +719,7 @@ void over_streams_through_a_pipe() { auto const one_shot = codecs::decode(chain, text); BOOST_TEST(!one_shot.has_value() && one_shot.error() == expected_error); test::for_each_chunking( - characters_of(text), [&](std::span const> chunks) { + test::characters_of(text), [&](std::span const> chunks) { decoder.reset(); auto const streamed = test::stream_whole(decoder, chunks, 3); BOOST_TEST(!streamed.has_value() && streamed.error() == expected_error); @@ -759,10 +743,10 @@ void over_streams_through_a_pipe() { assignment. */ void a_moved_from_transformer_restarts() { - std::vector const bytes = random_bytes(31); + std::vector const bytes = test::random_bytes(31); std::string const text = codecs::encode(test::letters, bytes).value(); std::array const, 1> const byte_chunks{bytes_of(bytes)}; - std::array const, 1> const text_chunks{characters_of(text)}; + std::array const, 1> const text_chunks{test::characters_of(text)}; auto source = codecs::encoder(test::letters); BOOST_TEST(source.send(bytes).has_value()); @@ -781,11 +765,13 @@ void a_moved_from_transformer_restarts() { std::string_view(restarted->data(), restarted->size()) == text); auto decoder_source = codecs::decoder(test::letters); - BOOST_TEST(decoder_source.send(characters_of(std::string_view{text}.substr(0, 3))).has_value()); + BOOST_TEST( + decoder_source.send(test::characters_of(std::string_view{text}.substr(0, 3))).has_value()); BOOST_TEST_EQ(receive_until_done(decoder_source, 4), 1U); auto decoder_target = codecs::decoder(test::letters); decoder_target = std::move(decoder_source); - BOOST_TEST(decoder_target.send(characters_of(std::string_view{text}.substr(3))).has_value()); + BOOST_TEST( + decoder_target.send(test::characters_of(std::string_view{text}.substr(3))).has_value()); BOOST_TEST_EQ(receive_until_done(decoder_target, 64), bytes.size() - 1); // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from decoder converts from the start auto const decoded = test::stream_whole(decoder_source, std::span{text_chunks}, 5); @@ -822,7 +808,7 @@ void a_secret_transformer_runs_the_secret_arithmetic() { BOOST_TEST(public_encoder.transform(bytes, text).has_value()); BOOST_TEST_EQ(public_encoder.output_size(bytes), 4U); auto const public_decoder = codecs::decoder(test::tagged_letters); - BOOST_TEST(public_decoder.transform(characters_of("bcklpo"), decoded).error() == + BOOST_TEST(public_decoder.transform(test::characters_of("bcklpo"), decoded).error() == codecs::error::output_too_small); BOOST_TEST_EQ(test::tagged_calls.total(), 0U); @@ -835,11 +821,11 @@ void a_secret_transformer_runs_the_secret_arithmetic() { BOOST_TEST_EQ(test::tagged_calls.encoded_size, 2U); auto const secret_decoder = codecs::decoder(test::tagged_letters, codecs::secret_operation); - BOOST_TEST(secret_decoder.transform(characters_of("bckl"), decoded).has_value()); + BOOST_TEST(secret_decoder.transform(test::characters_of("bckl"), decoded).has_value()); BOOST_TEST(std::ranges::equal(decoded, bytes)); BOOST_TEST_EQ(test::tagged_calls.decode, 1U); BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); - BOOST_TEST_EQ(secret_decoder.output_size(characters_of("bckl")), 2U); + BOOST_TEST_EQ(secret_decoder.output_size(test::characters_of("bckl")), 2U); BOOST_TEST_EQ(test::tagged_calls.decoded_size, 2U); test::tagged_calls.reset(); @@ -858,7 +844,7 @@ void a_secret_transformer_runs_the_secret_arithmetic() { */ void a_holding_decoder_gives_what_it_read() { auto decoder = codecs::decoder(test::holding_letters, codecs::capacity<8>); - std::array const, 1> const chunks{characters_of("abcd")}; + std::array const, 1> const chunks{test::characters_of("abcd")}; auto const decoded = test::stream_whole(decoder, std::span{chunks}, 4); BOOST_TEST(decoded.has_value() && (decoded.value() == std::vector{0x01, 0x23})); BOOST_TEST(decoder.label() == "HOLDING"); diff --git a/test/hex_stream_test.cpp b/test/hex_stream_test.cpp index 3e5f276..d99cdcd 100644 --- a/test/hex_stream_test.cpp +++ b/test/hex_stream_test.cpp @@ -19,6 +19,8 @@ #include "support/counting.hpp" #include "support/chunkings.hpp" +#include "support/letter_cases.hpp" +#include "support/samples.hpp" #include #include @@ -32,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -90,44 +91,6 @@ static_assert(!std::is_copy_constructible_v); static_assert(!std::is_copy_constructible_v); static_assert(std::is_copy_constructible_v); -/** `size` bytes from a generator of a fixed seed. */ -std::vector random_bytes(std::size_t size) { - // A fixed seed, so that every lane and every run sees the same bytes. - // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) - std::mt19937_64 generator{20261126}; - std::uniform_int_distribution byte_value{0, 255}; - std::vector bytes(size); - for (std::uint8_t& byte : bytes) { - byte = static_cast(byte_value(generator)); - } - return bytes; -} - -/** The characters of `text` as the span a decoder reads. */ -std::span characters_of(std::string_view text) { - return {text.data(), text.size()}; -} - -/** The bytes of `characters` as the span an encoder reads. */ -std::span bytes_of(std::string_view characters) { - // A char is read through an unsigned char, which may alias any object. - return {reinterpret_cast(characters.data()), characters.size()}; -} - -/** `text` with every other letter's case changed: mixed case. */ -std::string mixed_case(std::string_view text) { - std::string mixed{text}; - for (std::size_t index = 0; index < mixed.size(); index += 2) { - char const character = mixed[index]; - if (character >= 'a' && character <= 'f') { - mixed[index] = static_cast(character - 'a' + 'A'); - } else if (character >= 'A' && character <= 'F') { - mixed[index] = static_cast(character - 'A' + 'a'); - } - } - return mixed; -} - /** The encoders, in either case, and the decoder of the lower, upper and mixed-case texts, public and secret, over every chunking of `bytes`, equal the one-shot forms. @@ -136,33 +99,33 @@ void expect_every_chunking_of(std::span bytes) { std::string const lower = codecs::encode(formats::hex, bytes).value(); std::string const upper = codecs::encode(formats::hex(formats::letter_case::upper), bytes).value(); - std::string const mixed = mixed_case(upper); + std::string const mixed = test::mixed_case(upper); auto lower_encoder = codecs::encoder(formats::hex); auto upper_encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); auto decoder = codecs::decoder(formats::hex); test::expect_every_chunking(lower_encoder, bytes, lower); test::expect_every_chunking(upper_encoder, bytes, upper); - test::expect_every_chunking(decoder, characters_of(lower), bytes); - test::expect_every_chunking(decoder, characters_of(upper), bytes); - test::expect_every_chunking(decoder, characters_of(mixed), bytes); + test::expect_every_chunking(decoder, test::characters_of(lower), bytes); + test::expect_every_chunking(decoder, test::characters_of(upper), bytes); + test::expect_every_chunking(decoder, test::characters_of(mixed), bytes); auto secret_encoder = codecs::encoder(formats::hex, codecs::secret_operation); auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); test::expect_every_chunking(secret_encoder, bytes, lower); - test::expect_every_chunking(secret_decoder, characters_of(mixed), bytes); + test::expect_every_chunking(secret_decoder, test::characters_of(mixed), bytes); } /** RFC 4648 section 10's inputs and random bytes of 0 to 1000 bytes, over every chunking. */ void every_chunking_equals_the_one_shot_form() { for (std::string_view const input : {"", "f", "fo", "foo", "foob", "fooba", "foobar"}) { - expect_every_chunking_of(bytes_of(input)); + expect_every_chunking_of(test::bytes_of(input)); } for (std::size_t const size : std::array{0, 1, 31, 32, 33, 1000}) { - std::vector const bytes = random_bytes(size); + std::vector const bytes = test::random_bytes(size); expect_every_chunking_of(bytes); } // RFC 4648's upper-case text through the upper-case encoder, as the RFC writes it. auto upper_encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); - test::expect_every_chunking(upper_encoder, bytes_of("foobar"), + test::expect_every_chunking(upper_encoder, test::bytes_of("foobar"), std::string_view{"666F6F626172"}); } @@ -174,12 +137,12 @@ void expect_the_one_shot_verdict(std::string_view text) { auto const one_shot = codecs::decode(formats::hex, text); auto decoder = codecs::decoder(formats::hex); if (one_shot.has_value()) { - test::expect_every_chunking(decoder, characters_of(text), one_shot.value()); + test::expect_every_chunking(decoder, test::characters_of(text), one_shot.value()); return; } auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); test::for_each_chunking( - characters_of(text), [&](std::span const> chunks) { + test::characters_of(text), [&](std::span const> chunks) { for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { decoder.reset(); BOOST_TEST(test::error_after_flush(decoder, chunks, span_size) == one_shot.error()); @@ -255,7 +218,7 @@ bool is_step(codecs::result const& actual, std::size_t count, code received until needs_input. */ void send_while_output_is_pending() { - std::vector const bytes = random_bytes(68); + std::vector const bytes = test::random_bytes(68); auto encoder = codecs::encoder(formats::hex); BOOST_TEST(is_step(encoder.send(std::span{bytes}.first(64)), 64, codecs::flow::output_pending)); BOOST_TEST( @@ -268,8 +231,8 @@ void send_while_output_is_pending() { BOOST_TEST(is_step(encoder.send({}), 0, codecs::flow::needs_input)); // A lone digit is absorbed into the decoder's state, which frees the input at once. auto decoder = codecs::decoder(formats::hex); - BOOST_TEST(is_step(decoder.send(characters_of("a")), 1, codecs::flow::needs_input)); - BOOST_TEST(is_step(decoder.send(characters_of("bcd")), 3, codecs::flow::output_pending)); + BOOST_TEST(is_step(decoder.send(test::characters_of("a")), 1, codecs::flow::needs_input)); + BOOST_TEST(is_step(decoder.send(test::characters_of("bcd")), 3, codecs::flow::output_pending)); std::array decoded{}; BOOST_TEST(is_step(decoder.receive(decoded), 2, codecs::flow::needs_input)); BOOST_TEST((decoded == std::array{0xab, 0xcd})); @@ -305,7 +268,7 @@ bool failed_with(Result const& actual, codecs::error expected) { */ void after_an_error() { auto decoder = codecs::decoder(formats::hex); - BOOST_TEST(decoder.send(characters_of("0g12")).has_value()); + BOOST_TEST(decoder.send(test::characters_of("0g12")).has_value()); std::array decoded{}; BOOST_TEST(is_step(decoder.receive(decoded), 2, codecs::flow::needs_input)); BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_character)); @@ -313,16 +276,18 @@ void after_an_error() { BOOST_TEST(failed_with(decoder.receive(decoded), codecs::error::invalid_character)); BOOST_TEST(failed_with(decoder.receive(decoded), codecs::error::invalid_character)); BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); - BOOST_TEST(failed_with(decoder.send(characters_of("12")), codecs::error::invalid_character)); + BOOST_TEST( + failed_with(decoder.send(test::characters_of("12")), codecs::error::invalid_character)); BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_character)); decoder.reset(); - BOOST_TEST(is_step(decoder.send(characters_of("C0fFeE")), 6, codecs::flow::output_pending)); + BOOST_TEST( + is_step(decoder.send(test::characters_of("C0fFeE")), 6, codecs::flow::output_pending)); BOOST_TEST(decoder.flush().has_value()); BOOST_TEST(is_step(decoder.receive(decoded), 3, codecs::flow::finished)); BOOST_TEST(decoded[0] == 0xc0 && decoded[1] == 0xff && decoded[2] == 0xee); decoder.reset(); - BOOST_TEST(decoder.send(characters_of("abc")).has_value()); + BOOST_TEST(decoder.send(test::characters_of("abc")).has_value()); BOOST_TEST(is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); BOOST_TEST(failed_with(decoder.flush(), codecs::error::invalid_length)); } @@ -356,7 +321,7 @@ void empty_input() { */ template void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { - std::vector const bytes = random_bytes(31); + std::vector const bytes = test::random_bytes(31); std::string const text = codecs::encode(formats::hex, bytes).value(); BOOST_TEST(encoder.send(bytes).has_value()); std::array one_character{}; @@ -371,32 +336,20 @@ void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decode auto const again = test::stream_whole(encoder, whole, 7); BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); - BOOST_TEST(decoder.send(characters_of(text).first(3)).has_value()); + BOOST_TEST(decoder.send(test::characters_of(text).first(3)).has_value()); std::array one_byte{}; BOOST_TEST(is_step(decoder.receive(one_byte), 1, codecs::flow::needs_input)); Decoder moved_decoder{std::move(decoder)}; - std::vector> const tail{characters_of(text).subspan(3)}; + std::vector> const tail{test::characters_of(text).subspan(3)}; auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); BOOST_TEST(decoded_rest.has_value() && one_byte[0] == bytes[0] && std::ranges::equal(*decoded_rest, std::span{bytes}.subspan(1))); - std::vector> const whole_text{characters_of(text)}; + std::vector> const whole_text{test::characters_of(text)}; // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 auto const decoded_again = test::stream_whole(decoder, whole_text, 3); BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); } -/** Runs `body` and checks that the counting operator new saw nothing of it. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const before = test::allocations(); - body(); - std::size_t const allocated = test::allocations() - before; - if (allocated != 0) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(allocated, 0U); -} - /** The spec's "A file in base64 with no heap", on hex: a file of 64 KiB is read in 4096-byte chunks into one buffer, each sent to encoder(hex) and drained into a fixed span before the next chunk is @@ -404,12 +357,12 @@ void expect_no_allocation(char const* what, Body body) { no allocation counted. */ void a_file_with_no_heap() { - std::vector const file = random_bytes(std::size_t{64} * 1024); + std::vector const file = test::random_bytes(std::size_t{64} * 1024); std::string const expected = codecs::encode(formats::hex, file).value(); std::string text(expected.size(), ' '); // the output, made before the window std::vector decoded(file.size()); bool volatile verdict = false; - expect_no_allocation("a file through encoder(hex) and decoder(hex)", [&] { + test::expect_no_allocation("a file through encoder(hex) and decoder(hex)", [&] { std::array chunk{}; std::array fixed_span{}; std::size_t written = 0; @@ -508,7 +461,7 @@ void a_secret_streams_carries_are_wiped() { std::optional decoder; decoder.emplace(formats::hex); - BOOST_TEST(decoder->send(characters_of("abc")).has_value()); + BOOST_TEST(decoder->send(test::characters_of("abc")).has_value()); std::array one_byte{}; BOOST_TEST(is_step(decoder->receive(one_byte), 1, codecs::flow::needs_input)); test::clear_wipes(); @@ -527,7 +480,7 @@ void a_secret_streams_carries_are_wiped() { BOOST_TEST(public_encoder.receive(one_character).has_value()); public_encoder.reset(); stream_decoder public_decoder{formats::hex}; - BOOST_TEST(public_decoder.send(characters_of("abc")).has_value()); + BOOST_TEST(public_decoder.send(test::characters_of("abc")).has_value()); public_decoder.reset(); } BOOST_TEST_EQ(test::wipes.count, 0U); diff --git a/test/hex_test.cpp b/test/hex_test.cpp index 943e0da..6efdcb9 100644 --- a/test/hex_test.cpp +++ b/test/hex_test.cpp @@ -18,6 +18,8 @@ #include "support/counting.hpp" #include "support/arena.hpp" +#include "support/letter_cases.hpp" +#include "support/samples.hpp" #include #include @@ -135,37 +137,6 @@ std::string reference_hex(std::span input, formats::letter_c return text; } -/** The bytes of a text read as bytes. */ -std::span bytes_of(std::string_view characters) { - // A char is read through an unsigned char, which may alias any object. - return {reinterpret_cast(characters.data()), characters.size()}; -} - -/** `text` with every other letter's case changed: mixed case. */ -std::string mixed_case(std::string_view text) { - std::string mixed{text}; - for (std::size_t index = 0; index < mixed.size(); index += 2) { - char const character = mixed[index]; - if (character >= 'a' && character <= 'f') { - mixed[index] = static_cast(character - 'a' + 'A'); - } else if (character >= 'A' && character <= 'F') { - mixed[index] = static_cast(character - 'A' + 'a'); - } - } - return mixed; -} - -/** `text` in lower case. */ -std::string lower_case(std::string_view text) { - std::string lowered{text}; - for (char& character : lowered) { - if (character >= 'A' && character <= 'F') { - character = static_cast(character - 'A' + 'a'); - } - } - return lowered; -} - /** A vector of RFC 4648 section 10: the input and its base16, in upper case. */ struct base16_vector { /** The input. */ @@ -188,7 +159,7 @@ constexpr std::array rfc4648_base16{ /** Whether `decoded` holds the bytes of `expected`. */ bool decodes_to(codecs::result> const& decoded, std::string_view expected) { - return decoded.has_value() && std::ranges::equal(decoded.value(), bytes_of(expected)); + return decoded.has_value() && std::ranges::equal(decoded.value(), test::bytes_of(expected)); } /** @@ -199,7 +170,7 @@ void rfc4648_base16_vectors() { for (base16_vector const& vector : rfc4648_base16) { auto const upper = codecs::encode(formats::hex(formats::letter_case::upper), vector.input); BOOST_TEST(upper.has_value() && upper.value() == vector.upper); - std::string const lower = lower_case(vector.upper); + std::string const lower = test::lower_case(vector.upper); auto const defaulted = codecs::encode(formats::hex, vector.input); BOOST_TEST(defaulted.has_value() && defaulted.value() == lower); auto const chosen_lower = @@ -208,7 +179,7 @@ void rfc4648_base16_vectors() { BOOST_TEST(decodes_to(codecs::decode(formats::hex, vector.upper), vector.input)); BOOST_TEST(decodes_to(codecs::decode(formats::hex, lower), vector.input)); BOOST_TEST( - decodes_to(codecs::decode(formats::hex, mixed_case(vector.upper)), vector.input)); + decodes_to(codecs::decode(formats::hex, test::mixed_case(vector.upper)), vector.input)); // The case of the format is what it writes: either decodes any case. BOOST_TEST(decodes_to(codecs::decode(formats::hex(formats::letter_case::upper), lower), vector.input)); @@ -222,18 +193,9 @@ void rfc4648_base16_vectors() { "\x01\x23\x45\x67\x89\xab\xcd\xef\xab\xcd\xef")); } -/** 32 bytes, 0x00 to 0xf8 by steps of 8, then turned so that every digit appears. */ -std::array digest_bytes() { - std::array digest{}; - for (std::size_t index = 0; index < digest.size(); ++index) { - digest[index] = static_cast((index * 8U) ^ (index >> 1U)); - } - return digest; -} - /** The spec's "A short buffer": 32 bytes in 63 characters are refused, the buffer unchanged. */ void a_short_buffer() { - std::array const digest = digest_bytes(); + std::array const digest = test::digest_bytes(); std::array buffer{}; buffer.fill('x'); auto const refused = codecs::encode(formats::hex, digest, std::span{buffer}.first(63)); @@ -259,26 +221,14 @@ void a_short_buffer() { BOOST_TEST(std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0x5a; })); } -/** Runs `body` and checks that the counting operator new saw nothing of it. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const before = test::allocations(); - body(); - std::size_t const allocated = test::allocations() - before; - if (allocated != 0) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(allocated, 0U); -} - /** The spec's "A digest's hex with no heap": a std::array of 32 bytes encodes to text<64> and decodes back to bytes<32>, equal to the digest, with nothing allocated; upper case likewise. */ void a_digests_hex_with_no_heap() { - std::array const digest = digest_bytes(); + std::array const digest = test::digest_bytes(); bool volatile verdict = false; - expect_no_allocation("a digest's hex", [&] { + test::expect_no_allocation("a digest's hex", [&] { codecs::result> const encoded = codecs::encode(formats::hex, digest); codecs::result> const decoded = codecs::decode(formats::hex, encoded.value()); @@ -301,11 +251,11 @@ void a_digests_hex_with_no_heap() { invalid_length; with nothing allocated. */ void a_key_from_hex_into_a_fixed_array() { - std::array const digest = digest_bytes(); + std::array const digest = test::digest_bytes(); std::string const text = reference_hex(digest, formats::letter_case::lower); std::string_view const short_text = std::string_view{text}.substr(0, 62); bool volatile verdict = false; - expect_no_allocation("decode>", [&] { + test::expect_no_allocation("decode>", [&] { auto const key = codecs::decode>(formats::hex, text); auto const short_key = codecs::decode>(formats::hex, short_text); @@ -321,12 +271,12 @@ void a_key_from_hex_into_a_fixed_array() { every allocation and the global operator new counts none. */ void a_pmr_string_token() { - std::array const digest = digest_bytes(); + std::array const digest = test::digest_bytes(); std::string const expected = reference_hex(digest, formats::letter_case::lower); test::recording_resource arena; std::pmr::string appended{&arena}; std::optional> returned; - expect_no_allocation("hex into pmr string tokens", [&] { + test::expect_no_allocation("hex into pmr string tokens", [&] { auto const appended_result = codecs::encode(formats::hex, digest, tokens::append_to(appended)); BOOST_TEST(appended_result.has_value()); @@ -473,7 +423,7 @@ void decoding_in_place() { /** Review Focus 3, the encodes: empty input in every form gives an empty result: the default results - in place and on the heap, the buffer form (0 written), the tokens and the size. + in place and on the heap, the buffer form (0 written), the tokens, the secret tag and the size. */ void empty_input_in_every_encode() { std::array const nothing{}; @@ -492,6 +442,8 @@ void empty_input_in_every_encode() { std::string kept{"kept"}; BOOST_TEST(codecs::encode(formats::hex, nothing, tokens::append_to(kept)).has_value()); BOOST_TEST(kept == "kept"); + auto const secret_empty = codecs::encode(formats::hex, nothing, tokens::secret); + BOOST_TEST(secret_empty.has_value() && secret_empty.value().size() == 0); BOOST_TEST_EQ(codecs::encoded_size(formats::hex, std::vector{}), 0U); } diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp index e8c635c..f9c27fc 100644 --- a/test/secret_operation_test.cpp +++ b/test/secret_operation_test.cpp @@ -981,28 +981,13 @@ void the_secret_arithmetic_runs_in_a_secret_operation_alone() { BOOST_TEST(plain_encoded.value().view() == text_value); } -/** Runs `body` and checks that the counting operator new saw nothing of it. */ -template -void expect_no_allocation(char const* what, Body body) { - std::size_t const new_before = test::counted_new.load(); - std::size_t const c_before = test::counted_c.load(); - body(); - std::size_t const new_after = test::counted_new.load(); - std::size_t const c_after = test::counted_c.load(); - if (new_after != new_before || c_after != c_before) { - std::printf("allocated: %s\n", what); - } - BOOST_TEST_EQ(new_after - new_before, 0U); - BOOST_TEST_EQ(c_after - c_before, 0U); -} - void the_fixed_secret_forms_allocate_nothing() { key32 const key = make_key32(); secure::secret<32> const secret_key = make_secret(); std::array const public_bytes = key_bytes(); auto const fixed_text = codecs::encode(test::letters, public_bytes); bool volatile verdict = false; - expect_no_allocation("the fixed secret forms", [&] { + test::expect_no_allocation("the fixed secret forms", [&] { auto const from_key = codecs::encode(test::letters, key); auto const from_secret = codecs::encode(test::letters, secret_key); auto const through_token = codecs::encode(test::letters, public_bytes, tokens::secret); @@ -1049,7 +1034,7 @@ void the_spec_scenarios_on_hex() { std::is_same_v>(formats::hex, expected)), codecs::result>>); bool volatile verdict = false; - expect_no_allocation("hex of secure's secret and back", [&] { + test::expect_no_allocation("hex of secure's secret and back", [&] { auto const encoded = codecs::encode(formats::hex, secret_key); test::clear_wipes(); auto const decoded = @@ -1063,7 +1048,7 @@ void the_spec_scenarios_on_hex() { BOOST_TEST(verdict); verdict = false; - expect_no_allocation("decode> of hex", [&] { + test::expect_no_allocation("decode> of hex", [&] { test::clear_wipes(); auto const decoded = codecs::decode>(formats::hex, expected); verdict = decoded.has_value() && std::ranges::equal(decoded.value().view(), key_bytes()) && diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp index e63866d..853adf9 100644 --- a/test/secret_stream_test.cpp +++ b/test/secret_stream_test.cpp @@ -25,6 +25,7 @@ #include "support/allocators.hpp" #include "support/letters.hpp" +#include "support/samples.hpp" #include #include @@ -399,11 +400,6 @@ std::vector bytes_of(Stream& stream, std::span return output; } -/** The characters of `text`, as a decoder reads them. */ -std::span characters_of(std::string_view text) { - return {text.data(), text.size()}; -} - /** The wipes of `size` bytes, every byte zero when reported, whose first byte is inside the `object_size` bytes at `object`: an object's own storage, alive or destroyed. @@ -509,13 +505,14 @@ void every_call_of_a_secret_format_transformer_is_guarded() { BOOST_TEST_EQ(guarded([&] { return encoder.output_size(input); }), 62U); auto decoder = codecs::decoder(test::letters, codecs::secret_operation); std::vector decoded; - BOOST_TEST(stream_guarded(decoder, characters_of(text), 7, decoded)); + BOOST_TEST(stream_guarded(decoder, test::characters_of(text), 7, decoded)); BOOST_TEST(std::ranges::equal(decoded, input)); guarded([&] { decoder.reset(); }); std::array byte_buffer{}; - BOOST_TEST( - guarded([&] { return decoder.transform(characters_of(text), byte_buffer); }).has_value()); - BOOST_TEST_EQ(guarded([&] { return decoder.output_size(characters_of(text)); }), 31U); + BOOST_TEST(guarded([&] { + return decoder.transform(test::characters_of(text), byte_buffer); + }).has_value()); + BOOST_TEST_EQ(guarded([&] { return decoder.output_size(test::characters_of(text)); }), 31U); // A public transformer enters no guard. std::size_t const before = test::timing_all_entries; @@ -640,7 +637,7 @@ void a_secret_decoders_pending_state_is_wiped() { std::optional source; source.emplace(test::letters); // Three letters: a byte of the first two, the third held. - BOOST_TEST(source->send(characters_of(text).first(3)).has_value()); + BOOST_TEST(source->send(test::characters_of(text).first(3)).has_value()); std::array byte{}; auto const first = source->receive(byte); BOOST_TEST(first.has_value() && first->count == 1 && first->flow == codecs::flow::needs_input); @@ -651,11 +648,11 @@ void a_secret_decoders_pending_state_is_wiped() { target.emplace(std::move(*source)); BOOST_TEST_EQ(wipes_in(*source, 1), 2U); std::vector rest{input[0]}; - BOOST_TEST(stream_guarded(*target, characters_of(text).subspan(3), 1, rest)); + BOOST_TEST(stream_guarded(*target, test::characters_of(text).subspan(3), 1, rest)); BOOST_TEST(rest == expected); std::vector again; - BOOST_TEST(stream_guarded(*source, characters_of(text), 1, again)); + BOOST_TEST(stream_guarded(*source, test::characters_of(text), 1, again)); BOOST_TEST(again == expected); test::clear_wipes(); diff --git a/test/support/counting.hpp b/test/support/counting.hpp index 6dfa2be..080b6fd 100644 --- a/test/support/counting.hpp +++ b/test/support/counting.hpp @@ -38,10 +38,12 @@ #include #include #include +#include #include #include #include +#include #ifdef __APPLE__ #include @@ -63,6 +65,18 @@ inline std::size_t allocations() { return counted_new.load() + counted_c.load(); } +/** Runs `body` and checks that it allocated nothing, through operator new or the C library. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const before = allocations(); + body(); + std::size_t const allocated = allocations() - before; + if (allocated != 0) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(allocated, 0U); +} + /** Whether this target counts the C library's allocations too. */ inline constexpr bool c_allocations_counted = #if defined(__GLIBC__) || defined(__EMSCRIPTEN__) || defined(__APPLE__) diff --git a/test/support/letter_cases.hpp b/test/support/letter_cases.hpp new file mode 100644 index 0000000..bbcc48d --- /dev/null +++ b/test/support/letter_cases.hpp @@ -0,0 +1,47 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The case changes the tests of a case-insensitive format (hex, base32's lower case, bech32's +// all-lower or all-upper) make of a text, once for all of them. The letters changed are `a` to `f` +// and `A` to `F`, the digits of hex; other characters stay. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_LETTER_CASES_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_LETTER_CASES_HPP + +#include +#include +#include + +namespace webcpp::codecs::test { + +/** `text` with every other letter's case changed: mixed case. */ +inline std::string mixed_case(std::string_view text) { + std::string mixed{text}; + for (std::size_t index = 0; index < mixed.size(); index += 2) { + char const character = mixed[index]; + if (character >= 'a' && character <= 'f') { + mixed[index] = static_cast(character - 'a' + 'A'); + } else if (character >= 'A' && character <= 'F') { + mixed[index] = static_cast(character - 'A' + 'a'); + } + } + return mixed; +} + +/** `text` in lower case. */ +inline std::string lower_case(std::string_view text) { + std::string lowered{text}; + for (char& character : lowered) { + if (character >= 'A' && character <= 'F') { + character = static_cast(character - 'A' + 'a'); + } + } + return lowered; +} + +} // namespace webcpp::codecs::test + +#endif diff --git a/test/support/samples.hpp b/test/support/samples.hpp new file mode 100644 index 0000000..0918583 --- /dev/null +++ b/test/support/samples.hpp @@ -0,0 +1,60 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The inputs every format's tests build the same way, once for all of them: random_bytes, bytes +// drawn from std::mt19937_64{20261126}, the seed of chunkings.hpp, so that every lane and every +// run sees the same; digest_bytes, 32 bytes in which every nibble appears; bytes_of and +// characters_of, a text read as the span an encoder reads and as the span a decoder reads. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_SAMPLES_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_SAMPLES_HPP + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** `size` bytes from a generator of a fixed seed. */ +inline std::vector random_bytes(std::size_t size) { + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::uniform_int_distribution byte_value{0, 255}; + std::vector bytes(size); + for (std::uint8_t& byte : bytes) { + byte = static_cast(byte_value(generator)); + } + return bytes; +} + +/** 32 bytes, 0x00 to 0xf8 by steps of 8, then turned so that every digit appears. */ +inline std::array digest_bytes() { + std::array digest{}; + for (std::size_t index = 0; index < digest.size(); ++index) { + digest[index] = static_cast((index * 8U) ^ (index >> 1U)); + } + return digest; +} + +/** The characters of `text` as the span a decoder reads. */ +inline std::span characters_of(std::string_view text) { + return {text.data(), text.size()}; +} + +/** The bytes of `characters` as the span an encoder reads. */ +inline std::span bytes_of(std::string_view characters) { + // A char is read through an unsigned char, which may alias any object. + return {reinterpret_cast(characters.data()), characters.size()}; +} + +} // namespace webcpp::codecs::test + +#endif From 4b86c97beb253538649ecd46ae91ba2573586f1c Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 22:40:05 -0300 Subject: [PATCH 082/157] codecs: the tests' random bytes and chunk sizes drawn from the engine alone, through no distribution, so that every standard library sees the same --- test/allocation_test.cpp | 6 ++++-- test/support/chunkings.hpp | 13 +++++++------ test/support/samples.hpp | 16 +++++++++------- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 792b579..f9ace3e 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -981,7 +981,6 @@ void check_hex_streams() { test::expect_no_allocation( "1 MiB through pipe(encoder(hex), decoder(hex)) in random chunks", [&] { auto piped = codecs::pipe(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); - std::uniform_int_distribution chunk_size{0, 3000}; std::size_t compared = 0; bool same = true; auto const sink = [&](std::span piece) noexcept { @@ -992,7 +991,10 @@ void check_hex_streams() { bool streamed = true; std::array fixed_span{}; for (std::size_t position = 0; position < input.size() && streamed;) { - std::size_t const size = std::min(chunk_size(generator), input.size() - position); + // The engine's output modulo the sizes, through no distribution, whose output is + // each standard library's own. + auto const drawn = static_cast(generator() % 3001U); + std::size_t const size = std::min(drawn, input.size() - position); auto const sent = piped.send(std::span{input}.subspan(position, size)); streamed = sent.has_value() && codecs::drain(piped, sink, std::span{fixed_span}).has_value(); diff --git a/test/support/chunkings.hpp b/test/support/chunkings.hpp index 3563734..acb1e6f 100644 --- a/test/support/chunkings.hpp +++ b/test/support/chunkings.hpp @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -105,18 +106,18 @@ void for_each_chunking(std::span input, Callback callback) { } call_back(); - // A fixed seed, so that every lane and every run sees the same chunkings. + // A fixed seed, so that every lane and every run sees the same chunkings: std::mt19937_64's + // output is fixed by the standard, a distribution's is each standard library's own, so a + // chunk's size is the engine's output modulo the sizes, through no distribution. // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) std::mt19937_64 generator{20261126}; - std::uniform_int_distribution chunk_size{ - 0, - std::max(4, input.size() / 8), - }; + std::uint64_t const chunk_sizes = std::max(4, input.size() / 8) + 1; for (int chunking = 0; chunking < 32; ++chunking) { chunks.clear(); std::size_t position = 0; while (position < input.size()) { - std::size_t const size = std::min(chunk_size(generator), input.size() - position); + auto const drawn = static_cast(generator() % chunk_sizes); + std::size_t const size = std::min(drawn, input.size() - position); chunks.push_back(input.subspan(position, size)); position += size; } diff --git a/test/support/samples.hpp b/test/support/samples.hpp index 0918583..ae9acbe 100644 --- a/test/support/samples.hpp +++ b/test/support/samples.hpp @@ -4,10 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The inputs every format's tests build the same way, once for all of them: random_bytes, bytes -// drawn from std::mt19937_64{20261126}, the seed of chunkings.hpp, so that every lane and every -// run sees the same; digest_bytes, 32 bytes in which every nibble appears; bytes_of and -// characters_of, a text read as the span an encoder reads and as the span a decoder reads. +// The inputs every format's tests build the same way, once for all of them: random_bytes, the low +// bytes of std::mt19937_64{20261126}'s outputs, the seed of chunkings.hpp, through no distribution, +// so that every lane and every run sees the same; digest_bytes, 32 bytes in which every nibble +// appears; bytes_of and characters_of, a text read as the span an encoder reads and as the span a +// decoder reads. #ifndef WEBCPP_CODECS_TEST_SUPPORT_SAMPLES_HPP #define WEBCPP_CODECS_TEST_SUPPORT_SAMPLES_HPP @@ -24,13 +25,14 @@ namespace webcpp::codecs::test { /** `size` bytes from a generator of a fixed seed. */ inline std::vector random_bytes(std::size_t size) { - // A fixed seed, so that every lane and every run sees the same bytes. + // A fixed seed, so that every lane and every run sees the same bytes: std::mt19937_64's output + // is fixed by the standard, a distribution's is each standard library's own, so each byte is + // the low byte of the engine's output, through no distribution. // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) std::mt19937_64 generator{20261126}; - std::uniform_int_distribution byte_value{0, 255}; std::vector bytes(size); for (std::uint8_t& byte : bytes) { - byte = static_cast(byte_value(generator)); + byte = static_cast(generator()); } return bytes; } From 92c157664b47aa3e61b722028d9c707e0ec76abf Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 22:52:09 -0300 Subject: [PATCH 083/157] codecs: the constant-time lane, memcheck, MemorySanitizer and dudect over hex, with a planted leak that must fail --- test/Jamfile | 4 + test/constant_time/Jamfile | 108 +++ test/constant_time/ctgrind_planted_test.cpp | 11 + test/constant_time/ctgrind_test.cpp | 25 + test/constant_time/dudect.hpp | 706 ++++++++++++++++++++ test/constant_time/dudect_harness_test.cpp | 234 +++++++ test/constant_time/dudect_judge.py | 149 +++++ test/constant_time/dudect_planted_test.cpp | 90 +++ test/constant_time/dudect_test.cpp | 151 +++++ test/constant_time/msan_planted_test.cpp | 11 + test/constant_time/msan_report.mjs | 51 ++ test/constant_time/msan_test.cpp | 28 + test/constant_time/package-lock.json | 10 + test/constant_time/package.json | 1 + test/constant_time/paths.hpp | 359 ++++++++++ test/constant_time/valgrind.mjs | 40 ++ test/support/constant_time_marks.hpp | 142 ++++ 17 files changed, 2120 insertions(+) create mode 100644 test/constant_time/Jamfile create mode 100644 test/constant_time/ctgrind_planted_test.cpp create mode 100644 test/constant_time/ctgrind_test.cpp create mode 100644 test/constant_time/dudect.hpp create mode 100644 test/constant_time/dudect_harness_test.cpp create mode 100755 test/constant_time/dudect_judge.py create mode 100644 test/constant_time/dudect_planted_test.cpp create mode 100644 test/constant_time/dudect_test.cpp create mode 100644 test/constant_time/msan_planted_test.cpp create mode 100644 test/constant_time/msan_report.mjs create mode 100644 test/constant_time/msan_test.cpp create mode 100644 test/constant_time/package-lock.json create mode 100644 test/constant_time/package.json create mode 100644 test/constant_time/paths.hpp create mode 100644 test/constant_time/valgrind.mjs create mode 100644 test/support/constant_time_marks.hpp diff --git a/test/Jamfile b/test/Jamfile index ce6aa5e..ddda12c 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -144,3 +144,7 @@ codecs-compile noexcept : noexcept_test.cpp ; # The refusals and a forgotten format header stop the build with their messages. build-project messages ; + +# The own lane constant-time: memcheck, MemorySanitizer and dudect over every +# constant-time format, with planted leaks that must fail. +build-project constant_time ; diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile new file mode 100644 index 0000000..21c9d95 --- /dev/null +++ b/test/constant_time/Jamfile @@ -0,0 +1,108 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Constant time: Valgrind's memcheck and MemorySanitizer on Linux, and dudect's +# statistics natively, as the own lane constant-time, outside the ordinary +# lanes; secure's test/constant_time/Jamfile at 951401a, with codecs' names, is +# the model (pre-flight F27). Both checkers run the same paths, paths.hpp: +# every format's encode and decode, one-shot, in the buffer form, to a secret +# result and streamed in fixed chunks through encoder(format, secret_operation) +# and decoder(format, secret_operation), their input marked secret (each +# format's task adds its block; hex's first). Each checker is shown to fail on +# a planted leak in a function of its own that the report must name, a hex +# encode that indexes its digits by each nibble (planted_hex); dudect to find +# one, a hex validation that exits at the first character that is no hex +# digit (dudect_planted). WEBCPP_SECURE_CT_VALGRIND and WEBCPP_SECURE_CT_MSAN +# are the checkers' defines, which secure's declassify reads, so that the +# library's own branch on a verdict is not reported. +# +# The lane's programs are native only, each one build of its checker: they are +# not declared through test/Jamfile's codecs-run, and have no _no_exceptions +# twins (this is a project of its own, where that rule is not visible, and a +# checker's build is a release build of one configuration). +project : requirements /webcpp/codecs//codecs ; + +import webcpp os ; + +webcpp.targets native ; + +webcpp.original node ; + +# Valgrind and MemorySanitizer run on Linux alone: elsewhere their programs +# are not built, and the lane runs dudect alone. +rule linux-only ( properties * ) +{ + if ! linux in $(properties) + { + return no ; + } +} + +# MemorySanitizer is clang's alone: its programs are built with clang on +# Linux, and not with GCC (-fsanitize=memory is no option of GCC's). +rule clang-on-linux ( properties * ) +{ + if ! linux in $(properties) || ! clang in $(properties) + { + return no ; + } +} + +CTGRIND = release on @linux-only + WEBCPP_SECURE_CT_VALGRIND 300 ; + +webcpp.drive ctgrind : ctgrind_test.cpp : $(CTGRIND) : valgrind.mjs : : native ; +# The formats compile in the user's translation unit, so they are checked at +# both optimisations: ctgrind is release, which is +# speed in b2, and ctgrind_space the other, a program of its +# own, where an optimiser may if-convert a mask differently. +webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space + : valgrind.mjs : : native ; +# The planted leak, run before every path: memcheck must report it in its own +# function (valgrind.mjs --in). The same source, its own define. +webcpp.drive ctgrind_planted_hex : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_CODECS_PLANTED_HEX + : valgrind.mjs : --expect-leak --in planted_hex : native ; + +# MemorySanitizer's checking of what a function is passed and returns, eager +# since clang 16, is off: a value derived from a secret is passed and returned +# by design, and only a branch or an index on one is a leak. +MSAN_FLAGS = -fsanitize=memory -fno-sanitize-memory-param-retval ; +MSAN = WEBCPP_SECURE_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory + release on @clang-on-linux ; + +webcpp.run msan : msan_test.cpp : $(MSAN) : native ; +# The planted leak under MemorySanitizer: it passes only on its report whose +# first frame is the planted function (msan_report.mjs --in). +webcpp.drive msan_planted_hex : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_CODECS_PLANTED_HEX + : msan_report.mjs : --in planted_hex : native ; + +# dudect's statistics on every format's secret operations, each with its A/A +# control, natively: each operation holds secure's guard, which sets DIT in +# each call on arm64 where the CPU has it, and the program fails if DIT is set +# outside the calls, or not set inside a guard (dudect.hpp). On a runner GitHub +# hosts each |t| is printed and the program does not judge it (secure's +# Jamfile says why), and the CI's dudect_judge.py warns at 10 and measures a +# case over 10 again in two fresh processes, failing when two of the three are +# 10 or more. dudect_planted is judged everywhere. +DUDECT = release ; +if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted +{ + DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; +} +# Named dudect_formats, not dudect: the CI's judge reads every dudect_*.output +# (pre-flight F10). +webcpp.run dudect_formats : dudect_test.cpp : $(DUDECT) : native ; +webcpp.run dudect_planted : dudect_planted_test.cpp : release : native ; + +# dudect.hpp itself, on synthetic data and without timing: the statistics, the +# A/A control's preparation, --case and the lines the CI's judge reads. +webcpp.run dudect_harness : dudect_harness_test.cpp : : native ; + +webcpp.lane constant-time : ctgrind ctgrind_space ctgrind_planted_hex msan + msan_planted_hex dudect_formats dudect_planted dudect_harness + : native ; diff --git a/test/constant_time/ctgrind_planted_test.cpp b/test/constant_time/ctgrind_planted_test.cpp new file mode 100644 index 0000000..7b27175 --- /dev/null +++ b/test/constant_time/ctgrind_planted_test.cpp @@ -0,0 +1,11 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ctgrind_test.cpp with a planted leak, a source of its own so that b2 compiles it with its own +// define: the build the lane expects memcheck to fail, in its planted function (paths.hpp), run +// before every path. With WEBCPP_TEST_CODECS_PLANTED_HEX, a hex encode that indexes its digits by +// each secret nibble. +#include "ctgrind_test.cpp" // NOLINT(bugprone-suspicious-include) diff --git a/test/constant_time/ctgrind_test.cpp b/test/constant_time/ctgrind_test.cpp new file mode 100644 index 0000000..42f09ab --- /dev/null +++ b/test/constant_time/ctgrind_test.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Under Valgrind's memcheck, the input of every format's encode and decode, one-shot, in the +// buffer form, to a secret result and streamed in fixed chunks, is marked undefined (paths.hpp, +// shared with msan_test.cpp): a branch or a memory index that depends on it is an error, and the +// run fails (valgrind.mjs's --error-exitcode). memcheck follows a subtraction's carry, so each +// output is also checked to be undefined until it is marked public: the mark reaches it, so the +// path is traced. A planted program (ctgrind_planted_test.cpp) runs its planted leak first, which +// memcheck must report. secure's ctgrind_test.cpp at 951401a is the model (pre-flight F27). + +#include "paths.hpp" + +#include + +int main() { + using checker = webcpp::codecs::test::memcheck; + webcpp::codecs::test::run_planted(); + int const failures = webcpp::codecs::test::format_paths(); + std::printf("constant time under memcheck: %s\n", failures == 0 ? "ok" : "FAILED"); + return failures == 0 ? 0 : 1; +} diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp new file mode 100644 index 0000000..dd0434b --- /dev/null +++ b/test/constant_time/dudect.hpp @@ -0,0 +1,706 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Copied from webcpp::secure's test/constant_time/dudect.hpp at 951401a (pre-flight F27, the +// design's O5: codecs keeps its own constant-time support, as secure does, until webcpp::core holds +// it), with its namespace webcpp::secure::test renamed webcpp::codecs::test and its include guard +// renamed; nothing else differs. Its comments are secure's: "the blocks" and dudect_blocks are +// secure's, whose cases codecs' dudect_formats follows with hex's secret operations, each holding +// its own guard as constant_time_equal does. +// +// Welch's t-test over two classes of timings, with dudect's cropping. Copied from crypto's +// test/constant_time/dudect.hpp, which keeps its own (secure's tests keep their own support): the +// measurements its comments cite were made on crypto's lane, whose cases the reasons were found on. + +#ifndef WEBCPP_TEST_CODECS_DUDECT_HPP +#define WEBCPP_TEST_CODECS_DUDECT_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#include +#endif + +#ifdef __APPLE__ +#include +#endif + +namespace webcpp::codecs::test { + +/** + * Waits until every instruction before it has completed, so that a clock read after it does + * not start while the preparation's last instructions still run: `isb` on 64-bit ARM, `lfence` + * on x86. Without it the clock is read out of order, and what the preparation does by class + * (it copies the fixed input or just-drawn bytes) leaks into the measured time (measured + * natively on an Apple M5, 2026-11-18: |t| 25 to 35 on a ChaCha20-Poly1305 decryption that + * never reads the classes' input, below 2 with the barriers; an early-exit comparison's |t| + * rose from 18 to 42). WebAssembly has no such instruction: there the clock is a host call. + */ +inline void serialise() noexcept { +#ifdef __aarch64__ + __asm__ volatile("isb" ::: "memory"); +#elif defined(__x86_64__) || defined(__i386__) + __asm__ volatile("lfence" ::: "memory"); +#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + _mm_lfence(); +#elif defined(_MSC_VER) && defined(_M_ARM64) + __isb(_ARM64_BARRIER_SY); +#endif +} + +/** + * Prints, in one line, what the program finds of 64-bit ARM's DIT (Data Independent Timing) bit, + * PSTATE.DIT, and whether the measurements may go on. The harness never sets DIT for the + * measurements: `constant_time_equal` sets it in each call through secure's guard + * (`secure::timing_guard`), and the lane measures that, what a program gets; the blocks hold no + * guard, and dudect_blocks measures each inside one, as the guarded functions that call them run + * them. Where the CPU has DIT, the line + * also shows the guard at work, once, before any measurement: DIT set inside a guard's scope and + * clear again after it. It must be clear on this thread outside the calls, or the timings would + * be those of a DIT the program set itself, not the guard's. + * @return false where the CPU has DIT and it is set on this thread outside a guard, or not set + * inside one, so that the program fails rather than measure it; true otherwise: where the CPU has + * DIT and the guard sets and clears it, where the CPU has none, and where the guard does not + * apply (not arm64 under macOS, Linux or Windows: x86 and WebAssembly, where the engine decides). + */ +inline bool report_data_independent_timing() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!secure::cpu_has_dit()) { + std::printf("DIT (data-independent timing): not on this CPU\n"); + return true; + } + bool const set_before = secure::dit_is_set(); + bool set_inside = false; + { + secure::timing_guard const timing_scope; + set_inside = secure::dit_is_set(); + } + bool const set_after = secure::dit_is_set(); + bool const outside_set = set_before || set_after; + std::printf( + "DIT (data-independent timing): the CPU has it; secure's guard sets it in each measured " + "call, the harness does not (%s inside a guard; %s)\n", + set_inside ? "set" : "NOT set", + outside_set ? "set on this thread outside the calls: not measured" + : "clear on this thread outside the calls"); + return set_inside && !outside_set; +#else + std::printf( + "DIT (data-independent timing): not applicable here (not arm64 under macOS, Linux or " + "Windows)\n"); + return true; +#endif +} + +/** Online mean and variance of one class, Welford's. */ +struct moments { + /** The number of values pushed. */ + double n = 0; + /** Their mean. */ + double mean = 0; + /** The sum of squared differences from the mean. */ + double m2 = 0; + + /** + * Adds a value. + * @param x The value. + */ + void push(double x) { + n += 1; + double const delta = x - mean; + mean += delta / n; + m2 += delta * (x - mean); + } + + /** + * The sample variance. + * @return The variance, 0 below two values. + */ + [[nodiscard]] double variance() const { return n > 1 ? m2 / (n - 1) : 0; } +}; + +/** + * Welch's t of two classes. + * @param a The first class. + * @param b The second class. + * @return t, 0 when both variances are 0. + */ +inline double welch(moments const& a, moments const& b) { + double const denominator = std::sqrt((a.variance() / a.n) + (b.variance() / b.n)); + return denominator == 0 ? 0 : (a.mean - b.mean) / denominator; +} + +/** One class's count and mean at a cropping. */ +struct class_summary { + /** The number of its timings kept. */ + std::size_t count; + /** Their mean, in nanoseconds. */ + double mean_ns; +}; + +/** The largest |t| of a set of timings, with what gave it. */ +struct t_statistic { + /** The largest |t| over the whole set and dudect's 100 croppings. */ + double t; + /** The cropping that gave it: -1 for the whole set, else 0 to 99. */ + int crop; + /** The largest timing that cropping kept, in nanoseconds. */ + double limit_ns; + /** Each class's count and mean at that cropping. */ + std::array classes; +}; + +/** + * A |t| as the lines print it, rounded to two decimals: every decision reads this value (the + * evidence's condition, a case's pass, `twice`'s second run, the planted leak's verdict), so that + * a |t| of 9.996 prints 10.00, with its evidence, and fails as 10.00 does, and the CI's judge, + * which reads the printed value, agrees with the program. + * @param t The |t|. + * @return It rounded to two decimals. + */ +inline double printed(double t) { + return std::round(t * 100) / 100; +} + +/** + * The largest |t| over the whole set and dudect's 100 croppings, each of which keeps the timings + * at or below a percentile, with the cropping that gave it and each class's count and mean there. + * A cropping that leaves a class empty has no t and is skipped; of equal values the first, the + * whole set before the croppings, is kept. + * @param timings The measurements, at least one. + * @param classes The class, 0 or 1, of each. + * @return The largest |t| and what gave it. + */ +inline t_statistic largest_t(std::vector const& timings, std::vector const& classes) { + std::vector sorted = timings; + std::ranges::sort(sorted); + t_statistic largest{.t = 0, .crop = -1, .limit_ns = sorted.back(), .classes = {}}; + for (int k = -1; k < 100; ++k) { + double const keep = k < 0 ? 1.0 : 1.0 - std::pow(0.5, 10.0 * (k + 1) / 100.0); + double const limit = + sorted[static_cast(keep * static_cast(sorted.size() - 1))]; + std::array m{}; + for (std::size_t i = 0; i < timings.size(); ++i) { + if (timings[i] <= limit) { + m[static_cast(classes[i])].push(timings[i]); + } + } + double const t = std::fabs(welch(m[0], m[1])); + if (!std::isfinite(t) || (k >= 0 && !(t > largest.t))) { + continue; + } + largest = { + .t = t, + .crop = k, + .limit_ns = limit, + .classes = + { + class_summary{.count = static_cast(m[0].n), .mean_ns = m[0].mean}, + class_summary{.count = static_cast(m[1].n), .mean_ns = m[1].mean}, + }, + }; + } + return largest; +} + +/** + * Draws `Size` bytes, then writes into `input` either `fixed`, for class 0, or the drawn bytes, + * for class 1, so that the two classes differ in the bytes written and in nothing else. Both + * classes draw the same bytes, read both `fixed` and the drawn bytes, and write `input` with the + * same instructions: each byte is blended through a mask read from a volatile, which the + * compiler cannot see through, so that it can neither split the work by class nor read one + * source alone. Whatever a class does differently before the measured call leaks the class into + * it. A copy from a volatile pointer to the chosen source (until 2026-11-20) read the fixed + * input for class 0 and the bytes just drawn, still in the store buffer, for class 1: on the + * CI's x86-64 runners the measured call then differed by class whatever it computed (measured + * on GitHub's ubuntu-24.04 runners, 2026-11-20: equal at |t| 31 to 56 on an Intel Xeon 6975P-C + * and ChaCha20-Poly1305's seal at 28 to 85 on AMD EPYC 9V45 and 9V74; through this blend, on + * the Xeon, the EPYC 9V74 and an AMD EPYC 7763, idle and with every processor busy, every case + * of 23 runs of 24 stayed below 4.4, the 24th is in `judged`). Before it, + * a choice the optimiser made of `which == 0 ? 0 : drawn` split the copy into a store of + * constants and a store of drawn bytes (measured natively on an Apple M5, 2026-11-18: |t| 16 to + * 18 on equal and 9 to 26 on open with the split, below 3 for both without it). + * With `Control`, the A/A control: the bytes are drawn, then overwritten with `fixed`, and blended + * through the same volatile mask, so that both classes write the fixed value with the same + * instructions as a case's and the generator advances as it does; its |t| shows what the + * measurement on that machine finds where nothing differs. + * @tparam Control Whether both classes write `fixed`. + * @param which The class, 0 or 1. + * @param generator The seeded generator. + * @param fixed The class 0 input. + * @param input Where the input of the class is written. + */ +template +void choose(int which, Generator& generator, std::array const& fixed, + std::array& input) { + std::array drawn{}; + for (auto& byte : drawn) { + byte = static_cast(generator()); + } + if constexpr (Control) { + // Read through a volatile, so that the compiler cannot know the two sources of the blend + // below equal and fold it into a copy: the control blends as every case does. + for (std::size_t index = 0; index < Size; ++index) { + drawn[index] = static_cast(fixed[index]); + } + } + std::uint8_t volatile const chosen = which == 0 ? 0xFFU : 0x00U; + unsigned const keep = chosen; + unsigned const drop = keep ^ 0xFFU; + for (std::size_t index = 0; index < Size; ++index) { + input[index] = static_cast((unsigned{fixed[index]} & keep) | + (unsigned{drawn[index]} & drop)); + } +} + +/** + * The largest |t| of `count` measurements of `run`, each after `prepare(class, generator)` + * with a class drawn at random from the seeded generator, prepare unmeasured; each clock read + * is fenced by `serialise`. + * @param seed The generator's seed. + * @param count The number of measurements. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The largest |t|, with what gave it. + */ +template +t_statistic measure(std::uint64_t seed, std::size_t count, Prepare&& prepare, Run&& run) { + std::mt19937_64 generator(seed); + std::vector timings; + std::vector classes; + timings.reserve(count); + classes.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + int const which = static_cast(generator() & 1U); + prepare(which, generator); + serialise(); + auto const start = std::chrono::steady_clock::now(); + serialise(); + run(); + serialise(); + auto const end = std::chrono::steady_clock::now(); + timings.push_back(std::chrono::duration(end - start).count()); + classes.push_back(which); + } + return largest_t(timings, classes); +} + +/** + * The largest |t| of a first run, and of a second with another seed when the first, as printed, + * is at least 10. + * @param count The number of measurements of each run. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The first run's statistic when its |t|, as printed, is below 10, else that of the run + * with the smaller |t|. + */ +template +t_statistic twice(std::size_t count, Prepare&& prepare, Run&& run) { + t_statistic const first = measure(20261011, count, prepare, run); + if (printed(first.t) < 10) { + return first; + } + t_statistic const second = measure(20261012, count, prepare, run); + return second.t < first.t ? second : first; +} + +/** A buffer a case measures, named in its addresses line. */ +struct address { + /** + * Names a buffer, as `{"data", data.data()}` does in a case's list. + * @param name Its name in the line, as `data` or `object`. + * @param buffer Where it is. + */ + constexpr address(char const* name, void const* buffer) noexcept : label(name), where(buffer) {} + + /** Its name in the line, as `data` or `object`. */ + char const* label; + /** Where it is. */ + void const* where; +}; + +/** + * The lines of a case, which the CI's judge reads (design D6 of the change api-gaps): `dudect + * case= t=<|t|> threshold=10 judged=`, and, when |t| is at least 10, `dudect + * evidence case= crop= limit_ns= class0_n= class0_mean_ns= class1_n= + * class1_mean_ns=`, the cropping that gave |t| and each class there, and `dudect addresses + * case=
buffers) { + std::array line{}; + double const t = printed(result.t); + static_cast(std::snprintf(line.data(), line.size(), + "dudect case=%s t=%.2f threshold=10 judged=%s\n", name, t, + judged_case ? "yes" : "no")); + std::string text = line.data(); + if (!(t >= 10)) { + return text; + } + static_cast(std::snprintf( + line.data(), line.size(), + "dudect evidence case=%s crop=%d limit_ns=%.2f class0_n=%zu class0_mean_ns=%.2f " + "class1_n=%zu class1_mean_ns=%.2f\n", + name, result.crop, result.limit_ns, result.classes[0].count, result.classes[0].mean_ns, + result.classes[1].count, result.classes[1].mean_ns)); + text += line.data(); + text += "dudect addresses case="; + text += name; + for (address const& buffer : buffers) { + static_cast(std::snprintf( + line.data(), line.size(), " %s=0x%03x", buffer.label, + static_cast(reinterpret_cast(buffer.where) & 0xFFFU))); + text += line.data(); + } + text += '\n'; + return text; +} + +/** + * Prints a case's lines (`case_lines`) to `out`, stdout by default, and flushes them. + * @param name The case's name, as `--case` takes it. + * @param result Its statistic. + * @param judged_case Whether its |t| counts in the program's verdict. + * @param buffers The buffers it measures: its input, its output and its object. + * @param out Where: `std::cout`, the program's stdout, whose other lines (`std::printf`) it keeps + * in order, since the standard streams are synchronised with C's; a test's string stream. + */ +inline void report_case(char const* name, t_statistic const& result, bool judged_case, + std::initializer_list
buffers, std::ostream& out = std::cout) { + out << case_lines(name, result, judged_case, buffers) << std::flush; +} + +/** + * The smallest nonzero difference of 10,000 pairs of `steady_clock::now()` read back to back, + * each read fenced by `serialise`. + * @return The clock's resolution in nanoseconds, 0 when every pair read the same time. + */ +inline double clock_resolution_ns() { + double smallest = 0; + for (int pair = 0; pair < 10'000; ++pair) { + serialise(); + auto const first = std::chrono::steady_clock::now(); + serialise(); + auto const second = std::chrono::steady_clock::now(); + serialise(); + double const difference = std::chrono::duration(second - first).count(); + if (difference > 0 && (smallest == 0 || difference < smallest)) { + smallest = difference; + } + } + return smallest; +} + +/** What the machine line says of the CPU. */ +struct cpu_identity { + /** The model, with no double quote in it. */ + std::string cpu = "unavailable"; + /** The microcode's version, with no space or double quote in it. */ + std::string microcode = "unavailable"; +}; + +/** + * Makes a CPU's identity fit the machine line: a double quote in the model becomes a single one, + * so that the quoted value does not end early, and a space or double quote in the microcode an + * underscore. + * @param identity The identity as the system gave it. + * @return The identity to print. + */ +inline cpu_identity printable(cpu_identity identity) { + std::ranges::replace(identity.cpu, '"', '\''); + for (char& character : identity.microcode) { + if (character == ' ' || character == '"') { + character = '_'; + } + } + return identity; +} + +/** + * Reads the CPU's identity from the text of Linux's /proc/cpuinfo: the first `model name` and + * `microcode` (x86); where there is no `model name` (arm64), the first `CPU implementer`, `CPU + * part`, `CPU variant` and `CPU revision`, as `arm64 implementer= part= variant= + * revision=` with the fields found. What the text does not hold stays `unavailable`. + * @param text The file's text. + * @return The identity, `printable`. + */ +inline cpu_identity parse_cpuinfo(std::string_view text) { + using field = std::pair; + std::array fields{ + field{"model name", {}}, field{"microcode", {}}, field{"CPU implementer", {}}, + field{"CPU part", {}}, field{"CPU variant", {}}, field{"CPU revision", {}}, + }; + constexpr std::string_view blank = " \t\r"; + while (!text.empty()) { + auto const end = text.find('\n'); + std::string_view const line = text.substr(0, end); + text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1); + auto const colon = line.find(':'); + if (colon == std::string_view::npos) { + continue; + } + std::string_view key = line.substr(0, colon); + std::string_view value = line.substr(colon + 1); + auto const key_end = key.find_last_not_of(blank); + key = key_end == std::string_view::npos ? std::string_view{} : key.substr(0, key_end + 1); + auto const value_start = value.find_first_not_of(blank); + value = + value_start == std::string_view::npos ? std::string_view{} : value.substr(value_start); + value = value.substr(0, value.find_last_not_of(blank) + 1); + for (auto& [name, found] : fields) { + if (key == name && found.empty()) { + found = value; + } + } + } + cpu_identity identity; + if (!fields[0].second.empty()) { + identity.cpu = fields[0].second; + } else if (!fields[2].second.empty()) { + identity.cpu = "arm64"; + constexpr std::array labels{"implementer", "part", "variant", "revision"}; + for (std::size_t index = 0; index < labels.size(); ++index) { + if (!fields[index + 2].second.empty()) { + identity.cpu += ' '; + identity.cpu += labels[index]; + identity.cpu += '='; + identity.cpu += fields[index + 2].second; + } + } + } + if (!fields[1].second.empty()) { + identity.microcode = fields[1].second; + } + return printable(identity); +} + +/** + * The CPU a measurement runs on: /proc/cpuinfo's model and microcode (`parse_cpuinfo`) on Linux, + * `machdep.cpu.brand_string` on macOS with the microcode `unavailable`, and `unavailable` + * elsewhere, WebAssembly included, as where the system does not tell them. + * @return The identity, `printable`. + */ +inline cpu_identity machine_identity() { + cpu_identity identity; +#ifdef __linux__ + if (std::FILE* const file = std::fopen("/proc/cpuinfo", "r")) { + std::string text; + std::array buffer{}; + std::size_t read = 0; + while ((read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0) { + text.append(buffer.data(), read); + } + static_cast(std::fclose(file)); + identity = parse_cpuinfo(text); + } +#elif defined(__APPLE__) + std::array brand{}; + std::size_t size = brand.size(); + if (sysctlbyname("machdep.cpu.brand_string", brand.data(), &size, nullptr, 0) == 0 && + brand[0] != '\0') { + brand.back() = '\0'; + identity.cpu = brand.data(); + } + identity = printable(identity); +#endif + return identity; +} + +/** + * Prints, once per program, the machine a measurement ran on: `dudect machine cpu="" + * microcode= clock_resolution_ns=`, the CPU's `machine_identity`; the resolution is + * `clock_resolution_ns`'s, with two decimals, or `below_resolution` when it measured none. + */ +inline void report_machine() { + static bool printed_once = false; + if (printed_once) { + return; + } + printed_once = true; + cpu_identity const identity = machine_identity(); + double const resolution = clock_resolution_ns(); + std::array written{}; + if (resolution > 0) { + static_cast(std::snprintf(written.data(), written.size(), "%.2f", resolution)); + } else { + static_cast(std::snprintf(written.data(), written.size(), "below_resolution")); + } + std::printf("dudect machine cpu=\"%s\" microcode=%s clock_resolution_ns=%s\n", + identity.cpu.c_str(), identity.microcode.c_str(), written.data()); + static_cast(std::fflush(stdout)); +} + +/** The case a program measures: every one, or the one `--case` names. */ +struct case_selection { + /** The one case to measure, or none for every case. */ + char const* only = nullptr; + + /** + * Whether a case is measured. + * @param name The case's name. + * @return true when no case was named or this one was. + */ + [[nodiscard]] bool runs(char const* name) const { + return only == nullptr || std::strcmp(only, name) == 0; + } +}; + +/** + * Reads a dudect program's arguments: none, to measure every case, or `--case `, to measure + * that case alone, so that the CI measures a case again in a fresh process. + * @param argc main's argc. + * @param argv main's argv. + * @param names The program's cases. + * @return The selection; empty, after a line on stderr that lists the cases (`unknown case ; + * the cases: ` for a name not among them), when the arguments are neither. + */ +inline std::optional select_case(int argc, char const* const* argv, + std::initializer_list names) { + std::string list; + for (char const* const name : names) { + list += list.empty() ? "" : ", "; + list += name; + } + if (argc <= 1) { + return case_selection{}; + } + if (argc == 3 && std::strcmp(argv[1], "--case") == 0) { + for (char const* const name : names) { + if (std::strcmp(argv[2], name) == 0) { + return case_selection{name}; + } + } + static_cast( + std::fprintf(stderr, "unknown case %s; the cases: %s\n", argv[2], list.c_str())); + return std::nullopt; + } + static_cast(std::fprintf(stderr, "usage: %s [--case ]; the cases: %s\n", + argc > 0 ? argv[0] : "dudect", list.c_str())); + return std::nullopt; +} + +/** + * The cases a program measured: each one's lines printed as it is recorded, the human line that + * lists them, and whether every judged one passes. + */ +class case_results { +public: + /** + * Prints a case's lines (`report_case`) and adds it to the human line and to the verdict. + * @param name The case's name, as `--case` takes it. + * @param label Its name in the human line. + * @param result Its statistic. + * @param judged_case Whether its |t| counts in the verdict. + * @param buffers The buffers it measures: its input, its output and its object. + * @param note Printed after its value in the human line. + */ + void record(char const* name, char const* label, t_statistic const& result, bool judged_case, + std::initializer_list
buffers, char const* note = "") { + report_case(name, result, judged_case, buffers); + std::array value{}; + static_cast(std::snprintf(value.data(), value.size(), "%s%s %.2f%s", + human_.empty() ? "" : ", ", label, printed(result.t), + note)); + human_ += value.data(); + passes_ = passes_ && (!judged_case || printed(result.t) < 10); + } + + /** Prints the human line: `|t| ` or +`basic_secret_byte_vector` when the size is not known at compile time, and +the in-place result, ignoring the allocator, when it is; and `append_to` and +`assign_to` use the allocator of the container they are given, a +`std::pmr::string` among them. The decode's bytes go to a `std::vector` +the same way. + +The `std::pmr` aliases, in `codecs::pmr`, are `codecs::pmr::secret_string` and +`codecs::pmr::secret_byte_vector`, the secret heap types over +`std::pmr::polymorphic_allocator`, as the containers of `std::pmr` are over the +standard's allocators. Their `std::allocator` aliases are `codecs::secret_string` and +`codecs::secret_byte_vector`. + +[source,cpp] +---- +include::{examples}/pmr_arena.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/pmr_arena.expected[] +---- + +The arena in the program records every allocation, and the global `operator new` +sees none: codecs' tests check that for every form that takes an allocator, with +a recording memory resource and with allocators of their own that the +standard's rules are checked against. + +=== An allocator that throws + +An allocator that cannot give the memory throws, as `std::pmr::null_memory_resource` +does once the arena is full. That exception propagates unchanged out of the +allocating function, which is not `noexcept`, and codecs throws nothing of its +own (<>). What the program finds after it: + +* a token's container still holds what it held: `append_to` is put back as it + was, `assign_to` gives the container nothing before the conversion succeeds, + and in the example the string still holds `kept`; +* every buffer of a secret operation that was allocated is wiped before it is + given back, and a secret heap type whose allocation throws keeps its value; +* `each` and `buffered` with an allocator: a `send` that throws accepts nothing, + and the stream converts the same input after the exception; a `receive` + that throws leaves its item pending; a `flush` that throws leaves the stream + as it was before the flush, valid and resettable. + +Without exceptions the allocator's failure follows the build's handler: codecs +adds no handling. + +=== Pitfalls + +* The allocator of `over` is for its intermediate alone. The allocator of a + token is for its result alone. Neither is the other's. +* A `std::pmr::monotonic_buffer_resource` never gives memory back: an encode of a + megabyte through an arena of a kilobyte throws once, and a loop that reuses the + arena must release it. +* A secret result over a pmr allocator is wiped before its memory goes back to + the resource, but the resource may keep the pages: that is the resource's. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 84238ca..fa68a60 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,5 +16,14 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added webcpp::codecs' skeleton, its configuration and its errors. +* Added codecs.hpp and config.hpp: encode, decode, tokens, results, secrecy and over, errors as values. +* Added the stream contract: one-shot and stream transformers, pipe, drain, each, buffered, encoder and decoder. +* Added hex.hpp: the format hex, constant time, decoding in place, and streaming natively. +* Added base32.hpp: base32 and base32hex of RFC 4648, with padding as an option. +* Added base64.hpp: base64 and base64url of RFC 4648, canonical on decode, and streaming natively. +* Added base58.hpp: basic_base58, with a bound, an alphabet and a checksum as parameters. +* Added bech32.hpp: bech32 and bech32m, with a maximum length, words and bytes data. +* Added percent.hpp: percent-encoding over Boost.URL, with any CharSet, and the target percent. +* Added armor.hpp: RFC 7468's strict armor, composing over any bytes format. +* Added the guide, with its examples built and run on every target. // end::unreleased[] diff --git a/doc/codecs.adoc b/doc/codecs.adoc index 4365671..ba67459 100644 --- a/doc/codecs.adoc +++ b/doc/codecs.adoc @@ -20,6 +20,41 @@ base32, base58, base64, bech32, percent-encoding and RFC 7468's armor. It is built on webcpp::secure, so that the conversions of secrets keep their timing and their memory clean. +The page teaches the library in the order a program meets it. <> +says what codecs is and what it is not, <> has one section for +each format, with its example and its pitfalls, and the chapters after it teach +what every format shares: <> (where a result goes), +<> (the default and fixed results and the typed decode), +<> (what a secret operation is), <> +(`over`), <> (the two transformer concepts, `pipe`, `drain`, +`each` and `buffered`) and <> (what allocates, and the +`codecs::pmr` aliases). <> and +<> are for the library that adds a format of its +own, and a transformer of data that is no text. Every program shown is in +`example/`, built and run on every target with the output it prints. The +<> that closes the page lists every name the headers +declare. + +include::overview.adoc[] + +include::formats.adoc[] + +include::tokens.adoc[] + +include::results.adoc[] + +include::secrecy.adoc[] + +include::composition.adoc[] + +include::streams.adoc[] + +include::allocators.adoc[] + +include::writing_a_format.adoc[] + +include::writing_a_transformer.adoc[] + [#reference] == Reference diff --git a/doc/composition.adoc b/doc/composition.adoc new file mode 100644 index 0000000..13982da --- /dev/null +++ b/doc/composition.adoc @@ -0,0 +1,83 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#codecs-composition] +== Composition: over + +`codecs::over{outer, inner}` is a format made of two. Encoding encodes with the +inner format and then encodes that output, as bytes, with the outer; decoding +decodes with the outer and then with the inner. `Inner` may be the format of a `codec` +or of a value codec, whose value `over` converts to bytes first +(<>); `Outer` must be the format of a `codec`, since its input is +the inner's output read as bytes. The armor over any bytes format is the usual +use (`over{formats::armor("PUBLIC KEY"), inner}`). + +[source,cpp] +---- +include::{examples}/over_chain.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/over_chain.expected[] +---- + +The name of the chain is the outer link's name, `" over "` and the inner's, +and the chain is constructed from values by class template argument deduction, +as `over{formats::hex, formats::base64}` shows. It is constant time when +every link is, and secret when any link's operation is: the core runs the links' +secret arithmetic, and the intermediate is wiped by `secure::erase_secret`. + +=== Where the intermediate lives + +The intermediate, the bytes between the two links, is held: + +* *in place*, in the frame of each function of `over`, when its bound is known + at compile time: when the input's type states its size (a `std::array`, a + `std::span` of a static extent, a `secure::secret`, `text`, `bytes`) or + the value codec states `max_encoded_size`. There is no cap: the cost is the + stack, an array of the middle bound, the inner link's bound on the input's size + for an encode and the outer link's bound on the text's size for a decode, in + every level of a chain of chains; +* *on the heap*, from the allocator of `over`, for any other input. The third + template parameter of `over` is that allocator, `std::allocator` by default, + deduced from `over{outer, inner, allocator}`. A program that passes an input of a + static size and wants the intermediate on the heap passes it as a view of a + dynamic extent, a `std::span` or a `std::string_view`. + +The allocator of a result or a token is not the intermediate's, and the +allocator of `over` is used for nothing else. A heap intermediate makes the exact +`encoded_size` and `decoded_size`, which run the inner link into it, and +`encode` and `decode` allocate: those forms are not `noexcept`, an allocator's +exception reaches the caller, and on a secret chain every buffer is wiped +before it goes back. With a bound known at compile time they are `noexcept` and +allocate nothing, which the allocation test checks. + +=== One-shot, with a stream of links + +`over` is a format of the one-shot operations. Its transformers, +`codecs::encoder(chain)` and `codecs::decoder(chain)`, stream through a pipe of +the links' streams when both links stream natively (<>), and +are one-shot otherwise: a chain with base58 in it streams through `buffered`. + +=== Errors + +A fault of a link's configuration is the chain's, the outer link's first, and +every form reports it before it reads any data, in either link: a chain with +`formats::bech32` configured with a human-readable part of 84 characters +refuses every form with `invalid_prefix`. A data error of either link is the chain's: +the decode of `414` in the program is the outer link's, hex, odd length. + +=== Pitfalls + +* The intermediate on the stack grows with the input's static size, and a chain + of chains has one in each level's frame. A program that puts a large array + through `over` passes a view of a dynamic extent to move the intermediate to + the heap. +* The inner link's output is bytes, and the outer reads them as bytes, whatever + the inner's text was. The armor over hex, as in the program of + <>, armors the hex text; a program that wants the armor of + the bytes themselves uses the armor alone. diff --git a/doc/formats.adoc b/doc/formats.adoc new file mode 100644 index 0000000..659ba51 --- /dev/null +++ b/doc/formats.adoc @@ -0,0 +1,399 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#codecs-formats] +== The formats + +Each section says what the format is, shows a program, and ends with what +catches a program that has not read the section. Every format is a value in +`webcpp::codecs::formats`, copyable, with a `name`; a format with options is +configured by a call that gives another value (`formats::hex(letter_case::upper)`), +so that a format is a constant a program names and never a type it builds. +The sections that follow say what every format shares: the tokens, the results, +the secret operations and the streams. + +A decode reads its whole text before it writes a byte, so that on every error +nothing is written; its buffer form leaves the bytes past the result as they +were. Which formats decode into the text's own storage, which the table in +<> lists, is a promise of the format's page and not of the +core: hex, base32, base64 and percent write byte `i` after the characters it +comes from are read, and base58, bech32 and the armor ask that the input and +the output do not overlap. + +[#codecs-hex] +=== hex + +hex, or base16 (RFC 4648 section 8), writes each byte as two hex digits, its +high nibble first. `formats::hex` writes lower case, and +`formats::hex(formats::letter_case::upper)` upper case, as the RFC does. +Decode takes either case, mixed included, and refuses a text of an odd length +with `invalid_length` and any character that is no hex digit with +`invalid_character`, which wins when both are found. It is constant time on +every call, one-shot and streamed, and streams natively: the encoder holds the +low digit of a byte its output had no room for, and the decoder one digit of a +pair. + +[source,cpp] +---- +include::{examples}/digest_hex.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/digest_hex.expected[] +---- + +*Pitfalls.* + +* Decode takes digits and nothing else: `0x` in front, a space between two + bytes and a trailing line feed are each `invalid_character`. Trim the text + before decoding it. +* A decode into a fixed type is exact. `decode>` + of 62 digits is `invalid_length`, not a shorter array. +* Constant time covers the data. The length of the text, the length of the + result and whether the call succeeded are public, as they are for every + format of codecs (<>). +* The bytes a stream decoder delivers before an error are no result: a caller + discards them (<>). + +[#codecs-base32] +=== base32 and base32hex + +`formats::base32` is RFC 4648 section 6's alphabet and `formats::base32hex` +section 7's. Each writes upper case and its padding, `=`, by default, and takes +the padding as an option: `formats::base32(formats::padding::omitted)`. Decode +is canonical. It takes the format's own alphabet in either case, the padding +the option says, and nothing else: a character of the other alphabet or a line +break is `invalid_character`, a length no encoding has is `invalid_length`, and +padding against the option, a `=` out of its place and non-zero bits at the end +of the last group are `invalid_padding`. + +[source,cpp] +---- +include::{examples}/rfc4648.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/rfc4648.expected[] +---- + +*Pitfalls.* + +* `MZ======` and `MZXW6Y==` have a valid length, so their error is + `invalid_padding`; `MZXW6YQ` with the padding written has none, and is + `invalid_length`. When a text has both, the lowest value wins. +* The two alphabets are not interchangeable: `base32hex` has the digits `0`, + `1`, `8` and `9`, which `base32` refuses. +* A padded stream decoder holds the bytes that the characters of a group's + fourth, fifth, seventh and eighth places give, since those places are `=` in + the last group of a short input, until the next character shows that the + group is not the last, or until `flush`. A stream that has delivered less + than the text seems to give is not stuck: it waits for the next character or + for `flush`. + +[#codecs-base64] +=== base64 and base64url + +`formats::base64` is RFC 4648 section 4's alphabet with its padding written; +`formats::base64url` is section 5's, with `-` and `_` and its padding omitted +by default, as JOSE and URLs write it. Each takes the other padding by option, +`formats::base64url(formats::padding::written)`. Decode is canonical, as base32's +is: only the format's alphabet, the padding of the option, and zero bits at the +end of the last group. `Zh==` is `invalid_padding` since `Zg==` is the +encoding of `f`, and a text with a line break or a space is `invalid_character`. Both +formats are constant time on every call, stream natively, and decode in place. +The program of the base32 section shows both alphabets of base64 beside +base32's: the default padding of each, the two symbols in which the alphabets +differ (`+/8=` and `-_8` for the bytes `fb ff`) and the canonical refusals. The +next program is the secret use, a key as base64. + +[source,cpp] +---- +include::{examples}/key_base64.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/key_base64.expected[] +---- + +*Pitfalls.* + +* PEM and MIME wrap base64 in lines; `formats::base64` refuses the line breaks. + PEM's own format is `formats::armor` (<>). +* A padded stream decoder holds the bytes that the characters of a group's + third and fourth places give, which are `=` in the last group of a short input, + until the next character or `flush`, as base32's does. +* A secret key goes through a `secure::secret`, which makes the operation + secret and the result a `secret_text`; the same call with a `std::vector` is + a public operation (<>). + +[#codecs-base58] +=== base58 + +base58 writes the bytes as one number in base 58, its digits in an alphabet of +58 characters and each leading zero byte as the alphabet's first character, as +Bitcoin Core's `EncodeBase58` does. The format is +`formats::basic_base58`, and `formats::base58` +is the one a program names for Bitcoin: 100 bytes of payload, Bitcoin's +alphabet, no checksum. The program shows each of the three parameters, and the +stream. + +[source,cpp] +---- +include::{examples}/base58_address.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/base58_address.expected[] +---- + +*The cost is quadratic, so the bound caps it.* Every digit depends on the whole +number, so the work grows with the square of the input's length; there is no +streaming form and no way around it. `MaximumBytes` is the payload's bound +without the checksum, 100 for `formats::base58`, and an input longer than it +and a text longer than `maximum_characters` (137 for 100 bytes) are +`input_too_long` by their length, before any read. A program that needs more +names a larger instance, `formats::basic_base58<1024, formats::bitcoin_alphabet>{}`; +a decode whose payload would be longer than `maximum_bytes` is +`input_too_long` too. + +*The scratch is in place, on the stack.* Every instance converts in an array +sized by its template, about one and a third bytes for each byte of the bound. +Nothing allocates, every size is exact, and the functions are `noexcept`: the +price is the stack, which a larger bound makes larger (about 1.4 KiB for 1024), +in every frame that converts. A secret conversion runs in the same scratch and +wipes it. + +*An alphabet of the program's own is a type.* It has a +`static constexpr std::string_view characters` of 58 characters, digit 0 first, +from which the tables are built at compile time. `basic_base58` stops the build +with a message that says an alphabet is 58 distinct characters when they are +not. The ones of the library are `bitcoin_alphabet`, `ripple_alphabet` and +`flickr_alphabet`, and the formats `base58_bitcoin`, `base58_ripple` and +`base58_flickr`, whose bound is 100 bytes. + +*The checksum is a parameter.* With `no_checksum`, the default, the payload is +the whole number. With a checksum type of the program's own, a +`static constexpr std::size_t size` and a `static void compute(payload, out)` +that is `noexcept`, encode appends `compute(payload)` to the payload before the +conversion, and decode splits the last `size` bytes off, recomputes the checksum +of the rest, compares the two with `secure::constant_time_equal` and gives the +payload without it. A mismatch is `checksum_mismatch`, and fewer decoded bytes +than the checksum's `size` are `invalid_length`. codecs defines no checksum +algorithm: webcpp::hash's `base58_with_checksum`, a format over its double +SHA-256, is what Bitcoin calls Base58Check, and the checksum of the program +above is a toy. A checksum's `compute` runs on secrets in a secret operation, +so it must be constant time, which the concept cannot check. + +*It is constant time only when the operation is secret.* A public operation +runs Bitcoin Core's conversion, with its early exits (`codec::constant_time` +is false). A secret one, with a `secure::secret` or a `secret_bytes` as the +input or a secret token as the destination, runs a conversion whose operations +depend on the length of the input alone, the alphabet read by +`secure::constant_time::lookup`, and the checksum compared inside the engaged +timing guard (`constant_time_when_secret` is true for every instance). The +length of the text and the success of the call are public. + +*Pitfalls.* + +* `formats::base58` refuses 101 bytes. It is a bound and not a bug; name the + larger instance. +* A secret input's result is a `secret_text` with `N` the bound for the + input's length, so that the text of a 32-byte key is held in 44 characters, + 42 of them here. +* A drain of `codecs::encoder(formats::base58)` does not compile: base58 has no + native stream, and the message names `codecs::buffered`. The program + streams through `buffered(encoder(format), codecs::capacity<100>)`, which + accumulates the input in place and converts at `flush`; an input past the + capacity is accepted and reported at `flush` as `input_too_long`. +* Input and output must not overlap. + +[#codecs-bech32] +=== bech32 and bech32m + +bech32 (BIP-173) and bech32m (BIP-350) write a human-readable part, the +separator `1`, the data in 5-bit groups and a checksum of six characters over +both, in an alphabet of 32 characters. `formats::bech32` and `formats::bech32m` +are the instances of 90 characters over bytes, and the human-readable part is +configured by a call and held in the format value: `formats::bech32("npub")`. +A format with none decodes any part, and encodes nothing: +`codecs::decode(formats::bech32, text)` gives +the part and the data of any text. Encode writes lower case; decode takes +either, not both (`mixed_case`). + +[source,cpp] +---- +include::{examples}/nostr_bech32.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/nostr_bech32.expected[] +---- + +*The maximum length is a template parameter.* `basic_bech32` +names the longest text, 90 by default, so that the scratch, the stream +decoder's hold and the results of every form are in place, sized from it, and +nothing allocates. A text past it is `input_too_long`, before it is read. A +Lightning invoice, which has no length limit of BIP-173's 90 characters, is +read by a larger instance (2048 in the program); `formats::bech32` reports +`input_too_long` for it, and its stream decoder has delivered nothing. The +shortest text is 8 characters, and a smaller `MaximumLength` stops the build. + +*A word is a 5-bit value, not a machine word.* In bytes mode, the default, the +data are bytes regrouped from 8 bits to 5 with zero padding, as BIP-173's +`convertbits` does, and decode refuses more than 4 padding bits or a non-zero +one with `invalid_padding`. In words mode, `format.words()`, each element is one +value from 0 to 31 written and read as it is, and a value above 31 is refused +on encode with `invalid_character`. `formats::append_words_from_bytes(words, bytes)` +regroups bytes into words after a word the program has put first, and +`formats::bytes_from_words(words, output)` regroups words back into bytes, in +constant time as the format is. + +*A segwit version is a word, never a byte.* This is the pitfall of the example: +BIP-350's Taproot address is the version word 1 followed by the program's +words, and the bytes mode of the same two values, the byte `0x01` and then the +program, is a different text, which is not the address. A program that builds +an address puts the version into a words-mode format first, `bech32` for +version 0 and `bech32m` above, and the same program takes the version back from +the first word of the decoded words. + +*What it leaves to webcpp::bitcoin.* codecs applies none of segwit's rules, the +versions, the sizes of the programs and the networks' prefixes, and parses none +of Lightning's fields: a segwit decoder checks the version and the program's +size, and a Lightning one reads the invoice's tagged fields from the words. A +future webcpp::bitcoin owns both. What codecs checks is the format: the +checksum, the case, the alphabet, the part, the length. + +*Pitfalls.* + +* The human-readable part of the format is a configuration, and a fault of it + (84 characters, or one outside 33 to 126) is `invalid_prefix`, reported + before any data is read, by the one-shot call and by the stream's first + call. +* A decode with a part other than the format's is `invalid_prefix` even when + the checksum is right; the format with no part is how a program reads any. +* The stream decoder holds the raw characters, up to the maximum length, and + delivers nothing before `flush` has checked the checksum: a program that + reads an invoice from a socket sees no byte until the last character. The + hold is `codecs::decoder(format, codecs::capacity)`, at most the + format's maximum length, which stops the build when it is more. +* The stream encoder writes the part and the data as it goes and the checksum at + `flush`. + +[#codecs-percent] +=== percent + +percent is percent-encoding (RFC 3986 section 2.1) over Boost.URL: each byte +outside a `CharSet` as `%` and two hex digits. `formats::percent` leaves the +unreserved characters as they are, and `formats::percent(char_set, options)` +takes any Boost.URL `CharSet`, `boost::urls::pchars` or a set of the program's +own built with `boost::urls::grammar::lut_chars`, and a +`boost::urls::encoding_opts`, which chooses the case of the digits and writes a +space as a plus sign. The sizes, encode and decode are Boost.URL's own, byte for +byte. It is the one header that includes Boost.URL, and a program that includes +it names `/webcpp/codecs//percent`, whose decode is compiled. + +[source,cpp] +---- +include::{examples}/percent_segment.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/percent_segment.expected[] +---- + +*Pitfalls.* + +* The `CharSet` is the characters left as they are, and each piece of a URL has + its own: a path segment `pchars`, a query value the same with + `+encoding_opts{true}+` for the plus sign, and a program that picks the default + `unreserved` set escapes more than a URL needs and never less. +* The percent sign is never in the set: it is written `%25` whatever the set + holds. +* Decode does not check that the characters it takes as they are belong to the + set. A text that holds a character the set would escape decodes to that + character; checking the text against a grammar is Boost.URL's parser's job. +* A `%` followed by a character that is no hex digit is `invalid_character`, + and a text that ends inside an escape is `invalid_length`; `%g` is both and + gets the lower value, `invalid_character`. +* percent is not constant time. A secret that must not leak through time is + written in a format that is. + +[#codecs-armor] +=== armor + +The armor is RFC 7468's strict textual encoding, which OpenSSL writes as PEM: +`-----BEGIN