-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuman_bytes.v
70 lines (54 loc) · 1.78 KB
/
human_bytes.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module human_bytes
import math { floor, is_inf, log, log10, min, pow }
import strconv { format_fl }
const (
binary_bit_units = ['b', 'kibit', 'Mibit', 'Gibit', 'Tibit', 'Pibit', 'Eibit', 'Zibit', 'Yibit']
binary_byte_units = ['B', 'kiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
bit_units = ['b', 'kbit', 'Mbit', 'Gbit', 'Tbit', 'Pbit', 'Ebit', 'Zbit', 'Ybit']
byte_units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
)
fn format(prefix string, value f64, precision int) string {
return prefix + format_fl(value, rm_tail_zero: true, len1: precision)
}
fn display_unit(units []string, index int) string {
return ' ${units[index]}'
}
struct Options {
bits bool
binary bool
signed bool
precision int = 2
}
pub fn convert(input_val f64) string {
return convert_opt(input_val, {})
}
pub fn convert_opt(input_val f64, options Options) string {
mut value := input_val
units := if options.binary {
if options.bits { binary_bit_units } else { binary_byte_units }
} else {
if options.bits { bit_units } else { byte_units }
}
if is_inf(input_val, 0) {
return format('', 0, options.precision) + display_unit(units, 0)
}
if options.signed && value == 0 {
return format(' ', 0, options.precision) + display_unit(units, 0)
}
negative := value < 0
prefix := if negative {
'-'
} else {
if options.signed { '+' } else { '' }
}
if negative {
value = -value
}
if value < 1 {
return format(prefix, value, options.precision) + display_unit(units, 0)
}
floored := floor(if options.binary { log(value) / log(1024) } else { log10(value) / 3 })
exponent := min(floored, units.len - 1)
value /= pow(if options.binary { 1024 } else { 1000 }, exponent)
return format(prefix, value, options.precision) + display_unit(units, int(exponent))
}