We can't output better memory sizes if we want to be compatible with libvirt
older than the one which introduced /memory/unit, but for new things we can just
output nicer capacity to the user if available. And this function enables that.
Signed-off-by: Martin Kletzander <mkletzan(a)redhat.com>
---
src/libvirt_private.syms | 1 +
src/util/virutil.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++
src/util/virutil.h | 3 +++
3 files changed, 54 insertions(+)
diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms
index 36cd5b55b249..d4bae6150bb8 100644
--- a/src/libvirt_private.syms
+++ b/src/libvirt_private.syms
@@ -2954,6 +2954,7 @@ virParseNumber;
virParseOwnershipIds;
virParseVersionString;
virPipeReadUntilEOF;
+virPrettySize;
virScaleInteger;
virSetBlocking;
virSetCloseExec;
diff --git a/src/util/virutil.c b/src/util/virutil.c
index 170e921920ef..dcfb65262aff 100644
--- a/src/util/virutil.c
+++ b/src/util/virutil.c
@@ -1993,3 +1993,53 @@ virMemoryMaxValue(bool capped)
else
return LLONG_MAX;
}
+
+
+/**
+ * virPrettySize
+ *
+ * @val: Value in bytes to be shortened
+ * @unit: unit to be used
+ *
+ * Similar to vshPrettyCapacity, but operates on integers and not doubles
+ *
+ * Returns shortened value that can be used with @unit.
+ */
+unsigned long long
+virPrettySize(unsigned long long val, const char **unit)
+{
+ unsigned long long limit = 1024;
+
+ if (val % limit || val == 0) {
+ *unit = "B";
+ return val;
+ }
+ limit *= 1024;
+ if (val % limit) {
+ *unit = "KiB";
+ return val / (limit / 1024);
+ }
+ limit *= 1024;
+ if (val % limit) {
+ *unit = "MiB";
+ return val / (limit / 1024);
+ }
+ limit *= 1024;
+ if (val % limit) {
+ *unit = "GiB";
+ return val / (limit / 1024);
+ }
+ limit *= 1024;
+ if (val % limit) {
+ *unit = "TiB";
+ return val / (limit / 1024);
+ }
+ limit *= 1024;
+ if (val % limit) {
+ *unit = "PiB";
+ return val / (limit / 1024);
+ }
+ limit *= 1024;
+ *unit = "EiB";
+ return val / (limit / 1024);
+}
diff --git a/src/util/virutil.h b/src/util/virutil.h
index ff89d1aaaa5f..72e35fc9a607 100644
--- a/src/util/virutil.h
+++ b/src/util/virutil.h
@@ -222,4 +222,7 @@ unsigned long long virMemoryMaxValue(bool ulong) ATTRIBUTE_NOINLINE;
# define VIR_ASSIGN_IS_OVERFLOW(lvalue, rvalue) \
(((lvalue) = (rvalue)) != (rvalue))
+unsigned long long
+virPrettySize(unsigned long long val, const char **unit);
+
#endif /* __VIR_UTIL_H__ */
--
2.15.0