//SPDX-License-Identifier: LGPL-3.0-only //SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® export module Nostro:Currency; import std; export namespace Nostro { enum class Currency : std::uint16_t { Euro }; constexpr Currency GetCurrency(std::string_view name) { if(name == "EUR" || name == "eur") { return Currency::Euro; } else { throw std::runtime_error(std::format("unsupported currency '{}'", name)); } } constexpr std::string_view GetCurrencyCode(Currency code) { switch(code) { case Currency::Euro: return "EUR"; } std::unreachable(); } constexpr std::string_view GetCurrencySymbol(Currency code) { switch(code) { case Currency::Euro: return "€"; } std::unreachable(); } constexpr std::uint8_t GetCurrencyDecimals(Currency code) { switch(code) { case Currency::Euro: return 2; } std::unreachable(); } constexpr std::int64_t ParseAmount(std::string_view value, Currency currency) { const std::uint8_t decimals = GetCurrencyDecimals(currency); std::string_view rest = value; const bool negative = rest.starts_with('-'); if(negative) { rest.remove_prefix(1); } const std::size_t dot = rest.find('.'); const std::string_view whole = rest.substr(0, dot); const std::string_view fraction = dot == std::string_view::npos ? std::string_view() : rest.substr(dot + 1); if(whole.empty() || fraction.size() > decimals) { throw std::runtime_error(std::format("malformed amount '{}'", value)); } std::string digits(whole); digits += fraction; digits.append(decimals - fraction.size(), '0'); std::int64_t minor = 0; for(const char c : digits) { if(c < '0' || c > '9') { throw std::runtime_error(std::format("malformed amount '{}'", value)); } minor = minor * 10 + (c - '0'); } return negative ? -minor : minor; } constexpr std::string FormatAmount(std::int64_t minor, Currency currency) { const std::uint8_t decimals = GetCurrencyDecimals(currency); const bool negative = minor < 0; std::uint64_t magnitude = negative ? std::uint64_t{0} - static_cast(minor) : static_cast(minor); std::string digits; do { digits.push_back(static_cast('0' + magnitude % 10)); magnitude /= 10; } while(magnitude != 0); std::ranges::reverse(digits); if(digits.size() <= decimals) { digits.insert(0, decimals + 1 - digits.size(), '0'); } if(decimals > 0) { digits.insert(digits.size() - decimals, 1, '.'); } if(negative) { digits.insert(0, 1, '-'); } return digits; } } template<> struct std::formatter : std::formatter { auto format(const Nostro::Currency& obj, std::format_context& ctx) const { return std::formatter::format(std::format("{}", GetCurrencySymbol(obj)), ctx); } };