Skip to content

Commit d9e697a

Browse files
committed
Add ImmutableArrayExtensions class
- Implement AsView methods to create ArrayView<T> over immutable arrays.
1 parent 28dbfe4 commit d9e697a

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using System.Collections.Immutable;
2+
using System.Runtime.InteropServices;
3+
4+
namespace Ramstack.Collections;
5+
6+
/// <summary>
7+
/// Provides extension methods for the <see cref="ImmutableArray{T}"/> structure.
8+
/// </summary>
9+
public static class ImmutableArrayExtensions
10+
{
11+
/// <summary>
12+
/// Creates an <see cref="ArrayView{T}"/> over an immutable array.
13+
/// </summary>
14+
/// <param name="value">The immutable array to wrap.</param>
15+
/// <returns>
16+
/// The read-only view of the array.
17+
/// </returns>
18+
public static ArrayView<T> AsView<T>(this ImmutableArray<T> value) =>
19+
ImmutableCollectionsMarshal.AsArray(value).AsView();
20+
21+
/// <summary>
22+
/// Creates an <see cref="ArrayView{T}"/> over an immutable array starting at a specified position to the end of the array.
23+
/// </summary>
24+
/// <param name="value">The immutable array to wrap.</param>
25+
/// <param name="index">The index at which to begin the array view.</param>
26+
/// <returns>
27+
/// The read-only view of the array.
28+
/// </returns>
29+
public static ArrayView<T> AsView<T>(this ImmutableArray<T> value, int index) =>
30+
ImmutableCollectionsMarshal.AsArray(value).AsView(index);
31+
32+
/// <summary>
33+
/// Creates an <see cref="ArrayView{T}"/> over an immutable array starting at a specified position for a specified length.
34+
/// </summary>
35+
/// <param name="value">The immutable array to wrap.</param>
36+
/// <param name="index">The index at which to begin the array view.</param>
37+
/// <param name="count">The number of items in the array view.</param>
38+
/// <returns>
39+
/// The read-only view of the array.
40+
/// </returns>
41+
public static ArrayView<T> AsView<T>(this ImmutableArray<T> value, int index, int count) =>
42+
ImmutableCollectionsMarshal.AsArray(value).AsView(index, count);
43+
}

0 commit comments

Comments
 (0)