break _bytecount subroutines out of FS::UI::Web
[freeside.git] / FS / FS / UI / bytecount.pm
1 package FS::UI::bytecount;
2
3 use strict;
4 use vars qw($DEBUG $me);
5 use FS::Conf;
6 use Number::Format;
7
8 $DEBUG = 0;
9 $me = '[FS::UID::bytecount]';
10
11 =head1 NAME
12
13 FS::UI::bytecount - Subroutines for parsing and displaying byte counters
14
15 =head1 SYNOPSIS
16
17   use FS::UI::bytecount;
18
19 =head1 SUBROUTINES
20
21 =over 4
22
23 =item bytecount_unexact COUNT
24
25 Returns a two decimal place value for COUNT followed by bytes, Kbytes, Mbytes,
26 or GBytes as appropriate.
27
28 =cut
29
30 sub bytecount_unexact {
31   my $bc = shift;
32   return("$bc bytes")
33     if ($bc < 1000);
34   return(sprintf("%.2f Kbytes", $bc/1000))
35     if ($bc < 1000000);
36   return(sprintf("%.2f Mbytes", $bc/1000000))
37     if ($bc < 1000000000);
38   return(sprintf("%.2f Gbytes", $bc/1000000000));
39 }
40
41 =item parse_bytecount AMOUNT
42
43 Accepts a number (digits and a decimal point) possibly followed by k, m, g, or
44 t (and an optional 'b') in either case.  Returns a pure number representing
45 the input or the input itself if unparsable.
46
47 =cut
48
49 sub parse_bytecount {
50   my $bc = shift;
51   return $bc if (($bc =~ tr/.//) > 1);
52   $bc =~ /^\s*([\d.]*)\s*([kKmMgGtT]?)[bB]?\s*$/ or return $bc;
53   my $base = $1;
54   return $bc unless length $base;
55   my $exponent = index ' kmgt', lc($2);
56   return $bc if ($exponent < 0 && $2);
57   $exponent = 0 if ($exponent < 0);
58   return $base * 1024 ** $exponent;
59 }
60
61 =item display_bytecount AMOUNT
62
63 Converts a pure number to a value followed possibly followed by k, m, g, or
64 t via Number::Format
65
66 =cut
67
68 sub display_bytecount {
69   my $bc = shift;
70   return $bc unless ($bc =~ /^(\d+)$/);
71   my $conf = new FS::Conf;
72   my $f = new Number::Format;
73   my $precision = $conf->exists('datavolume-significantdigits')
74                 ? $conf->config('datavolume-significantdigits')
75                 : 3;
76   my $unit = $conf->exists('datavolume-forcemegabytes') ? 'M' : 'A';
77
78   return $f->format_bytes($bc, precision => $precision, unit => $unit);
79 }
80
81 =back
82
83 =head1 BUGS
84
85 Fly
86
87 =head1 SEE ALSO
88
89 L<Number::Format>
90
91 =cut
92
93 1;
94