Nostro/interfaces/Nostro-Currency.cppm

101 lines
3.2 KiB
Text
Raw Normal View History

2026-10-06 15:39:17 +02:00
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Currency;
import std;
export namespace Nostro {
2026-10-31 20:50:57 +01:00
enum class Currency : std::uint16_t {
2026-10-06 15:39:17 +02:00
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<std::uint64_t>(minor) : static_cast<std::uint64_t>(minor);
std::string digits;
do {
digits.push_back(static_cast<char>('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<Nostro::Currency> : std::formatter<std::string> {
auto format(const Nostro::Currency& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("{}", GetCurrencySymbol(obj)), ctx);
}
};