-
Notifications
You must be signed in to change notification settings - Fork 110
Local date range #189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Local date range #189
Changes from all commits
Commits
Show all changes
60 commits
Select commit
Hold shift + click to select a range
ac5ec5f
Add minus operator to DatePeriod and DateTimePeriod
PeterAttardo a962bde
Add unary minus operator to DatePeriod and DateTimePeriod
PeterAttardo 740434f
Add LocalDateRange class and associated tests. Exists to enable Kotlin
PeterAttardo 2ea4cdb
Add tests for minus and unaryMinus operators for DatePeriod and
PeterAttardo d3ab645
Merge remote-tracking branch 'origin/master' into local-date-range
PeterAttardo 59bd4fd
Rework LocalDateRange to match proposed spec
PeterAttardo e249b20
Revert "Add tests for minus and unaryMinus operators for DatePeriod and"
PeterAttardo 2e0b957
Revert "Add unary minus operator to DatePeriod and DateTimePeriod"
PeterAttardo 375b6da
Revert "Add minus operator to DatePeriod and DateTimePeriod"
PeterAttardo 9a7c507
Make LocalDateProgressionIterator private
PeterAttardo 33222c6
Specify that steps are in days in string representation of LocalDateP…
PeterAttardo 372fa1b
Add deprecation warning to endExclusive of LocalDateRange
PeterAttardo 72fa3a5
Remove downUntil from LocalDateRange
PeterAttardo df405c7
Simplify LocalDateProgression.random()
PeterAttardo f2d2566
Use safeMultiply in LocalDateRange
PeterAttardo fd1179a
Make fromClosedRange internal
PeterAttardo 01455c6
Simplify equals method in LocalDateProgression
PeterAttardo 358e60d
Add to/from epoch days in Long to LocalDate
PeterAttardo 4911221
Correct LocalDateRangeTest
PeterAttardo 430bfdc
Switch from IntProgression to LongProgression in LocalDateProgression
PeterAttardo 77c9ab1
Delete downUntil test
PeterAttardo c04b640
Samples and documentation for LocalDateRange
PeterAttardo bb7991f
Simplify LocalDateRange.EMPTY
PeterAttardo 7bff3cc
Fix logic of LongProgression.contains
PeterAttardo c8f88ab
Move LocalDate range operators from extension functions to class methods
PeterAttardo 22d263c
Add tests for LocalDateRange
PeterAttardo 0042bfa
Return EMPTY in case of rangeUntil LocalDate.MIN
PeterAttardo fad37f9
Add tests for non-1 step in LocalDateProgression.getSize()
PeterAttardo d0265f2
Add test for LocalDateProgression.random()
PeterAttardo ca43825
Merge remote-tracking branch 'origin/master' into local-date-range
PeterAttardo 66a058b
Update core/commonKotlin/src/LocalDate.kt
PeterAttardo 4255bf3
Reduce duplication
PeterAttardo 0880589
Update LocalDateRangeSamples
PeterAttardo 56ca1ae
Update core/commonJs/src/LocalDate.kt
PeterAttardo 63a4c42
Update core/commonKotlin/src/LocalDate.kt
PeterAttardo 614038d
Update core/common/test/LocalDateRangeTest.kt
PeterAttardo b5db45c
Update core/common/test/LocalDateRangeTest.kt
PeterAttardo cc9d7a1
Update core/common/test/LocalDateRangeTest.kt
PeterAttardo a4a2ead
Update core/common/test/LocalDateRangeTest.kt
PeterAttardo 9ba1ac1
Update core/common/src/LocalDateRange.kt
PeterAttardo 53f6227
Fix LocalDateRange test
PeterAttardo f4b5bc0
Add tests to last() for LocalDateRangeTest
PeterAttardo 89101cb
Add documentation to LocalDateRange.EMPTY
PeterAttardo fef8e59
Update core/common/src/LocalDateRange.kt
PeterAttardo 5e97217
Update core/common/src/LocalDateRange.kt
PeterAttardo 1f2ac18
Update core/common/src/LocalDateRange.kt
PeterAttardo 37a213e
Update core/common/src/LocalDateRange.kt
PeterAttardo 28e1806
Word choice in comments
PeterAttardo d161989
Add safeMultiplyOrClamp
PeterAttardo dbac356
Clamp steps that overflow Long
PeterAttardo 56c042b
Unused variables
PeterAttardo 163f585
Import clampToInt for js
PeterAttardo 405f034
Fix getSize test in LocalDateRangeTest
PeterAttardo 179478e
Make LocalDateRangeTest stricter
PeterAttardo b16b329
Add equals and hashcode tests to LocalDateRangeTest
PeterAttardo fe39e5c
Fix whitespace
PeterAttardo 6f67327
Unify parameter name for LocalDateRange.contains() and LocalDateProgr…
PeterAttardo d29d53d
Merge remote-tracking branch 'upstream/master' into local-date-range
PeterAttardo b6d56ce
Add type checks for unexpected variance in LocalDateProgression
PeterAttardo c58c61f
Switch LocalDateRange.random() to throw NoSuchElementException instea…
PeterAttardo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,285 @@ | ||
/* | ||
* Copyright 2019-2022 JetBrains s.r.o. | ||
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. | ||
*/ | ||
|
||
package kotlinx.datetime | ||
|
||
import kotlinx.datetime.internal.clampToInt | ||
import kotlinx.datetime.internal.safeAdd | ||
import kotlinx.datetime.internal.safeMultiplyOrClamp | ||
import kotlin.random.Random | ||
import kotlin.random.nextLong | ||
|
||
private class LocalDateProgressionIterator(private val iterator: LongIterator) : Iterator<LocalDate> { | ||
override fun hasNext(): Boolean = iterator.hasNext() | ||
override fun next(): LocalDate = LocalDate.fromEpochDays(iterator.next()) | ||
} | ||
|
||
/** | ||
* A progression of values of type [LocalDate]. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.progressionWithStep | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.reversedProgression | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.firstAndLast | ||
*/ | ||
public open class LocalDateProgression | ||
internal constructor(internal val longProgression: LongProgression) : Collection<LocalDate> { | ||
|
||
internal constructor( | ||
start: LocalDate, | ||
endInclusive: LocalDate, | ||
step: Long | ||
) : this(LongProgression.fromClosedRange(start.toEpochDaysLong(), endInclusive.toEpochDaysLong(), step)) | ||
|
||
/** | ||
* Returns the first [LocalDate] of the progression | ||
*/ | ||
public val first: LocalDate = LocalDate.fromEpochDays(longProgression.first) | ||
|
||
/** | ||
* Returns the last [LocalDate] of the progression | ||
*/ | ||
public val last: LocalDate = LocalDate.fromEpochDays(longProgression.last) | ||
|
||
/** | ||
* Returns an [Iterator] that traverses the progression from [first] to [last] | ||
*/ | ||
override fun iterator(): Iterator<LocalDate> = LocalDateProgressionIterator(longProgression.iterator()) | ||
|
||
/** | ||
* Returns true iff the progression contains no values. | ||
* i.e. [first] < [last] if step is positive, or [first] > [last] if step is negative. | ||
*/ | ||
public override fun isEmpty(): Boolean = longProgression.isEmpty() | ||
|
||
/** | ||
* Returns a string representation of the progression. | ||
* Uses the range operator notation if the progression is increasing, and `downTo` if it is decreasing. | ||
* The step is referenced in days. | ||
*/ | ||
override fun toString(): String = if (longProgression.step > 0) "$first..$last step ${longProgression.step}D" else "$first downTo $last step ${longProgression.step}D" | ||
|
||
/** | ||
* Returns the number of dates in the progression. | ||
* Returns [Int.MAX_VALUE] if the number of dates overflows [Int] | ||
*/ | ||
override val size: Int | ||
get() = longProgression.size | ||
|
||
/** | ||
* Returns true iff every element in [elements] is a member of the progression. | ||
*/ | ||
override fun containsAll(elements: Collection<LocalDate>): Boolean = | ||
(elements as Collection<*>).all { it is LocalDate && contains(it) } | ||
|
||
/** | ||
* Returns true iff [value] is a member of the progression. | ||
*/ | ||
override fun contains(value: LocalDate): Boolean { | ||
@Suppress("USELESS_CAST") | ||
if ((value as Any?) !is LocalDate) return false | ||
|
||
return longProgression.contains(value.toEpochDaysLong()) | ||
} | ||
|
||
override fun equals(other: Any?): Boolean = other is LocalDateProgression && longProgression == other.longProgression | ||
|
||
override fun hashCode(): Int = longProgression.hashCode() | ||
|
||
public companion object { | ||
internal fun fromClosedRange( | ||
rangeStart: LocalDate, | ||
rangeEnd: LocalDate, | ||
stepValue: Long, | ||
stepUnit: DateTimeUnit.DayBased | ||
): LocalDateProgression = LocalDateProgression(rangeStart, rangeEnd, safeMultiplyOrClamp(stepValue, stepUnit.days.toLong())) | ||
} | ||
} | ||
|
||
/** | ||
* A range of values of type [LocalDate]. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.simpleRangeCreation | ||
*/ | ||
public class LocalDateRange(start: LocalDate, endInclusive: LocalDate) : LocalDateProgression(start, endInclusive, 1), ClosedRange<LocalDate>, OpenEndRange<LocalDate> { | ||
/** | ||
* Returns the lower bound of the range, inclusive. | ||
*/ | ||
override val start: LocalDate get() = first | ||
|
||
/** | ||
* Returns the upper bound of the range, inclusive. | ||
*/ | ||
override val endInclusive: LocalDate get() = last | ||
|
||
/** | ||
* Returns the upper bound of the range, exclusive. | ||
*/ | ||
@Deprecated( | ||
"This throws an exception if the exclusive end if not inside " + | ||
"the platform-specific boundaries for LocalDate. " + | ||
"The 'endInclusive' property does not throw and should be preferred.", | ||
level = DeprecationLevel.WARNING | ||
) | ||
override val endExclusive: LocalDate get(){ | ||
if (last == LocalDate.MAX) error("Cannot return the exclusive upper bound of a range that includes LocalDate.MAX.") | ||
return endInclusive.plus(1, DateTimeUnit.DAY) | ||
} | ||
|
||
/** | ||
* Returns true iff [value] is contained within the range. | ||
* i.e. [value] is between [start] and [endInclusive]. | ||
*/ | ||
@Suppress("ConvertTwoComparisonsToRangeCheck") | ||
override fun contains(value: LocalDate): Boolean { | ||
@Suppress("USELESS_CAST") | ||
if ((value as Any?) !is LocalDate) return false | ||
|
||
return first <= value && value <= last | ||
} | ||
|
||
/** | ||
* Returns true iff there are no dates contained within the range. | ||
*/ | ||
override fun isEmpty(): Boolean = first > last | ||
|
||
/** | ||
* Returns a string representation of the range using the range operator notation. | ||
*/ | ||
override fun toString(): String = "$first..$last" | ||
|
||
public companion object { | ||
/** An empty range of values of type LocalDate. */ | ||
public val EMPTY: LocalDateRange = LocalDateRange(LocalDate(1970, 1, 2), LocalDate(1970, 1, 1)) | ||
|
||
internal fun fromRangeUntil(start: LocalDate, endExclusive: LocalDate) : LocalDateRange { | ||
return if(endExclusive == LocalDate.MIN) EMPTY else fromRangeTo(start, endExclusive.minus(1, DateTimeUnit.DAY)) | ||
} | ||
|
||
internal fun fromRangeTo(start: LocalDate, endInclusive: LocalDate) : LocalDateRange { | ||
return LocalDateRange(start, endInclusive) | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Returns the first [LocalDate] of the [LocalDateProgression]. | ||
* | ||
* @throws NoSuchElementException if the progression is empty. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.firstAndLast | ||
*/ | ||
public fun LocalDateProgression.first(): LocalDate { | ||
if (isEmpty()) | ||
throw NoSuchElementException("Progression $this is empty.") | ||
return this.first | ||
} | ||
|
||
/** | ||
* Returns the last [LocalDate] of the [LocalDateProgression]. | ||
* | ||
* @throws NoSuchElementException if the progression is empty. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.firstAndLast | ||
*/ | ||
public fun LocalDateProgression.last(): LocalDate { | ||
if (isEmpty()) | ||
throw NoSuchElementException("Progression $this is empty.") | ||
return this.last | ||
} | ||
|
||
/** | ||
* Returns the first [LocalDate] of the [LocalDateProgression], or null if the progression is empty. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.firstAndLast | ||
*/ | ||
public fun LocalDateProgression.firstOrNull(): LocalDate? = if (isEmpty()) null else this.first | ||
|
||
/** | ||
* Returns the last [LocalDate] of the [LocalDateProgression], or null if the progression is empty. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.firstAndLast | ||
*/ | ||
public fun LocalDateProgression.lastOrNull(): LocalDate? = if (isEmpty()) null else this.last | ||
|
||
/** | ||
* Returns a reversed [LocalDateProgression], i.e. one that goes from [last] to [first]. | ||
* The sign of the step is switched, in order to reverse the direction of the progression. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.reversedProgression | ||
*/ | ||
public fun LocalDateProgression.reversed(): LocalDateProgression = LocalDateProgression(longProgression.reversed()) | ||
|
||
/** | ||
* Returns a [LocalDateProgression] with the same start and end, but a changed step value. | ||
* | ||
* **Pitfall**: the value parameter represents the magnitude of the step, not the direction, and therefore must be positive. | ||
* Its sign will be matched to the sign of the existing step, in order to maintain the direction of the progression. | ||
* If you wish to switch the direction of the progression, use [LocalDateProgression.reversed] | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.progressionWithStep | ||
*/ | ||
public fun LocalDateProgression.step(value: Int, unit: DateTimeUnit.DayBased) : LocalDateProgression = step(value.toLong(), unit) | ||
|
||
/** | ||
* Returns a [LocalDateProgression] with the same start and end, but a changed step value. | ||
* | ||
* **Pitfall**: the value parameter represents the magnitude of the step, not the direction, and therefore must be positive. | ||
* Its sign will be matched to the sign of the existing step, in order to maintain the direction of the progression. | ||
* If you wish to switch the direction of the progression, use [LocalDateProgression.reversed] | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.progressionWithStep | ||
*/ | ||
public fun LocalDateProgression.step(value: Long, unit: DateTimeUnit.DayBased) : LocalDateProgression = LocalDateProgression(longProgression.step(safeMultiplyOrClamp(value, unit.days.toLong()))) | ||
|
||
/** | ||
* Creates a [LocalDateProgression] from `this` down to [that], inclusive. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.simpleRangeCreation | ||
*/ | ||
public infix fun LocalDate.downTo(that: LocalDate) : LocalDateProgression = LocalDateProgression.fromClosedRange(this, that, -1, DateTimeUnit.DAY) | ||
|
||
/** | ||
* Returns a random [LocalDate] within the bounds of the [LocalDateProgression]. | ||
* | ||
* Takes the step into account; will not return any value within the range that would be skipped over by the progression. | ||
* | ||
* @throws IllegalArgumentException if the progression is empty. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.random | ||
*/ | ||
public fun LocalDateProgression.random(random: Random = Random): LocalDate = | ||
if (isEmpty()) throw NoSuchElementException("Cannot get random in empty range: $this") | ||
else longProgression.random(random).let(LocalDate.Companion::fromEpochDays) | ||
|
||
/** | ||
* Returns a random [LocalDate] within the bounds of the [LocalDateProgression] or null if the progression is empty. | ||
* | ||
* Takes the step into account; will not return any value within the range that would be skipped over by the progression. | ||
* | ||
* @sample kotlinx.datetime.test.samples.LocalDateRangeSamples.random | ||
*/ | ||
public fun LocalDateProgression.randomOrNull(random: Random = Random) : LocalDate? = longProgression.randomOrNull(random) | ||
?.let(LocalDate.Companion::fromEpochDays) | ||
|
||
// this implementation is incorrect in general (for example, `(Long.MIN_VALUE..Long.MAX_VALUE).random()` throws an exception), | ||
// but for the range of epoch days in LocalDate it's good enough | ||
private fun LongProgression.random(random: Random = Random) : Long = random.nextLong(0L..(last - first) / step) * step + first | ||
|
||
// incorrect in general; see `random` just above | ||
private fun LongProgression.randomOrNull(random: Random = Random) : Long? = if (isEmpty()) null else random(random) | ||
|
||
// this implementation is incorrect in general (for example, `(Long.MIN_VALUE..Long.MAX_VALUE).step(5).contains(2)` returns `false` | ||
// incorrectly https://www.wolframalpha.com/input?i=-2%5E63+%2B+1844674407370955162+*+5), | ||
// but for the range of epoch days in LocalDate it's good enough | ||
private fun LongProgression.contains(value: Long) : Boolean = value in (if(step > 0) first..last else last..first) && (value - first) % step == 0L | ||
|
||
// this implementation is incorrect in general (for example, `Long.MIN_VALUE..Long.MAX_VALUE` has size == 0), | ||
// but for the range of epoch days in LocalDate it's good enough | ||
private val LongProgression.size: Int | ||
get() = if(isEmpty()) 0 else try { | ||
(safeAdd(last, -first) / step + 1).clampToInt() | ||
} catch (e: ArithmeticException) { | ||
Int.MAX_VALUE | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.