calculator: do not crash on out-of-range date tokens
- Commit
bcb9de21b645425de09bea42f90f04a1397c2310- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-19 02:07 UTC (17 days ago)
- Parents
420b8bb
A user can insert a date token (#<epochSeconds>) from the picker and then append digits, producing an epoch far outside java.time.Instant's supported range, or so many digits that toDouble overflows to Infinity (whose toLong saturates to Long.MAX_VALUE). formatInstant called Instant.ofEpochSecond on that value, throwing DateTimeException. Callers render it during composition (renderInputForDisplay in the keypad, landscape view and Glance widget) and in the preview, where only ExpressionError is caught, so the exception crashed the app. Wrap the Instant conversion in runCatching and fall back to the re-parsable #<epoch> token form. Verified: ./gradlew :calculator:testDevUnitTest and ./check calculator both pass.
Diff
calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.ktindex 4f3fda14db..61caa1df9e 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt@@ -81,7 +81,15 @@ fun formatQuantity(q: Quantity, unit: UnitDef?, useToken: Boolean = false): Stri */ fun formatInstant(epochSeconds: Double, useToken: Boolean = false): String { if (useToken) return "#" + epochSeconds.toLong()- val zoned = Instant.ofEpochSecond(epochSeconds.toLong()).atZone(ZoneId.systemDefault())+ // A user-typed `#<digits>` token can name an epoch far outside the+ // range java.time.Instant supports (or overflow to Infinity, whose+ // toLong() saturates to Long.MAX_VALUE): ofEpochSecond then throws+ // DateTimeException. This renders during composition / preview, where+ // only ExpressionError is caught, so fall back to the token form+ // instead of crashing.+ val zoned = runCatching {+ Instant.ofEpochSecond(epochSeconds.toLong()).atZone(ZoneId.systemDefault())+ }.getOrElse { return "#" + epochSeconds.toLong() } val atMidnight = zoned.hour == 0 && zoned.minute == 0 && zoned.second == 0 val formatter = if (atMidnight) { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)