scoop:scoop.std:0.1.0
src/datetime/calendar_text.scoop
Selected production source · src/datetime/calendar_text.scoop
1
package scoop.datetime3
import scoop.text.padStart5
internal fun calendarTwoDigits(value: Int): String = value.toString().padStart(2L, '0')7
internal fun formatCalendarYear(year: Int): String =8
if (year < 0) "-" + (-year).toString().padStart(4L, '0')9
else if (year > 9999) "+" + year.toString() else year.toString().padStart(4L, '0')11
internal fun parseCalendarFields(text: String, withDay: Boolean): (Int, Int, Int)? {12
val chars = text.toCharArray()13
val yearEnd = chars.size - (if (withDay) 6L else 3L)14
if (yearEnd < 4L || chars[yearEnd] != '-') return None15
val negative = chars[0L] == '-'16
val positive = chars[0L] == '+'17
var index = if (negative || positive) 1L else 0L18
if (yearEnd - index < 4L || (!negative && !positive && yearEnd != 4L)) return None19
var year = 020
while (index < yearEnd) {21
val digit = chars[index].code - 4822
if (digit < 0 || digit > 9 || year > (999999999 - digit) / 10) return None23
year = year * 10 + digit24
index = index + 1L25
}26
if ((negative && year == 0) || (positive && year <= 9999)) return None27
if (negative) year = -year28
val month = calendarParseTwo(chars, yearEnd + 1L)29
var day = 130
if (withDay) {31
if (chars[yearEnd + 3L] != '-') return None32
day = calendarParseTwo(chars, yearEnd + 4L)33
}34
if (!validCalendarDate(year, month, day)) return None35
return Some((year, month, day))36
}38
internal fun calendarParseTwo(chars: List<Char>, index: Long): Int {39
val first = chars[index].code - 4840
val second = chars[index + 1L].code - 4841
return if (first >= 0 && first <= 9 && second >= 0 && second <= 9) first * 10 + second else -142
}