]> git.proxmox.com Git - pve-common.git/commit
Tools: add `convert_size` for generic byte conversion
authorThomas Lamprecht <t.lamprecht@proxmox.com>
Mon, 11 Sep 2017 08:41:34 +0000 (10:41 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Mon, 11 Sep 2017 09:12:41 +0000 (11:12 +0200)
commit8e677e74e72ba1e05cc82376df8e00ec6d9b89af
treef5fee5562fe725f9b1ed554a66350048e92d72cb
parenteead1ccaa509e8559e466ca5926c6625f27bff35
Tools: add `convert_size` for generic byte conversion

We often need to convert between file sizes, for formatting output,
but also code-internal. Some methods expect kilobytes, some gigabytes
and sometimes we need bytes.

While conversion from smaller to bigger units can be simply done with
a left-shift, the opposite conversion may need more attention -
depending on the used context.

If we allocate disks this is quite critical. For example, if we need
to allocate a disk with size 1023 bytes using the
PVE::Storage::vdisk_alloc method (which expects kilobytes) a
right shift by 10 (<=> division by 1024) would result in "0", which
obviously fails.

Thus we round up the converted value if a remainder was lost on the
transformation in this new method. This behaviour is opt-out, to be
on the safe side.

The method can be used in a clear way, as it gives information about
the source and target unit size, unlike "$var *= 1024", which doesn't
gives direct information at all, if not commented or derived
somewhere from its context.

For example:
 > my $size = convert_unit($value, 'gb' => 'kb');
is more clear than:
 > my $size = $value*1024*1024;

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
src/PVE/Tools.pm