Skip to content

Commit d387586

Browse files
committed
Support string constants that begin or end with numbers
1 parent cfbe052 commit d387586

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

core/common/src/internal/format/StringFormat.kt

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,25 @@ internal fun <T> FormatStructure<T>.formatter(): FormatterStructure<T> = when (t
134134
private fun <T> FormatStructure<T>.parser(): ParserStructure<T> = when (this) {
135135
is ConstantFormatStructure ->
136136
ParserStructure(
137-
operations = if (string.isNotEmpty()) listOf(PlainStringParserOperation(string)) else emptyList(),
137+
operations = when {
138+
string.isEmpty() -> emptyList()
139+
else -> buildList {
140+
val suffix = if (string[0].isDigit()) {
141+
add(NumberSpanParserOperation(listOf(ConstantNumberConsumer(string.takeWhile { it.isDigit() }))))
142+
string.dropWhile { it.isDigit() }
143+
} else {
144+
string
145+
}
146+
if (suffix.isNotEmpty()) {
147+
if (suffix[suffix.length - 1].isDigit()) {
148+
add(PlainStringParserOperation(suffix.dropLastWhile { it.isDigit() }))
149+
add(NumberSpanParserOperation(listOf(ConstantNumberConsumer(suffix.takeLastWhile { it.isDigit() }))))
150+
} else {
151+
add(PlainStringParserOperation(suffix))
152+
}
153+
}
154+
}
155+
},
138156
followedBy = emptyList()
139157
)
140158

@@ -238,4 +256,4 @@ internal class PropertyWithDefault<in T, E> private constructor(private val acce
238256
}
239257

240258
inline fun isDefaultComparisonPredicate() = ComparisonPredicate(defaultValue, accessor::getter)
241-
}
259+
}

core/common/src/internal/format/parser/NumberConsumer.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,9 @@ internal class ConstantNumberConsumer<in Receiver>(
103103
private val expected: String
104104
) : NumberConsumer<Receiver>(expected.length, "the predefined string $expected") {
105105
override fun consume(storage: Receiver, input: String): NumberConsumptionError? = if (input == expected) {
106-
NumberConsumptionError.WrongConstant(expected)
107-
} else {
108106
null
107+
} else {
108+
NumberConsumptionError.WrongConstant(expected)
109109
}
110110
}
111111

core/common/test/format/DateTimeFormatTest.kt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,18 @@ class DateTimeFormatTest {
7575
}
7676
""".trimIndent(), kotlinCode)
7777
}
78+
79+
@Test
80+
fun testParseStringWithNumbers() {
81+
val formats = listOf(
82+
"0123x0123",
83+
"0123x",
84+
"x0123",
85+
"0123",
86+
"x"
87+
)
88+
for (format in formats) {
89+
DateTimeComponents.Format { chars(format) }.parse(format)
90+
}
91+
}
7892
}

0 commit comments

Comments
 (0)