summaryrefslogtreecommitdiff
path: root/src/lib.c
diff options
context:
space:
mode:
authorFreya Murphy <freya@freyacat.org>2024-02-01 15:53:11 -0500
committerFreya Murphy <freya@freyacat.org>2024-02-01 15:53:11 -0500
commitef384ad9a7f81c1b5dac1bb9a80f9faf3e8023df (patch)
tree8a32d38c8152f57c09e01a39587237c99c4614fc /src/lib.c
parentupdate makefile (diff)
downloadcorn-ef384ad9a7f81c1b5dac1bb9a80f9faf3e8023df.tar.gz
corn-ef384ad9a7f81c1b5dac1bb9a80f9faf3e8023df.tar.bz2
corn-ef384ad9a7f81c1b5dac1bb9a80f9faf3e8023df.zip
display mem formatted
Diffstat (limited to 'src/lib.c')
-rw-r--r--src/lib.c77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/lib.c b/src/lib.c
index 7f3d79f..e298b00 100644
--- a/src/lib.c
+++ b/src/lib.c
@@ -128,6 +128,83 @@ int ctoi(char c) {
}
}
+static char fs_endings[] = {'K', 'M', 'G', 'T', 'P'};
+
+static size_t nth_pow(size_t i, size_t e) {
+ size_t a = i;
+ while(--e)
+ a *= i;
+ return a;
+}
+
+static char nth_digit(size_t bytes, size_t place) {
+ while (1) {
+ if (bytes < nth_pow(10, place))
+ break;
+ bytes /= 10;
+ }
+ return bytes %= 10;
+}
+
+char *btoa(const size_t bytes, char *buf) {
+
+ char *start = buf;
+
+ int idx = -1;
+
+ size_t b = bytes;
+ size_t s = b;
+ while (1) {
+ if (b < 1000)
+ break;
+ s = b;
+ b /= 1024;
+ idx++;
+ }
+
+ if (idx == -1) {
+ ultoa(bytes, buf, 10);
+ return start;
+ }
+
+ s = s * 1000 / 1024;
+
+ if (s < 1024) {
+ b = 1024;
+ idx--;
+ }
+
+ char fd = nth_digit(s, 1);
+ char sd = nth_digit(s, 2);
+ char td = nth_digit(s, 3);
+
+ *buf = fd + '0';
+ buf++;
+
+ if (b < 10) {
+ *buf = '.';
+ buf++;
+ }
+
+ *buf = sd + '0';
+ buf++;
+
+ if (b < 10)
+ goto end;
+
+ if (b > 99) {
+ *buf = td + '0';
+ buf++;
+ }
+
+end:
+
+ *buf = fs_endings[idx];
+ buf++;
+ *buf = '\0';
+ return start;
+}
+
#define UXTOA(type, name) \
char *name(unsigned type n, char *buffer, int radix) { \
if (n == 0) { \