util: Introduce virFormatIntPretty

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@redhat.com>
Reviewed-by: John Ferlan <jferlan@redhat.com>
This commit is contained in:
Martin Kletzander 2017-11-09 16:19:25 +01:00
parent b8bbc23fea
commit 87a8a30d61
3 changed files with 56 additions and 0 deletions

View File

@ -2927,6 +2927,7 @@ virDoubleToStr;
virEnumFromString;
virEnumToString;
virFormatIntDecimal;
virFormatIntPretty;
virGetDeviceID;
virGetDeviceUnprivSGIO;
virGetEnvAllowSUID;

View File

@ -485,6 +485,57 @@ virFormatIntDecimal(char *buf, size_t buflen, int val)
}
/**
* virFormatIntPretty
*
* @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
virFormatIntPretty(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);
}
const char *virEnumToString(const char *const*types,
unsigned int ntypes,
int type)

View File

@ -66,6 +66,10 @@ int virParseVersionString(const char *str, unsigned long *version,
char *virFormatIntDecimal(char *buf, size_t buflen, int val)
ATTRIBUTE_NONNULL(1) ATTRIBUTE_RETURN_CHECK;
unsigned long long
virFormatIntPretty(unsigned long long val,
const char **unit);
int virDiskNameParse(const char *name, int *disk, int *partition);
int virDiskNameToIndex(const char* str);
char *virIndexToDiskName(int idx, const char *prefix);