Files
aevolution/include/evo/accounting/ledger.hpp
T

72 lines
2.0 KiB
C++

#pragma once
#include <array>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <span>
#include <vector>
namespace evo::accounting {
struct Picojoules {
std::uint64_t value{};
auto operator<=>(const Picojoules&) const = default;
};
struct Femtograms {
std::uint64_t value{};
auto operator<=>(const Femtograms&) const = default;
};
enum class Element : std::uint8_t { carbon, nitrogen, phosphorus, other };
struct Inventory {
Picojoules energy{};
// Disjoint elemental categories; total mass is not an additional inventory.
std::array<Femtograms, 4> matter{};
auto operator<=>(const Inventory&) const = default;
};
struct ReservoirId {
std::uint32_t value{};
};
struct Transfer {
ReservoirId from;
ReservoirId to;
Inventory amount;
};
enum class LedgerError : std::uint8_t {
reservoir_limit,
overflow,
stale_action,
transfer_limit,
invalid_reservoir,
same_reservoir,
insufficient_inventory
};
inline constexpr std::size_t max_reservoirs = 4'096;
inline constexpr std::size_t max_transfers = 256;
class Ledger {
public:
[[nodiscard]] static std::expected<Ledger, LedgerError>
create(std::span<const Inventory> opening);
// Ordered legs form one atomic transaction. Single-owner access only.
[[nodiscard]] std::expected<void, LedgerError> transfer(std::uint64_t action,
std::span<const Transfer> legs);
// Inspection spans are invalidated by successful mutation or assignment.
[[nodiscard]] std::span<const Inventory> balances() const noexcept {
return balances_;
}
[[nodiscard]] Inventory conserved_totals() const noexcept {
return totals_;
}
[[nodiscard]] std::uint64_t last_action() const noexcept {
return last_action_;
}
private:
Ledger() = default;
std::vector<Inventory> balances_;
Inventory totals_{};
std::uint64_t last_action_{};
};
} // namespace evo::accounting