Runtime: Add BitConverter Span-based APIs

Created on 18 Jul 2017  Â·  6Comments  Â·  Source: dotnet/runtime

Separated out of https://github.com/dotnet/corefx/issues/21281 for tracking purposes.

  • [x] Implement in System.Private.CoreLib in coreclr (it's "shared" with corert)
  • [x] Expose from System.Runtime.Extensions contract in corefx
  • [x] Add tests to System.Runtime.Extensions tests in corefx

```C#
namespace System
{
public static class BitConverter
{
// Matching overloads for GetBytes. Copy to the destination span
// rather than allocating a new byte[]. Return false if the destination
// span isn't large enough, which can be determined before any copying.
public static bool TryWriteBytes(Span destination, bool value);
public static bool TryWriteBytes(Span destination, char value);
public static bool TryWriteBytes(Span destination, double value);
public static bool TryWriteBytes(Span destination, short value);
public static bool TryWriteBytes(Span destination, int value);
public static bool TryWriteBytes(Span destination, long value);
public static bool TryWriteBytes(Span destination, float value);
public static bool TryWriteBytes(Span destination, ushort value);
public static bool TryWriteBytes(Span destination, uint value);
public static bool TryWriteBytes(Span destination, ulong value);

    // Matching overloads for To*.  As with existing To* methods, throw if not
    // enough data in the source span.
    public static bool ToBoolean(ReadOnlySpan<byte> value);
    public static char ToChar(ReadOnlySpan<byte> value);
    public static double ToDouble(ReadOnlySpan<byte> value);
    public static short ToInt16(ReadOnlySpan<byte> value);
    public static int ToInt32(ReadOnlySpan<byte> value);
    public static long ToInt64(ReadOnlySpan<byte> value);
    public static float ToSingle(ReadOnlySpan<byte> value);
    public static ushort ToUInt16(ReadOnlySpan<byte> value);
    public static uint ToUInt32(ReadOnlySpan<byte> value);
    public static ulong ToUInt64(ReadOnlySpan<byte> value);

    …
}

}
```

api-approved area-System.Runtime

Most helpful comment

Would it be possible to have ToString(ReadOnlySpan<byte>) overload as well? If we have an ArraySegment and we want string representation, it will still not be possible without allocating an extra byte[] :(

All 6 comments

@stephentoub Since both my PRs are merged, is it safe to close this issue? :)

Yup :)

What do you think about supporting different Endianness (e.g. ToInt32(buffer, Endianness.LittleEndian)?
It would be very useful when working with data coming off the network, as it's much less consistent than memory Endianness.

@i3arnon, dotnet/corefx#22405

@stephentoub :). And I'm even subscribed to that issue.

Would it be possible to have ToString(ReadOnlySpan<byte>) overload as well? If we have an ArraySegment and we want string representation, it will still not be possible without allocating an extra byte[] :(

Was this page helpful?
0 / 5 - 0 ratings