|
| 1 | +compute_bytes <- function(bytes, smallest_unit = "B") { |
| 2 | + units0 <- c("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") |
| 3 | + |
| 4 | + stopifnot( |
| 5 | + is.numeric(bytes), |
| 6 | + is.character(smallest_unit), |
| 7 | + length(smallest_unit) == 1, |
| 8 | + !is.na(smallest_unit), |
| 9 | + smallest_unit %in% units0 |
| 10 | + ) |
| 11 | + |
| 12 | + negative <- (bytes < 0) |
| 13 | + bytes <- abs(bytes) |
| 14 | + smallest_idx <- match(smallest_unit, units0) |
| 15 | + |
| 16 | + limits <- c(1000, 999950 * 1000 ^ (seq_len(length(units0) - 2) - 1)) |
| 17 | + idx <- cut(bytes, c(0, limits, Inf), labels = FALSE, right = FALSE) |
| 18 | + idx <- pmax(idx, smallest_idx) |
| 19 | + |
| 20 | + amount <- bytes / signif(c(1, limits), 1)[idx] |
| 21 | + idx[is.na(idx)] <- smallest_idx |
| 22 | + unit <- units0[idx] |
| 23 | + |
| 24 | + data.frame( |
| 25 | + stringsAsFactors = FALSE, |
| 26 | + amount, |
| 27 | + unit, |
| 28 | + negative |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +pretty_bytes_default <- function(bytes) { |
| 33 | + szs <- compute_bytes(bytes) |
| 34 | + amt <- szs$amount * ifelse(szs$negative, -1, 1) |
| 35 | + |
| 36 | + is_int <- is.na(amt) | amt == as.integer(amt) |
| 37 | + |
| 38 | + ## String. For fractions we always show two fraction digits |
| 39 | + res <- ifelse( |
| 40 | + is_int, |
| 41 | + sprintf("%.0f%s", amt, ifelse(all(is_int) | (szs$unit == "B"), "", " ")), |
| 42 | + sprintf("%.2f", amt) |
| 43 | + ) |
| 44 | + |
| 45 | + format(paste(res, szs$unit), justify = "right") |
| 46 | +} |
| 47 | + |
| 48 | +pretty_bytes_nopad <- function(bytes) { |
| 49 | + sub("^\\s+", "", pretty_bytes_default(bytes)) |
| 50 | +} |
0 commit comments