fxos/include/fxos/util.h

116 lines
3.0 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 <ctime>
#include <vector>
/* Format a string with printf() syntax */
template<typename ... Args>
std::string format_do(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);
}
/* Convert std::string to char * when printing (@Zitrax on Github) */
template<typename T>
auto format_convert(T&& t)
{
if constexpr(std::is_same<std::remove_cv_t<std::remove_reference_t<T>>,
std::string>::value)
{
return std::forward<T>(t).c_str();
}
else
{
return std::forward<T>(t);
}
}
/* String formatting with std::string support in %s */
template<typename ... Args>
std::string format(std::string const &format, Args && ... args)
{
return format_do(format, format_convert(std::forward<Args>(args))...);
}
/* Format a string with colors */
std::string colors(std::string str);
/* 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);
/* 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);
/* Buffer size */
size_t size;
/* Data */
std::shared_ptr<char> data;
/* File path, when constructed from file */
std::string path;
};
/* Generic timer which returns times in ns using CLOCK_REALTIME */
struct timespec timer_start(void);
long long timer_end(struct timespec start);
/* Format ns durations to us, ms or s depending on the value */
std::string timer_format(long long duration);
#endif /* LIBFXOS_UTIL_H */