-
-
Notifications
You must be signed in to change notification settings - Fork 469
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Support for localized size units * Support for both `,` and `.` delimiters * Invalid size errors * Disable "save" if input is invalid
- Loading branch information
Showing
4 changed files
with
65 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package eu.darken.sdmse.common.ui | ||
|
||
import android.content.Context | ||
import android.text.format.Formatter | ||
import eu.darken.sdmse.common.debug.logging.log | ||
|
||
class SizeParser(private val context: Context) { | ||
|
||
private val sizeUnitsRegex = Regex("(\\d+(?:[,.]\\d+)?)\\s*(\\w+)", RegexOption.IGNORE_CASE) | ||
private val sizeUnitsLocalized by lazy { | ||
val unitDelimiterRegex = Regex("\\s") | ||
val sizeSplitter: (Long, String) -> Pair<String, Long> = { size, fallback -> | ||
val unit = Formatter.formatShortFileSize(context, size).split(unitDelimiterRegex).lastOrNull() ?: fallback | ||
unit.uppercase() to size | ||
} | ||
mapOf( | ||
sizeSplitter(1L, "B"), | ||
sizeSplitter(1_000L, "kB"), | ||
sizeSplitter(1_000_000L, "MB"), | ||
sizeSplitter(1_000_000_000L, "GB"), | ||
).also { log { "Size lookup map: $it" } } | ||
} | ||
|
||
fun parse(input: String): Long? { | ||
val match = sizeUnitsRegex.matchEntire(input.trim()) ?: return null | ||
val (value, unit) = match.destructured | ||
val factor = sizeUnitsLocalized[unit.uppercase()] ?: return null | ||
return (value.replace(',', '.').toDoubleOrNull()?.times(factor))?.toLong()?.also { | ||
log { "Parsed size '$input' to: $it" } | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters