]>
Commit | Line | Data |
---|---|---|
1 | package PVE::Format; | |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | ||
6 | use POSIX qw(strftime); | |
7 | use PVE::JSONSchema; | |
8 | ||
9 | use base 'Exporter'; | |
10 | our @EXPORT_OK = qw( | |
11 | render_timestamp | |
12 | render_timestamp_gmt | |
13 | render_duration | |
14 | render_fraction_as_percentage | |
15 | render_bytes | |
16 | ); | |
17 | ||
18 | sub render_timestamp { | |
19 | my ($epoch) = @_; | |
20 | ||
21 | # ISO 8601 date format | |
22 | return strftime("%F %H:%M:%S", localtime($epoch)); | |
23 | } | |
24 | ||
25 | sub render_timestamp_gmt { | |
26 | my ($epoch) = @_; | |
27 | ||
28 | # ISO 8601 date format, standard Greenwich time zone | |
29 | return strftime("%F %H:%M:%S", gmtime($epoch)); | |
30 | } | |
31 | ||
32 | sub render_duration { | |
33 | my ($duration_in_seconds) = @_; | |
34 | ||
35 | my $text = ''; | |
36 | my $rest = $duration_in_seconds; | |
37 | ||
38 | my $step = sub { | |
39 | my ($unit, $unitlength) = @_; | |
40 | ||
41 | if ((my $v = int($rest/$unitlength)) > 0) { | |
42 | $text .= " " if length($text); | |
43 | $text .= "${v}${unit}"; | |
44 | $rest -= $v * $unitlength; | |
45 | } | |
46 | }; | |
47 | ||
48 | $step->('w', 7*24*3600); | |
49 | $step->('d', 24*3600); | |
50 | $step->('h', 3600); | |
51 | $step->('m', 60); | |
52 | $step->('s', 1); | |
53 | ||
54 | return $text; | |
55 | } | |
56 | ||
57 | sub render_fraction_as_percentage { | |
58 | my ($fraction) = @_; | |
59 | ||
60 | return sprintf("%.2f%%", $fraction*100); | |
61 | } | |
62 | ||
63 | sub render_bytes { | |
64 | my ($value, $precision) = @_; | |
65 | ||
66 | my @units = qw(B KiB MiB GiB TiB PiB); | |
67 | ||
68 | my $max_unit = 0; | |
69 | if ($value > 1023) { | |
70 | $max_unit = int(log($value)/log(1024)); | |
71 | $value /= 1024**($max_unit); | |
72 | } | |
73 | my $unit = $units[$max_unit]; | |
74 | return sprintf "%." . ($precision || 2) . "f $unit", $value; | |
75 | } | |
76 | ||
77 | 1; |