fxos/include/fxos/util.h

88 lines
2.1 KiB
C++

//---
// fxos.util: Utility functions
//---
#ifndef LIBFXOS_UTIL_H
#define LIBFXOS_UTIL_H
#include <memory>
#include <iostream>
#include <string>
#include <memory>
#include <cstdio>
/* Format a string with printf() syntax */
template<typename ... Args>
std::string format(std::string const &format, Args ... args)
{
/* Reserve space for snprintf() to put its NUL */
size_t size = snprintf(nullptr, 0, format.c_str(), args ...) + 1;
std::unique_ptr<char[]> buf(new char[size]);
snprintf(buf.get(), size, format.c_str(), args ...);
/* Remove the NUL from the string */
return std::string(buf.get(), buf.get() + size - 1);
}
/* An object extracted from a targets, which has a virtual address */
template<typename T>
struct Addressable
{
/* Value */
T value;
/* Original virtual address */
uint32_t address;
Addressable() = default;
Addressable(T value): value(value), address(-1) {}
Addressable(uint32_t addr, T value): value(value), address(addr) {}
/* Implicitly decay to the base type */
operator T () const { return value; }
/* Return the address when using [&] */
uint32_t operator & () const { return address; }
};
/* An RAII contiguous memory buffer */
class Buffer
{
public:
/* Empty buffer initialized with given byte */
Buffer(size_t size, int fill=0x00);
/* Buffer initialized from file, reading the given size from the
beginning of the file. If the file is smaller than the specified
size, the buffer is padded.
If this constructor is used, the file path is remembered. */
Buffer(std::string filepath, ssize_t size=-1, int fill=0x00);
/* Create a buffer by copying another buffer */
Buffer(Buffer const &other);
/* Create a buffer by copying and resizing another buffer */
Buffer(Buffer const &other, size_t new_size, int fill=0x00);
/* Free allocated data, obviously */
~Buffer();
/* Get buffer size */
size_t size() const noexcept;
/* Get data */
char *data() noexcept;
char const *data() const noexcept;
/* Get file path, when constructed from file */
std::string path() const noexcept;
private:
void *m_data;
size_t m_size;
std::string m_path;
};
#endif /* LIBFXOS_UTIL_H */