Last active
June 29, 2022 15:20
-
-
Save bgrainger/fb2c18659c2cdfce494c82a8c4803360 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Licensed to the .NET Foundation under one or more agreements. | |
// The .NET Foundation licenses this file to you under the MIT license. | |
// See the LICENSE file in the project root for more information. | |
namespace System.Runtime.CompilerServices | |
{ | |
internal static class RuntimeHelpers | |
{ | |
/// <summary> | |
/// Slices the specified array using the specified range. | |
/// </summary> | |
public static T[] GetSubArray<T>(T[] array, Range range) | |
{ | |
if (array == null) | |
{ | |
throw new ArgumentNullException(); | |
} | |
(int offset, int length) = range.GetOffsetAndLength(array.Length); | |
if (default(T)! != null || typeof(T[]) == array.GetType()) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) | |
{ | |
// We know the type of the array to be exactly T[]. | |
if (length == 0) | |
{ | |
return Array.Empty<T>(); | |
} | |
var dest = new T[length]; | |
Array.Copy(array, offset, dest, 0, length); | |
return dest; | |
} | |
else | |
{ | |
// The array is actually a U[] where U:T. | |
T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType()!, length); | |
Array.Copy(array, offset, dest, 0, length); | |
return dest; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment