4

Are there any libraries that provide an object/class with implicits conversions (from Int, Long, Float) for human readable file size units (like Duration).

With Duration you can do this:

11.millis
1.5.minutes
10.hours

I wonder if there is some library that would allow me to do:

1.gibabyte
1024.megabytes
10.gibibytes
10.GB
50.GiB

I know I could implement this myself, but I'm trying to not reinvent the wheel.

Onilton Maciel
  • 3,559
  • 1
  • 25
  • 29
  • You could try Twitter Util: https://github.com/twitter/util#space – Eric Feb 24 '16 at 18:58
  • @Eric That's are really good alternavie! I'm using twitter utils, and didn't know they have that. Unfortunately they use Gibabytes as 1204 Megabytes (base 2). Since now we have both Gigabyte and Gibibyte (base 10 and base 2), I would like to avoid ambiguity. – Onilton Maciel Feb 24 '16 at 19:10

2 Answers2

8

Squants is a good solution, especially if you need more than just the human readable byte size conversion from the lib, but another possibility is to use this simple 4-line solution ported from an old SO java solution. You may not need the ZB and YB today, but maybe in the future ;)

  /**
    * @see https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
    * @see https://en.wikipedia.org/wiki/Zettabyte
    * @param fileSize Up to Exabytes
    * @return
    */
  def humanReadableByteSize(fileSize: Long): String = {
    if(fileSize <= 0) return "0 B"
    // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta
    val units: Array[String] = Array("B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    val digitGroup: Int = (Math.log10(fileSize)/Math.log10(1024)).toInt
    f"${fileSize/Math.pow(1024, digitGroup)}%3.3f ${units(digitGroup)}"
  }
Community
  • 1
  • 1
user4955663
  • 1,039
  • 2
  • 13
  • 21
4

I've just stumbled upon squants. As stated in their own site:

Squants is a framework of data types and a domain specific language (DSL) for representing Quantities, their Units of Measure, and their Dimensional relationships. The API supports typesafe dimensional analysis, improved domain models and more. All types are immutable and thread-safe.

With squants you can do:

10.kib
10.kibibytes
50.mib
100.gib

Although i didn't like that the unit symbols are all lowercase (i.e. gib instead of GiB)

Onilton Maciel
  • 3,559
  • 1
  • 25
  • 29