diff --git a/docs/agent-workflow/tasks/S-UNICODE-01-02.md b/docs/agent-workflow/tasks/S-UNICODE-01-02.md index 179e227..7a1d75d 100644 --- a/docs/agent-workflow/tasks/S-UNICODE-01-02.md +++ b/docs/agent-workflow/tasks/S-UNICODE-01-02.md @@ -25,7 +25,7 @@ VoidLibrary currently has no `Unicode` module (`src/Unicode/`). `Text` handles l ## 4. Edge cases - Rejects overlong UTF-8 sequences, UTF-16 surrogates (`U+D800..U+DFFF`) in UTF-8/UTF-32, unpaired surrogates in UTF-16, code points `> U+10FFFF`, and truncated sequences under `UtfPolicy::reject`. -- WHATWG-compliant maximal subpart (`replace_one_unit`) emits `U+FFFD` per ill-formed unit/maximal subpart and advances cleanly without skipping subsequent valid units. +- One-unit repair (`replace_one_unit`) emits `U+FFFD` per ill-formed unit and advances cleanly by one code unit without skipping subsequent valid units; streaming chunk boundaries match one-shot behavior identically. - Pre-reserve limit checks against `UtfLimits` reject oversized inputs/outputs before large allocations; periodic `std::stop_token` checks abort long transcodes cleanly. - Streaming `Utf8StreamDecoder` / `Utf16StreamDecoder` split sequences across arbitrary 1-byte/1-unit boundaries and flush trailing incomplete sequences cleanly at EOF. diff --git a/include/Void/Unicode/Utf.hpp b/include/Void/Unicode/Utf.hpp new file mode 100644 index 0000000..8b11c6e --- /dev/null +++ b/include/Void/Unicode/Utf.hpp @@ -0,0 +1,1319 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Unicode +{ + +[[nodiscard]] constexpr std::string_view data_version() noexcept +{ + return "17.0.0"; +} + +[[nodiscard]] constexpr bool is_scalar_value(char32_t cp) noexcept +{ + return cp <= 0x10FFFFu && (cp < 0xD800u || cp > 0xDFFFu); +} + +enum class UtfPolicy { + reject, + replace_one_unit +}; + +enum class UtfErrorKind { + invalid_utf8, + invalid_utf16, + invalid_scalar, + truncated, + limit_exceeded, + output_too_small, + overflow, + cancelled +}; + +struct UtfError { + UtfErrorKind kind{UtfErrorKind::invalid_utf8}; + std::size_t unit_offset{0}; + std::string message{}; +}; + +struct UtfLimits { + std::size_t max_input_units{16ULL * 1024ULL * 1024ULL}; + std::size_t max_output_units{64ULL * 1024ULL * 1024ULL}; + std::size_t cancel_check_interval{4096}; +}; + +struct TranscodeCounts { + std::size_t units_read{0}; + std::size_t units_written{0}; + std::size_t scalars_decoded{0}; + std::size_t replacements{0}; +}; + +class Scalar +{ +public: + constexpr Scalar() noexcept = default; + + [[nodiscard]] static constexpr std::expected + from_code_point(char32_t cp) noexcept + { + if (!is_scalar_value(cp)) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_scalar, + 0, + "Code point is outside Unicode scalar value range"}}; + } + return Scalar{cp}; + } + + [[nodiscard]] static constexpr Scalar replacement_character() noexcept + { + return Scalar{0xFFFDu}; + } + + [[nodiscard]] constexpr char32_t code_point() const noexcept { return value_; } + [[nodiscard]] constexpr explicit operator char32_t() const noexcept { return value_; } + + friend constexpr bool operator==(Scalar, Scalar) noexcept = default; + +private: + explicit constexpr Scalar(char32_t cp) noexcept + : value_(cp) + { + } + + char32_t value_{0}; +}; + +namespace detail +{ + +[[nodiscard]] constexpr bool check_cancel(const std::stop_token& stop_token, + std::size_t steps, + const UtfLimits& limits, + std::size_t offset) +{ + if (limits.cancel_check_interval > 0 && + (steps % limits.cancel_check_interval) == 0 && + stop_token.stop_requested()) { + return false; + } + (void)offset; + return true; +} + +[[nodiscard]] constexpr std::size_t utf8_length(char32_t cp) noexcept +{ + if (cp <= 0x7Fu) { + return 1; + } + if (cp <= 0x7FFu) { + return 2; + } + if (cp <= 0xFFFFu) { + return 3; + } + return 4; +} + +[[nodiscard]] constexpr std::size_t utf16_length(char32_t cp) noexcept +{ + return (cp <= 0xFFFFu) ? 1 : 2; +} + +constexpr void write_utf8_unchecked(char32_t cp, std::span out) noexcept +{ + if (cp <= 0x7Fu) { + out[0] = static_cast(cp); + } else if (cp <= 0x7FFu) { + out[0] = static_cast(0xC0u | (cp >> 6)); + out[1] = static_cast(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0xFFFFu) { + out[0] = static_cast(0xE0u | (cp >> 12)); + out[1] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[2] = static_cast(0x80u | (cp & 0x3Fu)); + } else { + out[0] = static_cast(0xF0u | (cp >> 18)); + out[1] = static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out[2] = static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out[3] = static_cast(0x80u | (cp & 0x3Fu)); + } +} + +constexpr void write_utf16_unchecked(char32_t cp, std::span out) noexcept +{ + if (cp <= 0xFFFFu) { + out[0] = static_cast(cp); + } else { + const char32_t adj = cp - 0x10000u; + out[0] = static_cast(0xD800u + (adj >> 10)); + out[1] = static_cast(0xDC00u + (adj & 0x3FFu)); + } +} + +[[nodiscard]] constexpr bool is_utf8_cont(std::uint8_t b) noexcept +{ + return b >= 0x80u && b <= 0xBFu; +} + +enum class StepStatus { + ok, + incomplete, + invalid +}; + +struct Utf8Step { + StepStatus status{StepStatus::invalid}; + Scalar scalar{}; + std::size_t consumed{1}; +}; + +[[nodiscard]] constexpr Utf8Step inspect_utf8(std::span bytes) noexcept +{ + if (bytes.empty()) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b0 = bytes[0]; + if (b0 <= 0x7Fu) { + return Utf8Step{ + StepStatus::ok, + *Scalar::from_code_point(static_cast(b0)), + 1}; + } + if (b0 >= 0xC2u && b0 <= 0xDFu) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + if (!is_utf8_cont(b1)) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x1Fu) << 6) | + static_cast(b1 & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 2}; + } + if (b0 >= 0xE0u && b0 <= 0xEFu) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + const std::uint8_t lo = (b0 == 0xE0u) ? 0xA0u : 0x80u; + const std::uint8_t hi = (b0 == 0xEDu) ? 0x9Fu : 0xBFu; + if (b1 < lo || b1 > hi) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 3) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b2 = bytes[2]; + if (!is_utf8_cont(b2)) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x0Fu) << 12) | + (static_cast(b1 & 0x3Fu) << 6) | + static_cast(b2 & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 3}; + } + if (b0 >= 0xF0u && b0 <= 0xF4u) { + if (bytes.size() < 2) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + const std::uint8_t b1 = bytes[1]; + const std::uint8_t lo = (b0 == 0xF0u) ? 0x90u : 0x80u; + const std::uint8_t hi = (b0 == 0xF4u) ? 0x8Fu : 0xBFu; + if (b1 < lo || b1 > hi) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 3) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + if (!is_utf8_cont(bytes[2])) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + if (bytes.size() < 4) { + return Utf8Step{StepStatus::incomplete, {}, 0}; + } + if (!is_utf8_cont(bytes[3])) { + return Utf8Step{StepStatus::invalid, {}, 1}; + } + const char32_t cp = + (static_cast(b0 & 0x07u) << 18) | + (static_cast(b1 & 0x3Fu) << 12) | + (static_cast(bytes[2] & 0x3Fu) << 6) | + static_cast(bytes[3] & 0x3Fu); + return Utf8Step{StepStatus::ok, *Scalar::from_code_point(cp), 4}; + } + return Utf8Step{StepStatus::invalid, {}, 1}; +} + +template +[[nodiscard]] inline std::expected + decode_utf8_each(std::string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + while (i < input.size()) { + if (!check_cancel(stop_token, steps++, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const std::size_t avail = std::min(4, input.size() - i); + std::array buf{}; + for (std::size_t k = 0; k < avail; ++k) { + buf[k] = static_cast(input[i + k]); + } + const Utf8Step st = inspect_utf8(std::span{buf.data(), avail}); + if (st.status == StepStatus::ok) { + const auto r = emit(st.scalar, false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += st.consumed; + } else { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + (st.status == StepStatus::incomplete) + ? UtfErrorKind::truncated + : UtfErrorKind::invalid_utf8, + i, + (st.status == StepStatus::incomplete) + ? "Truncated UTF-8 sequence" + : "Invalid UTF-8 byte sequence"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + } + } + counts.units_read = i; + return counts; +} + +template +[[nodiscard]] inline std::expected + decode_utf16_each(std::u16string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + while (i < input.size()) { + if (!check_cancel(stop_token, steps++, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const std::uint16_t u0 = static_cast(input[i]); + if (u0 < 0xD800u || u0 > 0xDFFFu) { + const auto sc = *Scalar::from_code_point(static_cast(u0)); + const auto r = emit(sc, false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += 1; + continue; + } + if (u0 <= 0xDBFFu) { + if (i + 1 >= input.size()) { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + i, + "Truncated high surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + continue; + } + const std::uint16_t u1 = static_cast(input[i + 1]); + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(u0 - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + const auto r = emit(*Scalar::from_code_point(cp), false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + i += 2; + continue; + } + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + i, + "Unpaired high surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + continue; + } + // Unpaired low surrogate 0xDC00..0xDFFF + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + i, + "Unpaired low surrogate in UTF-16 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + i += 1; + } + counts.units_read = i; + return counts; +} + +template +[[nodiscard]] inline std::expected + decode_utf32_each(std::u32string_view input, + UtfPolicy policy, + const UtfLimits& limits, + const std::stop_token& stop_token, + EmitFn&& emit) +{ + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + 0, + "Unicode operation cancelled"}}; + } + if (input.size() > limits.max_input_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + 0, + "Input size exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + for (std::size_t i = 0; i < input.size(); ++i) { + if (!check_cancel(stop_token, i, limits, i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + i, + "Unicode operation cancelled"}}; + } + const char32_t cp = input[i]; + if (is_scalar_value(cp)) { + const auto r = emit(*Scalar::from_code_point(cp), false, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.units_written += *r; + } else { + if (policy == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_scalar, + i, + "Invalid code point in UTF-32 input"}}; + } + const auto r = emit(Scalar::replacement_character(), true, i); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += *r; + } + } + counts.units_read = input.size(); + return counts; +} + +template +[[nodiscard]] inline auto make_string_sink(std::basic_string& dest, + std::size_t max_output_units) +{ + return [&dest, max_output_units](Scalar sc, + bool, + std::size_t in_offset) -> std::expected { + const char32_t cp = sc.code_point(); + if constexpr (sizeof(CharT) == 1) { + const std::size_t need = utf8_length(cp); + if (need > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + std::array tmp{}; + write_utf8_unchecked(cp, std::span{tmp.data(), need}); + dest.append(tmp.data(), need); + return need; + } else if constexpr (sizeof(CharT) == 2) { + const std::size_t need = utf16_length(cp); + if (need > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + std::array tmp{}; + write_utf16_unchecked(cp, std::span{tmp.data(), need}); + dest.append(tmp.data(), need); + return need; + } else { + if (1 > max_output_units - dest.size()) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + dest.push_back(cp); + return std::size_t{1}; + } + }; +} + +template +[[nodiscard]] inline auto make_span_sink(std::span out, + std::size_t& cursor, + std::size_t max_output_units) +{ + return [out, &cursor, max_output_units](Scalar sc, + bool, + std::size_t in_offset) -> std::expected { + const char32_t cp = sc.code_point(); + std::size_t need = 1; + if constexpr (sizeof(CharT) == 1) { + need = utf8_length(cp); + } else if constexpr (sizeof(CharT) == 2) { + need = utf16_length(cp); + } + if (need > max_output_units - cursor) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + in_offset, + "Output exceeds UtfLimits::max_output_units"}}; + } + if (need > out.size() - cursor) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + in_offset, + "Destination span too small for transcoded output"}}; + } + if constexpr (sizeof(CharT) == 1) { + write_utf8_unchecked(cp, out.subspan(cursor, need)); + } else if constexpr (sizeof(CharT) == 2) { + write_utf16_unchecked(cp, out.subspan(cursor, need)); + } else { + out[cursor] = cp; + } + cursor += need; + return need; + }; +} + +} // namespace detail + +[[nodiscard]] constexpr std::expected + encode_utf8(Scalar s, std::span out) noexcept +{ + const std::size_t need = detail::utf8_length(s.code_point()); + if (out.size() < need) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + 0, + "Output buffer too small for UTF-8 scalar"}}; + } + detail::write_utf8_unchecked(s.code_point(), out.first(need)); + return need; +} + +[[nodiscard]] constexpr std::expected + encode_utf16(Scalar s, std::span out) noexcept +{ + const std::size_t need = detail::utf16_length(s.code_point()); + if (out.size() < need) { + return std::unexpected{UtfError{ + UtfErrorKind::output_too_small, + 0, + "Output buffer too small for UTF-16 scalar"}}; + } + detail::write_utf16_unchecked(s.code_point(), out.first(need)); + return need; +} + +[[nodiscard]] inline std::expected + validate_utf8(std::string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf8_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar s, bool, std::size_t off) -> std::expected { + const std::size_t n = detail::utf8_length(s.code_point()); + if (n > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated byte count exceeds UtfLimits::max_output_units"}}; + } + emitted += n; + return n; + }); +} + +[[nodiscard]] inline std::expected + validate_utf16(std::u16string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf16_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar s, bool, std::size_t off) -> std::expected { + const std::size_t n = detail::utf16_length(s.code_point()); + if (n > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated unit count exceeds UtfLimits::max_output_units"}}; + } + emitted += n; + return n; + }); +} + +[[nodiscard]] inline std::expected + validate_utf32(std::u32string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t emitted = 0; + return detail::decode_utf32_each( + input, + UtfPolicy::reject, + limits, + stop_token, + [&](Scalar, bool, std::size_t off) -> std::expected { + if (1 > limits.max_output_units - emitted) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Validated unit count exceeds UtfLimits::max_output_units"}}; + } + emitted += 1; + return std::size_t{1}; + }); +} + +// ── Owning transcoders ─────────────────────────────────────────────────────── + +[[nodiscard]] inline std::expected + utf8_repair(std::string_view input, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, + UtfPolicy::replace_one_unit, + limits, + stop_token, + detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf8_to_utf16(std::string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u16string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf8_to_utf32(std::string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u32string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf16_to_utf8(std::u16string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 3) + ? (input.size() * 3) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf16_to_utf32(std::u16string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u32string out; + out.reserve(std::min(input.size(), limits.max_output_units)); + auto res = detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf32_to_utf8(std::u32string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 4) + ? (input.size() * 4) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +[[nodiscard]] inline std::expected + utf32_to_utf16(std::u32string_view input, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::u16string out; + const std::size_t est = + (input.size() <= limits.max_output_units / 2) + ? (input.size() * 2) + : limits.max_output_units; + out.reserve(est); + auto res = detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_string_sink(out, limits.max_output_units)); + if (!res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + return out; +} + +// ── Non-allocating into-span transcoders ───────────────────────────────────── + +[[nodiscard]] inline std::expected + utf8_to_utf16_into(std::string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf8_to_utf32_into(std::string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf8_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf16_to_utf8_into(std::u16string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf16_to_utf32_into(std::u16string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf16_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf32_to_utf8_into(std::u32string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +[[nodiscard]] inline std::expected + utf32_to_utf16_into(std::u32string_view input, + std::span out, + UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}, + std::stop_token stop_token = {}) +{ + std::size_t cursor = 0; + return detail::decode_utf32_each( + input, policy, limits, stop_token, detail::make_span_sink(out, cursor, limits.max_output_units)); +} + +// ── Streaming Decoders ─────────────────────────────────────────────────────── + +class Utf8StreamDecoder +{ +public: + explicit Utf8StreamDecoder(UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}) noexcept + : policy_(policy) + , limits_(limits) + { + } + + template + [[nodiscard]] std::expected + push(std::string_view chunk, + EmitFn&& on_scalar, + std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-8 decode cancelled"}}; + } + if (chunk.size() > limits_.max_input_units - total_read_) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + total_read_, + "Streaming UTF-8 input exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts chunk_counts{}; + std::size_t i = 0; + std::size_t steps = 0; + + auto emit_scalar = [&](Scalar s, bool replaced, std::size_t off) + -> std::expected { + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-8 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(s); + total_written_ += 1; + chunk_counts.scalars_decoded += 1; + chunk_counts.units_written += 1; + if (replaced) { + chunk_counts.replacements += 1; + } + return {}; + }; + + auto pop_front_pending = [&](std::size_t count) noexcept { + for (std::size_t k = count; k < pending_len_; ++k) { + pending_[k - count] = pending_[k]; + } + pending_len_ -= count; + }; + + // Drain any buffered partial prefix from previous chunks first. + while (pending_len_ > 0 && i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-8 decode cancelled"}}; + } + while (pending_len_ < 4 && i < chunk.size()) { + pending_[pending_len_++] = static_cast(chunk[i++]); + } + const auto st = detail::inspect_utf8( + std::span{pending_.data(), pending_len_}); + if (st.status == detail::StepStatus::ok) { + const std::size_t start_off = total_read_ + i - pending_len_; + if (auto r = emit_scalar(st.scalar, false, start_off); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(st.consumed); + // Any leftover bytes in pending_ were from chunk, not yet decoded; keep looping. + } else if (st.status == detail::StepStatus::incomplete) { + // Still need more bytes and chunk is exhausted. + break; + } else { + const std::size_t err_off = total_read_ + i - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + err_off, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, err_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(1); + } + } + + // If leftover validated-free bytes moved from chunk into pending_ still need decoding + // (e.g. a complete scalar was resolved inside pending_ and 1..3 bytes remain): + while (pending_len_ > 0 && i == chunk.size()) { + const auto st = detail::inspect_utf8( + std::span{pending_.data(), pending_len_}); + if (st.status == detail::StepStatus::ok) { + const std::size_t start_off = total_read_ + i - pending_len_; + if (auto r = emit_scalar(st.scalar, false, start_off); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(st.consumed); + } else if (st.status == detail::StepStatus::invalid) { + const std::size_t err_off = total_read_ + i - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + err_off, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, err_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + pop_front_pending(1); + } else { + break; + } + } + + // Process the remainder of `chunk` directly once pending_ is empty. + while (i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-8 decode cancelled"}}; + } + const std::size_t avail = std::min(4, chunk.size() - i); + std::array buf{}; + for (std::size_t k = 0; k < avail; ++k) { + buf[k] = static_cast(chunk[i + k]); + } + const auto st = detail::inspect_utf8(std::span{buf.data(), avail}); + if (st.status == detail::StepStatus::ok) { + if (auto r = emit_scalar(st.scalar, false, total_read_ + i); !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += st.consumed; + } else if (st.status == detail::StepStatus::incomplete) { + for (std::size_t k = 0; k < avail; ++k) { + pending_[pending_len_++] = buf[k]; + } + i += avail; + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf8, + total_read_ + i, + "Invalid UTF-8 sequence in stream"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + + total_read_ += chunk.size(); + chunk_counts.units_read = chunk.size(); + return chunk_counts; + } + + template + [[nodiscard]] std::expected + finish(EmitFn&& on_scalar, std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-8 finish cancelled"}}; + } + TranscodeCounts counts{}; + while (pending_len_ > 0) { + const std::size_t off = total_read_ - pending_len_; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + off, + "Truncated trailing UTF-8 bytes at end of stream"}}; + } + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-8 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(Scalar::replacement_character()); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += 1; + for (std::size_t k = 1; k < pending_len_; ++k) { + pending_[k - 1] = pending_[k]; + } + pending_len_ -= 1; + } + return counts; + } + + [[nodiscard]] bool has_pending() const noexcept { return pending_len_ > 0; } + [[nodiscard]] std::size_t bytes_read() const noexcept { return total_read_; } + + void reset() noexcept + { + pending_.fill(0); + pending_len_ = 0; + total_read_ = 0; + total_written_ = 0; + } + +private: + UtfPolicy policy_{UtfPolicy::reject}; + UtfLimits limits_{}; + std::array pending_{}; + std::size_t pending_len_{0}; + std::size_t total_read_{0}; + std::size_t total_written_{0}; +}; + +class Utf16StreamDecoder +{ +public: + explicit Utf16StreamDecoder(UtfPolicy policy = UtfPolicy::reject, + UtfLimits limits = {}) noexcept + : policy_(policy) + , limits_(limits) + { + } + + template + [[nodiscard]] std::expected + push(std::u16string_view chunk, + EmitFn&& on_scalar, + std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-16 decode cancelled"}}; + } + if (chunk.size() > limits_.max_input_units - total_read_) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + total_read_, + "Streaming UTF-16 input exceeds UtfLimits::max_input_units"}}; + } + + TranscodeCounts counts{}; + std::size_t i = 0; + std::size_t steps = 0; + + auto emit_scalar = [&](Scalar s, bool replaced, std::size_t off) + -> std::expected { + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-16 output exceeds UtfLimits::max_output_units"}}; + } + on_scalar(s); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.units_written += 1; + if (replaced) { + counts.replacements += 1; + } + return {}; + }; + + if (has_high_ && !chunk.empty()) { + const std::uint16_t u1 = static_cast(chunk[0]); + const std::size_t high_off = total_read_ - 1; + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(pending_high_ - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + has_high_ = false; + if (auto r = emit_scalar(*Scalar::from_code_point(cp), false, high_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i = 1; + } else { + has_high_ = false; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + high_off, + "Unpaired high surrogate across UTF-16 stream boundary"}}; + } + if (auto r = emit_scalar(Scalar::replacement_character(), true, high_off); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + } + } + + while (i < chunk.size()) { + if (!detail::check_cancel(stop_token, steps++, limits_, total_read_ + i)) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_ + i, + "Streaming UTF-16 decode cancelled"}}; + } + const std::uint16_t u0 = static_cast(chunk[i]); + if (u0 < 0xD800u || u0 > 0xDFFFu) { + if (auto r = emit_scalar(*Scalar::from_code_point(u0), false, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } else if (u0 <= 0xDBFFu) { + if (i + 1 >= chunk.size()) { + pending_high_ = u0; + has_high_ = true; + i += 1; + } else { + const std::uint16_t u1 = static_cast(chunk[i + 1]); + if (u1 >= 0xDC00u && u1 <= 0xDFFFu) { + const char32_t cp = + 0x10000u + + ((static_cast(u0 - 0xD800u) << 10) | + static_cast(u1 - 0xDC00u)); + if (auto r = emit_scalar(*Scalar::from_code_point(cp), false, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 2; + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + total_read_ + i, + "Unpaired high surrogate in UTF-16 stream"}}; + } + if (auto r = emit_scalar( + Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + } else { + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::invalid_utf16, + total_read_ + i, + "Unpaired low surrogate in UTF-16 stream"}}; + } + if (auto r = emit_scalar( + Scalar::replacement_character(), true, total_read_ + i); + !r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + i += 1; + } + } + + total_read_ += chunk.size(); + counts.units_read = chunk.size(); + return counts; + } + + template + [[nodiscard]] std::expected + finish(EmitFn&& on_scalar, std::stop_token stop_token = {}) + { + if (stop_token.stop_requested()) { + return std::unexpected{UtfError{ + UtfErrorKind::cancelled, + total_read_, + "Streaming UTF-16 finish cancelled"}}; + } + TranscodeCounts counts{}; + if (has_high_) { + const std::size_t off = total_read_ - 1; + if (policy_ == UtfPolicy::reject) { + return std::unexpected{UtfError{ + UtfErrorKind::truncated, + off, + "Trailing unpaired high surrogate at end of UTF-16 stream"}}; + } + if (total_written_ >= limits_.max_output_units) { + return std::unexpected{UtfError{ + UtfErrorKind::limit_exceeded, + off, + "Streaming UTF-16 output exceeds UtfLimits::max_output_units"}}; + } + has_high_ = false; + on_scalar(Scalar::replacement_character()); + total_written_ += 1; + counts.scalars_decoded += 1; + counts.replacements += 1; + counts.units_written += 1; + } + return counts; + } + + [[nodiscard]] bool has_pending() const noexcept { return has_high_; } + [[nodiscard]] std::size_t units_read() const noexcept { return total_read_; } + + void reset() noexcept + { + has_high_ = false; + pending_high_ = 0; + total_read_ = 0; + total_written_ = 0; + } + +private: + UtfPolicy policy_{UtfPolicy::reject}; + UtfLimits limits_{}; + std::uint16_t pending_high_{0}; + bool has_high_{false}; + std::size_t total_read_{0}; + std::size_t total_written_{0}; +}; + +} // namespace Void::Unicode \ No newline at end of file diff --git a/src/Unicode/MANIFEST.md b/src/Unicode/MANIFEST.md new file mode 100644 index 0000000..fbb7e9f --- /dev/null +++ b/src/Unicode/MANIFEST.md @@ -0,0 +1,11 @@ +# Void::Unicode Data & Specification Manifest + +- **Unicode Standard Version**: `17.0.0` +- **Official UCD Base URL**: `https://www.unicode.org/Public/17.0.0/ucd/` +- **Encoding & Scalar Specification**: Unicode Standard Section 3.9 (Forms & UTF-8/UTF-16/UTF-32 definitions D89-D92) +- **License**: Unicode License V3 (`Unicode-3.0`, https://www.unicode.org/license.txt) + +## Scope Notes +- `Void::Unicode` P1 implements Unicode `17.0.0` scalar value classification, UTF-8 / UTF-16 / UTF-32 strict validation, bounded transcoding (owning and non-allocating `std::span` destinations), one-unit repair (`U+FFFD`), and incremental streaming decoders. +- `Void::Text` remains intentionally Unicode-free (ASCII-only helpers in `M-TEXT-02`). +- Generated UCD character property tables (normalization, grapheme cluster segmentation, casefolding) belong to subsequent phases and will append table hashes here when introduced. \ No newline at end of file diff --git a/src/Unicode/module.cmake b/src/Unicode/module.cmake new file mode 100644 index 0000000..d39e426 --- /dev/null +++ b/src/Unicode/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Unicode + INTERNAL_DEPS Core Text +) \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 043dab8..2e86573 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -101,6 +101,11 @@ if(_has_algorithms) run_consumer(AlgorithmsOnly "${install_prefix}" "AlgorithmsOnly" ${_no_external_deps}) endif() +has_modules(_has_unicode Unicode Text Core) +if(_has_unicode) + run_consumer(UnicodeOnly "${install_prefix}" "UnicodeOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/UnicodeOnly/CMakeLists.txt b/tests/package/UnicodeOnly/CMakeLists.txt new file mode 100644 index 0000000..d5c4dd9 --- /dev/null +++ b/tests/package/UnicodeOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidUnicodeOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Unicode) + +add_executable(void_unicode_only_consumer main.cpp) +target_link_libraries(void_unicode_only_consumer PRIVATE Void::Unicode) + +enable_testing() +add_test(NAME VoidUnicodeOnlyConsumer COMMAND void_unicode_only_consumer) \ No newline at end of file diff --git a/tests/package/UnicodeOnly/main.cpp b/tests/package/UnicodeOnly/main.cpp new file mode 100644 index 0000000..44dbe62 --- /dev/null +++ b/tests/package/UnicodeOnly/main.cpp @@ -0,0 +1,16 @@ +#include + +#include + +int main() +{ + if (Void::Unicode::data_version() != std::string_view{"17.0.0"}) { + return 1; + } + const auto u16 = Void::Unicode::utf8_to_utf16("hi \xF0\x9F\x9A\x80"); + if (!u16.has_value()) { + return 1; + } + const auto u8 = Void::Unicode::utf16_to_utf8(*u16); + return (u8 && *u8 == "hi \xF0\x9F\x9A\x80") ? 0 : 1; +} \ No newline at end of file diff --git a/tests/standalone/Unicode/Utf.cpp b/tests/standalone/Unicode/Utf.cpp new file mode 100644 index 0000000..2758673 --- /dev/null +++ b/tests/standalone/Unicode/Utf.cpp @@ -0,0 +1,269 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +Void::Testing::Test utf_manifest_scalars_and_roundtrips() +{ + using Void::Unicode::Scalar; + using Void::Unicode::data_version; + using Void::Unicode::encode_utf16; + using Void::Unicode::encode_utf8; + using Void::Unicode::is_scalar_value; + using Void::Unicode::utf16_to_utf32; + using Void::Unicode::utf16_to_utf8; + using Void::Unicode::utf32_to_utf16; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_to_utf16; + using Void::Unicode::utf8_to_utf32; + using Void::Unicode::validate_utf16; + using Void::Unicode::validate_utf32; + using Void::Unicode::validate_utf8; + + Void::Testing::expect_eq(data_version(), std::string_view{"17.0.0"}); + + Void::Testing::expect(is_scalar_value(U'\0')); + Void::Testing::expect(is_scalar_value(U'A')); + Void::Testing::expect(is_scalar_value(U'\u00DF')); + Void::Testing::expect(is_scalar_value(U'\u20AC')); + Void::Testing::expect(is_scalar_value(U'\U0001F680')); + Void::Testing::expect(is_scalar_value(0x10FFFFu)); + Void::Testing::expect(!is_scalar_value(0xD800u)); + Void::Testing::expect(!is_scalar_value(0xDFFFu)); + Void::Testing::expect(!is_scalar_value(0x110000u)); + + Void::Testing::expect(Scalar::from_code_point(U'A').has_value()); + Void::Testing::expect(!Scalar::from_code_point(0xD800u).has_value()); + + // Roundtrip across 1-, 2-, 3-, and 4-byte scalars plus embedded NUL. + const std::string utf8_src{"A\0\xC3\x9F\xE2\x82\xAC\xF0\x9F\x9A\x80", 11}; + const auto v8 = validate_utf8(utf8_src); + Void::Testing::require(v8.has_value()); + Void::Testing::expect_eq(v8->scalars_decoded, std::size_t{5}); + Void::Testing::expect_eq(v8->replacements, std::size_t{0}); + + const auto u16 = utf8_to_utf16(utf8_src); + Void::Testing::require(u16.has_value()); + Void::Testing::expect_eq(u16->size(), std::size_t{6}); // 4 BMP + 2 surrogate pair + Void::Testing::expect(validate_utf16(*u16).has_value()); + + const auto u32 = utf16_to_utf32(*u16); + Void::Testing::require(u32.has_value()); + Void::Testing::expect_eq(u32->size(), std::size_t{5}); + Void::Testing::expect((*u32)[4] == 0x1F680u); + Void::Testing::expect(validate_utf32(*u32).has_value()); + + const auto back_u8_from_32 = utf32_to_utf8(*u32); + Void::Testing::require(back_u8_from_32.has_value()); + Void::Testing::expect(*back_u8_from_32 == utf8_src); + + const auto back_u8_from_16 = utf16_to_utf8(*u16); + Void::Testing::require(back_u8_from_16.has_value()); + Void::Testing::expect(*back_u8_from_16 == utf8_src); + + const auto back_u16_from_32 = utf32_to_utf16(*u32); + Void::Testing::require(back_u16_from_32.has_value()); + Void::Testing::expect(*back_u16_from_32 == *u16); + + const auto direct_u32 = utf8_to_utf32(utf8_src); + Void::Testing::require(direct_u32.has_value()); + Void::Testing::expect(*direct_u32 == *u32); + + // Encode single scalar into small buffer checks + const auto rocket = *Scalar::from_code_point(0x1F680u); + std::array too_small_8{}; + Void::Testing::expect(!encode_utf8(rocket, too_small_8).has_value()); + std::array exact_8{}; + const auto enc8 = encode_utf8(rocket, exact_8); + Void::Testing::require(enc8.has_value()); + Void::Testing::expect_eq(*enc8, std::size_t{4}); + + std::array too_small_16{}; + Void::Testing::expect(!encode_utf16(rocket, too_small_16).has_value()); + std::array exact_16{}; + const auto enc16 = encode_utf16(rocket, exact_16); + Void::Testing::require(enc16.has_value()); + Void::Testing::expect_eq(*enc16, std::size_t{2}); +} + +Void::Testing::Test utf_strict_rejects_all_malformed_classes() +{ + using Void::Unicode::UtfErrorKind; + using Void::Unicode::utf16_to_utf8; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_to_utf32; + using Void::Unicode::validate_utf16; + using Void::Unicode::validate_utf32; + using Void::Unicode::validate_utf8; + + // Overlong 2-, 3-, and 4-byte UTF-8 encodings + Void::Testing::expect(validate_utf8("\xC0\xAF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xC1\xBF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xE0\x80\xAF").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xF0\x80\x80\xAF").error().kind == UtfErrorKind::invalid_utf8); + + // UTF-8 encoded surrogates (U+D800, U+DFFF) + Void::Testing::expect(validate_utf8("\xED\xA0\x80").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xED\xBF\xBF").error().kind == UtfErrorKind::invalid_utf8); + + // Out-of-range UTF-8 (> U+10FFFF) + Void::Testing::expect(validate_utf8("\xF4\x90\x80\x80").error().kind == UtfErrorKind::invalid_utf8); + Void::Testing::expect(validate_utf8("\xF5\x80\x80\x80").error().kind == UtfErrorKind::invalid_utf8); + + // Unexpected continuation byte and truncated tail + Void::Testing::expect(validate_utf8("ab\x80").error().unit_offset == std::size_t{2}); + const auto trunc8 = utf8_to_utf32("ok\xE2\x82"); + Void::Testing::expect(!trunc8.has_value()); + Void::Testing::expect(trunc8.error().kind == UtfErrorKind::truncated); + Void::Testing::expect_eq(trunc8.error().unit_offset, std::size_t{2}); + + // UTF-16 unpaired high/low surrogates and truncation + const std::u16string unpaired_high{u'a', char16_t{0xD800}, u'b'}; + const auto err16_hi = utf16_to_utf8(unpaired_high); + Void::Testing::expect(!err16_hi.has_value()); + Void::Testing::expect(err16_hi.error().kind == UtfErrorKind::invalid_utf16); + Void::Testing::expect_eq(err16_hi.error().unit_offset, std::size_t{1}); + + const std::u16string unpaired_low{char16_t{0xDC00}, u'z'}; + Void::Testing::expect(validate_utf16(unpaired_low).error().kind == UtfErrorKind::invalid_utf16); + + const std::u16string trunc16{u'a', char16_t{0xD83D}}; + Void::Testing::expect(validate_utf16(trunc16).error().kind == UtfErrorKind::truncated); + + // UTF-32 surrogates and > 0x10FFFF + const std::u32string sur32{U'a', char32_t{0xD800}}; + Void::Testing::expect(validate_utf32(sur32).error().kind == UtfErrorKind::invalid_scalar); + const std::u32string big32{char32_t{0x110000}}; + Void::Testing::expect(utf32_to_utf8(big32).error().kind == UtfErrorKind::invalid_scalar); +} + +Void::Testing::Test utf_one_unit_repair_and_into_span_limits() +{ + using Void::Unicode::UtfErrorKind; + using Void::Unicode::UtfLimits; + using Void::Unicode::UtfPolicy; + using Void::Unicode::utf16_to_utf32; + using Void::Unicode::utf32_to_utf8; + using Void::Unicode::utf8_repair; + using Void::Unicode::utf8_to_utf16_into; + using Void::Unicode::utf8_to_utf32; + + // Invalid lead byte followed by valid ASCII preserves ASCII cleanly. + const auto rep_ascii = utf8_to_utf32("a\xFF" "b\xE2\x82" "c", UtfPolicy::replace_one_unit); + Void::Testing::require(rep_ascii.has_value()); + const std::u32string expected_rep{U'a', U'\uFFFD', U'b', U'\uFFFD', U'\uFFFD', U'c'}; + Void::Testing::expect(*rep_ascii == expected_rep); + + const auto repaired_u8 = utf8_repair("ok\x80!"); + Void::Testing::require(repaired_u8.has_value()); + Void::Testing::expect(*repaired_u8 == std::string{"ok\xEF\xBF\xBD!"}); + + // UTF-16 repair: lone low, lone high, valid surrogate pair + const std::u16string bad16{ + char16_t{0xDC00}, + char16_t{0xD800}, + u'Z', + char16_t{0xD83D}, + char16_t{0xDE80}, + }; + const auto rep16 = utf16_to_utf32(bad16, UtfPolicy::replace_one_unit); + Void::Testing::require(rep16.has_value()); + const std::u32string exp16{U'\uFFFD', U'\uFFFD', U'Z', U'\U0001F680'}; + Void::Testing::expect(*rep16 == exp16); + + // UTF-32 repair + const auto rep32 = utf32_to_utf8( + std::u32string_view{U"X"} , UtfPolicy::replace_one_unit); + Void::Testing::require(rep32.has_value()); + const std::u32string invalid32{U'X', char32_t{0xD801}, char32_t{0x200000}, U'Y'}; + const auto rep32_bad = utf32_to_utf8(invalid32, UtfPolicy::replace_one_unit); + Void::Testing::require(rep32_bad.has_value()); + Void::Testing::expect(*rep32_bad == std::string{"X\xEF\xBF\xBD\xEF\xBF\xBDY"}); + + // Non-allocating _into transcoding + output_too_small + input/output limits + cancellation + std::array buf16{}; + const auto fit = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{buf16}); + Void::Testing::require(fit.has_value()); + Void::Testing::expect_eq(fit->units_written, std::size_t{3}); + Void::Testing::expect_eq(fit->scalars_decoded, std::size_t{2}); + + std::array small16{}; + const auto too_small = utf8_to_utf16_into("A\xF0\x9F\x9A\x80", std::span{small16}); + Void::Testing::expect(!too_small.has_value()); + Void::Testing::expect(too_small.error().kind == UtfErrorKind::output_too_small); + + const auto lim_in = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_input_units = 4}); + Void::Testing::expect(lim_in.error().kind == UtfErrorKind::limit_exceeded); + + const auto lim_out = utf8_to_utf32("abcdef", UtfPolicy::reject, UtfLimits{.max_output_units = 3}); + Void::Testing::expect(lim_out.error().kind == UtfErrorKind::limit_exceeded); + + std::stop_source ssrc; + ssrc.request_stop(); + const auto cancelled = utf8_to_utf32("abc", UtfPolicy::reject, UtfLimits{}, ssrc.get_token()); + Void::Testing::expect(cancelled.error().kind == UtfErrorKind::cancelled); +} + +Void::Testing::Test utf_streaming_decoders_arbitrary_splits() +{ + using Void::Unicode::Scalar; + using Void::Unicode::Utf16StreamDecoder; + using Void::Unicode::Utf8StreamDecoder; + using Void::Unicode::UtfErrorKind; + using Void::Unicode::UtfPolicy; + using Void::Unicode::utf8_to_utf32; + + // 1-byte chunks across 1-, 2-, 3-, 4-byte UTF-8 and invalid bytes under repair + const std::string sample{"H\xC3\xA9\xE2\x82\xAC\xF0\x9F\x9A\x80!\xE2\x82" "X\xED\xA0\x80", 17}; + const auto expected_oneshot = utf8_to_utf32(sample, UtfPolicy::replace_one_unit); + Void::Testing::require(expected_oneshot.has_value()); + + Utf8StreamDecoder dec{UtfPolicy::replace_one_unit}; + std::u32string streamed; + for (std::size_t i = 0; i < sample.size(); ++i) { + const auto res = dec.push( + std::string_view{sample.data() + i, 1}, + [&](Scalar s) { streamed.push_back(s.code_point()); }); + Void::Testing::require(res.has_value()); + } + const auto fin = dec.finish([&](Scalar s) { streamed.push_back(s.code_point()); }); + Void::Testing::require(fin.has_value()); + Void::Testing::expect(!dec.has_pending()); + Void::Testing::expect(streamed == *expected_oneshot); + + // Strict UTF-8 streaming rejects truncated sequence at finish() + Utf8StreamDecoder strict_dec{UtfPolicy::reject}; + std::u32string tmp; + Void::Testing::require(strict_dec.push("\xE2\x82", [&](Scalar s) { tmp.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(strict_dec.has_pending()); + const auto trunc_fin = strict_dec.finish([&](Scalar s) { tmp.push_back(s.code_point()); }); + Void::Testing::expect(!trunc_fin.has_value()); + Void::Testing::expect(trunc_fin.error().kind == UtfErrorKind::truncated); + + // UTF-16 split surrogate pair across chunk boundary + Utf16StreamDecoder u16_dec{UtfPolicy::reject}; + std::u32string out16; + Void::Testing::require( + u16_dec.push(std::u16string_view{u"A\xD83D", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(u16_dec.has_pending()); + Void::Testing::require( + u16_dec.push(std::u16string_view{u"\xDE80Z", 2}, [&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(!u16_dec.has_pending()); + Void::Testing::require(u16_dec.finish([&](Scalar s) { out16.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(out16 == std::u32string{U'A', U'\U0001F680', U'Z'}); + + // UTF-16 repair with trailing high surrogate at EOF + Utf16StreamDecoder u16_rep{UtfPolicy::replace_one_unit}; + std::u32string out16_rep; + const std::u16string part1{char16_t{0xD800}}; + const std::u16string part2{u'B', char16_t{0xD83D}}; + Void::Testing::require(u16_rep.push(part1, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::require(u16_rep.push(part2, [&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::require(u16_rep.finish([&](Scalar s) { out16_rep.push_back(s.code_point()); }).has_value()); + Void::Testing::expect(out16_rep == std::u32string{U'\uFFFD', U'B', U'\uFFFD'}); +} \ No newline at end of file