| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="DateTimeRange.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | |
| | | 10 | | using MyNet.Primitives.Intervals; |
| | | 11 | | |
| | | 12 | | namespace MyNet.Temporal.Intervals; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Configurable civil <see cref="DateTime"/> interval. Defaults to half-open <c>[start, end)</c>. |
| | | 16 | | /// Use <see cref="DateTimePeriod"/> when the half-open contract must be enforced; use this type when |
| | | 17 | | /// inclusivity is caller-defined. <see cref="DateTime.Kind"/> is not normalized. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <param name="start">Start bound.</param> |
| | | 20 | | /// <param name="end">End bound.</param> |
| | | 21 | | /// <param name="inclusiveStart">Whether start is inclusive (default true).</param> |
| | | 22 | | /// <param name="inclusiveEnd">Whether end is inclusive (default false).</param> |
| | | 23 | | public sealed class DateTimeRange(DateTime start, DateTime end, bool inclusiveStart = true, bool inclusiveEnd = false) |
| | 21 | 24 | | : DateTimeInterval<DateTimeRange>(start, end, inclusiveStart, inclusiveEnd) |
| | | 25 | | { |
| | | 26 | | /// <summary> |
| | | 27 | | /// Enumerates values from start to end using a fixed <paramref name="step"/>. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="step"/> is not positive.</exception> |
| | | 30 | | public IEnumerable<DateTime> Enumerate(TimeSpan step) |
| | | 31 | | { |
| | 3 | 32 | | ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(step, TimeSpan.Zero); |
| | | 33 | | |
| | 3 | 34 | | var current = Start!.Value.Value; |
| | 3 | 35 | | if (!Start.Value.IsInclusive) |
| | | 36 | | { |
| | 3 | 37 | | current += step; |
| | | 38 | | } |
| | | 39 | | |
| | 9 | 40 | | while (current < End!.Value.Value || (End.Value.IsInclusive && current == End.Value.Value)) |
| | | 41 | | { |
| | 6 | 42 | | yield return current; |
| | 6 | 43 | | current += step; |
| | | 44 | | } |
| | 3 | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <inheritdoc /> |
| | | 48 | | protected override DateTimeRange Create(IntervalBoundary<DateTime>? start, IntervalBoundary<DateTime>? end) => |
| | 3 | 49 | | !start.HasValue || !end.HasValue |
| | 3 | 50 | | ? throw new InvalidOperationException("DateTimeRange must be bounded.") |
| | 3 | 51 | | : new DateTimeRange(start.Value.Value, end.Value.Value, start.Value.IsInclusive, end.Value.IsInclusive); |
| | | 52 | | } |
| | | 53 | | |