Skip to content

BinaryData.Empty.ToString throws ArgumentNullException #68262

Closed
@amis92

Description

@amis92

Description

Using package System.Memory.Data v6+, System.BinaryData.ToString() called on an instance with zero-length data (BinaryData.FromStream(Stream.Null), BinaryData.FromString(string.Empty), BinaryData.FromBytes(Array.Empty<byte>()) etc.) throws System.ArgumentNullException.

Reproduction Steps

BinaryData.Empty.ToString()

Expected behavior

Method should return empty string, as it did/does in package v1 (1.0.0, 1.0.1, 1.0.2).
The expression BinaryData.FromString(data).ToString() == data where data is any valid non-null string instance should be true.

Actual behavior

ArgumentNullException is thrown:

System.ArgumentNullException: System.ArgumentNullException: Array cannot be null. (Parameter 'bytes')
  + System.Text.Encoding.GetString(System.Byte*, int)
  + System.BinaryData.ToString()

Regression?

The method does not throw and returns an empty string using System.Memory.Data v1.

Known Workarounds

No response

Configuration

No response

Other information

The original implementation was:

        public override string ToString()
        {
            if (MemoryMarshal.TryGetArray(_bytes, out ArraySegment<byte> segment))
                return Encoding.UTF8.GetString(segment.Array, segment.Offset, segment.Count);
            return Encoding.UTF8.GetString(_bytes.ToArray());
        }

Now it uses byte* which seems to be the problem (empty Span casts as a null ref):

public override unsafe string ToString()
{
ReadOnlySpan<byte> span = _bytes.Span;
fixed (byte* ptr = span)
{
return Encoding.UTF8.GetString(ptr, span.Length);
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Memorybuggood first issueIssue should be easy to implement, good for first-time contributorshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions