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