Edytuj

Udostępnij za pośrednictwem


ReadOnlySpanExtensions.DangerousGetLookupReferenceAt<T> Method

Definition

Returns a reference to the first element within a given ReadOnlySpan<T>, clamping the input index in the valid range. If the i parameter exceeds the length of span, it will be clamped to 0. Therefore, the returned reference will always point to a valid element within span, assuming it is not empty. This method is specifically meant to efficiently index lookup tables, especially if they point to constant data. Consider this example where a lookup table is used to validate whether a given character is within a specific set:

public static ReadOnlySpan<bool> ValidSetLookupTable => new bool[]
{
    false, true, true, true, true, true, false, true,
    false, false, true, false, true, false, true, false,
    true, false, false, true, false, false, false, false,
    false, false, false, false, true, true, false, true
};

int ch = Console.Read();
bool isValid = ValidSetLookupTable.DangerousGetLookupReference(ch);

Even if the input index is outside the range of the lookup table, being clamped to 0, it will just cause the value 0 to be returned in this case, which is functionally the same for the check being performed. This extension can easily be used whenever the first position in a lookup table being referenced corresponds to a falsey value, like in this case. Additionally, the example above leverages a compiler optimization introduced with C# 7.3, which allows ReadOnlySpan<T> instances pointing to compile-time constant data to be directly mapped to the static .text section in the final assembly: the array being created in code will never actually be allocated, and the ReadOnlySpan<T> will just point to constant data. Note that this only works for blittable values that are not dependent on the byte endianness of the system, like Byte or Boolean. For more info, see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static/.

public static ref readonly T DangerousGetLookupReferenceAt<T> (this ReadOnlySpan<T> span, int i);
static member DangerousGetLookupReferenceAt : ReadOnlySpan<'T> * int -> 'T
<Extension()>
Public Function DangerousGetLookupReferenceAt(Of T) (span As ReadOnlySpan(Of T), i As Integer) As T

Type Parameters

T

The type of elements in the input ReadOnlySpan<T> instance.

Parameters

span
ReadOnlySpan<T>

The input ReadOnlySpan<T> instance.

i
Int32

The index of the element to retrieve within span.

Returns

T

A reference to the element within span at the index specified by i, or a reference to the first element within span if i was not a valid index.

Applies to