Skip to content

Commit

Permalink
Add valueOnly parameter so the FormatterFileSize is usable for unit…
Browse files Browse the repository at this point in the history
… tests
  • Loading branch information
KevinBoulongne committed May 8, 2024
1 parent 9d0b7b8 commit fb7f0dd
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions src/main/java/com/infomaniak/lib/core/utils/FormatterFileSize.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,26 @@ object FormatterFileSize {
private const val FLAG_SI_UNITS = 1 shl 2
private const val FLAG_SHORTER = 1 shl 0

fun Context.formatShortFileSize(bytes: Long): String = runCatching {
val (value, unit) = formatFileSize(bytes, FLAG_IEC_UNITS or FLAG_SHORTER)
getString(
resources.getIdentifier("fileSizeSuffix", "string", "android"),
value,
unit,
)
fun Context.formatShortFileSize(bytes: Long, valueOnly: Boolean = false): String = runCatching {
val (value, unit) = formatFileSize(bytes, FLAG_IEC_UNITS or FLAG_SHORTER, valueOnly)
return@runCatching if (unit == null) {
value
} else {
getString(
resources.getIdentifier("fileSizeSuffix", "string", "android"),
value,
unit,
)
}
}.getOrElse {
Formatter.formatShortFileSize(this, bytes)
return@getOrElse Formatter.formatShortFileSize(this, bytes)
}

private fun Context.formatFileSize(bytes: Long, flags: Int): Pair<String, String?> {
private fun Context.formatFileSize(bytes: Long, flags: Int, valueOnly: Boolean): Pair<String, String?> {

fun getSuffix(suffixes: MutableList<String>) = resources.getIdentifier(suffixes.removeFirstOrNull(), "string", "android")
fun getSuffix(suffixes: MutableList<String>): Int? {
return if (valueOnly) null else resources.getIdentifier(suffixes.removeFirstOrNull(), "string", "android")
}

val suffixes = mutableListOf(
"byteShort",
Expand Down Expand Up @@ -77,7 +83,7 @@ object FormatterFileSize {

result = abs(result)
val resultValue = String.format(roundFormat, result)
val resultUnit = resources.getString(suffix)
val resultUnit = suffix?.let(resources::getString)

return resultValue to resultUnit
}
Expand Down

0 comments on commit fb7f0dd

Please sign in to comment.