Scoop API

scoop:scoop.std:0.1.0

src/time/instant.scoop

Selected production source · src/time/instant.scoop

1package scoop.time
3import scoop.decodeTextValue
5import scoop.datetime.*
7/**
8 * A source of absolute instants. Implementations define accuracy and whether readings can move
9 * backward.
10 */
11public interface Clock {
12 /**
13 * Reads the current absolute instant from this clock.
14 */
15 public fun now(): Instant
18/**
19 * An absolute point on the Unix timeline at nanosecond precision. The supported range corresponds
20 * to LocalDate.MIN through LocalDate.MAX in UTC.
21 */
22public class Instant private constructor(
23 /**
24 * Whole seconds since 1970-01-01T00:00:00Z, rounded toward negative infinity.
25 */
26 public val epochSeconds: Long,
27 /**
28 * The nonnegative fractional nanoseconds within the epoch second.
29 */
30 public val nanosecondsOfSecond: Int)
31 : Equals<Instant>, Compare<Instant>, Hash, ToString, Add<Duration, Instant>, Sub<Duration, Instant> {
32 /**
33 * Compares the stored value components for equality.
34 */
35 public override operator fun equals(other: Instant): Boolean =
36 epochSeconds == other.epochSeconds && nanosecondsOfSecond == other.nanosecondsOfSecond
37 /**
38 * Orders values by their chronological or numeric value; only the result sign is significant.
39 */
40 public override operator fun compareTo(other: Instant): Long =
41 if (epochSeconds != other.epochSeconds) epochSeconds.compareTo(other.epochSeconds)
42 else nanosecondsOfSecond.compareTo(other.nanosecondsOfSecond)
43 /**
44 * Computes a hash consistent with component equality.
45 */
46 public override fun hash(): Long = epochSeconds.hash() * 31L + nanosecondsOfSecond.hash()
47 /**
48 * Advances by an elapsed duration, rejecting results outside the supported range.
49 */
50 public override operator fun plus(other: Duration): Instant = Instant.fromDuration(asDuration() + other)
51 /**
52 * Subtracts an elapsed duration, or returns the signed elapsed duration from another instant
53 * to this one.
54 */
55 public override operator fun minus(other: Duration): Instant = Instant.fromDuration(asDuration() - other)
56 /**
57 * Subtracts an elapsed duration, or returns the signed elapsed duration from another instant
58 * to this one.
59 */
60 public operator fun minus(other: Instant): Duration =
61 Duration.seconds(epochSeconds - other.epochSeconds, nanosecondsOfSecond.toLong() - other.nanosecondsOfSecond.toLong())
62 private fun asDuration(): Duration = Duration.seconds(epochSeconds, nanosecondsOfSecond.toLong())
63 /**
64 * Returns epoch milliseconds rounded toward negative infinity; overflow throws
65 * ArithmeticException.
66 */
67 public fun toEpochMilliseconds(): Long = instantMilliseconds(epochSeconds, nanosecondsOfSecond)
68 /**
69 * Converts to local calendar fields at the supplied fixed UTC offset; unsupported dates throw.
70 */
71 public fun toLocalDateTime(offset: UtcOffset): LocalDateTime {
72 val seconds = epochSeconds + offset.totalSeconds.toLong()
73 val day = calendarFloorDiv(seconds, 86400L)
74 if (day < LocalDate.MIN.toEpochDays() || day > LocalDate.MAX.toEpochDays()) throw ArithmeticException()
75 val nanos = (seconds - day * 86400L) * 1000000000L + nanosecondsOfSecond.toLong()
76 return LocalDateTime(LocalDate.fromEpochDays(day), LocalTime.fromNanosecondOfDay(nanos))
77 }
78 /**
79 * Formats this instant in UTC with a trailing Z.
80 */
81 public override fun toString(): String = toLocalDateTime(UtcOffset.ZERO).toString() + "Z"
83 /**
84 * Value construction and serialization helpers.
85 */
86 public companion object : ValueEncoder<Instant>, ValueDecoder<Instant> {
87 /**
88 * Encodes the value as its canonical text representation.
89 */
90 public override fun encode(value: Instant, encoder: Encoder) { encoder.singleValue().writeString(value.toString()) }
91 /**
92 * Reads a string value and validates it using this type's parser.
93 */
94 public override fun decode(decoder: Decoder): Instant =
95 decodeTextValue<Instant>(decoder, { text -> parseOrNone(text) }, "instant")
97 /**
98 * The earliest or smallest supported value.
99 */
100 public val MIN: Instant = Instant(LocalDate.MIN.toEpochDays() * 86400L, 0)
101 /**
102 * The latest or largest supported value.
103 */
104 public val MAX: Instant = Instant(LocalDate.MAX.toEpochDays() * 86400L + 86399L, 999999999)
105 /**
106 * Combines epoch seconds and a signed nanosecond adjustment, normalizing and validating
107 * the supported range.
108 */
109 public fun fromEpochSeconds(seconds: Long, nanosecondAdjustment: Long = 0L): Instant {
110 val extra = calendarFloorDiv(nanosecondAdjustment, 1000000000L)
111 if (seconds < MIN.epochSeconds - extra || seconds > MAX.epochSeconds - extra) {
112 throw IllegalArgumentException(Some("instant outside supported range"))
113 }
114 val remainder = nanosecondAdjustment % 1000000000L
115 return Instant(seconds + extra, (remainder + (if (remainder < 0L) 1000000000L else 0L)).toInt())
116 }
117 /**
118 * Constructs an instant from signed milliseconds since the Unix epoch.
119 */
120 public fun fromEpochMilliseconds(value: Long): Instant = fromEpochSeconds(value / 1000L, (value % 1000L) * 1000000L)
121 internal fun fromComponents(seconds: Long, nanos: Int): Instant {
122 if (seconds < MIN.epochSeconds || seconds > MAX.epochSeconds) throw ArithmeticException()
123 return Instant(seconds, nanos)
124 }
125 internal fun fromDuration(value: Duration): Instant = fromComponents(value.floorSeconds, value.nanosecondsOfSecond)
126 /**
127 * Parses ISO date-time with an explicit offset, returning None for malformed or
128 * out-of-range input.
129 */
130 public fun parseOrNone(text: String): Instant? = when (OffsetDateTime.parseOrNone(text)) {
131 case Some(val value) -> {
132 val seconds = localEpochSeconds(value.dateTime) - value.offset.totalSeconds.toLong()
133 if (seconds < MIN.epochSeconds || seconds > MAX.epochSeconds) None
134 else Some(Instant(seconds, value.dateTime.nanosecond))
135 }
136 case None -> None
137 }
138 /**
139 * Parses ISO date-time with an explicit offset or throws IllegalArgumentException for
140 * invalid input.
141 */
142 public fun parse(text: String): Instant = when (parseOrNone(text)) {
143 case Some(val value) -> value
144 case None -> throw IllegalArgumentException(Some("invalid instant"))
145 }
146 }