[pve-devel] [PATCH pve-common 2/4] Added PVE::JSONSchema::parse_size/format_size

Wolfgang Bumiller w.bumiller at proxmox.com
Thu Oct 1 10:04:54 CEST 2015


---
 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.1.4





More information about the pve-devel mailing list