Skip to content

[API Proposal]: Vector.Contains(scalar), .IndexOf(scalar) and LastIndexOf(scalar) #83010

@neon-sunset

Description

@neon-sunset

Background and motivation

Today, ReadOnly/Span<T> extensions offer a rich set of APIs suitable both for high level and low level processing - Contains, IndexOf, IndexOfAny, LastIndexOf, and etc. Using those, developers can be sure to get both good performance and usability.

However, if for some reason the desired behavior is not covered by the above (e.g. counting special characters in chunks with extra handling once found), it is necessary to write quite involved implementation by hand with VectorXXX APIs. Such implementation may either have to be a full vectorized loop or a workaround employing slicing and re-slicing spans to use existing span extensions which has its own drawbacks and overhead.

In general, cross-platform VectorXXX extensions in .NET 7 and Span<T> methods significantly reduce the effort required for fast processing of spans, but it seems there are still areas where additional QoL improvements can be offered.

Proposal specifically targets Vector<T> as a higher-level abstraction. There might be sense to add parity with VectorXXX despite most of its users not much benefiting since these can be written in a couple of lines - feedback on this is welcomed.

API Proposal

namespace System.Numerics;

public static partial class VectorExtensions
{
    public bool Contains<T>(this Vector<T> vector, T value);

    public int IndexOf<T>(this Vector<T> vector, T value);
    
    public int LastIndexOf<T>(this Vector<T> vector, T value);
}

API Usage

var span = GetSpanOf<int>();
var remainderLength = span.Length % Vector<int>.Count;
var vectorized = MemoryMarshal.Cast<int, Vector<int>>(span[..^remainderLength]);
var remainder = span[^remainderLength..];

foreach (var vector in vectorized)
{
    var index = vector.IndexOf(valueOfInterest);
    if (index >= 0)
    {
        // Do something with index
    }
    else if (vector.Contains(controlValue))
    {
        // Signal control value found
    }
}

foreach (var element in remainder)
{
    // Handle remainder
}

Alternative Designs

N/A, providing implementation in user code or via third-party packages is possible.

Risks

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Memory

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions