96 lines
2.2 KiB
C++
96 lines
2.2 KiB
C++
/**
|
|
* @file utils.hpp
|
|
* @author Gustice
|
|
* @brief Template
|
|
*
|
|
* @copyright Copyright (c) 2024
|
|
*/
|
|
#pragma once
|
|
|
|
#include <cassert>
|
|
#include <exception>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <cstdint>
|
|
|
|
/**
|
|
* @brief Simple exception
|
|
*/
|
|
class CoreException : public std::exception {
|
|
char const *Text;
|
|
|
|
public:
|
|
/// @brief Constructor with simple pointer to text
|
|
CoreException(char const *text) : Text(text) {
|
|
}
|
|
|
|
/// @brief error message getter
|
|
char const *what() const throw() override { return Text; }
|
|
};
|
|
|
|
/**
|
|
* @brief Common interface for character streams
|
|
*/
|
|
class CharStream {
|
|
public:
|
|
/// @brief Read method
|
|
/// @return string
|
|
virtual std::string read() = 0;
|
|
|
|
/// @brief Write character
|
|
/// @param c character to write
|
|
virtual void write(char c) = 0;
|
|
|
|
/// @brief Write string
|
|
/// @param str string to write
|
|
virtual void write(std::string str) = 0;
|
|
};
|
|
|
|
/**
|
|
* @brief Common interface
|
|
*/
|
|
class ByteStream {
|
|
/// @brief Read method
|
|
/// @return series of bytes
|
|
virtual std::vector<uint8_t> read() = 0;
|
|
|
|
/// @brief write single byte
|
|
/// @param b byte to write
|
|
virtual void write(uint8_t b) = 0;
|
|
|
|
/// @brief write series of bytes
|
|
/// @param data series to write
|
|
virtual void write(std::vector<uint8_t> data) = 0;
|
|
};
|
|
|
|
/**
|
|
* @brief Base for constructs that allow only one concurrently active instance
|
|
*
|
|
* @tparam T
|
|
* @note needs a `T * T::SingleActive<T>::active{};` definition in source
|
|
*/
|
|
template <typename T>
|
|
class SingleActive {
|
|
static bool active;
|
|
|
|
public:
|
|
/// @brief Constructor, memorizes if already on instance was successfully build
|
|
SingleActive() {
|
|
if (active) {
|
|
throw "Instance already active";
|
|
}
|
|
assert(active == false && "Constructor my only be run if no instance active");
|
|
active = true;
|
|
}
|
|
|
|
/// @brief Destructor, clears memory of existing instance
|
|
~SingleActive() {
|
|
assert(active == true && "Destructor my only be run on active instance");
|
|
active = false;
|
|
}
|
|
|
|
// Disable move and assignment
|
|
SingleActive(SingleActive &other) = delete;
|
|
void operator=(const SingleActive &) = delete;
|
|
};
|