Skip to content

[API Proposal]: Unsafe.IsAddressLessThanOrEqualTo / IsAddressGreaterThanOrEqualTo #88478

@stephentoub

Description

@stephentoub

Background and motivation

When using Unsafe to write ref-based loops, it's common to want to iterate while one address is <= another. But there's no Unsafe.IsAddressLessThanOrEqualTo, so instead of being able to write:

do
{
    ...
}
while (Unsafe.IsAddressLessThanOrEqualTo(ref pos, ref oneVectorFromEnd));

you end up needing to do the mental gymnastics to come up with:

do
{
    ...
}
while (!Unsafe.IsAddressLessThan(ref oneVectorFromEnd, ref pos));

API Proposal

namespace System.Runtime.CompilerServices;

public static class Unsafe
{
    // Existing
    public static bool IsAddressGreaterThan<T>([AllowNull] ref T left, [AllowNull] ref T right);
    public static bool IsAddressLessThan<T>([AllowNull] ref T left, [AllowNull] ref T right);

    // New
+   public static bool IsAddressGreaterThanOrEqualTo<T>([AllowNull] ref T left, [AllowNull] ref T right);
+   public static bool IsAddressLessThanOrEqualTo<T>([AllowNull] ref T left, [AllowNull] ref T right);
}

API Usage

ref int oneVectorFromEnd = ref Unsafe.Subtract(ref end, Vector<int>.Count);
do
{
    current.StoreUnsafe(ref pos);
    current += increment;
    pos = ref Unsafe.Add(ref pos, Vector<int>.Count);
}
while (Unsafe.IsAddressLessThanOrEqualTo(ref pos, ref oneVectorFromEnd));

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Runtime.CompilerServicesin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions