Xinqi Bao's Git

Implement esnprintf() and make formatted calls more efficient
[slstatus.git] / util.c
diff --git a/util.c b/util.c
index 08f14ff..923d4df 100644 (file)
--- a/util.c
+++ b/util.c
@@ -48,6 +48,27 @@ die(const char *fmt, ...)
        exit(1);
 }
 
+int
+esnprintf(char *str, size_t size, const char *fmt, ...)
+{
+       va_list ap;
+       int ret;
+
+       va_start(ap, fmt);
+       ret = vsnprintf(str, size, fmt, ap);
+       va_end(ap);
+
+       if (ret < 0) {
+               warn("snprintf:");
+               return -1;
+       } else if ((size_t)ret >= size) {
+               warn("snprintf: Output truncated");
+               return -1;
+       }
+
+       return ret;
+}
+
 const char *
 bprintf(const char *fmt, ...)
 {
@@ -65,6 +86,22 @@ bprintf(const char *fmt, ...)
        return buf;
 }
 
+const char *
+fmt_scaled(size_t bytes)
+{
+       unsigned int i;
+       float scaled;
+       const char *units[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
+                               "ZiB", "YiB" };
+
+       scaled = bytes;
+       for (i = 0; i < LEN(units) && scaled >= 1024; i++) {
+               scaled /= 1024.0;
+       }
+
+       return bprintf("%.1f%s", scaled, units[i]);
+}
+
 int
 pscanf(const char *path, const char *fmt, ...)
 {