This commit is contained in:
2026-05-10 21:17:36 +02:00
parent f28cd4c31a
commit 9bd2357b96
7 changed files with 118 additions and 33 deletions

View File

@@ -4,12 +4,42 @@
#include <unistd.h>
#include <glob.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include "log.h"
#include "utils.h"
#define MKPATH(path, dir, file) do {char *nt = stpcpy(path, dir); *nt++ = '/'; stpcpy(nt, file); } while (0)
inline void timespec_add_ms(struct timespec *ts, const uint16_t ms) {
ts->tv_nsec += ms * 1000000L;
if (ts->tv_nsec >= 1000000000L) {
ts->tv_sec++;
ts->tv_nsec -= 1000000000L;
}
}
inline uint64_t timespec_diff_us(const struct timespec *a, const struct timespec *b) {
const int64_t sec = a->tv_sec - b->tv_sec;
const int64_t nsec = a->tv_nsec - b->tv_nsec;
return sec * 1000000LL + nsec / 1000LL;
}
char *pretty_bytes(const uint64_t bytes, int8_t start_suffix, char *buf, const size_t bufsz) {
constexpr char suffix_list[] = {'K', 'M', 'G', 'T', 'P', 'E', 'Z'};
start_suffix *= -1;
double bytes_d = (double)bytes;
while (bytes_d > 1024.0) {
bytes_d /= 1024.0;
start_suffix++;
}
const uint8_t decimals = (bytes_d < 10) ? 2 : (bytes_d < 100) ? 1 : 0;
snprintf(buf, bufsz, "%.*f%c", decimals, bytes_d, suffix_list[MAX(0, start_suffix)]);
return buf;
}
inline bool file_exists(const char* path) {
return access(path, F_OK) == 0;
}
@@ -17,10 +47,10 @@ inline bool file_exists(const char* path) {
/* path has to have at least 8 free chars at the end for glob */
int get_hwmon_dir(char* path) {
glob_t g;
strncat(path, "/hwmon*", 8);
strncat(path, "/hwmon*", 10);
if (glob(path, 0, nullptr, &g) == 0) {
strncpy(path, g.gl_pathv[0], 256);
strncpy(path, g.gl_pathv[0], 128); // bug prone, careful
globfree(&g);
return 0;
}
@@ -47,6 +77,13 @@ inline void fast_read_num_u64(const char* dir, const char* file, char* buf, uint
*result = strtoull(buf, nullptr, 10) / divider;
}
inline void fast_read_num_u16(const char* dir, const char* file, char* buf, uint16_t* result, const uint16_t divider) {
char path[256];
MKPATH(path, dir, file);
read_file(path, buf, 32);
*result = strtol(buf, nullptr, 10) / divider;
}
inline void fast_read_num_i16(const char* dir, const char* file, char* buf, int16_t* result, const uint16_t divider) {
char path[256];
MKPATH(path, dir, file);