main

square/leakcanary

Last updated at: 29/12/2023 09:38

Size.kt

TLDR

This file provides a function humanReadableByteCount that converts a given number of bytes into a human-readable string representation.

Methods

humanReadableByteCount

This method takes in two parameters, bytes and si, and returns a human-readable string converted from the given number of bytes. The bytes parameter represents the number of bytes to be converted, while the si parameter is a flag that indicates whether the conversion should use SI units (base 1000) or binary units (base 1024). The method first determines the appropriate unit to use based on the size of the input bytes. It then calculates the exponent for the unit based on logarithms and returns the string representation with the unit symbol and appropriate decimal prefix.

package leakcanary.internal.utils

import kotlin.math.ln
import kotlin.math.pow

// https://stackoverflow.com/a/3758880
internal fun humanReadableByteCount(
  bytes: Long,
  si: Boolean
): String {
  val unit = if (si) 1000 else 1024
  if (bytes < unit) return "$bytes B"
  val exp = (ln(bytes.toDouble()) / ln(unit.toDouble())).toInt()
  val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i"
  return String.format("%.1f %sB", bytes / unit.toDouble().pow(exp.toDouble()), pre)
}