-
Notifications
You must be signed in to change notification settings - Fork 6.4k
Expand file tree
/
Copy pathDuration.kt
More file actions
1483 lines (1298 loc) · 69.7 KB
/
Copy pathDuration.kt
File metadata and controls
1483 lines (1298 loc) · 69.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.time
import kotlin.contracts.*
import kotlin.jvm.JvmInline
import kotlin.math.*
/**
* Represents the amount of time one instant of time is away from another instant.
*
* A negative duration is possible in a situation when the second instant is earlier than the first one.
*
* The type can store duration values up to ±146 years with nanosecond precision,
* and up to ±146 million years with millisecond precision.
* If a duration-returning operation provided in `kotlin.time` produces a duration value that doesn't fit into the above range,
* the returned `Duration` is infinite.
*
* An infinite duration value [Duration.INFINITE] can be used to represent infinite timeouts.
*
* To construct a duration use either the extension function [toDuration],
* or the extension properties [hours], [minutes], [seconds], and so on,
* available on [Int], [Long], and [Double] numeric types.
*
* To get the value of this duration expressed in a particular [duration units][DurationUnit]
* use the functions [toInt], [toLong], and [toDouble]
* or the properties [inWholeHours], [inWholeMinutes], [inWholeSeconds], [inWholeNanoseconds], and so on.
*/
@SinceKotlin("1.6")
@WasExperimental(ExperimentalTime::class)
@JvmInline
public value class Duration internal constructor(private val rawValue: Long) : Comparable<Duration> {
private val value: Long get() = rawValue shr 1
private inline val unitDiscriminator: Int get() = rawValue.toInt() and 1
private fun isInNanos() = unitDiscriminator == 0
private fun isInMillis() = unitDiscriminator == 1
private val storageUnit get() = if (isInNanos()) DurationUnit.NANOSECONDS else DurationUnit.MILLISECONDS
init {
if (durationAssertionsEnabled) {
if (isInNanos()) {
if (value !in -MAX_NANOS..MAX_NANOS) throw AssertionError("$value ns is out of nanoseconds range")
} else {
if (value !in -MAX_MILLIS..MAX_MILLIS) throw AssertionError("$value ms is out of milliseconds range")
if (value in -MAX_NANOS_IN_MILLIS..MAX_NANOS_IN_MILLIS) throw AssertionError("$value ms is denormalized")
}
}
}
companion object {
/** The duration equal to exactly 0 seconds. */
public val ZERO: Duration = Duration(0L)
/** The duration whose value is positive infinity. It is useful for representing timeouts that should never expire. */
public val INFINITE: Duration = durationOfMillis(MAX_MILLIS)
internal val NEG_INFINITE: Duration = durationOfMillis(-MAX_MILLIS)
/** Converts the given time duration [value] expressed in the specified [sourceUnit] into the specified [targetUnit]. */
@ExperimentalTime
public fun convert(value: Double, sourceUnit: DurationUnit, targetUnit: DurationUnit): Double =
convertDurationUnit(value, sourceUnit, targetUnit)
// Duration construction extension properties in Duration companion scope
/** Returns a [Duration] equal to this [Int] number of nanoseconds. */
@kotlin.internal.InlineOnly
public inline val Int.nanoseconds get() = toDuration(DurationUnit.NANOSECONDS)
/** Returns a [Duration] equal to this [Long] number of nanoseconds. */
@kotlin.internal.InlineOnly
public inline val Long.nanoseconds get() = toDuration(DurationUnit.NANOSECONDS)
/**
* Returns a [Duration] equal to this [Double] number of nanoseconds.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.nanoseconds get() = toDuration(DurationUnit.NANOSECONDS)
/** Returns a [Duration] equal to this [Int] number of microseconds. */
@kotlin.internal.InlineOnly
public inline val Int.microseconds get() = toDuration(DurationUnit.MICROSECONDS)
/** Returns a [Duration] equal to this [Long] number of microseconds. */
@kotlin.internal.InlineOnly
public inline val Long.microseconds get() = toDuration(DurationUnit.MICROSECONDS)
/**
* Returns a [Duration] equal to this [Double] number of microseconds.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.microseconds get() = toDuration(DurationUnit.MICROSECONDS)
/** Returns a [Duration] equal to this [Int] number of milliseconds. */
@kotlin.internal.InlineOnly
public inline val Int.milliseconds get() = toDuration(DurationUnit.MILLISECONDS)
/** Returns a [Duration] equal to this [Long] number of milliseconds. */
@kotlin.internal.InlineOnly
public inline val Long.milliseconds get() = toDuration(DurationUnit.MILLISECONDS)
/**
* Returns a [Duration] equal to this [Double] number of milliseconds.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.milliseconds get() = toDuration(DurationUnit.MILLISECONDS)
/** Returns a [Duration] equal to this [Int] number of seconds. */
@kotlin.internal.InlineOnly
public inline val Int.seconds get() = toDuration(DurationUnit.SECONDS)
/** Returns a [Duration] equal to this [Long] number of seconds. */
@kotlin.internal.InlineOnly
public inline val Long.seconds get() = toDuration(DurationUnit.SECONDS)
/**
* Returns a [Duration] equal to this [Double] number of seconds.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.seconds get() = toDuration(DurationUnit.SECONDS)
/** Returns a [Duration] equal to this [Int] number of minutes. */
@kotlin.internal.InlineOnly
public inline val Int.minutes get() = toDuration(DurationUnit.MINUTES)
/** Returns a [Duration] equal to this [Long] number of minutes. */
@kotlin.internal.InlineOnly
public inline val Long.minutes get() = toDuration(DurationUnit.MINUTES)
/**
* Returns a [Duration] equal to this [Double] number of minutes.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.minutes get() = toDuration(DurationUnit.MINUTES)
/** Returns a [Duration] equal to this [Int] number of hours. */
@kotlin.internal.InlineOnly
public inline val Int.hours get() = toDuration(DurationUnit.HOURS)
/** Returns a [Duration] equal to this [Long] number of hours. */
@kotlin.internal.InlineOnly
public inline val Long.hours get() = toDuration(DurationUnit.HOURS)
/**
* Returns a [Duration] equal to this [Double] number of hours.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.hours get() = toDuration(DurationUnit.HOURS)
/** Returns a [Duration] equal to this [Int] number of days. */
@kotlin.internal.InlineOnly
public inline val Int.days get() = toDuration(DurationUnit.DAYS)
/** Returns a [Duration] equal to this [Long] number of days. */
@kotlin.internal.InlineOnly
public inline val Long.days get() = toDuration(DurationUnit.DAYS)
/**
* Returns a [Duration] equal to this [Double] number of days.
*
* Depending on its magnitude, the value is rounded to an integer number of nanoseconds or milliseconds.
*
* @throws IllegalArgumentException if this [Double] value is `NaN`.
*/
@kotlin.internal.InlineOnly
public inline val Double.days get() = toDuration(DurationUnit.DAYS)
// deprecated static factory functions
/** Returns a [Duration] representing the specified [value] number of nanoseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.nanoseconds' extension property from Duration.Companion instead.", ReplaceWith("value.nanoseconds", "kotlin.time.Duration.Companion.nanoseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun nanoseconds(value: Int): Duration = value.toDuration(DurationUnit.NANOSECONDS)
/** Returns a [Duration] representing the specified [value] number of nanoseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.nanoseconds' extension property from Duration.Companion instead.", ReplaceWith("value.nanoseconds", "kotlin.time.Duration.Companion.nanoseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun nanoseconds(value: Long): Duration = value.toDuration(DurationUnit.NANOSECONDS)
/**
* Returns a [Duration] representing the specified [value] number of nanoseconds.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.nanoseconds' extension property from Duration.Companion instead.", ReplaceWith("value.nanoseconds", "kotlin.time.Duration.Companion.nanoseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun nanoseconds(value: Double): Duration = value.toDuration(DurationUnit.NANOSECONDS)
/** Returns a [Duration] representing the specified [value] number of microseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.microseconds' extension property from Duration.Companion instead.", ReplaceWith("value.microseconds", "kotlin.time.Duration.Companion.microseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun microseconds(value: Int): Duration = value.toDuration(DurationUnit.MICROSECONDS)
/** Returns a [Duration] representing the specified [value] number of microseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.microseconds' extension property from Duration.Companion instead.", ReplaceWith("value.microseconds", "kotlin.time.Duration.Companion.microseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun microseconds(value: Long): Duration = value.toDuration(DurationUnit.MICROSECONDS)
/**
* Returns a [Duration] representing the specified [value] number of microseconds.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.microseconds' extension property from Duration.Companion instead.", ReplaceWith("value.microseconds", "kotlin.time.Duration.Companion.microseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun microseconds(value: Double): Duration = value.toDuration(DurationUnit.MICROSECONDS)
/** Returns a [Duration] representing the specified [value] number of milliseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.milliseconds' extension property from Duration.Companion instead.", ReplaceWith("value.milliseconds", "kotlin.time.Duration.Companion.milliseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun milliseconds(value: Int): Duration = value.toDuration(DurationUnit.MILLISECONDS)
/** Returns a [Duration] representing the specified [value] number of milliseconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.milliseconds' extension property from Duration.Companion instead.", ReplaceWith("value.milliseconds", "kotlin.time.Duration.Companion.milliseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun milliseconds(value: Long): Duration = value.toDuration(DurationUnit.MILLISECONDS)
/**
* Returns a [Duration] representing the specified [value] number of milliseconds.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.milliseconds' extension property from Duration.Companion instead.", ReplaceWith("value.milliseconds", "kotlin.time.Duration.Companion.milliseconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun milliseconds(value: Double): Duration = value.toDuration(DurationUnit.MILLISECONDS)
/** Returns a [Duration] representing the specified [value] number of seconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.seconds' extension property from Duration.Companion instead.", ReplaceWith("value.seconds", "kotlin.time.Duration.Companion.seconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun seconds(value: Int): Duration = value.toDuration(DurationUnit.SECONDS)
/** Returns a [Duration] representing the specified [value] number of seconds. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.seconds' extension property from Duration.Companion instead.", ReplaceWith("value.seconds", "kotlin.time.Duration.Companion.seconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun seconds(value: Long): Duration = value.toDuration(DurationUnit.SECONDS)
/**
* Returns a [Duration] representing the specified [value] number of seconds.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.seconds' extension property from Duration.Companion instead.", ReplaceWith("value.seconds", "kotlin.time.Duration.Companion.seconds"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun seconds(value: Double): Duration = value.toDuration(DurationUnit.SECONDS)
/** Returns a [Duration] representing the specified [value] number of minutes. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.minutes' extension property from Duration.Companion instead.", ReplaceWith("value.minutes", "kotlin.time.Duration.Companion.minutes"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun minutes(value: Int): Duration = value.toDuration(DurationUnit.MINUTES)
/** Returns a [Duration] representing the specified [value] number of minutes. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.minutes' extension property from Duration.Companion instead.", ReplaceWith("value.minutes", "kotlin.time.Duration.Companion.minutes"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun minutes(value: Long): Duration = value.toDuration(DurationUnit.MINUTES)
/**
* Returns a [Duration] representing the specified [value] number of minutes.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.minutes' extension property from Duration.Companion instead.", ReplaceWith("value.minutes", "kotlin.time.Duration.Companion.minutes"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun minutes(value: Double): Duration = value.toDuration(DurationUnit.MINUTES)
/** Returns a [Duration] representing the specified [value] number of hours. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.hours' extension property from Duration.Companion instead.", ReplaceWith("value.hours", "kotlin.time.Duration.Companion.hours"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun hours(value: Int): Duration = value.toDuration(DurationUnit.HOURS)
/** Returns a [Duration] representing the specified [value] number of hours. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.hours' extension property from Duration.Companion instead.", ReplaceWith("value.hours", "kotlin.time.Duration.Companion.hours"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun hours(value: Long): Duration = value.toDuration(DurationUnit.HOURS)
/**
* Returns a [Duration] representing the specified [value] number of hours.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.hours' extension property from Duration.Companion instead.", ReplaceWith("value.hours", "kotlin.time.Duration.Companion.hours"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun hours(value: Double): Duration = value.toDuration(DurationUnit.HOURS)
/** Returns a [Duration] representing the specified [value] number of days. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Int.days' extension property from Duration.Companion instead.", ReplaceWith("value.days", "kotlin.time.Duration.Companion.days"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun days(value: Int): Duration = value.toDuration(DurationUnit.DAYS)
/** Returns a [Duration] representing the specified [value] number of days. */
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Long.days' extension property from Duration.Companion instead.", ReplaceWith("value.days", "kotlin.time.Duration.Companion.days"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun days(value: Long): Duration = value.toDuration(DurationUnit.DAYS)
/**
* Returns a [Duration] representing the specified [value] number of days.
*
* @throws IllegalArgumentException if the provided `Double` [value] is `NaN`.
*/
@SinceKotlin("1.5")
@ExperimentalTime
@Deprecated("Use 'Double.days' extension property from Duration.Companion instead.", ReplaceWith("value.days", "kotlin.time.Duration.Companion.days"))
@DeprecatedSinceKotlin(warningSince = "1.6", errorSince = "1.8")
public fun days(value: Double): Duration = value.toDuration(DurationUnit.DAYS)
/**
* Parses a string that represents a duration and returns the parsed [Duration] value.
*
* The following formats are accepted:
*
* - ISO-8601 Duration format, e.g. `P1DT2H3M4.058S`, see [toIsoString] and [parseIsoString].
* - The format of string returned by the default [Duration.toString] and `toString` in a specific unit,
* e.g. `10s`, `1h 30m` or `-(1h 30m)`.
*
* @throws IllegalArgumentException if the string doesn't represent a duration in any of the supported formats.
* @sample samples.time.Durations.parse
*/
public fun parse(value: String): Duration = try {
parseDuration(value, strictIso = false)
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid duration string format: '$value'.", e)
}
/**
* Parses a string that represents a duration in a restricted ISO-8601 composite representation
* and returns the parsed [Duration] value.
* Composite representation is a relaxed version of ISO-8601 duration format that supports
* negative durations and negative values of individual components.
*
* The following restrictions are imposed:
*
* - The only allowed non-time designator is days (`D`). `Y` (years), `W` (weeks), and `M` (months) are not supported.
* - Day is considered to be exactly 24 hours (24-hour clock time scale).
* - Alternative week-based representation `["P"][number]["W"]` is not supported.
*
* @throws IllegalArgumentException if the string doesn't represent a duration in ISO-8601 format.
* @sample samples.time.Durations.parseIsoString
*/
public fun parseIsoString(value: String): Duration = try {
parseDuration(value, strictIso = true)
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid ISO duration string format: '$value'.", e)
}
/**
* Parses a string that represents a duration and returns the parsed [Duration] value,
* or `null` if the string doesn't represent a duration in any of the supported formats.
*
* The following formats are accepted:
*
* - Restricted ISO-8601 duration composite representation, e.g. `P1DT2H3M4.058S`, see [toIsoString] and [parseIsoString].
* - The format of string returned by the default [Duration.toString] and `toString` in a specific unit,
* e.g. `10s`, `1h 30m` or `-(1h 30m)`.
* @sample samples.time.Durations.parse
*/
public fun parseOrNull(value: String): Duration? = try {
parseDuration(value, strictIso = false)
} catch (e: IllegalArgumentException) {
null
}
/**
* Parses a string that represents a duration in restricted ISO-8601 composite representation
* and returns the parsed [Duration] value or `null` if the string doesn't represent a duration in the format
* acceptable by [parseIsoString].
*
* @sample samples.time.Durations.parseIsoString
*/
public fun parseIsoStringOrNull(value: String): Duration? = try {
parseDuration(value, strictIso = true)
} catch (e: IllegalArgumentException) {
null
}
}
// arithmetic operators
/** Returns the negative of this value. */
public operator fun unaryMinus(): Duration = durationOf(-value, unitDiscriminator)
/**
* Returns a duration whose value is the sum of this and [other] duration values.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when adding infinite durations of different sign.
*/
public operator fun plus(other: Duration): Duration {
when {
this.isInfinite() -> {
if (other.isFinite() || (this.rawValue xor other.rawValue >= 0))
return this
else
throw IllegalArgumentException("Summing infinite durations of different signs yields an undefined result.")
}
other.isInfinite() -> return other
}
return when {
this.unitDiscriminator == other.unitDiscriminator -> {
val result = this.value + other.value // never overflows long, but can overflow long63
when {
isInNanos() ->
durationOfNanosNormalized(result)
else ->
durationOfMillisNormalized(result)
}
}
this.isInMillis() ->
addValuesMixedRanges(this.value, other.value)
else ->
addValuesMixedRanges(other.value, this.value)
}
}
private fun addValuesMixedRanges(thisMillis: Long, otherNanos: Long): Duration {
val otherMillis = nanosToMillis(otherNanos)
val resultMillis = thisMillis + otherMillis
return if (resultMillis in -MAX_NANOS_IN_MILLIS..MAX_NANOS_IN_MILLIS) {
val otherNanoRemainder = otherNanos - millisToNanos(otherMillis)
durationOfNanos(millisToNanos(resultMillis) + otherNanoRemainder)
} else {
durationOfMillis(resultMillis.coerceIn(-MAX_MILLIS, MAX_MILLIS))
}
}
/**
* Returns a duration whose value is the difference between this and [other] duration values.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when subtracting infinite durations of the same sign.
*/
public operator fun minus(other: Duration): Duration = this + (-other)
/**
* Returns a duration whose value is this duration value multiplied by the given [scale] number.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when multiplying an infinite duration by zero.
*/
public operator fun times(scale: Int): Duration {
if (isInfinite()) {
return when {
scale == 0 -> throw IllegalArgumentException("Multiplying infinite duration by zero yields an undefined result.")
scale > 0 -> this
else -> -this
}
}
if (scale == 0) return ZERO
val value = value
val result = value * scale
return if (isInNanos()) {
if (value in (MAX_NANOS / Int.MIN_VALUE)..(-MAX_NANOS / Int.MIN_VALUE)) {
// can't overflow nanos range for any scale
durationOfNanos(result)
} else {
if (result / scale == value) {
durationOfNanosNormalized(result)
} else {
val millis = nanosToMillis(value)
val remNanos = value - millisToNanos(millis)
val resultMillis = millis * scale
val totalMillis = resultMillis + nanosToMillis(remNanos * scale)
if (resultMillis / scale == millis && totalMillis xor resultMillis >= 0) {
durationOfMillis(totalMillis.coerceIn(-MAX_MILLIS..MAX_MILLIS))
} else {
if (value.sign * scale.sign > 0) INFINITE else NEG_INFINITE
}
}
}
} else {
if (result / scale == value) {
durationOfMillis(result.coerceIn(-MAX_MILLIS..MAX_MILLIS))
} else {
if (value.sign * scale.sign > 0) INFINITE else NEG_INFINITE
}
}
}
/**
* Returns a duration whose value is this duration value multiplied by the given [scale] number.
*
* The operation may involve rounding when the result cannot be represented exactly with a [Double] number.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when multiplying an infinite duration by zero.
*/
public operator fun times(scale: Double): Duration {
val intScale = scale.roundToInt()
if (intScale.toDouble() == scale) {
return times(intScale)
}
val unit = storageUnit
val result = toDouble(unit) * scale
return result.toDuration(unit)
}
/**
* Returns a duration whose value is this duration value divided by the given [scale] number.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when dividing zero duration by zero.
*/
public operator fun div(scale: Int): Duration {
if (scale == 0) {
return when {
isPositive() -> INFINITE
isNegative() -> NEG_INFINITE
else -> throw IllegalArgumentException("Dividing zero duration by zero yields an undefined result.")
}
}
if (isInNanos()) {
return durationOfNanos(value / scale)
} else {
if (isInfinite())
return this * scale.sign
val result = value / scale
if (result in -MAX_NANOS_IN_MILLIS..MAX_NANOS_IN_MILLIS) {
val rem = millisToNanos(value - (result * scale)) / scale
return durationOfNanos(millisToNanos(result) + rem)
}
return durationOfMillis(result)
}
}
/**
* Returns a duration whose value is this duration value divided by the given [scale] number.
*
* @throws IllegalArgumentException if the operation results in an undefined value for the given arguments,
* e.g. when dividing an infinite duration by infinity or zero duration by zero.
*/
public operator fun div(scale: Double): Duration {
val intScale = scale.roundToInt()
if (intScale.toDouble() == scale && intScale != 0) {
return div(intScale)
}
val unit = storageUnit
val result = toDouble(unit) / scale
return result.toDuration(unit)
}
/** Returns a number that is the ratio of this and [other] duration values. */
public operator fun div(other: Duration): Double {
val coarserUnit = maxOf(this.storageUnit, other.storageUnit)
return this.toDouble(coarserUnit) / other.toDouble(coarserUnit)
}
/** Returns true, if the duration value is less than zero. */
public fun isNegative(): Boolean = rawValue < 0
/** Returns true, if the duration value is greater than zero. */
public fun isPositive(): Boolean = rawValue > 0
/** Returns true, if the duration value is infinite. */
public fun isInfinite(): Boolean = rawValue == INFINITE.rawValue || rawValue == NEG_INFINITE.rawValue
/** Returns true, if the duration value is finite. */
public fun isFinite(): Boolean = !isInfinite()
/** Returns the absolute value of this value. The returned value is always non-negative. */
public val absoluteValue: Duration get() = if (isNegative()) -this else this
override fun compareTo(other: Duration): Int {
val compareBits = this.rawValue xor other.rawValue
if (compareBits < 0 || compareBits.toInt() and 1 == 0) // different signs or same sign/same range
return this.rawValue.compareTo(other.rawValue)
// same sign/different ranges
val r = this.unitDiscriminator - other.unitDiscriminator // compare ranges
return if (isNegative()) -r else r
}
// splitting to components
/**
* Splits this duration into days, hours, minutes, seconds, and nanoseconds and executes the given [action] with these components.
* The result of [action] is returned as the result of this function.
*
* - `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1_000_000_000;
* - `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60;
* - `minutes` represents the whole number of minutes in this duration, and its absolute value is less than 60;
* - `hours` represents the whole number of hours in this duration, and its absolute value is less than 24;
* - `days` represents the whole number of days in this duration.
*
* Infinite durations are represented as either [Long.MAX_VALUE] days, or [Long.MIN_VALUE] days (depending on the sign of infinity),
* and zeroes in the lower components.
*/
public inline fun <T> toComponents(action: (days: Long, hours: Int, minutes: Int, seconds: Int, nanoseconds: Int) -> T): T {
contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
return action(inWholeDays, hoursComponent, minutesComponent, secondsComponent, nanosecondsComponent)
}
/**
* Splits this duration into hours, minutes, seconds, and nanoseconds and executes the given [action] with these components.
* The result of [action] is returned as the result of this function.
*
* - `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1_000_000_000;
* - `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60;
* - `minutes` represents the whole number of minutes in this duration, and its absolute value is less than 60;
* - `hours` represents the whole number of hours in this duration.
*
* Infinite durations are represented as either [Long.MAX_VALUE] hours, or [Long.MIN_VALUE] hours (depending on the sign of infinity),
* and zeroes in the lower components.
*/
public inline fun <T> toComponents(action: (hours: Long, minutes: Int, seconds: Int, nanoseconds: Int) -> T): T {
contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
return action(inWholeHours, minutesComponent, secondsComponent, nanosecondsComponent)
}
/**
* Splits this duration into minutes, seconds, and nanoseconds and executes the given [action] with these components.
* The result of [action] is returned as the result of this function.
*
* - `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1_000_000_000;
* - `seconds` represents the whole number of seconds in this duration, and its absolute value is less than 60;
* - `minutes` represents the whole number of minutes in this duration.
*
* Infinite durations are represented as either [Long.MAX_VALUE] minutes, or [Long.MIN_VALUE] minutes (depending on the sign of infinity),
* and zeroes in the lower components.
*/
public inline fun <T> toComponents(action: (minutes: Long, seconds: Int, nanoseconds: Int) -> T): T {
contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
return action(inWholeMinutes, secondsComponent, nanosecondsComponent)
}
/**
* Splits this duration into seconds, and nanoseconds and executes the given [action] with these components.
* The result of [action] is returned as the result of this function.
*
* - `nanoseconds` represents the whole number of nanoseconds in this duration, and its absolute value is less than 1_000_000_000;
* - `seconds` represents the whole number of seconds in this duration.
*
* Infinite durations are represented as either [Long.MAX_VALUE] seconds, or [Long.MIN_VALUE] seconds (depending on the sign of infinity),
* and zero nanoseconds.
*/
public inline fun <T> toComponents(action: (seconds: Long, nanoseconds: Int) -> T): T {
contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }
return action(inWholeSeconds, nanosecondsComponent)
}
@PublishedApi
internal val hoursComponent: Int
get() = if (isInfinite()) 0 else (inWholeHours % 24).toInt()
@PublishedApi
internal val minutesComponent: Int
get() = if (isInfinite()) 0 else (inWholeMinutes % 60).toInt()
@PublishedApi
internal val secondsComponent: Int
get() = if (isInfinite()) 0 else (inWholeSeconds % 60).toInt()
@PublishedApi
internal val nanosecondsComponent: Int
get() = when {
isInfinite() -> 0
isInMillis() -> millisToNanos(value % 1_000).toInt()
else -> (value % 1_000_000_000).toInt()
}
// conversion to units
/**
* Returns the value of this duration expressed as a [Double] number of the specified [unit].
*
* The operation may involve rounding when the result cannot be represented exactly with a [Double] number.
*
* An infinite duration value is converted either to [Double.POSITIVE_INFINITY] or [Double.NEGATIVE_INFINITY] depending on its sign.
*/
public fun toDouble(unit: DurationUnit): Double {
return when (rawValue) {
INFINITE.rawValue -> Double.POSITIVE_INFINITY
NEG_INFINITE.rawValue -> Double.NEGATIVE_INFINITY
else -> {
// TODO: whether it's ok to convert to Double before scaling
convertDurationUnit(value.toDouble(), storageUnit, unit)
}
}
}
/**
* Returns the value of this duration expressed as a [Long] number of the specified [unit].
*
* If the result doesn't fit in the range of [Long] type, it is coerced into that range:
* - [Long.MIN_VALUE] is returned if it's less than `Long.MIN_VALUE`,
* - [Long.MAX_VALUE] is returned if it's greater than `Long.MAX_VALUE`.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public fun toLong(unit: DurationUnit): Long {
return when (rawValue) {
INFINITE.rawValue -> Long.MAX_VALUE
NEG_INFINITE.rawValue -> Long.MIN_VALUE
else -> convertDurationUnit(value, storageUnit, unit)
}
}
/**
* Returns the value of this duration expressed as an [Int] number of the specified [unit].
*
* If the result doesn't fit in the range of [Int] type, it is coerced into that range:
* - [Int.MIN_VALUE] is returned if it's less than `Int.MIN_VALUE`,
* - [Int.MAX_VALUE] is returned if it's greater than `Int.MAX_VALUE`.
*
* An infinite duration value is converted either to [Int.MAX_VALUE] or [Int.MIN_VALUE] depending on its sign.
*/
public fun toInt(unit: DurationUnit): Int =
toLong(unit).coerceIn(Int.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong()).toInt()
/** The value of this duration expressed as a [Double] number of days. */
@ExperimentalTime
@Deprecated("Use inWholeDays property instead or convert toDouble(DAYS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.DAYS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inDays: Double get() = toDouble(DurationUnit.DAYS)
/** The value of this duration expressed as a [Double] number of hours. */
@ExperimentalTime
@Deprecated("Use inWholeHours property instead or convert toDouble(HOURS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.HOURS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inHours: Double get() = toDouble(DurationUnit.HOURS)
/** The value of this duration expressed as a [Double] number of minutes. */
@ExperimentalTime
@Deprecated("Use inWholeMinutes property instead or convert toDouble(MINUTES) if a double value is required.", ReplaceWith("toDouble(DurationUnit.MINUTES)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inMinutes: Double get() = toDouble(DurationUnit.MINUTES)
/** The value of this duration expressed as a [Double] number of seconds. */
@ExperimentalTime
@Deprecated("Use inWholeSeconds property instead or convert toDouble(SECONDS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.SECONDS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inSeconds: Double get() = toDouble(DurationUnit.SECONDS)
/** The value of this duration expressed as a [Double] number of milliseconds. */
@ExperimentalTime
@Deprecated("Use inWholeMilliseconds property instead or convert toDouble(MILLISECONDS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.MILLISECONDS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inMilliseconds: Double get() = toDouble(DurationUnit.MILLISECONDS)
/** The value of this duration expressed as a [Double] number of microseconds. */
@ExperimentalTime
@Deprecated("Use inWholeMicroseconds property instead or convert toDouble(MICROSECONDS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.MICROSECONDS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inMicroseconds: Double get() = toDouble(DurationUnit.MICROSECONDS)
/** The value of this duration expressed as a [Double] number of nanoseconds. */
@ExperimentalTime
@Deprecated("Use inWholeNanoseconds property instead or convert toDouble(NANOSECONDS) if a double value is required.", ReplaceWith("toDouble(DurationUnit.NANOSECONDS)"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public val inNanoseconds: Double get() = toDouble(DurationUnit.NANOSECONDS)
/**
* The value of this duration expressed as a [Long] number of days.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeDays: Long
get() = toLong(DurationUnit.DAYS)
/**
* The value of this duration expressed as a [Long] number of hours.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeHours: Long
get() = toLong(DurationUnit.HOURS)
/**
* The value of this duration expressed as a [Long] number of minutes.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeMinutes: Long
get() = toLong(DurationUnit.MINUTES)
/**
* The value of this duration expressed as a [Long] number of seconds.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeSeconds: Long
get() = toLong(DurationUnit.SECONDS)
/**
* The value of this duration expressed as a [Long] number of milliseconds.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeMilliseconds: Long
get() {
return if (isInMillis() && isFinite()) value else toLong(DurationUnit.MILLISECONDS)
}
/**
* The value of this duration expressed as a [Long] number of microseconds.
*
* If the result doesn't fit in the range of [Long] type, it is coerced into that range:
* - [Long.MIN_VALUE] is returned if it's less than `Long.MIN_VALUE`,
* - [Long.MAX_VALUE] is returned if it's greater than `Long.MAX_VALUE`.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeMicroseconds: Long
get() = toLong(DurationUnit.MICROSECONDS)
/**
* The value of this duration expressed as a [Long] number of nanoseconds.
*
* If the result doesn't fit in the range of [Long] type, it is coerced into that range:
* - [Long.MIN_VALUE] is returned if it's less than `Long.MIN_VALUE`,
* - [Long.MAX_VALUE] is returned if it's greater than `Long.MAX_VALUE`.
*
* An infinite duration value is converted either to [Long.MAX_VALUE] or [Long.MIN_VALUE] depending on its sign.
*/
public val inWholeNanoseconds: Long
get() {
val value = value
return when {
isInNanos() -> value
value > Long.MAX_VALUE / NANOS_IN_MILLIS -> Long.MAX_VALUE
value < Long.MIN_VALUE / NANOS_IN_MILLIS -> Long.MIN_VALUE
else -> millisToNanos(value)
}
}
// shortcuts
/**
* Returns the value of this duration expressed as a [Long] number of nanoseconds.
*
* If the value doesn't fit in the range of [Long] type, it is coerced into that range, see the conversion [Double.toLong] for details.
*
* The range of durations that can be expressed as a `Long` number of nanoseconds is approximately ±292 years.
*/
@ExperimentalTime
@Deprecated("Use inWholeNanoseconds property instead.", ReplaceWith("this.inWholeNanoseconds"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public fun toLongNanoseconds(): Long = inWholeNanoseconds
/**
* Returns the value of this duration expressed as a [Long] number of milliseconds.
*
* The value is coerced to the range of [Long] type, if it doesn't fit in that range, see the conversion [Double.toLong] for details.
*
* The range of durations that can be expressed as a `Long` number of milliseconds is approximately ±292 million years.
*/
@ExperimentalTime
@Deprecated("Use inWholeMilliseconds property instead.", ReplaceWith("this.inWholeMilliseconds"))
@DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "1.8")
public fun toLongMilliseconds(): Long = inWholeMilliseconds
/**
* Returns a string representation of this duration value
* expressed as a combination of numeric components, each in its own unit.
*
* Each component is a number followed by the unit abbreviated name: `d`, `h`, `m`, `s`:
* `5h`, `1d 12h`, `1h 0m 30.340s`.
* The last component, usually seconds, can be a number with a fractional part.
*
* If the duration is less than a second, it is represented as a single number
* with one of sub-second units: `ms` (milliseconds), `us` (microseconds), or `ns` (nanoseconds):
* `140.884ms`, `500us`, `24ns`.
*
* A negative duration is prefixed with `-` sign and, if it consists of multiple components, surrounded with parentheses:
* `-12m` and `-(1h 30m)`.
*
* Special cases:
* - an infinite duration is formatted as `"Infinity"` or `"-Infinity"` without a unit.
*
* It's recommended to use [toIsoString] that uses more strict ISO-8601 format instead of this `toString`
* when you want to convert a duration to a string in cases of serialization, interchange, etc.
*
* @sample samples.time.Durations.toStringDefault
*/
override fun toString(): String = when (rawValue) {
0L -> "0s"
INFINITE.rawValue -> "Infinity"
NEG_INFINITE.rawValue -> "-Infinity"
else -> {
val isNegative = isNegative()
buildString {
if (isNegative) append('-')
absoluteValue.toComponents { days, hours, minutes, seconds, nanoseconds ->
val hasDays = days != 0L
val hasHours = hours != 0
val hasMinutes = minutes != 0
val hasSeconds = seconds != 0 || nanoseconds != 0
var components = 0
if (hasDays) {
append(days).append('d')
components++
}
if (hasHours || (hasDays && (hasMinutes || hasSeconds))) {
if (components++ > 0) append(' ')
append(hours).append('h')
}
if (hasMinutes || (hasSeconds && (hasHours || hasDays))) {
if (components++ > 0) append(' ')
append(minutes).append('m')
}
if (hasSeconds) {
if (components++ > 0) append(' ')
when {
seconds != 0 || hasDays || hasHours || hasMinutes ->
appendFractional(seconds, nanoseconds, 9, "s", isoZeroes = false)
nanoseconds >= 1_000_000 ->
appendFractional(nanoseconds / 1_000_000, nanoseconds % 1_000_000, 6, "ms", isoZeroes = false)
nanoseconds >= 1_000 ->
appendFractional(nanoseconds / 1_000, nanoseconds % 1_000, 3, "us", isoZeroes = false)
else ->
append(nanoseconds).append("ns")
}
}
if (isNegative && components > 1) insert(1, '(').append(')')
}