Skip to content

Commit

Permalink
Added Ensure extensions for range-related exceptions.
Browse files Browse the repository at this point in the history
Added implementation of IEquatable<Range<T>> to Range struct.
Exception check from the constructor of Range struct moved to Ensure extensions so its logic can be reused now.
Added more comments to Range struct.
Closes #5 and closes #6.
Version 0.0.3.
  • Loading branch information
Konard committed Jul 24, 2019
1 parent 3351b32 commit 887a473
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 10 deletions.
69 changes: 69 additions & 0 deletions EnsureExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Platform.Exceptions;

#pragma warning disable IDE0060 // Remove unused parameter

namespace Platform.Ranges
{
public static class EnsureExtensions
{
#region Always

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MaximumArgumentIsGreaterOrEqualToMinimum<T>(this EnsureAlwaysExtensionRoot root, T minimum, T maximum) => MaximumArgumentIsGreaterOrEqualToMinimum(root, minimum, maximum, nameof(maximum));

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void MaximumArgumentIsGreaterOrEqualToMinimum<T>(this EnsureAlwaysExtensionRoot root, T minimum, T maximum, string argumentName)
{
if (Comparer<T>.Default.Compare(maximum, minimum) < 0)
{
throw new ArgumentException("Maximum should be greater or equal to minimum.", argumentName);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ArgumentInRange<T>(this EnsureAlwaysExtensionRoot root, T argumentValue, T minimum, T maximum) => ArgumentInRange(root, argumentValue, new Range<T>(minimum, maximum), null);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ArgumentInRange<T>(this EnsureAlwaysExtensionRoot root, T argumentValue, T minimum, T maximum, string argumentName) => ArgumentInRange(root, argumentValue, new Range<T>(minimum, maximum), argumentName);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ArgumentInRange<T>(this EnsureAlwaysExtensionRoot root, T argumentValue, Range<T> range) => ArgumentInRange(root, argumentValue, range, null);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ArgumentInRange<T>(this EnsureAlwaysExtensionRoot root, T argumentValue, Range<T> range, string argumentName)
{
if (!range.ContainsValue(argumentValue))
{
throw new ArgumentOutOfRangeException(argumentName, argumentValue, $"Argument value [{argumentValue}] is out of range {range}.");
}
}

#endregion

#region OnDebug

[Conditional("DEBUG")]
public static void MaximumArgumentIsGreaterOrEqualToMinimum<T>(this EnsureOnDebugExtensionRoot root, T minimum, T maximum) => Ensure.Always.MaximumArgumentIsGreaterOrEqualToMinimum(minimum, maximum, null);

[Conditional("DEBUG")]
public static void MaximumArgumentIsGreaterOrEqualToMinimum<T>(this EnsureOnDebugExtensionRoot root, T minimum, T maximum, string argumentName) => Ensure.Always.MaximumArgumentIsGreaterOrEqualToMinimum(minimum, maximum, argumentName);

[Conditional("DEBUG")]
public static void ArgumentInRange<T>(this EnsureOnDebugExtensionRoot root, T argumentValue, T minimum, T maximum) => Ensure.Always.ArgumentInRange(argumentValue, new Range<T>(minimum, maximum), null);

[Conditional("DEBUG")]
public static void ArgumentInRange<T>(this EnsureOnDebugExtensionRoot root, T argumentValue, T minimum, T maximum, string argumentName) => Ensure.Always.ArgumentInRange(argumentValue, new Range<T>(minimum, maximum), argumentName);

[Conditional("DEBUG")]
public static void ArgumentInRange<T>(this EnsureOnDebugExtensionRoot root, T argument, Range<T> range) => Ensure.Always.ArgumentInRange(argument, range, null);

[Conditional("DEBUG")]
public static void ArgumentInRange<T>(this EnsureOnDebugExtensionRoot root, T argument, Range<T> range, string argumentName) => Ensure.Always.ArgumentInRange(argument, range, argumentName);

#endregion
}
}
17 changes: 13 additions & 4 deletions Platform.Ranges.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
<Description>LinksPlatform's Platform.Ranges Class Library</Description>
<Copyright>Konstantin Diachenko</Copyright>
<AssemblyTitle>Platform.Ranges</AssemblyTitle>
<VersionPrefix>0.0.2</VersionPrefix>
<VersionPrefix>0.0.3</VersionPrefix>
<Authors>Konstantin Diachenko</Authors>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>Platform.Ranges</AssemblyName>
<PackageId>Platform.Ranges</PackageId>
<PackageTags>LinksPlatform;Ranges;Range</PackageTags>
<PackageIconUrl>https://raw.githubusercontent.com/linksplatform/Documentation/0a9177c11892ebb2fe467dc3ea9eaf5a5588f610/doc/Avatar-rainbow.png</PackageIconUrl>
<PackageTags>LinksPlatform;Ranges;Range;EnsureExtensions</PackageTags>
<PackageIconUrl>https://raw.githubusercontent.com/linksplatform/Documentation/18469f4d033ee9a5b7b84caab9c585acab2ac519/doc/Avatar-rainbow-icon-64x64.png</PackageIconUrl>
<PackageProjectUrl>https://github.com/linksplatform/Ranges</PackageProjectUrl>
<PackageLicenseUrl>https://github.com/linksplatform/Ranges/blob/master/LICENSE</PackageLicenseUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>git://github.com/linksplatform/Ranges</RepositoryUrl>
Expand All @@ -21,6 +21,15 @@
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageReleaseNotes>Added Ensure extensions for range-related exceptions.
Added implementation of IEquatable&lt;Range&lt;T&gt;&gt; to Range struct.
Exception check from the constructor of Range struct moved to Ensure extensions so its logic can be reused now.
Added more comments to Range struct.
Two issues closed.</PackageReleaseNotes>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Platform.Exceptions" Version="0.1.0" />
</ItemGroup>

</Project>
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ NuGet package: https://www.nuget.org/packages/Platform.Ranges

`Range` *class* with `Floor` and `Ceiling` *fields*.

### [mnelsonwhite/Range.NET](https://github.com/mnelsonwhite/Range.NET)
### [mnelsonwhite/Range.NET](https://github.com/mnelsonwhite/Range.NET)

`Range` *class* with `Minumum` and `Maximum` *properties*.

### [sdcb/Sdcb.System.Range](https://github.com/sdcb/Sdcb.System.Range)

`Range` *struct* with `Start` and `End` *properties*.
`Range` *struct* with `Start` and `End` *properties*.
30 changes: 26 additions & 4 deletions Range.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using Platform.Exceptions;

namespace Platform.Ranges
{
Expand All @@ -10,9 +11,10 @@ namespace Platform.Ranges
/// <remarks>
/// Based on http://stackoverflow.com/questions/5343006/is-there-a-c-sharp-type-for-representing-an-integer-range
/// </remarks>
public struct Range<T>
public struct Range<T> : IEquatable<Range<T>>
{
private static readonly Comparer<T> _comparer = Comparer<T>.Default;
private static readonly EqualityComparer<T> _equalityComparer = EqualityComparer<T>.Default;

/// <summary>
/// Returns minimum value of the range.
Expand All @@ -26,15 +28,27 @@ public struct Range<T>
/// </summary>
public readonly T Maximum;

/// <summary>
/// Initializes a new instance of the Range class.
/// Инициализирует новый экземпляр класса Range.
/// </summary>
/// <param name="minimumAndMaximum">Single value for both Minimum and Maximum fields. Одно значение для полей Minimum и Maximum.</param>
public Range(T minimumAndMaximum)
: this(minimumAndMaximum, minimumAndMaximum)
{
Minimum = minimumAndMaximum;
Maximum = minimumAndMaximum;
}

/// <summary>
/// Initializes a new instance of the Range class.
/// Инициализирует новый экземпляр класса Range.
/// </summary>
/// <param name="minimum">The minimum value of the range. Минимальное значение диапазона.</param>
/// <param name="maximum">The maximum value of the range. Максимальное значение диапазона.</param>
/// <exception cref="ArgumentException">Thrown when maximum is less than minimum.</exception>
public Range(T minimum, T maximum)
{
if (_comparer.Compare(maximum, minimum) < 0)
throw new ArgumentException("Maximum should be greater or equal to minimum.", nameof(maximum));
Ensure.Always.MaximumArgumentIsGreaterOrEqualToMinimum(minimum, maximum, nameof(maximum));

Minimum = minimum;
Maximum = maximum;
Expand Down Expand Up @@ -70,5 +84,13 @@ public Range(T minimum, T maximum)
/// <param name="range">The child range to test. Дочерний диапазон для проверки.</param>
/// <returns>True if range is inside, else false. True, если диапазон находится внутри, иначе false.</returns>
public bool ContainsRange(Range<T> range) => ContainsValue(range.Minimum) && ContainsValue(range.Maximum);

/// <summary>
/// Indicates whether the current range is equal to another range.
/// Определяет, равен ли текущий диапазон другому диапазону.
/// </summary>
/// <param name="other">A range to compare with this range. Диапазон для сравнения с этим диапазоном.</param>
/// <returns>True if the current range is equal to the other range; otherwise, false. True, если текущий диапазон равен другому диапазону; иначе false.</returns>
public bool Equals(Range<T> other) => _equalityComparer.Equals(Minimum, other.Minimum) && _equalityComparer.Equals(Maximum, other.Maximum);
}
}

0 comments on commit 887a473

Please sign in to comment.