commit: 36500620827964b007ed258c3b4afb3d443b1aed
parent 0d8f00af117f6c66eb7501457fed6d56202d13bc
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Thu, 13 May 2021 22:26:12 +0200
bin/humanize.c: New util
Diffstat:
3 files changed, 70 insertions(+), 1 deletion(-)
diff --git a/bin/Makefile b/bin/Makefile
@@ -15,6 +15,9 @@ lolcat: lolcat.c Makefile
xcd: xcd.c Makefile
$(CC) -std=c11 $(CFLAGS) -o $@ $< -lm $(LDFLAGS)
+humanize: humanize.c Makefile
+ $(CC) -std=c11 $(CFLAGS) `pkg-config --cflags libbsd-overlay` -o $@ $< `pkg-config --libs libbsd-overlay` $(LDFLAGS)
+
install:
mkdir -p ${DESTDIR}${BINDIR}/
cp -p ${EXE} ${DESTDIR}${BINDIR}/
diff --git a/bin/Makefile.config b/bin/Makefile.config
@@ -1,2 +1,2 @@
-EXE = args basename date dirname echo lolcat mdate pwd range sizeof sname tty xcd
+EXE = args basename date dirname echo humanize lolcat mdate pwd range sizeof sname tty xcd
MAN1 = basename.1 date.1 dirname.1 lolcat.1 sname.1
diff --git a/bin/humanize.c b/bin/humanize.c
@@ -0,0 +1,66 @@
+#define _DEFAULT_SOURCE
+// strtonum
+#define _OPENBSD_SOURCE
+// On non-BSDs use libbsd
+#include <err.h> // errx,
+#include <errno.h> // EINVAL, ERANGE
+#include <stdio.h> // fprintf
+#include <stdlib.h> // humanize_number, strtonum
+#include <unistd.h> // opt*, getopt
+#include <limits.h> // LLONG_MIN, LLONG_MAX
+
+void
+usage()
+{
+ fprintf(stderr, "Usage: humanize [-bd] number");
+}
+
+int
+main(int argc, char *argv[])
+{
+ int c;
+ int flags = HN_DIVISOR_1000|HN_NOSPACE;
+
+ while((c = getopt(argc, argv, "d")) != -1)
+ {
+ switch(c)
+ {
+ case 'd': flags &= HN_DIVISOR_1000; break;
+ case 'b': flags &= ~HN_DIVISOR_1000; break;
+ case '?':
+ fprintf(stderr, "Error: Unrecognised option: '-%c'\n", optopt);
+ usage();
+ return 1;
+ }
+ }
+
+ for(; optind < argc; optind++)
+ {
+ const char *errstr = NULL;
+ char buffer[6] = "-";
+
+ // 1024^(6+1) goes higher than long long; don't ask for the moon
+ long long n = strtonum(argv[optind], LLONG_MIN, LLONG_MAX, &errstr);
+ if(errstr)
+ {
+ errx(1, "strtonum: %s is %s", argv[optind], errstr);
+ }
+
+ int err = humanize_number(buffer, sizeof(buffer), n, "", HN_AUTOSCALE, flags);
+ if(err < 0)
+ {
+ switch(errno)
+ {
+ case EINVAL: fprintf(stderr, "Number carried an unknown suffix.\n"); return 1;
+ case ERANGE: fprintf(stderr, "Represents a number that does not fit in result.\n"); return 1;
+ default: errx(1, "humanize_number: %s is %s", argv[optind], errstr);
+ }
+ }
+
+ printf("%s ", buffer);
+ }
+
+ printf("\n");
+
+ return 0;
+}