91 lines
2.3 KiB
C++
91 lines
2.3 KiB
C++
//---
|
|
// fxos.util: Utility functions
|
|
//---
|
|
|
|
#ifndef LIBFXOS_UTIL_H
|
|
#define LIBFXOS_UTIL_H
|
|
|
|
#include <memory>
|
|
#include <iostream>
|
|
#include <string>
|
|
#include <memory>
|
|
#include <cstdio>
|
|
#include <vector>
|
|
|
|
/* 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 target, 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 with size 0 and no pointer */
|
|
Buffer();
|
|
|
|
/* Empty buffer initialized with given byte */
|
|
Buffer(size_t size, int fill=0x00);
|
|
|
|
/* Object is movable and move assignable but not copyable */
|
|
Buffer(Buffer const &other) = delete;
|
|
Buffer(Buffer &&other);
|
|
Buffer & operator=(Buffer &&other);
|
|
|
|
/* 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);
|
|
|
|
/* Buffer initialized from file by looking in one of the specified
|
|
directories only. */
|
|
Buffer(std::string filepath, std::vector<std::string> &folders,
|
|
ssize_t size=-1, int fill=0x00);
|
|
|
|
/* 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();
|
|
|
|
/* Buffer size */
|
|
size_t size;
|
|
/* Data */
|
|
char *data;
|
|
/* File path, when constructed from file */
|
|
std::string path;
|
|
};
|
|
|
|
#endif /* LIBFXOS_UTIL_H */
|