ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
util/format.c
Go to the documentation of this file.
1
6
8#include <libplatform/system.h>
9#include <inttypes.h>
10
11void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity) {
12 const double KB = 1024.0;
13 const double MB = KB * 1024.0;
14 const double GB = MB * 1024.0;
15 const double TB = GB * 1024.0;
16 const double PB = TB * 1024.0;
17 const double EB = PB * 1024.0;
18
19 const double THRESHOLD = 0.8;
20
21 double byte_val = (double)bytes;
22
23 if (byte_val < THRESHOLD * KB) {
24 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%zu B", bytes));
25 } else if (byte_val < THRESHOLD * MB) {
26 double value = byte_val / KB;
27 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f KB", value));
28 } else if (byte_val < THRESHOLD * GB) {
29 double value = byte_val / MB;
30 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f MB", value));
31 } else if (byte_val < THRESHOLD * TB) {
32 double value = byte_val / GB;
33 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f GB", value));
34 } else if (byte_val < THRESHOLD * PB) {
35 double value = byte_val / TB;
36 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f TB", value));
37 } else if (byte_val < THRESHOLD * EB) {
38 double value = byte_val / PB;
39 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f PB", value));
40 } else {
41 double value = byte_val / EB;
42 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%.2f EB", value));
43 }
44}
45
46void format_number_compact(uint64_t value, char *out, size_t out_capacity) {
47 if (!out || !out_capacity)
48 return;
49 static const char suffixes[] = "kmbtpe";
50 if (value < 1000) {
51 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%" PRIu64, value));
52 return;
53 }
54 uint64_t scale = 1000;
55 size_t unit = 0;
56 while (unit + 1 < sizeof(suffixes) - 1 && value / scale >= 1000) {
57 scale *= 1000;
58 ++unit;
59 }
60 uint64_t whole = value / scale;
61 uint64_t step = scale / 10;
62 uint64_t fraction = (value % scale + step / 2) / step;
63 if (fraction == 10) {
64 ++whole;
65 fraction = 0;
66 }
67 if (whole == 1000 && unit + 1 < sizeof(suffixes) - 1) {
68 whole = 1;
69 ++unit;
70 }
71 if (fraction)
72 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%" PRIu64 ".%" PRIu64 "%c", whole, fraction, suffixes[unit]));
73 else
74 SAFE_IGNORE_PRINTF_RESULT(safe_snprintf(out, out_capacity, "%" PRIu64 "%c", whole, suffixes[unit]));
75}
unsigned long long uint64_t
void format_bytes_pretty(size_t bytes, char *out, size_t out_capacity)
Format byte count into human-readable string.
Definition util/format.c:11
static bool size_t gotel_query_t * out
Definition queries.h:8
void format_number_compact(uint64_t value, char *out, size_t out_capacity)
Definition util/format.c:46
📊 String Formatting Utilities