87 lines
2.5 KiB
C++
87 lines
2.5 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, bool ljust) {
|
|
if (len > s.size())
|
|
s.insert(ljust ? 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 readFile2(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 readFile2(std::string path, char* buffer, size_t maxlen) {
|
|
return readFile2(path.c_str(), buffer, maxlen);
|
|
}
|
|
|
|
std::string readFile(std::string path, size_t trim) {
|
|
char* buf = new char[trim + 2];
|
|
ssize_t len = readFile2(path, buf, trim + 2);
|
|
std::string out(buf);
|
|
delete[] buf;
|
|
if (!len) return "0";
|
|
return out.substr(0, len - 1);
|
|
}
|
|
|
|
int get_val(std::string_view target, std::string_view content) {
|
|
int result = -1;
|
|
std::size_t start = content.find(target);
|
|
if (start != std::string::npos) {
|
|
int begin = start + target.length();
|
|
std::size_t end = content.find("kB", start);
|
|
result = std::strtol(content.substr(begin, end - begin).data(), NULL, 10);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
std::string getFirstDir(std::string_view path) {
|
|
for (const auto& entry : std::filesystem::directory_iterator(path))
|
|
return entry.path();
|
|
return "";
|
|
}
|