]> git.proxmox.com Git - pve-common.git/blobdiff - src/PVE/Tools.pm
fix convert_size with decimal numbers and add tests
[pve-common.git] / src / PVE / Tools.pm
index 6d579d8f9cd1234cecafd986e60cf9eaec7a6c5b..f43424bb7307095debd575840b6495bb828eaf48 100644 (file)
@@ -1629,9 +1629,16 @@ sub encrypt_pw {
 }
 
 # intended usage: convert_size($val, "kb" => "gb")
-# on reduction (converting to a bigger unit) we round up by default if
-# information got lost. E.g. `convert_size(1023, "b" => "kb")` returns 1
+# we round up to the next integer by default
+# E.g. `convert_size(1023, "b" => "kb")` returns 1
 # use $no_round_up to switch this off, above example would then return 0
+# this is also true for converting down e.g. 0.0005 gb to mb returns 1
+# (0 if $no_round_up is true)
+# allowed formats for value:
+# 1234
+# 1234.
+# 1234.1234
+# .1234
 sub convert_size {
     my ($value, $from, $to, $no_round_up) = @_;
 
@@ -1644,21 +1651,22 @@ sub convert_size {
        pb => 5,
     };
 
-    $from = lc($from); $to = lc($to);
+    die "no value given"
+       if !defined($value) || $value eq "";
+
+    $from = lc($from // ''); $to = lc($to // '');
     die "unknown 'from' and/or 'to' units ($from => $to)"
-       if !(defined($units->{$from}) && defined($units->{$to}));
+       if !defined($units->{$from}) || !defined($units->{$to});
 
-    my $shift_amount = $units->{$from} - $units->{$to};
+    die "value '$value' is not a valid, positive number"
+       if $value !~ m/^(?:[0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)$/;
 
-    if ($shift_amount > 0) {
-       $value <<= ($shift_amount * 10);
-    } elsif ($shift_amount < 0) {
-       my $remainder = ($value & (1 << abs($shift_amount)*10) - 1);
-       $value >>= abs($shift_amount) * 10;
-       $value++ if $remainder && !$no_round_up;
-    }
+    my $shift_amount = ($units->{$from} - $units->{$to}) * 10;
+
+    $value *= 2**$shift_amount;
+    $value++ if !$no_round_up && ($value - int($value)) > 0.0;
 
-    return $value;
+    return int($value);
 }
 
 1;