From b3a762e66819c67be9cdd80de6fa95663e0a90c9 Mon Sep 17 00:00:00 2001 From: Diego Migotto Date: Fri, 30 Oct 2026 19:07:33 -0300 Subject: [PATCH] release: entity-generator 4.2.3 on dasmig-core 1.4.0 Vendors dasmig-core 1.4.0, which adds check digits, identifier patterns, money and time-zone rules in four new headers. Nothing this library uses changed, so its output and known answers are unchanged. The release lets this library share a translation unit with country-generator 3.3.0 and the libraries after it, which require core 1.4. Co-Authored-By: Claude Opus 5.5 --- Doxyfile | 2 +- README.md | 2 +- dasmig/core.hpp | 7 +- dasmig/core/check_digits.hpp | 546 ++++++++++++++++++++++++ dasmig/core/money.hpp | 181 ++++++++ dasmig/core/pattern.hpp | 592 ++++++++++++++++++++++++++ dasmig/core/tz.hpp | 783 +++++++++++++++++++++++++++++++++++ dasmig/core/version.hpp | 2 +- 8 files changed, 2111 insertions(+), 4 deletions(-) create mode 100644 dasmig/core/check_digits.hpp create mode 100644 dasmig/core/money.hpp create mode 100644 dasmig/core/pattern.hpp create mode 100644 dasmig/core/tz.hpp diff --git a/Doxyfile b/Doxyfile index 0a6ebb3..be06d37 100644 --- a/Doxyfile +++ b/Doxyfile @@ -2,7 +2,7 @@ # Run: doxygen Doxyfile PROJECT_NAME = "Entity Generator" -PROJECT_NUMBER = 4.2.2 +PROJECT_NUMBER = 4.2.3 PROJECT_BRIEF = "Composable, deterministic entity generation for C++23" PROJECT_LOGO = doc/entity-generator.png diff --git a/README.md b/README.md index eaedc3a..12df23d 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ Tested with: | Dependency | Version | Bundled | Purpose | |-----------|---------|---------|---------| -| [dasmig-core](https://github.com/dasmig/dasmig-core) | 1.3 | Yes (`core.hpp`, `core/`) | Platform-independent random engine and distributions, JSON | +| [dasmig-core](https://github.com/dasmig/dasmig-core) | 1.4 | Yes (`core.hpp`, `core/`) | Platform-independent random engine and distributions, JSON | | [Catch2](https://github.com/catchorg/Catch2) | 3.x | Yes (amalgamated) | Unit testing | | [EnTT](https://github.com/skypjack/entt), [Flecs](https://github.com/SanderMertens/flecs) | - | No | Only for the optional adapter headers in `dasmig/ext/` | diff --git a/dasmig/core.hpp b/dasmig/core.hpp index cfdfefe..cc3d610 100644 --- a/dasmig/core.hpp +++ b/dasmig/core.hpp @@ -6,7 +6,8 @@ /// @file core.hpp /// @brief dasmig-core: the shared foundation of the dasmig generator -/// libraries (random engine, distributions, data tables, JSON). +/// libraries (random engine, distributions, data tables, JSON, check +/// digits, patterns, money and time-zone rules). /// @author Diego Dasso Migotto (diegomigotto at hotmail dot com) /// @see See doc/usage.md for the narrative tutorial. /// @@ -16,11 +17,14 @@ #include "core/version.hpp" #include "core/batch.hpp" +#include "core/check_digits.hpp" #include "core/country.hpp" #include "core/dataset.hpp" #include "core/distributions.hpp" #include "core/json.hpp" #include "core/math.hpp" +#include "core/money.hpp" +#include "core/pattern.hpp" #include "core/resources.hpp" #include "core/rng.hpp" #include "core/seed_signature.hpp" @@ -28,6 +32,7 @@ #include "core/sinks.hpp" #include "core/table.hpp" #include "core/tsv.hpp" +#include "core/tz.hpp" #include "core/utf8.hpp" #include "core/weighted_table.hpp" diff --git a/dasmig/core/check_digits.hpp b/dasmig/core/check_digits.hpp new file mode 100644 index 0000000..f64998e --- /dev/null +++ b/dasmig/core/check_digits.hpp @@ -0,0 +1,546 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2020-2026 Diego Dasso Migotto + +#ifndef DASMIG_CORE_CHECK_DIGITS_HPP +#define DASMIG_CORE_CHECK_DIGITS_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +/// @file check_digits.hpp +/// @brief Check-digit schemes used by identifiers: Luhn, ISO 7064 (MOD 97-10, +/// MOD 11-2, MOD 11,10), IBAN, weighted sums, GTIN, ICAO 9303 and +/// Verhoeff. +/// @author Diego Dasso Migotto (diegomigotto at hotmail dot com) +/// +/// Inputs are the electronic form: no spaces, dashes or dots. A library that +/// shows a grouped form groups after computing. The `*_digit` functions throw +/// `std::invalid_argument` for an empty or malformed body, naming the function +/// and the 0-based position (`luhn_digit: position 3: '-' is not a digit`); +/// the `*_valid` functions never throw, and malformed input is simply not +/// valid. Nothing here allocates except to build an error message, and every +/// function can run at compile time. +/// +/// The national mod-11 rules (Brazil's CPF, the UK's NHS number and others) +/// reduce a weighted sum each in their own way, so they stay in the libraries, +/// built on weighted_sum(). + +namespace dasmig::core +{ + +/// @cond INTERNAL +namespace detail +{ + +[[nodiscard]] constexpr bool is_digit(char c) noexcept { return c >= '0' && c <= '9'; } +[[nodiscard]] constexpr bool is_capital(char c) noexcept { return c >= 'A' && c <= 'Z'; } +[[nodiscard]] constexpr bool is_digit_or_capital(char c) noexcept +{ + return is_digit(c) || is_capital(c); +} + +[[nodiscard]] constexpr bool all_digits(std::string_view s) noexcept +{ + return std::ranges::all_of(s, is_digit); +} + +[[nodiscard]] constexpr bool all_digits_or_capitals(std::string_view s) noexcept +{ + return std::ranges::all_of(s, is_digit_or_capital); +} + +// "'-'" for a printable ASCII character, "byte 0x80" for anything else. +[[nodiscard]] inline std::string describe_char(char c) +{ + const auto b = static_cast(c); + if (b >= 0x20U && b <= 0x7EU) return std::string{'\''} + c + '\''; + constexpr std::string_view hex = "0123456789ABCDEF"; + return std::string{"byte 0x"} + hex[b >> 4U] + hex[b & 0x0FU]; +} + +// ": position : is not ". +[[noreturn]] inline void throw_bad_char(std::string_view function, std::size_t position, + char c, std::string_view expected) +{ + throw std::invalid_argument(std::string{function} + ": position " + + std::to_string(position) + ": " + describe_char(c) + + " is not " + std::string{expected}); +} + +[[noreturn]] inline void throw_empty(std::string_view function) +{ + throw std::invalid_argument(std::string{function} + ": empty input"); +} + +[[noreturn]] inline void throw_at(std::string_view function, std::size_t position, + const std::exception& e) +{ + throw std::invalid_argument(std::string{function} + ": position " + + std::to_string(position) + ": " + e.what()); +} + +// The digit at s[i], or an error naming the function and the position. +[[nodiscard]] constexpr unsigned digit_at(std::string_view function, std::string_view s, // NOLINT(bugprone-easily-swappable-parameters) + std::size_t i) +{ + if (!is_digit(s[i])) throw_bad_char(function, i, s[i], "a digit"); + return static_cast(s[i] - '0'); +} + +// '0'-'9' as 0-9 and 'A'-'Z' as 10-35 at s[i], or an error. +[[nodiscard]] constexpr unsigned alnum_at(std::string_view function, std::string_view s, // NOLINT(bugprone-easily-swappable-parameters) + std::size_t i) +{ + const char c = s[i]; + if (is_digit(c)) return static_cast(c - '0'); + if (is_capital(c)) return static_cast(c - 'A') + 10U; + throw_bad_char(function, i, c, "a digit or capital letter"); +} + +// One character value into an ISO 7064 MOD 97-10 remainder: a value of 10 or +// more is two decimal digits, as ISO 13616 writes letters. +[[nodiscard]] constexpr unsigned mod97_feed(unsigned r, unsigned value) noexcept +{ + if (value >= 10U) r = ((r * 10U) + (value / 10U)) % 97U; + return ((r * 10U) + (value % 10U)) % 97U; +} + +// The remainder after feeding every character of s (digits and capitals only). +[[nodiscard]] constexpr unsigned mod97_run(unsigned r, std::string_view function, + std::string_view s) +{ + for (std::size_t i = 0; i < s.size(); ++i) + { + r = mod97_feed(r, alnum_at(function, s, i)); + } + return r; +} + +[[nodiscard]] constexpr std::array mod97_check(unsigned r) noexcept +{ + r = (r * 100U) % 97U; // the two placeholder check digits, both 0 + const unsigned c = 98U - r; + return {static_cast('0' + (c / 10U)), static_cast('0' + (c % 10U))}; +} + +// Verhoeff (1969): multiplication in the dihedral group D5, the position +// permutation and the inverse. +inline constexpr std::array, 10> verhoeff_d{{ + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, + {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, + {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, + {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, + {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, + {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, + {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, + {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, + {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, +}}; +inline constexpr std::array, 8> verhoeff_p{{ + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, + {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, + {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, + {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, + {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, + {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, + {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, +}}; +inline constexpr std::array verhoeff_inv{0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; + +} // namespace detail +/// @endcond + +// --- Character values --------------------------------------------------------- + +/// @brief The value of a decimal digit. +/// @param c `'0'` to `'9'`. +/// @return 0 to 9. +/// @throws std::invalid_argument For any other character. +[[nodiscard]] constexpr unsigned digit_value(char c) +{ + if (!detail::is_digit(c)) + { + throw std::invalid_argument("digit_value: " + detail::describe_char(c) + + " is not a digit"); + } + return static_cast(c - '0'); +} + +/// @brief The value of a digit or capital letter, as ISO 7064 counts them. +/// @param c `'0'` to `'9'` (0 to 9) or `'A'` to `'Z'` (10 to 35). +/// @return 0 to 35. +/// @throws std::invalid_argument For any other character, lower case included. +[[nodiscard]] constexpr unsigned alnum_value(char c) +{ + if (detail::is_digit(c)) return static_cast(c - '0'); + if (detail::is_capital(c)) return static_cast(c - 'A') + 10U; + throw std::invalid_argument("alnum_value: " + detail::describe_char(c) + + " is not a digit or capital letter"); +} + +// --- Luhn (ISO/IEC 7812-1 Annex B) ---------------------------------------------- + +/// @brief The Luhn check digit of a body of digits. +/// +/// Over the digits from the right, with i = 0 for the rightmost: the digit, +/// doubled when i is even, minus 9 when the double exceeds 9, summed. The +/// check digit is `(10 - sum mod 10) mod 10`. +/// +/// @param body Digits, without the check digit. +/// @return `'0'` to `'9'`. +/// @throws std::invalid_argument If @p body is empty or holds a non-digit. +[[nodiscard]] constexpr char luhn_digit(std::string_view body) +{ + if (body.empty()) detail::throw_empty("luhn_digit"); + unsigned sum = 0; + for (std::size_t k = 0; k < body.size(); ++k) + { + unsigned v = detail::digit_at("luhn_digit", body, body.size() - 1 - k); + if (k % 2 == 0) + { + v *= 2; + if (v > 9) v -= 9; + } + sum += v; + } + return static_cast('0' + ((10U - (sum % 10U)) % 10U)); +} + +/// @brief Whether a value ends in its Luhn check digit. +/// @param full Body and check digit. +/// @return True for at least two digits whose last is the body's Luhn digit. +[[nodiscard]] constexpr bool luhn_valid(std::string_view full) noexcept +{ + if (full.size() < 2 || !detail::all_digits(full)) return false; + return luhn_digit(full.substr(0, full.size() - 1)) == full.back(); +} + +// --- ISO 7064 MOD 97-10 and IBAN (ISO 13616) ---------------------------------------- + +/// @brief The two ISO 7064 MOD 97-10 check digits of a body. +/// +/// Each character's value (digits as themselves, A to Z as 10 to 35) is +/// written in decimal and fed into `r = (r * 10 + digit) mod 97`, then two +/// placeholder zeros; the check digits are `98 - r`, from `02` to `98`. +/// +/// @param body Digits and capital letters, without the check digits. +/// @return The two check digits. +/// @throws std::invalid_argument If @p body is empty or holds another character. +[[nodiscard]] constexpr std::array mod97_10_digits(std::string_view body) +{ + if (body.empty()) detail::throw_empty("mod97_10_digits"); + return detail::mod97_check(detail::mod97_run(0, "mod97_10_digits", body)); +} + +/// @brief Whether a value ends in its two ISO 7064 MOD 97-10 check digits. +/// @param full Body followed by the two check digits. +/// @return True when the whole value, fed as in mod97_10_digits(), leaves 1. +[[nodiscard]] constexpr bool mod97_10_valid(std::string_view full) noexcept +{ + if (full.size() < 3 || !detail::all_digits_or_capitals(full) || + !detail::all_digits(full.substr(full.size() - 2))) + { + return false; + } + return detail::mod97_run(0, "mod97_10_valid", full) == 1; +} + +/// @brief The two IBAN check digits for a country and a BBAN. +/// +/// `mod97_10_digits(bban + country)`: ISO 13616 moves the country code and +/// the check digits to the end, and the check digits are the placeholders. +/// +/// @param country ISO 3166-1 alpha-2 code, two capital letters. +/// @param bban Basic bank account number: digits and capital letters. +/// @return The two check digits that follow the country code. +/// @throws std::invalid_argument If @p country is not two capital letters, or +/// @p bban is empty or holds another character. +[[nodiscard]] constexpr std::array iban_check_digits(std::string_view country, // NOLINT(bugprone-easily-swappable-parameters) + std::string_view bban) +{ + if (country.size() != 2) + { + throw std::invalid_argument("iban_check_digits: country must be two capital letters"); + } + for (std::size_t i = 0; i < 2; ++i) + { + if (!detail::is_capital(country[i])) + { + detail::throw_bad_char("iban_check_digits: country", i, country[i], "a capital letter"); + } + } + if (bban.empty()) detail::throw_empty("iban_check_digits"); + const unsigned r = detail::mod97_run(0, "iban_check_digits: bban", bban); + return detail::mod97_check(detail::mod97_run(r, "iban_check_digits: country", country)); +} + +/// @brief Whether an IBAN's check digits are right. +/// +/// Checks the electronic form (no spaces): 15 to 34 characters, two capital +/// letters, two digits, then digits and capital letters, and MOD 97-10 over +/// the BBAN followed by the first four characters. The length each country +/// requires is data, and is not checked here. +/// +/// @param iban The IBAN. +/// @return True when the shape and the check digits are right. +[[nodiscard]] constexpr bool iban_valid(std::string_view iban) noexcept +{ + if (iban.size() < 15 || iban.size() > 34 || !detail::is_capital(iban[0]) || + !detail::is_capital(iban[1]) || !detail::is_digit(iban[2]) || + !detail::is_digit(iban[3]) || !detail::all_digits_or_capitals(iban.substr(4))) + { + return false; + } + const unsigned r = detail::mod97_run(0, "iban_valid", iban.substr(4)); + return detail::mod97_run(r, "iban_valid", iban.substr(0, 4)) == 1; +} + +// --- ISO 7064 MOD 11-2 and MOD 11,10 ---------------------------------------------- + +/// @brief The ISO 7064 MOD 11-2 check character of a body of digits. +/// +/// The pure system: `p = ((p + digit) * 2) mod 11` from p = 0, then +/// `c = (12 - p) mod 11`, written `X` when 10. +/// +/// @param body Digits, without the check character. +/// @return `'0'` to `'9'` or `'X'`. +/// @throws std::invalid_argument If @p body is empty or holds a non-digit. +[[nodiscard]] constexpr char mod11_2_digit(std::string_view body) +{ + if (body.empty()) detail::throw_empty("mod11_2_digit"); + unsigned p = 0; + for (std::size_t i = 0; i < body.size(); ++i) + { + p = ((p + detail::digit_at("mod11_2_digit", body, i)) * 2U) % 11U; + } + const unsigned c = (12U - p) % 11U; + return c == 10U ? 'X' : static_cast('0' + c); +} + +/// @brief Whether a value ends in its ISO 7064 MOD 11-2 check character. +/// @param full Digits followed by the check character (a digit or `X`). +/// @return True when the check character is right. +[[nodiscard]] constexpr bool mod11_2_valid(std::string_view full) noexcept +{ + if (full.size() < 2) return false; + const std::string_view body = full.substr(0, full.size() - 1); + if (!detail::all_digits(body) || (!detail::is_digit(full.back()) && full.back() != 'X')) + { + return false; + } + return mod11_2_digit(body) == full.back(); +} + +/// @brief The ISO 7064 MOD 11,10 check digit of a body of digits. +/// +/// The hybrid system: from p = 10, for each digit `s = (p + digit) mod 10` +/// (10 when 0) and `p = (2 * s) mod 11`; the check digit is `(11 - p) mod 10`. +/// +/// @param body Digits, without the check digit. +/// @return `'0'` to `'9'`. +/// @throws std::invalid_argument If @p body is empty or holds a non-digit. +[[nodiscard]] constexpr char mod11_10_digit(std::string_view body) +{ + if (body.empty()) detail::throw_empty("mod11_10_digit"); + unsigned p = 10; + for (std::size_t i = 0; i < body.size(); ++i) + { + unsigned s = (p + detail::digit_at("mod11_10_digit", body, i)) % 10U; + if (s == 0) s = 10; + p = (2U * s) % 11U; + } + return static_cast('0' + ((11U - p) % 10U)); +} + +/// @brief Whether a value ends in its ISO 7064 MOD 11,10 check digit. +/// @param full Body and check digit. +/// @return True when the check digit is right. +[[nodiscard]] constexpr bool mod11_10_valid(std::string_view full) noexcept +{ + if (full.size() < 2 || !detail::all_digits(full)) return false; + return mod11_10_digit(full.substr(0, full.size() - 1)) == full.back(); +} + +// --- Weighted sums ------------------------------------------------------------------ + +/// @brief The weighted sum the national mod-11 rules (and others) start from. +/// +/// `sum of value_of(body[i]) * weights[i mod weights.size()]`, left to right, +/// in 64-bit unsigned arithmetic. The caller reduces it and maps the +/// remainder, as its rule says. +/// +/// @code +/// // Brazil's CPF: weights 10 to 2, digit 0 when the remainder is below 2. +/// constexpr std::array w{10, 9, 8, 7, 6, 5, 4, 3, 2}; +/// const auto r = core::weighted_sum("111444777", w) % 11; // 8 +/// const char first = static_cast('0' + (r < 2 ? 0 : 11 - r)); // '3' +/// @endcode +/// +/// @tparam ValueOf Callable from char to an unsigned value. +/// @param body Characters to sum; may be empty (the sum is then 0). +/// @param weights Weights, repeated from the left when shorter than @p body. +/// @param value_of Character value; digit_value() by default. +/// @return The sum. +/// @throws std::invalid_argument If @p weights is empty, or @p value_of throws +/// it for a character (the message then names the position). +template +[[nodiscard]] constexpr std::uint64_t weighted_sum(std::string_view body, + std::span weights, + ValueOf value_of = &digit_value) +{ + if (weights.empty()) + { + throw std::invalid_argument("weighted_sum: no weights"); + } + std::uint64_t sum = 0; + for (std::size_t i = 0; i < body.size(); ++i) + { + std::uint64_t v = 0; + try + { + v = value_of(body[i]); + } + catch (const std::invalid_argument& e) + { + detail::throw_at("weighted_sum", i, e); + } + sum += v * weights[i % weights.size()]; + } + return sum; +} + +// --- GTIN (GS1) ----------------------------------------------------------------------- + +/// @brief The GS1 check digit (GTIN-8, -12, -13, -14, SSCC, ISBN-13). +/// +/// From the right, with i = 0 for the rightmost body digit: weight 3 when i is +/// even, else 1. The check digit is `(10 - sum mod 10) mod 10`. Any length. +/// +/// @param body Digits, without the check digit. +/// @return `'0'` to `'9'`. +/// @throws std::invalid_argument If @p body is empty or holds a non-digit. +[[nodiscard]] constexpr char gtin_digit(std::string_view body) +{ + if (body.empty()) detail::throw_empty("gtin_digit"); + unsigned sum = 0; + for (std::size_t k = 0; k < body.size(); ++k) + { + const unsigned d = detail::digit_at("gtin_digit", body, body.size() - 1 - k); + sum += k % 2 == 0 ? 3U * d : d; + } + return static_cast('0' + ((10U - (sum % 10U)) % 10U)); +} + +/// @brief Whether a value ends in its GS1 check digit. +/// @param full Body and check digit. +/// @return True when the check digit is right. +[[nodiscard]] constexpr bool gtin_valid(std::string_view full) noexcept +{ + if (full.size() < 2 || !detail::all_digits(full)) return false; + return gtin_digit(full.substr(0, full.size() - 1)) == full.back(); +} + +// --- ICAO Doc 9303 machine-readable zones ------------------------------------------------ + +/// @brief The check digit of a field of an ICAO 9303 machine-readable zone. +/// +/// Weights 7, 3, 1 repeating from the left; `<` counts 0, digits as +/// themselves, A to Z as 10 to 35. The check digit is `sum mod 10`. +/// +/// @param field Digits, capital letters and `<`. +/// @return `'0'` to `'9'`. +/// @throws std::invalid_argument If @p field is empty or holds another character. +[[nodiscard]] constexpr char icao9303_digit(std::string_view field) +{ + if (field.empty()) detail::throw_empty("icao9303_digit"); + constexpr std::array weights{7, 3, 1}; + unsigned sum = 0; + for (std::size_t i = 0; i < field.size(); ++i) + { + const char c = field[i]; + unsigned v = 0; // '<' + if (detail::is_digit(c)) + { + v = static_cast(c - '0'); + } + else if (detail::is_capital(c)) + { + v = static_cast(c - 'A') + 10U; + } + else if (c != '<') + { + detail::throw_bad_char("icao9303_digit", i, c, "a digit, capital letter or '<'"); + } + sum += v * weights.at(i % 3); + } + return static_cast('0' + (sum % 10U)); +} + +/// @brief Whether an ICAO 9303 field ends in its check digit. +/// @param field_and_digit The field followed by its check digit. +/// @return True when the check digit is right. +[[nodiscard]] constexpr bool icao9303_valid(std::string_view field_and_digit) noexcept +{ + if (field_and_digit.size() < 2 || !detail::is_digit(field_and_digit.back())) return false; + const std::string_view field = field_and_digit.substr(0, field_and_digit.size() - 1); + for (const char c : field) + { + if (!detail::is_digit_or_capital(c) && c != '<') return false; + } + return icao9303_digit(field) == field_and_digit.back(); +} + +// --- Verhoeff --------------------------------------------------------------------------- + +/// @brief The Verhoeff check digit of a body of digits. +/// +/// With the dihedral multiplication table d, the permutation table p and the +/// inverse table inv published by Verhoeff (1969): c = 0; for the digits from +/// the right, with i = 0 for the rightmost, `c = d[c][p[(i + 1) mod 8][digit]]`; +/// the check digit is `inv[c]`. +/// +/// @param body Digits, without the check digit. +/// @return `'0'` to `'9'`. +/// @throws std::invalid_argument If @p body is empty or holds a non-digit. +[[nodiscard]] constexpr char verhoeff_digit(std::string_view body) +{ + if (body.empty()) detail::throw_empty("verhoeff_digit"); + std::uint8_t c = 0; + for (std::size_t k = 0; k < body.size(); ++k) + { + const unsigned d = detail::digit_at("verhoeff_digit", body, body.size() - 1 - k); + c = detail::verhoeff_d.at(c).at(detail::verhoeff_p.at((k + 1) % 8).at(d)); + } + return static_cast('0' + detail::verhoeff_inv.at(c)); +} + +/// @brief Whether a value ends in its Verhoeff check digit. +/// +/// Runs from the right over the whole value with `p[i mod 8]`; valid when +/// the result is 0. +/// +/// @param full Body and check digit. +/// @return True when the check digit is right. +[[nodiscard]] constexpr bool verhoeff_valid(std::string_view full) noexcept +{ + if (full.size() < 2 || !detail::all_digits(full)) return false; + std::uint8_t c = 0; + for (std::size_t k = 0; k < full.size(); ++k) + { + const auto d = static_cast(full[full.size() - 1 - k] - '0'); + c = detail::verhoeff_d.at(c).at(detail::verhoeff_p.at(k % 8).at(d)); + } + return c == 0; +} + +} // namespace dasmig::core + +#endif // DASMIG_CORE_CHECK_DIGITS_HPP diff --git a/dasmig/core/money.hpp b/dasmig/core/money.hpp new file mode 100644 index 0000000..b3817f0 --- /dev/null +++ b/dasmig/core/money.hpp @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2020-2026 Diego Dasso Migotto + +#ifndef DASMIG_CORE_MONEY_HPP +#define DASMIG_CORE_MONEY_HPP + +#include "json.hpp" +#include "math.hpp" + +#include +#include +#include +#include +#include +#include + +/// @file money.hpp +/// @brief An amount in integer minor units with its ISO 4217 currency. +/// @author Diego Dasso Migotto (diegomigotto at hotmail dot com) +/// +/// The core knows no currencies: the minor unit (2 for BRL, 0 for JPY, 3 for +/// KWD) comes from the caller, typically country-generator's +/// `currency_digits`. There is no arithmetic beyond equality and no +/// conversion; locale formatting (grouping, symbols) is country-generator's +/// `format_money`. + +namespace dasmig::core +{ + +/// @brief An amount of money: integer minor units, a currency and its minor unit. +/// +/// Make one with from_minor() or from_major(), which check the invariants: +/// a code of three capital letters, digits from 0 to 4, and |minor| at most +/// 2^53, so minor converts to a double exactly and major() is the closest +/// double to the amount. Up to 2^51 minor units, the JSON number times +/// 10^digits rounds back to minor exactly. +/// +/// @code +/// auto income = core::money::from_major(core::lognormal(r, 10.4, 0.6), "BRL", 2); +/// income.decimal(); // for example "32861.07" +/// income.write_json(w); // {"amount":32861.07,"currency":"BRL"} +/// core::money::from_minor(-5, "USD", 2).decimal(); // "-0.05" +/// @endcode +struct money +{ + std::int64_t minor{}; ///< Amount in minor units (cents); negative allowed. + std::string currency; ///< ISO 4217 alphabetic code: three capital letters. + std::uint8_t digits{2}; ///< ISO 4217 minor unit, 0 to 4. + + /// @brief Largest |minor| accepted: 2^53. + static constexpr std::int64_t max_minor = 9007199254740992; + + /// @brief An amount from minor units. + /// @param minor Amount in minor units. + /// @param currency ISO 4217 alphabetic code. + /// @param digits The currency's minor unit, 0 to 4. + /// @return The amount. + /// @throws std::invalid_argument For a code that is not three capital + /// letters, digits above 4, or |minor| above 2^53. + [[nodiscard]] static money from_minor(std::int64_t minor, std::string currency, + std::uint8_t digits) + { + check(currency, digits, "money::from_minor"); + if (minor > max_minor || minor < -max_minor) + { + throw std::invalid_argument("money::from_minor: " + std::to_string(minor) + + " minor units is beyond 2^53"); + } + return money{.minor = minor, .currency = std::move(currency), .digits = digits}; + } + + /// @brief An amount from major units, rounded to the minor unit. + /// + /// `y = |amount| * 10^digits` (one correctly rounded multiplication by an + /// exact power of ten), `f = floor(y)`, plus 1 when `y - f >= 0.5` + /// (halves away from zero), with the sign put back. 1.005 gives 100 cents, + /// because the double 1.005 is just below 1.005; draw minor units with + /// from_minor() when an exact decimal amount matters. + /// + /// @param amount Amount in major units. + /// @param currency ISO 4217 alphabetic code. + /// @param digits The currency's minor unit, 0 to 4. + /// @return The amount. + /// @throws std::invalid_argument As from_minor(), or if @p amount is NaN + /// or infinite. + [[nodiscard]] static money from_major(double amount, std::string currency, + std::uint8_t digits) + { + check(currency, digits, "money::from_major"); + if (!std::isfinite(amount)) + { + throw std::invalid_argument("money::from_major: amount is not finite"); + } + const double y = math::fenced(std::abs(amount) * pow10(digits)); + if (y > static_cast(max_minor)) + { + throw std::invalid_argument("money::from_major: amount is beyond 2^53 minor units"); + } + double f = std::floor(y); + if (y - f >= 0.5) f += 1.0; // never past 2^53: doubles that large are integers + const auto units = static_cast(f); + return money{.minor = amount < 0.0 ? -units : units, + .currency = std::move(currency), + .digits = digits}; + } + + /// @brief The amount in major units. + /// @return `minor / 10^digits` (one correctly rounded division). + [[nodiscard]] double major() const noexcept + { + return static_cast(minor) / pow10(digits); + } + + /// @brief The exact amount as decimal text. + /// + /// Integer arithmetic: the sign, the major units, and when digits > 0 a + /// `.` and the minor units padded to @c digits characters. No grouping + /// and no locale. + /// + /// @return For example `"1234.50"`, `"-0.05"`, `"1000"`, `"0.125"`. + [[nodiscard]] std::string decimal() const + { + const auto magnitude = minor < 0 ? 0 - static_cast(minor) + : static_cast(minor); + std::uint64_t scale = 1; + for (std::uint8_t i = 0; i < digits; ++i) scale *= 10; + std::string text = minor < 0 ? "-" : ""; + text += std::to_string(magnitude / scale); + if (digits > 0) + { + const std::string fraction = std::to_string(magnitude % scale); + text += '.'; + text.append(digits - fraction.size(), '0'); + text += fraction; + } + return text; + } + + /// @brief Write the amount as a JSON object. + /// + /// `{"amount":1234.5,"currency":"BRL"}`: the amount is major() written + /// as json_writer writes a double, the shortest text that reads back to + /// the same value. Write the key first, as for any value. + /// + /// @param w Writer, where a value is expected. + void write_json(json_writer& w) const + { + w.begin_object().field("amount", major()).field("currency", currency).end_object(); + } + + /// @brief Equal when the minor units, the currency and the digits are. + friend bool operator==(const money&, const money&) = default; + + private: + static void check(const std::string& currency, std::uint8_t digits, const char* function) + { + if (currency.size() != 3 || currency[0] < 'A' || currency[0] > 'Z' || currency[1] < 'A' || + currency[1] > 'Z' || currency[2] < 'A' || currency[2] > 'Z') + { + throw std::invalid_argument(std::string{function} + ": currency '" + currency + + "' is not three capital letters"); + } + if (digits > 4) + { + throw std::invalid_argument(std::string{function} + ": " + std::to_string(digits) + + " minor-unit digits, above 4"); + } + } + + // 10^n, exact for n up to 22. + [[nodiscard]] static constexpr double pow10(std::uint8_t n) noexcept + { + double p = 1.0; + for (std::uint8_t i = 0; i < n; ++i) p *= 10.0; + return p; + } +}; + +} // namespace dasmig::core + +#endif // DASMIG_CORE_MONEY_HPP diff --git a/dasmig/core/pattern.hpp b/dasmig/core/pattern.hpp new file mode 100644 index 0000000..350810c --- /dev/null +++ b/dasmig/core/pattern.hpp @@ -0,0 +1,592 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2020-2026 Diego Dasso Migotto + +#ifndef DASMIG_CORE_PATTERN_HPP +#define DASMIG_CORE_PATTERN_HPP + +#include "distributions.hpp" +#include "rng.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/// @file pattern.hpp +/// @brief A small pattern language for identifiers: draw a string, test a +/// string, count the strings a pattern can make. +/// @author Diego Dasso Migotto (diegomigotto at hotmail dot com) +/// +/// Letters are literals and the tokens are symbols, so a pattern reads like +/// the value it makes: +/// +/// | Syntax | Meaning | +/// | --- | --- | +/// | `#` | a digit, `0`-`9` | +/// | `@` | a capital letter, `A`-`Z` | +/// | `*` | a digit or capital letter, `0`-`9` then `A`-`Z` | +/// | `[...]` | one character of a class, in the order written; `A-Z` ranges; `-` is literal first or last | +/// | `(a\|b)` | one of the alternatives, each a sequence; groups nest | +/// | `{n}`, `{n,m}` | the item before it, exactly n, or n to m times (n may be 0) | +/// | `\x` | the character x as a literal | +/// | anything else | itself | +/// +/// pattern::draw()'s use of the engine is part of the core's output contract. + +namespace dasmig::core +{ + +/// @brief A parsed identifier pattern. +/// +/// Immutable once parsed, copyable, and safe to share between threads. +/// Parse a library's patterns when its tables load, so a bad pattern is a +/// load error with its row. +/// +/// @code +/// static const auto nino = core::pattern::parse("[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]######[A-D]"); +/// std::string id = nino.draw(r); // "JG103759A" +/// bool ok = nino.matches(id); // true +/// @endcode +class pattern +{ + public: + /// @brief Most characters of pattern text. + static constexpr std::size_t max_text = 1024; + /// @brief Deepest nesting of groups. + static constexpr std::size_t max_depth = 8; + /// @brief Largest repetition count in a quantifier. + static constexpr std::size_t max_count = 64; + /// @brief Most characters in a string the pattern can make. + static constexpr std::size_t max_length = 256; + + /// @brief The empty pattern, which makes only the empty string. + pattern() = default; + + /// @brief Parse pattern text. + /// @param text Printable ASCII pattern (see the file description). + /// @return The pattern. + /// @throws std::invalid_argument With the 0-based position, for a byte + /// outside printable ASCII, a `|` outside a group, an empty + /// alternative, an unclosed `(`, `[` or `{`, a stray `)`, `]` or + /// `}`, a dangling `\`, an empty class, a reversed range or a + /// repeated character in a class, a quantifier after nothing or + /// after another quantifier, a bad count (above 64, m < n or + /// m = 0), or text, nesting or strings beyond the limits. + [[nodiscard]] static pattern parse(std::string_view text) + { + if (text.size() > max_text) + { + throw std::invalid_argument("pattern::parse: " + std::to_string(text.size()) + + " characters, above " + std::to_string(max_text)); + } + for (std::size_t i = 0; i < text.size(); ++i) + { + const auto b = static_cast(text[i]); + if (b < 0x20U || b > 0x7EU) + { + constexpr std::string_view hex = "0123456789ABCDEF"; + parser::fail(i, std::string{"byte 0x"} + hex[b >> 4U] + hex[b & 0x0FU] + + ": patterns are printable ASCII"); + } + } + pattern p; + p._text = std::string{text}; + p._nodes.clear(); + p._sequences.clear(); + p._refs.clear(); + parser ps{.out = &p, .text = text}; + p._root = ps.parse_sequence(0); // at depth 0 it reads to the end or throws + const stats s = p.sequence_stats(p._root); + if (s.longest > max_length) + { + throw std::invalid_argument( + "pattern::parse: makes strings of up to " + + (s.longest == std::numeric_limits::max() ? std::string{"2^64"} + : std::to_string(s.longest)) + + " characters, above " + std::to_string(max_length)); + } + p._shortest = static_cast(s.shortest); + p._longest = static_cast(s.longest); + p._count = s.count; + return p; + } + + /// @brief Draw a string the pattern can make. + /// + /// Left to right: a literal appends itself and draws nothing; a token or + /// class appends `chars[bounded(r, chars.size())]`, its characters in the + /// order written (ranges expanded upwards; `#` is `0`-`9`, `@` is `A`-`Z`, + /// `*` is `0`-`9` then `A`-`Z`); a group draws `k = bounded(r, + /// alternatives)` and then alternative k; `{n}` draws its item n times, + /// and `{n,m}` with n < m first draws `c = uniform_int(r, n, m)`, then its + /// item c times. Alternatives are equally likely whatever their size. + /// + /// @param r Engine. + /// @return The string. + [[nodiscard]] std::string draw(rng& r) const + { + std::string out; + out.reserve(_longest); + draw_sequence(_root, r, out); + return out; + } + + /// @brief Whether a string is one the pattern can make. + /// + /// Computes the set of positions each item can end at, so the time is + /// polynomial in the length of @p s for any pattern. Check digits are not + /// checked: call the check-digit function after. + /// + /// @param s Candidate string. + /// @return True when the whole of @p s matches. + [[nodiscard]] bool matches(std::string_view s) const noexcept + { + if (s.size() < _shortest || s.size() > _longest) return false; + try + { + matcher m{*this, s}; + positions start; + start.set(0); + return m.sequence_ends(_root, start).test(s.size()); + } + catch (...) + { + return false; // allocation failure + } + } + + /// @brief The number of strings the pattern can make. + /// + /// Alternatives are counted as disjoint and different repetition counts + /// as different strings, so it is an upper bound when they overlap. + /// Saturates at 2^64 - 1. Use it to refuse a unique batch larger than + /// the space. + /// + /// @return The count. + [[nodiscard]] std::uint64_t count() const noexcept { return _count; } + + /// @brief The shortest and longest strings' lengths. + /// @return {shortest, longest}. + [[nodiscard]] std::pair lengths() const noexcept + { + return {_shortest, _longest}; + } + + /// @brief The pattern text, as parsed. + /// @return The text. + [[nodiscard]] std::string_view text() const noexcept { return _text; } + + /// @brief Patterns are equal when their text is. + /// @param a A pattern. + /// @param b Another. + /// @return Whether the texts are equal. + friend bool operator==(const pattern& a, const pattern& b) noexcept + { + return a._text == b._text; + } + + private: + enum class kind : std::uint8_t + { + literal, + set, + group + }; + + // One item. A literal or a set holds its characters; a group holds its + // alternatives (sequence indices) in _refs[first, first + size). + struct node + { + kind type{kind::literal}; + std::uint8_t min{1}; + std::uint8_t max{1}; + std::uint32_t first{0}; + std::uint32_t size{0}; + std::uint32_t group{0}; // ordinal among the groups, for matching + std::string chars; + std::array mask{}; // chars as a bitmap of ASCII + + [[nodiscard]] bool has(char c) const noexcept + { + const auto b = static_cast(c); + return b < 128U && ((mask.at(b >> 6U) >> (b & 63U)) & 1U) != 0; + } + }; + + [[nodiscard]] static node make_node(kind type) + { + node n; + n.type = type; + return n; + } + + // Items (node indices) in _refs[first, first + size). + struct sequence + { + std::uint32_t first{0}; + std::uint32_t size{0}; + }; + + struct stats + { + std::uint64_t shortest; + std::uint64_t longest; + std::uint64_t count; + }; + + using positions = std::bitset; + + [[nodiscard]] static constexpr std::uint64_t sat_add(std::uint64_t a, std::uint64_t b) noexcept + { + return a > std::numeric_limits::max() - b + ? std::numeric_limits::max() + : a + b; + } + + [[nodiscard]] static constexpr std::uint64_t sat_mul(std::uint64_t a, std::uint64_t b) noexcept + { + if (a == 0 || b == 0) return 0; + return a > std::numeric_limits::max() / b + ? std::numeric_limits::max() + : a * b; + } + + // Recursive-descent parser for the grammar in the file description. + struct parser + { + pattern* out; + std::string_view text; + std::size_t pos{0}; + + [[noreturn]] static void fail(std::size_t at, const std::string& reason) + { + throw std::invalid_argument("pattern::parse: position " + std::to_string(at) + ": " + + reason); + } + + static std::string quoted(char c) { return std::string{'\''} + c + '\''; } + + [[nodiscard]] std::uint32_t add_node(node n) const + { + out->_nodes.push_back(std::move(n)); + return static_cast(out->_nodes.size() - 1); + } + + [[nodiscard]] std::uint32_t add_set(std::string_view chars) const + { + node n = make_node(kind::set); + for (const char c : chars) add_char(n, c); + return add_node(std::move(n)); + } + + static void add_char(node& n, char c) + { + const auto b = static_cast(c); + n.chars += c; + n.mask.at(b >> 6U) |= std::uint64_t{1} << (b & 63U); + } + + [[nodiscard]] std::uint32_t add_literal(char c) const + { + node n = make_node(kind::literal); + add_char(n, c); + return add_node(std::move(n)); + } + + // Parse a sequence up to the end, or (inside a group) up to a '|' or + // ')'; returns its index in _sequences. + std::uint32_t parse_sequence(std::size_t depth) // NOLINT(misc-no-recursion): groups nest at most max_depth + { + std::vector items; + bool quantified = false; + while (pos < text.size()) + { + const char c = text[pos]; + if (c == '|' || c == ')') + { + if (depth == 0) fail(pos, c == '|' ? "'|' outside a group" : "stray ')'"); + break; + } + if (c == '{') + { + if (items.empty()) fail(pos, "quantifier after nothing"); + if (quantified) fail(pos, "quantifier after another quantifier"); + quantifier(out->_nodes[items.back()]); + quantified = true; + continue; + } + quantified = false; + switch (c) + { + case '#': items.push_back(add_set("0123456789")); ++pos; break; + case '@': items.push_back(add_set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); ++pos; break; + case '*': + items.push_back(add_set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")); + ++pos; + break; + case '[': items.push_back(char_class()); break; + case '(': items.push_back(group(depth + 1)); break; + case ']': + case '}': fail(pos, "stray " + quoted(c)); + case '\\': + if (pos + 1 == text.size()) fail(pos, "dangling '\\'"); + items.push_back(add_literal(text[pos + 1])); + pos += 2; + break; + default: items.push_back(add_literal(c)); ++pos; + } + } + const sequence s{.first = static_cast(out->_refs.size()), + .size = static_cast(items.size())}; + out->_refs.insert(out->_refs.end(), items.begin(), items.end()); + out->_sequences.push_back(s); + return static_cast(out->_sequences.size() - 1); + } + + std::uint32_t group(std::size_t depth) // NOLINT(misc-no-recursion): as parse_sequence + { + const std::size_t start = pos++; + if (depth > max_depth) + { + fail(start, "groups nested deeper than " + std::to_string(max_depth)); + } + std::vector alternatives; + for (;;) + { + const std::uint32_t s = parse_sequence(depth); + if (out->_sequences[s].size == 0) fail(pos, "empty alternative"); + alternatives.push_back(s); + if (pos == text.size()) fail(start, "unclosed '('"); + if (text[pos++] == ')') break; // else '|' + } + node n = make_node(kind::group); + n.first = static_cast(out->_refs.size()); + n.size = static_cast(alternatives.size()); + n.group = static_cast(out->_groups++); + out->_refs.insert(out->_refs.end(), alternatives.begin(), alternatives.end()); + return add_node(std::move(n)); + } + + std::uint32_t char_class() + { + const std::size_t start = pos++; + node n = make_node(kind::set); + for (;;) + { + if (pos == text.size()) fail(start, "unclosed '['"); + const char c = text[pos]; + if (c == ']') break; + if (pos + 2 < text.size() && text[pos + 1] == '-' && text[pos + 2] != ']') + { + const char last = text[pos + 2]; + if (last < c) + { + fail(pos, "reversed range " + quoted(c) + "-" + quoted(last)); + } + for (char x = c; x <= last; ++x) + { + if (n.has(x)) fail(pos, "repeated " + quoted(x) + " in class"); + add_char(n, x); + } + pos += 3; + continue; + } + if (n.has(c)) fail(pos, "repeated " + quoted(c) + " in class"); + add_char(n, c); + ++pos; + } + if (n.chars.empty()) fail(start, "empty class"); + ++pos; + return add_node(std::move(n)); + } + + // A count inside the quantifier opened at @p brace. + std::size_t number(std::size_t brace) + { + const std::size_t start = pos; + std::size_t value = 0; + while (pos < text.size() && text[pos] >= '0' && text[pos] <= '9') + { + value = std::min((value * 10) + static_cast(text[pos] - '0'), + max_text); + ++pos; + } + if (pos == text.size()) fail(brace, "unclosed '{'"); + if (pos == start) fail(pos, "expected a count, found " + quoted(text[pos])); + if (value > max_count) + { + fail(start, "count above " + std::to_string(max_count)); + } + return value; + } + + void quantifier(node& n) + { + const std::size_t start = pos++; + const std::size_t lo = number(start); + std::size_t hi = lo; + if (text[pos] == ',') + { + ++pos; + hi = number(start); + } + if (text[pos] != '}') fail(pos, "expected '}', found " + quoted(text[pos])); + ++pos; + if (hi < lo) fail(start, "quantifier maximum below its minimum"); + if (hi == 0) fail(start, "quantifier of zero"); + n.min = static_cast(lo); + n.max = static_cast(hi); + } + }; + + // The end positions each item can reach in one string, memoised per group + // and start position. + struct matcher + { + matcher(const pattern& owner, std::string_view text) + : p{&owner}, s{text}, memo(owner._groups * (text.size() + 1)), + known(owner._groups * (text.size() + 1)) + { + } + + const pattern* p; + std::string_view s; + std::vector memo; // group ordinal * (s.size() + 1) + start + std::vector known; + + // Positions reachable after one occurrence of a node from @p start. + positions once(const node& n, std::size_t start) // NOLINT(misc-no-recursion): as parse_sequence + { + positions ends; + if (n.type != kind::group) + { + if (start < s.size() && n.has(s[start])) ends.set(start + 1); + return ends; + } + const std::size_t slot = (n.group * (s.size() + 1)) + start; + if (known[slot] != 0) return memo[slot]; + positions from; + from.set(start); + for (std::uint32_t a = 0; a < n.size; ++a) + { + ends |= sequence_ends(p->_refs[n.first + a], from); + } + memo[slot] = ends; + known[slot] = 1; + return ends; + } + + // Positions reachable after an item (with its quantifier) from any + // position in @p from. + positions item_ends(const node& n, const positions& from) // NOLINT(misc-no-recursion) + { + positions result; + if (n.min == 0) result = from; + positions current = from; + for (std::size_t c = 1; c <= n.max && current.any(); ++c) + { + positions next; + for (std::size_t i = 0; i <= s.size(); ++i) + { + if (current.test(i)) next |= once(n, i); + } + current = next; + if (c >= n.min) result |= current; + } + return result; + } + + positions sequence_ends(std::uint32_t index, positions from) // NOLINT(misc-no-recursion) + { + const sequence& seq = p->_sequences[index]; + for (std::uint32_t i = 0; i < seq.size && from.any(); ++i) + { + from = item_ends(p->_nodes[p->_refs[seq.first + i]], from); + } + return from; + } + }; + + [[nodiscard]] stats once_stats(const node& n) const // NOLINT(misc-no-recursion): as parse_sequence + { + if (n.type == kind::literal) return {.shortest = 1, .longest = 1, .count = 1}; + if (n.type == kind::set) return {.shortest = 1, .longest = 1, .count = n.chars.size()}; + stats g{.shortest = std::numeric_limits::max(), .longest = 0, .count = 0}; + for (std::uint32_t a = 0; a < n.size; ++a) + { + const stats s = sequence_stats(_refs[n.first + a]); + g.shortest = std::min(g.shortest, s.shortest); + g.longest = std::max(g.longest, s.longest); + g.count = sat_add(g.count, s.count); + } + return g; + } + + [[nodiscard]] stats sequence_stats(std::uint32_t index) const // NOLINT(misc-no-recursion) + { + const sequence& seq = _sequences[index]; + stats total{.shortest = 0, .longest = 0, .count = 1}; + for (std::uint32_t i = 0; i < seq.size; ++i) + { + const node& n = _nodes[_refs[seq.first + i]]; + const stats once = once_stats(n); + // The count of an item is the sum of once.count^c for c in [min, max]. + std::uint64_t item_count = 0; + std::uint64_t power = 1; + for (std::size_t c = 0; c <= n.max; ++c) + { + if (c >= n.min) item_count = sat_add(item_count, power); + power = sat_mul(power, once.count); + } + total.shortest = sat_add(total.shortest, sat_mul(once.shortest, n.min)); + total.longest = sat_add(total.longest, sat_mul(once.longest, n.max)); + total.count = sat_mul(total.count, item_count); + } + return total; + } + + void draw_sequence(std::uint32_t index, rng& r, std::string& out) const // NOLINT(misc-no-recursion) + { + const sequence& seq = _sequences[index]; + for (std::uint32_t i = 0; i < seq.size; ++i) + { + const node& n = _nodes[_refs[seq.first + i]]; + const std::uint64_t times = + n.min == n.max ? n.min : uniform_int(r, n.min, n.max); + for (std::uint64_t t = 0; t < times; ++t) + { + switch (n.type) + { + case kind::literal: out += n.chars[0]; break; + case kind::set: + out += n.chars[static_cast(bounded(r, n.chars.size()))]; + break; + case kind::group: + draw_sequence(_refs[n.first + static_cast(bounded(r, n.size))], r, out); + break; + } + } + } + } + + std::string _text; + std::vector _nodes; + std::vector _sequences{sequence{}}; // the empty pattern's root + std::vector _refs; + std::uint32_t _root{0}; + std::size_t _groups{0}; + std::size_t _shortest{0}; + std::size_t _longest{0}; + std::uint64_t _count{1}; +}; + +} // namespace dasmig::core + +#endif // DASMIG_CORE_PATTERN_HPP diff --git a/dasmig/core/tz.hpp b/dasmig/core/tz.hpp new file mode 100644 index 0000000..3f090db --- /dev/null +++ b/dasmig/core/tz.hpp @@ -0,0 +1,783 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2020-2026 Diego Dasso Migotto + +#ifndef DASMIG_CORE_TZ_HPP +#define DASMIG_CORE_TZ_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/// @file tz.hpp +/// @brief Time-zone rules: a list of periods plus a POSIX TZ rule, the offset +/// at an instant, and local time to UTC and back. +/// @author Diego Dasso Migotto (diegomigotto at hotmail dot com) +/// +/// `std::chrono::tzdb` reads the operating system's time-zone database, which +/// differs by platform and update level and is missing from Emscripten and +/// older libc++, so the same seed would give different local times on +/// different machines. A tz_rules holds a zone's rules as plain text the +/// caller gives it (country-generator ships them), and uses only +/// `std::chrono`'s durations and calendar arithmetic. +/// +/// Text form: periods are `utc-seconds/offset-seconds/abbreviation/s|d` +/// separated by single spaces, with strictly increasing starts; the offset is +/// east of UTC, and `s` or `d` says standard or daylight time. The POSIX rule +/// (the footer of a TZif file, RFC 8536) applies after the last period. For +/// example, Berlin from 2000: +/// +/// @code +/// auto berlin = core::tz_rules::parse( +/// "946684800/3600/CET/s 954032400/7200/CEST/d 972781200/3600/CET/s", +/// "CET-1CEST,M3.5.0,M10.5.0/3"); +/// auto info = berlin.at(std::chrono::sys_days{2024y / 7 / 1}); // +02:00, CEST +/// @endcode +/// +/// Instants from the first period's start (valid_from()) to the end of the +/// year 9999 are supported. + +namespace dasmig::core +{ + +/// @brief Which instant to_utc() returns for a local time that occurs twice. +enum class tz_choose : std::uint8_t +{ + earliest, ///< The first occurrence (still on daylight time, when clocks go back). + latest ///< The second occurrence. +}; + +/// @brief The rules in force at an instant. +struct tz_info +{ + std::chrono::seconds offset; ///< East of UTC. + bool dst; ///< Daylight time. + std::string_view abbreviation; ///< Valid while the tz_rules it came from lives. + + /// @brief Equal when the offset, the flag and the abbreviation text are. + friend bool operator==(const tz_info&, const tz_info&) = default; +}; + +/// @cond INTERNAL +namespace detail +{ + +inline constexpr std::chrono::sys_seconds tz_first{ + std::chrono::sys_days{std::chrono::year{-9999} / 1 / 1}}; +inline constexpr std::chrono::sys_seconds tz_last{ + std::chrono::sys_days{std::chrono::year{10000} / 1 / 1} - std::chrono::seconds{1}}; + +// "2024-03-31T01:00:00Z"; years below 0 with a minus, padded to 4 digits. +// Instants far outside the supported years (whose calendar date would +// overflow chrono's day count) are written as seconds since the epoch. +[[nodiscard]] inline std::string iso_utc(std::chrono::sys_seconds t) +{ + constexpr std::chrono::days margin{366}; + if (t < tz_first - margin || t > tz_last + margin) + { + return std::to_string(t.time_since_epoch().count()) + " s after 1970-01-01T00:00:00Z"; + } + const auto day = std::chrono::floor(t); + const std::chrono::year_month_day ymd{day}; + const auto secs = (t - day).count(); + const auto two = [](long long v) { + return std::string{static_cast('0' + (v / 10)), static_cast('0' + (v % 10))}; + }; + int y = static_cast(ymd.year()); + std::string out = y < 0 ? "-" : ""; + y = y < 0 ? -y : y; + const std::string digits = std::to_string(y); + out.append(digits.size() < 4 ? 4 - digits.size() : 0, '0'); + out += digits; + out += '-' + two(static_cast(ymd.month())) + '-' + + two(static_cast(ymd.day())) + 'T' + two(secs / 3600) + ':' + + two((secs / 60) % 60) + ':' + two(secs % 60) + 'Z'; + return out; +} + +[[nodiscard]] constexpr bool tz_abbreviation_char(char c) noexcept +{ + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '+' || c == '-'; +} + +[[nodiscard]] constexpr bool tz_abbreviation(std::string_view s) noexcept +{ + return s.size() >= 3 && s.size() <= 6 && std::ranges::all_of(s, tz_abbreviation_char); +} + +} // namespace detail +/// @endcond + +/// @brief A time zone's rules: periods from a start instant, then a POSIX rule. +/// +/// Immutable, copyable and safe to share between threads. Nothing is cached: +/// at() is a binary search, or three small rule evaluations after the last +/// period. A default-constructed zone is UTC. +class tz_rules +{ + public: + /// @brief UTC (`fixed(0s, "UTC")`). + tz_rules() : tz_rules{fixed(std::chrono::seconds{0}, "UTC")} {} + + /// @brief Parse a zone from its text form. + /// + /// The POSIX rule is `std offset [dst [offset] [,rule,rule]]`: names of 3 + /// to 6 letters, or `<...>` around 3 to 6 of `A-Z a-z 0-9 + -`; offsets + /// `[+|-]hh[:mm[:ss]]` west of UTC (hours to 24; a daylight name without + /// an offset is one hour ahead of standard); rules `Jn` (1 to 365, + /// February 29 never counted), `n` (0 to 365, counting it) or `Mm.w.d` + /// (weekday d, 0 = Sunday, of week w, 5 = last, of month m), each with an + /// optional `/time` from -167 to 167 hours (default 02:00), local + /// standard time for the start and local daylight time for the end. A + /// daylight name needs the two rules. An empty rule means the last period + /// holds forever. + /// + /// @param periods Periods in the text form of the file description. + /// @param posix POSIX TZ rule, or empty. + /// @return The zone. + /// @throws std::invalid_argument With the position, for malformed text, no + /// period, starts that do not increase, a start outside the years + /// -9999 to 9999, an offset beyond ±86,399 seconds, or an + /// abbreviation outside the forms above. + [[nodiscard]] static tz_rules parse(std::string_view periods, std::string_view posix) // NOLINT(bugprone-easily-swappable-parameters) + { + tz_rules z{no_init{}}; + z.parse_periods(periods); + z._posix = std::string{posix}; + posix_reader reader{.zone = &z, .text = posix}; + reader.read(); + return z; + } + + /// @brief A zone with one offset forever, for the `UTC+03:00` kind of zone. + /// + /// One period from the start of the year -9999, and the POSIX rule + /// `offset`. + /// + /// @param offset East of UTC, within ±86,399 seconds. + /// @param abbreviation 3 to 6 of `A-Z a-z 0-9 + -` (`+03`, `UTC`). + /// @return The zone. + /// @throws std::invalid_argument For an offset or abbreviation outside those. + [[nodiscard]] static tz_rules fixed(std::chrono::seconds offset, std::string_view abbreviation) + { + const std::string name{abbreviation}; + if (offset.count() > max_offset || offset.count() < -max_offset) + { + throw std::invalid_argument("tz_rules::fixed: offset " + std::to_string(offset.count()) + + " s is beyond 86399 s"); + } + if (!detail::tz_abbreviation(abbreviation)) + { + throw std::invalid_argument("tz_rules::fixed: abbreviation '" + name + + "' is not 3 to 6 of A-Z a-z 0-9 + -"); + } + // POSIX offsets are west of UTC: +03:00 is "<+03>-3". + const long long west = -offset.count(); + const long long magnitude = west < 0 ? -west : west; + std::string posix = "<" + name + ">" + (west < 0 ? "-" : "") + + std::to_string(magnitude / 3600); + if (magnitude % 3600 != 0) + { + const std::string clock = detail::iso_utc( + std::chrono::sys_seconds{std::chrono::seconds{magnitude % 3600}}); + posix += ':' + clock.substr(14, 2); // minutes of "1970-01-01T00:mm:ssZ" + if (magnitude % 60 != 0) posix += ':' + clock.substr(17, 2); + } + return parse(std::to_string(detail::tz_first.time_since_epoch().count()) + "/" + + std::to_string(offset.count()) + "/" + name + "/s", + posix); + } + + /// @brief The rules in force at an instant. + /// + /// Before the last period's start, or with no daylight rule, the period + /// that contains @p t. After it, the latest transition of the POSIX rule + /// in the UTC years around @p t that is after the last period's start + /// and not after @p t, or the last period if there is none. A transition + /// of the rule never overrides the list. + /// + /// @param t Instant. + /// @return Offset, daylight flag and abbreviation. + /// @throws std::out_of_range Before valid_from() or after the year 9999. + [[nodiscard]] tz_info at(std::chrono::sys_seconds t) const + { + check_range(t, "tz_rules::at"); + const period& last = _periods.back(); + if (!_footer.has_dst || t.time_since_epoch().count() < last.start) + { + const auto it = std::ranges::upper_bound(_periods, t.time_since_epoch().count(), {}, + &period::start); + return info(*(it - 1)); + } + const int y = static_cast( + std::chrono::year_month_day{std::chrono::floor(t)}.year()); + bool found = false; + change best{}; + for (int year = y - 1; year <= y + 1; ++year) + { + for (const change& c : changes(year)) + { + if (c.at <= last.start || c.at > t.time_since_epoch().count()) continue; + // At one instant (daylight time all year), daylight time wins. + if (!found || c.at > best.at || (c.at == best.at && c.dst)) + { + best = c; + found = true; + } + } + } + return found ? footer_info(best.dst) : info(last); + } + + /// @brief Local time at an instant. + /// @param t Instant. + /// @return `t + at(t).offset`, as a local time. + /// @throws std::out_of_range As at(). + [[nodiscard]] std::chrono::local_seconds to_local(std::chrono::sys_seconds t) const + { + return std::chrono::local_seconds{t.time_since_epoch() + at(t).offset}; + } + + /// @brief The instant of a local time. + /// + /// With o1 and o2 the offsets in force one day before and after the local + /// time read as UTC, the candidates are `l - o1` and `l - o2`; a candidate + /// is valid when the offset at it is the one that made it. Two valid + /// candidates are a repeated local time, resolved by @p choose; one is the + /// answer; none means the local time was skipped, and the answer is + /// `l - o1` (02:30 on a spring-forward night in Berlin is 01:30Z, which + /// is 03:30 CEST). Assumes the offset changes at most once in two days. + /// + /// @param l Local time. + /// @param choose Which instant a repeated local time gives. + /// @return The instant. + /// @throws std::out_of_range When the instant is outside the zone's data. + [[nodiscard]] std::chrono::sys_seconds to_utc(std::chrono::local_seconds l, + tz_choose choose = tz_choose::earliest) const + { + constexpr std::chrono::days one_day{1}; + const std::chrono::sys_seconds as_utc{l.time_since_epoch()}; + if (as_utc < detail::tz_first - one_day || as_utc > detail::tz_last + one_day) + { + // Far outside any zone's data; also keeps the probes below from overflowing. + check_range(as_utc, "tz_rules::to_utc"); + } + const auto probe = [&](std::chrono::sys_seconds t) { + return at(std::clamp(t, valid_from(), detail::tz_last)).offset; + }; + const std::chrono::seconds o1 = probe(as_utc - one_day); + const std::chrono::seconds o2 = probe(as_utc + one_day); + const std::chrono::sys_seconds u1 = as_utc - o1; + const std::chrono::sys_seconds u2 = as_utc - o2; + const auto valid = [&](std::chrono::sys_seconds u, std::chrono::seconds o) { + return u >= valid_from() && u <= detail::tz_last && at(u).offset == o; + }; + const bool v1 = valid(u1, o1); + const bool v2 = valid(u2, o2); + if (v1 && v2 && u1 != u2) + { + return choose == tz_choose::earliest ? std::min(u1, u2) : std::max(u1, u2); + } + if (v2 && !v1) return u2; + check_range(u1, "tz_rules::to_utc"); + return u1; + } + + /// @brief The changes in [from, to), in order. + /// + /// Every listed period's start after the first, and every change of the + /// POSIX rule after the last period that changes the offset or the + /// daylight flag. + /// + /// @param from First instant (inclusive). + /// @param to Last instant (exclusive). + /// @return Each change's instant and the rules from it. + [[nodiscard]] std::vector> transitions( + std::chrono::sys_seconds from, std::chrono::sys_seconds to) const + { + std::vector> out; + from = std::max(from, valid_from()); + to = std::min(to, detail::tz_last + std::chrono::seconds{1}); + if (from >= to) return out; + for (std::size_t i = 1; i < _periods.size(); ++i) + { + const std::chrono::sys_seconds start{std::chrono::seconds{_periods[i].start}}; + if (start >= from && start < to) out.emplace_back(start, info(_periods[i])); + } + const period& last = _periods.back(); + const std::chrono::sys_seconds last_start{std::chrono::seconds{last.start}}; + if (!_footer.has_dst || to <= last_start) return out; + + const auto year_of = [](std::chrono::sys_seconds t) { + return static_cast( + std::chrono::year_month_day{std::chrono::floor(t)}.year()); + }; + const std::chrono::sys_seconds begin = std::max(from, last_start); + std::vector found; + for (int year = year_of(begin) - 1; year <= year_of(to - std::chrono::seconds{1}) + 1; ++year) + { + for (const change& c : changes(year)) + { + if (c.at > last.start && c.at >= begin.time_since_epoch().count() && + c.at < to.time_since_epoch().count()) + { + found.push_back(c); + } + } + } + std::ranges::sort(found, [](const change& a, const change& b) { + return a.at < b.at || (a.at == b.at && !a.dst && b.dst); + }); + tz_info previous = begin > last_start ? at(begin - std::chrono::seconds{1}) : info(last); + for (std::size_t i = 0; i < found.size(); ++i) + { + // Of two changes at one instant (daylight time all year), the later counts. + if (i + 1 < found.size() && found[i + 1].at == found[i].at) continue; + const tz_info now = footer_info(found[i].dst); + if (now.offset == previous.offset && now.dst == previous.dst) continue; + out.emplace_back(std::chrono::sys_seconds{std::chrono::seconds{found[i].at}}, now); + previous = now; + } + return out; + } + + /// @brief The first instant the zone has data for: the first period's start. + /// @return The instant. + [[nodiscard]] std::chrono::sys_seconds valid_from() const noexcept + { + return std::chrono::sys_seconds{std::chrono::seconds{_periods.front().start}}; + } + + /// @brief Whether daylight time is in force at an instant or begins after it. + /// @param t Instant. + /// @return True when a daylight period ends after @p t, or the POSIX rule + /// has daylight time. + [[nodiscard]] bool observes_dst_after(std::chrono::sys_seconds t) const noexcept + { + if (_footer.has_dst) return true; + for (std::size_t i = 0; i < _periods.size(); ++i) + { + const bool ends_after = i + 1 == _periods.size() || + _periods[i + 1].start > t.time_since_epoch().count(); + if (_periods[i].dst && ends_after) return true; + } + return false; + } + + /// @brief The periods in their text form. + /// @return Text that parse() reads back to an equal zone. + [[nodiscard]] std::string periods_text() const + { + std::string out; + for (const period& p : _periods) + { + if (!out.empty()) out += ' '; + out += std::to_string(p.start) + '/' + std::to_string(p.offset) + '/' + + std::string{abbreviation(p.abbr, p.abbr_size)} + '/' + (p.dst ? 'd' : 's'); + } + return out; + } + + /// @brief The POSIX rule, as parsed. + /// @return The rule text (empty when there is none). + [[nodiscard]] std::string_view posix() const noexcept { return _posix; } + + /// @brief Equal when the periods and the POSIX rule text are. + /// @param a A zone. + /// @param b Another. + /// @return Whether they are equal. + friend bool operator==(const tz_rules& a, const tz_rules& b) noexcept + { + return a._posix == b._posix && + std::ranges::equal(a._periods, b._periods, [&](const period& x, const period& y) { + return x.start == y.start && x.offset == y.offset && x.dst == y.dst && + a.abbreviation(x.abbr, x.abbr_size) == b.abbreviation(y.abbr, y.abbr_size); + }); + } + + private: + static constexpr std::int32_t max_offset = 86399; + + struct no_init + { + }; + explicit tz_rules(no_init /*unused*/) {} + + struct period + { + std::int64_t start; // UTC seconds + std::int32_t offset; // east of UTC + std::uint16_t abbr; // position in _abbreviations + std::uint8_t abbr_size; + bool dst; + }; + + enum class date_kind : std::uint8_t + { + julian, // Jn: 1-365, February 29 never counted + ordinal, // n: 0-365, counting it + weekday // Mm.w.d + }; + + struct rule_date + { + date_kind kind{date_kind::ordinal}; + std::uint16_t day{0}; + std::uint8_t month{0}; + std::uint8_t week{0}; + std::uint8_t weekday{0}; + std::int32_t time{7200}; // seconds after local midnight + }; + + struct footer + { + bool has_dst{false}; + std::int32_t std_offset{0}; // east of UTC + std::int32_t dst_offset{0}; + std::uint16_t std_abbr{0}; + std::uint8_t std_abbr_size{0}; + std::uint16_t dst_abbr{0}; + std::uint8_t dst_abbr_size{0}; + rule_date start; + rule_date end; + }; + + struct change + { + std::int64_t at{0}; + bool dst{false}; + }; + + // Reads the POSIX rule into a zone. + struct posix_reader + { + tz_rules* zone; + std::string_view text; + std::size_t pos{0}; + + [[noreturn]] static void fail(std::size_t at, const std::string& reason) + { + throw std::invalid_argument("tz_rules::parse: posix position " + std::to_string(at) + + ": " + reason); + } + + [[nodiscard]] bool done() const noexcept { return pos == text.size(); } + + void expect(char c) + { + if (done() || text[pos] != c) fail(pos, std::string{"expected '"} + c + "'"); + ++pos; + } + + std::string_view name() + { + const std::size_t start = pos; + if (!done() && text[pos] == '<') + { + const std::size_t close = text.find('>', pos); + if (close == std::string_view::npos) fail(start, "unclosed '<'"); + const std::string_view inner = text.substr(pos + 1, close - pos - 1); + if (!detail::tz_abbreviation(inner)) + { + fail(start, "a quoted abbreviation is 3 to 6 of A-Z a-z 0-9 + -"); + } + pos = close + 1; + return inner; + } + while (!done() && ((text[pos] >= 'A' && text[pos] <= 'Z') || (text[pos] >= 'a' && text[pos] <= 'z'))) + { + ++pos; + } + if (pos - start < 3 || pos - start > 6) fail(start, "expected an abbreviation of 3 to 6 letters"); + return text.substr(start, pos - start); + } + + std::int32_t number(std::size_t max_digits, std::int32_t max_value, const char* what) // NOLINT(bugprone-easily-swappable-parameters) + { + const std::size_t start = pos; + std::int32_t value = 0; + while (!done() && text[pos] >= '0' && text[pos] <= '9' && pos - start < max_digits) + { + value = (value * 10) + (text[pos] - '0'); + ++pos; + } + if (pos == start) fail(pos, std::string{"expected "} + what); + if (value > max_value) fail(start, std::string{what} + " above " + std::to_string(max_value)); + return value; + } + + // [+|-]h[h[h]][:mm[:ss]], in seconds. + std::int32_t clock(std::int32_t max_hours) + { + std::int32_t sign = 1; + if (!done() && (text[pos] == '+' || text[pos] == '-')) + { + sign = text[pos] == '-' ? -1 : 1; + ++pos; + } + std::int32_t seconds = number(max_hours > 99 ? 3 : 2, max_hours, "hours") * 3600; + if (!done() && text[pos] == ':') + { + ++pos; + seconds += number(2, 59, "minutes") * 60; + if (!done() && text[pos] == ':') + { + ++pos; + seconds += number(2, 59, "seconds"); + } + } + return sign * seconds; + } + + rule_date rule() + { + rule_date d; + const std::size_t start = pos; + if (!done() && text[pos] == 'J') + { + ++pos; + d.kind = date_kind::julian; + d.day = static_cast(number(3, 365, "a day")); + if (d.day == 0) fail(start, "a J day is 1 to 365"); + } + else if (!done() && text[pos] == 'M') + { + ++pos; + d.kind = date_kind::weekday; + d.month = static_cast(number(2, 12, "a month")); + expect('.'); + d.week = static_cast(number(1, 5, "a week")); + expect('.'); + d.weekday = static_cast(number(1, 6, "a weekday")); + if (d.month == 0 || d.week == 0) fail(start, "months are 1 to 12 and weeks 1 to 5"); + } + else if (!done() && text[pos] >= '0' && text[pos] <= '9') + { + d.kind = date_kind::ordinal; + d.day = static_cast(number(3, 365, "a day")); + } + else + { + fail(pos, "expected a rule date (Jn, n or Mm.w.d)"); + } + if (!done() && text[pos] == '/') + { + ++pos; + d.time = clock(167); + } + return d; + } + + void read() + { + if (done()) return; + footer& f = zone->_footer; + const std::string_view std_name = name(); + f.std_offset = -clock(24); + f.std_abbr = zone->add_abbreviation(std_name); + f.std_abbr_size = static_cast(std_name.size()); + if (done()) return; + const std::string_view dst_name = name(); + f.dst_offset = !done() && text[pos] != ',' ? -clock(24) : f.std_offset + 3600; + f.dst_abbr = zone->add_abbreviation(dst_name); + f.dst_abbr_size = static_cast(dst_name.size()); + if (done()) fail(pos, "daylight time needs its rules (,start,end)"); + expect(','); + f.start = rule(); + expect(','); + f.end = rule(); + if (!done()) fail(pos, "unexpected character"); + f.has_dst = true; + } + }; + + [[noreturn]] static void period_error(std::size_t at, const std::string& reason) + { + throw std::invalid_argument("tz_rules::parse: periods position " + std::to_string(at) + + ": " + reason); + } + + template + static T period_number(std::string_view text, std::size_t at, const char* what) + { + T value{}; + const char* first = text.data(); + const char* last = std::to_address(text.end()); + const auto [end, error] = std::from_chars(first, last, value); + if (text.empty() || error != std::errc{} || end != last) + { + period_error(at, std::string{"expected "} + what); + } + return value; + } + + // The four '/'-separated fields of the period at @p at. + static std::array period_fields(std::string_view item, std::size_t at) + { + std::array parts{}; + std::size_t n = 0; + std::size_t field = 0; + for (std::size_t i = 0; i <= item.size(); ++i) + { + if (i == item.size() || item[i] == '/') + { + if (n == parts.size()) period_error(at, "a period has four fields"); + parts.at(n++) = item.substr(field, i - field); + field = i + 1; + } + } + if (n != parts.size()) period_error(at, "a period has four fields (start/offset/abbreviation/s|d)"); + return parts; + } + + void parse_periods(std::string_view text) + { + if (text.empty()) period_error(0, "no period"); + std::size_t pos = 0; + while (pos <= text.size()) + { + const std::size_t space = std::min(text.find(' ', pos), text.size()); + const auto parts = period_fields(text.substr(pos, space - pos), pos); + const auto start = period_number(parts[0], pos, "a start in seconds"); + if (start < detail::tz_first.time_since_epoch().count() || + start > detail::tz_last.time_since_epoch().count()) + { + period_error(pos, "start outside the years -9999 to 9999"); + } + if (!_periods.empty() && start <= _periods.back().start) + { + period_error(pos, "starts must increase"); + } + const std::size_t offset_at = pos + parts[0].size() + 1; + const auto offset = period_number(parts[1], offset_at, "an offset in seconds"); + if (offset > max_offset || offset < -max_offset) + { + period_error(offset_at, "offset beyond 86399 s"); + } + const std::size_t abbr_at = offset_at + parts[1].size() + 1; + if (!detail::tz_abbreviation(parts[2])) + { + period_error(abbr_at, "an abbreviation is 3 to 6 of A-Z a-z 0-9 + -"); + } + if (parts[3] != "s" && parts[3] != "d") + { + period_error(abbr_at + parts[2].size() + 1, "expected s or d"); + } + _periods.push_back({.start = start, + .offset = offset, + .abbr = add_abbreviation(parts[2]), + .abbr_size = static_cast(parts[2].size()), + .dst = parts[3] == "d"}); + pos = space + 1; + } + } + + // Position of the text in _abbreviations, adding it when not already there. + std::uint16_t add_abbreviation(std::string_view text) + { + std::size_t found = _abbreviations.find(text); + if (found == std::string::npos) + { + found = _abbreviations.size(); + _abbreviations += text; + } + if (found > std::numeric_limits::max()) + { + throw std::invalid_argument("tz_rules::parse: too many abbreviations"); + } + return static_cast(found); + } + + [[nodiscard]] std::string_view abbreviation(std::uint16_t at, std::uint8_t size) const noexcept + { + return std::string_view{_abbreviations}.substr(at, size); + } + + [[nodiscard]] tz_info info(const period& p) const noexcept + { + return {.offset = std::chrono::seconds{p.offset}, + .dst = p.dst, + .abbreviation = abbreviation(p.abbr, p.abbr_size)}; + } + + [[nodiscard]] tz_info footer_info(bool dst) const noexcept + { + return dst ? tz_info{.offset = std::chrono::seconds{_footer.dst_offset}, + .dst = true, + .abbreviation = abbreviation(_footer.dst_abbr, _footer.dst_abbr_size)} + : tz_info{.offset = std::chrono::seconds{_footer.std_offset}, + .dst = false, + .abbreviation = abbreviation(_footer.std_abbr, _footer.std_abbr_size)}; + } + + void check_range(std::chrono::sys_seconds t, const char* function) const + { + if (t < valid_from()) + { + throw std::out_of_range(std::string{function} + ": " + detail::iso_utc(t) + + " is before the zone's data, which starts at " + + detail::iso_utc(valid_from())); + } + if (t > detail::tz_last) + { + throw std::out_of_range(std::string{function} + ": " + detail::iso_utc(t) + + " is after the last supported instant, " + + detail::iso_utc(detail::tz_last)); + } + } + + // The day a rule date falls on in a year. + [[nodiscard]] static std::chrono::sys_days date(const rule_date& d, int y) noexcept + { + const std::chrono::year year{y}; + const std::chrono::sys_days january{year / 1 / 1}; + switch (d.kind) + { + case date_kind::julian: + return january + std::chrono::days{d.day - 1 + (year.is_leap() && d.day >= 60 ? 1 : 0)}; + case date_kind::ordinal: return january + std::chrono::days{d.day}; + case date_kind::weekday: break; + } + const std::chrono::month month{d.month}; + const std::chrono::sys_days first{year / month / 1}; + const std::chrono::sys_days last{year / month / std::chrono::last}; + std::chrono::sys_days day = first + + (std::chrono::weekday{d.weekday} - std::chrono::weekday{first}) + + std::chrono::days{7 * (d.week - 1)}; + while (day > last) day -= std::chrono::days{7}; + return day; + } + + // The rule's two changes in a year: to daylight time, then to standard. + [[nodiscard]] std::array changes(int year) const noexcept + { + const auto at = [&](const rule_date& d, std::int32_t offset) { + return (std::chrono::sys_seconds{date(d, year)} + + std::chrono::seconds{d.time - offset}) + .time_since_epoch() + .count(); + }; + return {change{.at = at(_footer.start, _footer.std_offset), .dst = true}, + change{.at = at(_footer.end, _footer.dst_offset), .dst = false}}; + } + + std::vector _periods; + std::string _abbreviations; + std::string _posix; + footer _footer; +}; + +} // namespace dasmig::core + +#endif // DASMIG_CORE_TZ_HPP diff --git a/dasmig/core/version.hpp b/dasmig/core/version.hpp index 77cb774..dac81c3 100644 --- a/dasmig/core/version.hpp +++ b/dasmig/core/version.hpp @@ -16,7 +16,7 @@ /// incompatibly. #define DASMIG_CORE_VERSION_MAJOR 1 /// @brief Minor version. Changes when features are added compatibly. -#define DASMIG_CORE_VERSION_MINOR 3 +#define DASMIG_CORE_VERSION_MINOR 4 /// @brief Patch version. Changes for fixes that keep output identical. #define DASMIG_CORE_VERSION_PATCH 0