Skip to content

[API Proposal]: BinaryPrimitives.ReverseEndianness #75901

Closed
@stephentoub

Description

@stephentoub

Background and motivation

BinaryPrimitives today exposes a ReverseEndianness method for byte, ushort, uint, ulong, sbyte, short, int, and long, and #72107 proposes adding overloads for nuint, UInt128, nint, and Int128 as well. However, we lack versions of this API for processing multiple elements at a time. A developer can write this in their own loop, e.g.

but it'd be nice if a) they didn't have to, and b) it could be vectorized (for at least some data types).

API Proposal

namespace System.Buffers.Binary;

public static class BinaryPrimitives
{
+    public static void ReverseEndianness(ReadOnlySpan<ushort> source, Span<ushort> destination);
+    public static void ReverseEndianness(ReadOnlySpan<short> source, Span<short> destination);
+    public static void ReverseEndianness(ReadOnlySpan<uint> source, Span<uint> destination);
+    public static void ReverseEndianness(ReadOnlySpan<int> source, Span<int> destination);
+    public static void ReverseEndianness(ReadOnlySpan<ulong> source, Span<ulong> destination);
+    public static void ReverseEndianness(ReadOnlySpan<long> source, Span<long> destination);
+    public static void ReverseEndianness(ReadOnlySpan<nuint> source, Span<nuint> destination);
+    public static void ReverseEndianness(ReadOnlySpan<nint> source, Span<nint> destination);
+    public static void ReverseEndianness(ReadOnlySpan<UInt128> source, Span<UInt128> destination);
+    public static void ReverseEndianness(ReadOnlySpan<Int128> source, Span<Int128> destination);
}

source and destination may be the same.

I did not include overloads for byte/sbyte as they're useless (the current byte/sbyte overloads are useless, too).

API Usage

Span<uint> values = ...;
BinaryPrimitives.ReverseEndianness(values);

Alternative Designs

  • Instead of taking a source and a destination span, each overload could instead just take a Span<T> that's reversed in-place, and if you need the results in a different location, you first copy and then reverse in-place in the destination.

Risks

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions