2018-08-15 17:04:45 +00:00
|
|
|
package eu.depau.etchdroid.utils
|
2018-08-13 23:32:02 +00:00
|
|
|
|
|
|
|
// https://stackoverflow.com/a/3758880/1124621
|
|
|
|
|
2018-08-15 16:20:17 +00:00
|
|
|
private fun <T> humanReadableByteCount(bytes: T, si: Boolean = true): String where T : Comparable<T>, T : Number {
|
2018-08-13 23:32:02 +00:00
|
|
|
val unit: Long = if (si) 1000 else 1024
|
2018-08-14 17:08:56 +00:00
|
|
|
if (bytes.toLong() < unit) return String.format("%.2f B", bytes)
|
2018-08-13 23:32:02 +00:00
|
|
|
val exp = (Math.log(bytes.toDouble()) / Math.log(unit.toDouble())).toInt()
|
|
|
|
val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i"
|
2018-08-14 17:08:56 +00:00
|
|
|
return String.format("%.2f %sB", bytes.toDouble() / Math.pow(unit.toDouble(), exp.toDouble()), pre)
|
2018-08-13 23:32:02 +00:00
|
|
|
}
|
|
|
|
|
2018-08-15 16:20:17 +00:00
|
|
|
fun Long.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|
|
|
|
fun Float.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|
|
|
|
fun Double.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|
|
|
|
fun Int.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|
|
|
|
fun Byte.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|
|
|
|
fun Short.toHRSize(si: Boolean = true) = humanReadableByteCount(this, si)
|