From a0d1fee01e92f693641d625e3b754d5e76c69742 Mon Sep 17 00:00:00 2001 From: Max Wash Date: Wed, 1 Feb 2023 12:26:07 +0000 Subject: [PATCH] sandbox: add util functions --- sandbox/Makefile | 2 +- sandbox/util/data_size.c | 66 +++++++++++++++++++++++++++++++ sandbox/util/include/socks/util.h | 8 ++++ 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 sandbox/util/data_size.c create mode 100644 sandbox/util/include/socks/util.h diff --git a/sandbox/Makefile b/sandbox/Makefile index b25ec4a..25b8e0c 100644 --- a/sandbox/Makefile +++ b/sandbox/Makefile @@ -6,7 +6,7 @@ BUILD_DIR := $(SANDBOX_BASE_DIR)/../build/sandbox include $(SANDBOX_BASE_DIR)/../tools/make/gcc-host.mk EXEC_NAME := sandbox -DIR_LIST := memblock vm base queue btree +DIR_LIST := memblock vm base queue btree util INCLUDE_DIRS := $(foreach dir,$(DIR_LIST),-I$(dir)/include) SRC := $(foreach dir,$(DIR_LIST),$(wildcard $(dir)/*.c)) OBJ := $(addprefix $(BUILD_DIR)/,$(SRC:.c=.o)) diff --git a/sandbox/util/data_size.c b/sandbox/util/data_size.c new file mode 100644 index 0000000..665bbe9 --- /dev/null +++ b/sandbox/util/data_size.c @@ -0,0 +1,66 @@ +#include +#include + +struct magnitude { + size_t threshold; + const char *suffix; +}; + +#define USE_BASE2 + +/* This list must be in decending order of threshold */ +#ifdef USE_BASE2 +static struct magnitude k_magnitudes[] = { + { 0x10000000000, "TiB" }, + { 0x40000000, "GiB" }, + { 0x100000, "MiB" }, + { 0x400, "KiB" }, + { 0x00, "B" }, +}; +#else +static struct magnitude k_magnitudes[] = { + { 1000000000000, "TB" }, + { 1000000000, "GB" }, + { 1000000, "MB" }, + { 1000, "KB" }, + { 0, "B" }, +}; +#endif + +static void convert(size_t *big, size_t *small, size_t val, size_t threshold) +{ + if (!threshold) { + *big = val; + *small = 0; + return; + } + + *big = val / threshold; + size_t rem = val % threshold; + *small = (10 * rem) / threshold; +} + +void data_size_to_string(size_t value, char *out, size_t outsz) +{ + if (!value) { + snprintf(out, outsz, "0 B"); + return; + } + + size_t def_count = sizeof(k_magnitudes) / sizeof(struct magnitude); + + for (size_t i = 0; i < def_count; i++) { + if (value > k_magnitudes[i].threshold) { + size_t big, small; + convert(&big, &small, value, k_magnitudes[i].threshold); + if (small) { + snprintf(out, outsz, "%zu.%zu %s", big, small, k_magnitudes[i].suffix); + } else { + snprintf(out, outsz, "%zu %s", big, k_magnitudes[i].suffix); + } + return; + } + } + + *out = 0; +} diff --git a/sandbox/util/include/socks/util.h b/sandbox/util/include/socks/util.h new file mode 100644 index 0000000..ba2fd65 --- /dev/null +++ b/sandbox/util/include/socks/util.h @@ -0,0 +1,8 @@ +#ifndef SOCKS_UTIL_H_ +#define SOCKS_UTIL_H_ + +#include + +extern void data_size_to_string(size_t value, char *out, size_t outsz); + +#endif