R/hbytes.r

Defines functions hbytes

Documented in hbytes

#' Print bytes in nice human-readable format
#'
#' Basically format.object_size from utils, but vectorized and includes .0
#'
#' @param x   Number of bytes (integer)
#'
#' @examples
#' hbytes(12300)
#' hbytes(c(12300, 12345))
#' @export

hbytes <- function(x) {
  out <- character(length(x))
  for (i in 1:length(x)) {
    y <- format_object_size(x[i], 'auto')
    a <- gsub(' .*', '', y)
    b <- gsub('.* ', '', y)
    out[i] <- paste(sprintf('%.1f', as.numeric(a)), b)
  }
  out
}

#' This is literally copied from utils:::format.object_size
#' @param x,units,standard,digits,...  See `utils:::format.object_size()`
format_object_size <- function (x, units = "b", standard = "auto", digits = 1L, ...)
{
  known_bases <- c(legacy = 1024, IEC = 1024, SI = 1000)
  known_units <- list(SI = c("B", "kB", "MB", "GB", "TB", "PB",
                             "EB", "ZB", "YB"), IEC = c("B", "KiB", "MiB", "GiB",
                                                        "TiB", "PiB", "EiB", "ZiB", "YiB"), legacy = c("b", "Kb",
                                                                                                       "Mb", "Gb", "Tb", "Pb"), LEGACY = c("B", "KB", "MB",
                                                                                                                                           "GB", "TB", "PB"))
  units <- match.arg(units, c("auto", unique(unlist(known_units),
                                             use.names = FALSE)))
  standard <- match.arg(standard, c("auto", names(known_bases)))
  if (is.null(digits))
    digits <- 1L
  if (standard == "auto") {
    standard <- "legacy"
    if (units != "auto") {
      if (endsWith(units, "iB"))
        standard <- "IEC"
      else if (endsWith(units, "b"))
        standard <- "legacy"
      else if (units == "kB")
        stop("For SI units, specify 'standard = \"SI\"'")
    }
  }
  base <- known_bases[[standard]]
  units_map <- known_units[[standard]]
  if (units == "auto") {
    power <- if (x <= 0)
      0L
    else min(as.integer(log(x, base = base)), length(units_map) -
               1L)
  }
  else {
    power <- match(toupper(units), toupper(units_map)) -
      1L
    if (is.na(power))
      stop(gettextf("Unit \"%s\" is not part of standard \"%s\"",
                    sQuote(units), sQuote(standard)), domain = NA)
  }
  unit <- units_map[power + 1L]
  if (power == 0 && standard == "legacy")
    unit <- "bytes"
  paste(round(x/base^power, digits = digits), unit)
}
pbreheny/breheny documentation built on May 16, 2024, 9:09 a.m.