Skip to content

Commit 1b3a39d

Browse files
committed
feat(duration): add DurationValue struct for time representation
- Introduces a new `DurationValue` record struct to represent time quantities in specified units. - Removes the `None` duration unit from the `DurationUnit` enum. - Enforces non-negative counts in the `DurationValue` constructor. - Implements string formatting for displaying duration in a user-friendly manner. - Includes comparison logic to ensure durations of the same unit can be compared.
1 parent 599a7d0 commit 1b3a39d

2 files changed

Lines changed: 52 additions & 5 deletions

File tree

src/ES.FX/Primitives/DurationUnit.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,6 @@ namespace ES.FX.Primitives;
4545
[PublicAPI]
4646
public enum DurationUnit
4747
{
48-
/// <summary>
49-
/// No duration unit.
50-
/// </summary>
51-
None,
52-
5348
/// <summary>
5449
/// A 100-nanosecond interval.
5550
/// </summary>
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using JetBrains.Annotations;
2+
3+
namespace ES.FX.Primitives;
4+
5+
/// <summary>
6+
/// Represents a quantity of time, in a specified unit.
7+
/// </summary>
8+
[PublicAPI]
9+
public readonly record struct DurationValue : IComparable<DurationValue>
10+
{
11+
/// <summary>
12+
/// The number of units.
13+
/// </summary>
14+
public long Count { get; init; }
15+
16+
/// <summary>
17+
/// The unit of time for this duration.
18+
/// </summary>
19+
public DurationUnit Unit { get; init; }
20+
21+
/// <summary>
22+
/// Initializes a new <see cref="DurationValue"/> with the specified count and unit,
23+
/// enforcing non-negative counts.
24+
/// </summary>
25+
/// <param name="count">The number of units. Must be non-negative.</param>
26+
/// <param name="unit">The duration unit.</param>
27+
public DurationValue(long count, DurationUnit unit)
28+
{
29+
if (count < 0)
30+
throw new ArgumentOutOfRangeException(nameof(count), "Count must be non-negative");
31+
32+
Count = count;
33+
Unit = unit;
34+
}
35+
36+
/// <summary>
37+
/// Returns a string such as "7 Days".
38+
/// </summary>
39+
public override string ToString() => $"{Count} {Unit}{(Count == 1 ? string.Empty : "s")}";
40+
41+
/// <summary>
42+
/// Compares two durations of the same unit.
43+
/// Comparing different units is not supported.
44+
/// </summary>
45+
public int CompareTo(DurationValue other)
46+
{
47+
if (Unit != other.Unit)
48+
throw new InvalidOperationException("Cannot compare durations of different units.");
49+
50+
return Count.CompareTo(other.Count);
51+
}
52+
}

0 commit comments

Comments
 (0)