scoop:scoop.http:0.1.0
src/message/date.scoop
Selected production source · src/message/date.scoop
1
package scoop.http3
import scoop.datetime.UtcOffset4
import scoop.time.Instant6
/**7
* HTTP-date parsing and canonical IMF-fixdate formatting in GMT.8
*/9
public object HttpDate {10
/**11
* Formats the instant as canonical IMF-fixdate in GMT.12
*/13
public fun format(value: Instant): String = httpDateText(value, 1900, "HTTP date")15
/**16
* Parses a date or throws HttpFieldParseException when the input is invalid.17
*/18
public fun parse(value: List<Byte>, reference: Instant, caseInsensitive: Boolean = false): Instant =19
parseHttpDate(HttpFieldReader("HTTP-date", value), reference, caseInsensitive)20
/**21
* Parses a date or throws HttpFieldParseException when the input is invalid.22
*/23
public fun parse(value: String, reference: Instant, caseInsensitive: Boolean = false): Instant =24
parse(value.toByteArray(), reference, caseInsensitive)25
/**26
* Parses a date, returning None for invalid syntax or date values.27
*/28
public fun parseOrNone(value: List<Byte>, reference: Instant, caseInsensitive: Boolean = false): Instant? {29
try { return Some(parse(value, reference, caseInsensitive)) }30
catch (_: HttpFieldParseException) { return None }31
}32
/**33
* Parses a date, returning None for invalid syntax or date values.34
*/35
public fun parseOrNone(value: String, reference: Instant, caseInsensitive: Boolean = false): Instant? =36
parseOrNone(value.toByteArray(), reference, caseInsensitive)37
}39
internal fun httpDateText(value: Instant, minimumYear: Int, field: String): String {40
val time = value.toLocalDateTime(UtcOffset.ZERO)41
if (time.year < minimumYear || time.year > 9999)42
throw IllegalArgumentException(Some(field + " year must be " + minimumYear.toString() + "..9999"))43
val weekday = httpDateWeekdays[time.date.dayOfWeek.isoDayNumber.toLong() - 1L]44
return weekday + ", " + dateTwoDigits(time.dayOfMonth) + " " + httpDateMonths[time.monthNumber.toLong() - 1L] + " " +45
time.year.toString() + " " + dateTwoDigits(time.hour) + ":" + dateTwoDigits(time.minute) + ":" + dateTwoDigits(time.second) + " GMT"46
}48
private fun dateTwoDigits(value: Int): String = if (value < 10) "0" + value.toString() else value.toString()50
internal val httpDateWeekdays: Array<String> = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]51
internal val httpDateLongWeekdays: Array<String> = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]52
internal val httpDateMonths: Array<String> = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]