Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Collections.Immutable;
using FluentAssertions;
using Xunit;

namespace Light.GuardClauses.Tests.CollectionAssertions;

public static class MustHaveLengthInTests
{
[Theory]
[MemberData(nameof(LengthInRangeData))]
public static void LengthInRange(ImmutableArray<int> array, Range<int> range) =>
array.MustHaveLengthIn(range).Should().Equal(array);

public static readonly TheoryData<ImmutableArray<int>, Range<int>> LengthInRangeData =
new ()
{
{ [1, 2, 3], Range.FromInclusive(0).ToExclusive(10) },
{ [1, 2, 3, 4, 5], Range.FromInclusive(3).ToInclusive(5) },
{ ImmutableArray<int>.Empty, Range.FromInclusive(0).ToExclusive(100) },
{ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], Range.FromExclusive(5).ToInclusive(10) },
};

[Theory]
[MemberData(nameof(LengthNotInRangeData))]
public static void LengthNotInRange(ImmutableArray<int> array, Range<int> range)
{
var act = () => array.MustHaveLengthIn(range, nameof(array));

act.Should().Throw<ArgumentOutOfRangeException>()
.And.Message.Should().Contain($"must have its length in between {range.CreateRangeDescriptionText("and")}")
.And.Contain($"but it actually has length {array.Length}");
}

public static readonly TheoryData<ImmutableArray<int>, Range<int>> LengthNotInRangeData =
new ()
{
{ [1, 2, 3], Range.FromInclusive(10).ToInclusive(20) },
{ [1, 2, 3, 4], Range.FromExclusive(4).ToExclusive(10) },
{ ImmutableArray<int>.Empty, Range.FromInclusive(1).ToExclusive(50) },
{ [1, 2], Range.FromInclusive(100).ToExclusive(256) },
};

[Fact]
public static void CustomException() =>
Test.CustomException(
ImmutableArray.Create(1, 2, 3),
Range.FromInclusive(5).ToInclusive(10),
(array, r, exceptionFactory) => array.MustHaveLengthIn(r, exceptionFactory)
);

[Fact]
public static void CustomMessage() =>
Test.CustomMessage<ArgumentOutOfRangeException>(
message => ImmutableArray.Create(1, 2, 3).MustHaveLengthIn(
Range.FromInclusive(42).ToInclusive(50),
message: message
)
);

[Fact]
public static void CallerArgumentExpression()
{
var testArray = ImmutableArray.Create(1, 2, 3, 4, 5);

var act = () => testArray.MustHaveLengthIn(Range.FromInclusive(10).ToExclusive(20));

act.Should().Throw<ArgumentOutOfRangeException>()
.WithParameterName(nameof(testArray));
}
}
48 changes: 48 additions & 0 deletions Code/Light.GuardClauses/Check.MustHaveLengthIn.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Light.GuardClauses.ExceptionFactory;
Expand Down Expand Up @@ -57,4 +58,51 @@ public static string MustHaveLengthIn(

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" />'s length is within the specified range, or otherwise throws an <see cref="ArgumentOutOfRangeException" />.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="range">The range where the <see cref="ImmutableArray{T}" />'s length must be in-between.</param>
/// <param name="parameterName">The name of the parameter (optional).</param>
/// <param name="message">The message that will be passed to the resulting exception (optional).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the length of <paramref name="parameter" /> is not within the specified <paramref name="range" />.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustHaveLengthIn<T>(
this ImmutableArray<T> parameter,
Range<int> range,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
)
{
if (!range.IsValueWithinRange(parameter.Length))
{
Throw.ImmutableArrayLengthNotInRange(parameter, range, parameterName, message);
}

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" />'s length is within the specified range, or otherwise throws your custom exception.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="range">The range where the <see cref="ImmutableArray{T}" />'s length must be in-between.</param>
/// <param name="exceptionFactory">The delegate that creates your custom exception. <paramref name="parameter" /> and <paramref name="range" /> are passed to this delegate.</param>
/// <exception cref="Exception">Your custom exception thrown when the length of <paramref name="parameter" /> is not within the specified range.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[ContractAnnotation("exceptionFactory:null => halt")]
public static ImmutableArray<T> MustHaveLengthIn<T>(
this ImmutableArray<T> parameter,
Range<int> range,
Func<ImmutableArray<T>, Range<int>, Exception> exceptionFactory
)
{
if (!range.IsValueWithinRange(parameter.Length))
{
Throw.CustomException(exceptionFactory, parameter, range);
}

return parameter;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;

namespace Light.GuardClauses.ExceptionFactory;

public static partial class Throw
{
/// <summary>
/// Throws the default <see cref="ArgumentOutOfRangeException" /> indicating that an <see cref="ImmutableArray{T}" />'s length is not within the
/// given range, using the optional parameter name and message.
/// </summary>
[ContractAnnotation("=> halt")]
[DoesNotReturn]
public static void ImmutableArrayLengthNotInRange<T>(
ImmutableArray<T> parameter,
Range<int> range,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
) =>
throw new ArgumentOutOfRangeException(
parameterName,
message ??
$"{parameterName ?? "The immutable array"} must have its length in between {range.CreateRangeDescriptionText("and")}, but it actually has length {parameter.Length}."
);
}
23 changes: 23 additions & 0 deletions Code/Plans/issue-118-must-have-length-in-for-immutable-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Issue 118 - MustHaveLengthIn for ImmutableArray

## Context

The .NET library Light.GuardClauses already has several assertions for collections. They often rely on `IEnumerable<T>` or `IEnumerable`. However, these assertions would result in `ImmutableArray<T>` being boxed - we want to avoid that by providing dedicated assertions for this type which avoids boxing. For this issue, we implement the `MustHaveLengthIn` assertion for `ImmutableArray<T>`.

## Tasks for this issue

- [ ] The production code should be placed in the Light.GuardClauses project. The file `Check.MustHaveLengthIn.cs` already exists in the root folder of the project - extend this existing file.
- [ ] In this file, create several extension method overloads called `MustHaveLengthIn` for `ImmutableArray<T>`. It should be placed in the class `Check` which is marked as `partial`.
- [ ] Each assertion in Light.GuardClauses has two overloads - the first one takes the optional `parameterName` and `message` arguments and throw the default exception. The actual exception is thrown in the `Throw` class - use the existing `Throw.ValueNotInRange` method which is located in `ExceptionFactory/Throw.Range.cs`.
- [ ] The other overload takes a delegate which allows the caller to provide their own custom exceptions. Use the existing `Throw.CustomException` method and pass the delegate, the erroneous `ImmutableArray<T>` instance and the range.
- [ ] The assertion takes a `Range<int>` parameter to specify the valid length range.
- [ ] Use the `Length` property of `ImmutableArray<T>` instead of `Count` for performance and correctness.
- [ ] Create unit tests for both overloads. The corresponding tests should be placed in Light.GuardClauses.Tests project. There is already a file 'StringAssertions/MustHaveLengthInTests.cs' but you need to create a new file 'CollectionAssertions/MustHaveLengthInTests.cs' for collection-related length tests. Please follow conventions of the existing tests (e.g. use FluentAssertions' `Should()` for assertions).

## Notes

- There are already plenty of other assertions and tests in this library. All overloads are placed in the same file in the production code project. The test projects has top-level folders for different groups of assertions, like `CollectionAssertions`, `StringAssertions`, `DateTimeAssertions` and so on. Please take a look at them to follow a similar structure and code style.
- This assertion specifically targets `ImmutableArray<T>` to avoid boxing that would occur with generic `IEnumerable<T>` extensions.
- Use the `Length` property instead of `Count` as this is the appropriate property for `ImmutableArray<T>`.
- The assertion should verify that the `ImmutableArray<T>` length falls within the specified `Range<int>`.
- If you have any questions or suggestions, please ask me about them.