From 878fea8ef08496f4efd275e07c77bc55d90424b2 Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Thu, 1 Oct 2015 10:36:27 +0200 Subject: [PATCH] Added PVE::JSONSchema::parse_size/format_size --- src/PVE/JSONSchema.pm | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/PVE/JSONSchema.pm b/src/PVE/JSONSchema.pm index 51dfc89..5beebd8 100644 --- a/src/PVE/JSONSchema.pm +++ b/src/PVE/JSONSchema.pm @@ -438,6 +438,45 @@ sub check_format { } } +sub parse_size { + my ($value) = @_; + + return undef if $value !~ m/^(\d+(\.\d+)?)([KMGT])?$/; + my ($size, $unit) = ($1, $3); + if ($unit) { + if ($unit eq 'K') { + $size = $size * 1024; + } elsif ($unit eq 'M') { + $size = $size * 1024 * 1024; + } elsif ($unit eq 'G') { + $size = $size * 1024 * 1024 * 1024; + } elsif ($unit eq 'T') { + $size = $size * 1024 * 1024 * 1024 * 1024; + } + } + return int($size); +}; + +sub format_size { + my ($size) = @_; + + $size = int($size); + + my $kb = int($size/1024); + return $size if $kb*1024 != $size; + + my $mb = int($kb/1024); + return "${kb}K" if $mb*1024 != $kb; + + my $gb = int($mb/1024); + return "${mb}M" if $gb*1024 != $mb; + + my $tb = int($gb/1024); + return "${gb}G" if $tb*1024 != $gb; + + return "${tb}T"; +}; + sub parse_property_string { my ($format, $data, $path) = @_; -- 2.39.2