Skip to content

Instantly share code, notes, and snippets.

@nd3i
Created April 29, 2016 03:46
Show Gist options
  • Save nd3i/e7aa710778f18792346656edc880f11c to your computer and use it in GitHub Desktop.
Save nd3i/e7aa710778f18792346656edc880f11c to your computer and use it in GitHub Desktop.
use v6;
# add commas to a number (en_US only)
# adapted from: http://www.perlmonks.org/?node_id=653
sub cfy ($n --> Str) {
S:g/ (\d) <?before [\d ** 3]+ [\D|$$]> /$0\,/
given ~$n
}
constant powers = 60, 50, 40, 30, 20, 10;
constant units = <EB PB TB GB MB KB>;
# From: https://doc.perl6.org/language/operators#Hyper_Operators
sub pretty-file-size (Int $size --> Str) {
# rounding version of infix:</>(Int,Int)
sub infix:<r/>(Int \i1, Int \i2) {
round(i1 / i2, 0.1)
}
# build a vector of fractions of $size/unit
# and zip that with the fitting prefix
# e.g. size=123456; vector will be
# (0 EB 0 PB 0 TB 0 GB 0.1 MB 120.6 KB)
# starting with the biggest suffix,
# we take the first that is 0.5 of that suffix or bigger
for $size «r/« (2 «**« powers) Z units -> [\v, \suffix] {
return v ~ ' ' ~ suffix if v > 0.4
}
# this will be smaller or equal than 0.4 KB
return $size.Str;
}
for powers -> $test {
# generates a random size
my &a = { (2 ** $test) *
(1/4, 1/2, 1, 10, 100).pick *
(1..10).pick };
for a.Int xx 2 {
say cfy($_) ~ ' --> ' ~ pretty-file-size($_)
}
}
# OUTPUT:
# «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB»
# 4,035,225,266,123,964,416 --> 3.5 EB
# 115,292,150,460,684,697,600 --> 100 EB
# 1,970,324,836,974,592 --> 1.8 PB
# 6,755,399,441,055,744 --> 6 PB
# 659,706,976,665,600 --> 0.6 PB
# 2,199,023,255,552 --> 2 TB
# 107,374,182,400 --> 100 GB
# 21,474,836,480 --> 20 GB
# 524,288,000 --> 0.5 GB
# 4,194,304 --> 4 MB
# 716,800 --> 0.7 MB
# 1,024 --> 1 KB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment