81 lines
2.5 KiB
C++
81 lines
2.5 KiB
C++
#ifndef UTILS_HPP
|
|
#define UTILS_HPP
|
|
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <array>
|
|
#include <charconv>
|
|
#include <cstdint>
|
|
#include <log.hpp>
|
|
#include <filesystem>
|
|
#include <string>
|
|
|
|
namespace utils {
|
|
|
|
constexpr char fill_char = ' ';
|
|
enum just : uint8_t { right, left };
|
|
|
|
std::string pad(std::string s, uint8_t len, just j = right);
|
|
std::string center(std::string str, uint8_t len);
|
|
std::string getFirstDir(const std::string_view& path);
|
|
|
|
inline std::string pNum(const auto num, const uint8_t decs = 0) {
|
|
static std::array<char, 20> buf;
|
|
auto [ptr, ec] = std::to_chars(buf.data(), buf.data() + buf.size(), static_cast<double>(num), std::chars_format::fixed, decs);
|
|
return {buf.data(), ptr};
|
|
}
|
|
|
|
/* converts large number in (k)bytes to human-readable numer with suffix and sane decimal */
|
|
std::string pBytes(const auto bytes, const bool isKbytes = false) {
|
|
double bytes_d = bytes;
|
|
for (constexpr std::array suffix_list = {'K', 'M', 'G', 'T', 'P', 'E', 'Z'}; const auto& suffix : suffix_list) {
|
|
if (suffix == 'K' && isKbytes) continue; // skip first loop if already in Kbytes
|
|
bytes_d /= 1024.0;
|
|
if (bytes_d < 1024) {
|
|
if (bytes_d > 100) return pNum(bytes_d) + suffix;
|
|
if (bytes_d > 10) return pNum(bytes_d, 1) + suffix;
|
|
return pNum(bytes_d, 2) + suffix;
|
|
}
|
|
}
|
|
return "++++";
|
|
}
|
|
|
|
/* reads file into a std::array buffer */
|
|
template <size_t N>
|
|
inline ssize_t readFile(const std::string& path, std::array<char, N>& buffer) {
|
|
const int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
applog(LOG::ERR, "Error reading {}", path);
|
|
return 0;
|
|
}
|
|
const ssize_t len = read(fd, buffer.data(), buffer.size());
|
|
if (len >= 0) buffer[len] = '\0';
|
|
close(fd);
|
|
return len;
|
|
}
|
|
|
|
|
|
/* reads a number fast and divides it if needed */
|
|
template <uint32_t Divider = 1, typename T, size_t N>
|
|
inline void fastReadNum(const std::string& path, std::array<char, N>& buf, T& result) {
|
|
readFile(path, buf);
|
|
if constexpr (Divider == 1) {
|
|
std::from_chars(buf.data(), buf.data() + N, result);
|
|
return;
|
|
}
|
|
uint64_t temp{};
|
|
std::from_chars(buf.data(), buf.data() + N, temp);
|
|
if constexpr (std::is_floating_point_v<T>)
|
|
result = temp / static_cast<T>(Divider);
|
|
else
|
|
result = static_cast<T>(temp / Divider);
|
|
}
|
|
|
|
inline bool fileExists(const std::string_view& path) {
|
|
return std::filesystem::exists(path);
|
|
}
|
|
|
|
} // namespace utils
|
|
|
|
#endif
|