Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef BANK_H
- #define BANK_H
- #include <condition_variable>
- #include <iostream>
- #include <map>
- #include <memory>
- #include <mutex>
- #include <stdexcept>
- #include <string>
- #include <utility>
- #include <vector>
- namespace bank {
- const int INITIAL_BALANCE = 100;
- struct transfer_error : std::runtime_error {
- explicit transfer_error(std::string &&message)
- : std::runtime_error(message) {
- }
- };
- struct not_enough_funds_error : transfer_error {
- explicit not_enough_funds_error(const int a, const int b)
- : transfer_error("Not enough funds: " + std::to_string(a) +
- " XTS available, " + std::to_string(b) +
- " XTS requested") {
- }
- };
- struct error_with_transaction : transfer_error {
- explicit error_with_transaction(std::string &&message)
- : transfer_error(std::move(message)) {
- }
- };
- struct error_with_arguments : std::runtime_error {
- explicit error_with_arguments()
- : std::runtime_error("less arguments than must be") {
- }
- };
- class user;
- struct transaction {
- // NOLINTNEXTLINE
- const user *const counterparty;
- // NOLINTNEXTLINE
- const int balance_delta_xts;
- // NOLINTNEXTLINE
- const std::string comment;
- // NOLINTNEXTLINE
- transaction(const user *recipient,
- int amount,
- // cppcheck-suppress passedByValue
- std::string comment) noexcept
- : counterparty(recipient),
- balance_delta_xts(amount),
- comment(std::move(comment)) {
- }
- };
- class user_transactions_iterator {
- private:
- size_t size_ = 0;
- const user *pointer_on_user_;
- public:
- user_transactions_iterator(const size_t current_count_transactions,
- const user *pointer_on_user)
- : size_(current_count_transactions), pointer_on_user_(pointer_on_user) {
- }
- transaction wait_next_transaction() noexcept;
- };
- class user {
- private:
- std::string user_name;
- int balance = 0;
- mutable std::mutex user_mutex;
- std::vector<transaction> operations;
- mutable std::condition_variable cond;
- public:
- explicit user();
- explicit user(const std::string &new_name);
- void transfer(user &counterparty,
- int amount_xts,
- const std::string &comment);
- [[nodiscard]] int balance_xts() const;
- [[nodiscard]] user_transactions_iterator monitor() const noexcept;
- template <typename T>
- user_transactions_iterator snapshot_transactions(const T &functor) const {
- std::unique_lock ul(user_mutex);
- functor(operations, balance);
- return user_transactions_iterator{operations.size(), this};
- }
- [[nodiscard]] std::string name() const noexcept;
- friend user_transactions_iterator;
- };
- struct ledger {
- private:
- std::map<std::string, user> users;
- mutable std::mutex ledger_mutex;
- public:
- ledger() = default;
- user &get_or_create_user(const std::string &name) noexcept;
- };
- } // namespace bank
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement