Scoop API

scoop:scoop.std:0.1.0

src/datetime/calendar_text.scoop

Selected production source · src/datetime/calendar_text.scoop

1package scoop.datetime
3import scoop.text.padStart
5internal fun calendarTwoDigits(value: Int): String = value.toString().padStart(2L, '0')
7internal 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')
11internal 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 None
15 val negative = chars[0L] == '-'
16 val positive = chars[0L] == '+'
17 var index = if (negative || positive) 1L else 0L
18 if (yearEnd - index < 4L || (!negative && !positive && yearEnd != 4L)) return None
19 var year = 0
20 while (index < yearEnd) {
21 val digit = chars[index].code - 48
22 if (digit < 0 || digit > 9 || year > (999999999 - digit) / 10) return None
23 year = year * 10 + digit
24 index = index + 1L
25 }
26 if ((negative && year == 0) || (positive && year <= 9999)) return None
27 if (negative) year = -year
28 val month = calendarParseTwo(chars, yearEnd + 1L)
29 var day = 1
30 if (withDay) {
31 if (chars[yearEnd + 3L] != '-') return None
32 day = calendarParseTwo(chars, yearEnd + 4L)
33 }
34 if (!validCalendarDate(year, month, day)) return None
35 return Some((year, month, day))
38internal fun calendarParseTwo(chars: List<Char>, index: Long): Int {
39 val first = chars[index].code - 48
40 val second = chars[index + 1L].code - 48
41 return if (first >= 0 && first <= 9 && second >= 0 && second <= 9) first * 10 + second else -1