68 lines
2.0 KiB
C++
68 lines
2.0 KiB
C++
#include <fcntl.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
#include <array>
|
|
#include <cstdint>
|
|
#include <cstdlib>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <log.hpp>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <utils.hpp>
|
|
|
|
// pads given string to length
|
|
std::string pad(std::string s, uint8_t len, JUST j) {
|
|
if (len > s.size())
|
|
s.insert(j == JUST::LEFT ? s.end() : s.begin(), len - s.size(), FILL_CHAR);
|
|
return s;
|
|
}
|
|
|
|
// returns the string centered within given length
|
|
std::string center(std::string str, uint8_t len) {
|
|
uint8_t padding = len - str.size();
|
|
str.insert(str.begin(), padding / 2, FILL_CHAR);
|
|
str.insert(str.end(), padding / 2, FILL_CHAR);
|
|
return str;
|
|
}
|
|
|
|
// converts large number in (k)bytes to human readable numer with suffix and sane decimal
|
|
std::string pBytes(double bytes, bool isKbytes) {
|
|
std::array suffix_list = {'K', 'M', 'G', 'T', 'P', 'E', 'Z'};
|
|
for (auto& suffix : suffix_list) {
|
|
if (suffix == 'K' && isKbytes) continue; // skip first loop if already in Kbytes
|
|
bytes /= 1024.0;
|
|
if (bytes < 1024) {
|
|
if (bytes > 100) return pNum(bytes) + suffix;
|
|
if (bytes > 10) return pNum(bytes, 1) + suffix;
|
|
return pNum(bytes, 2) + suffix;
|
|
}
|
|
}
|
|
return "++++";
|
|
}
|
|
|
|
/* SENSOR GETTERS + UTILS*/
|
|
ssize_t readFile(const char* path, char* buffer, size_t maxlen) {
|
|
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
|
if (fd < 0) {
|
|
log(LOG::ERR, "readFile2", "Error reading {}", path);
|
|
return 0;
|
|
}
|
|
ssize_t len = read(fd, buffer, maxlen - 1);
|
|
if (len >= 0) buffer[len] = '\0';
|
|
close(fd);
|
|
return len;
|
|
}
|
|
|
|
ssize_t readFile(std::string path, char* buffer, size_t maxlen) {
|
|
return readFile(path.c_str(), buffer, maxlen);
|
|
}
|
|
|
|
/* finds first dir in path and returns it*/
|
|
std::string getFirstDir(std::string_view path) {
|
|
for (const auto& entry : std::filesystem::directory_iterator(path))
|
|
return entry.path();
|
|
return "";
|
|
}
|