The BinaryReader read data to a Span<byte> always failed.

I try to read byte array using stackalloc to reduce gc for better performance. And in 2021.2 there has complete support for Span. But when I test with BinaryReader, and find some problem. My test code is below:

using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine.Assertions;

public static class BinaryReaderSpan
{
    [MenuItem("Test/Test BinaryReader to Span")]
    private static void Test1()
    {
        using var stream = new MemoryStream();

        using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
        {
            Span<byte> bytes = stackalloc byte[16];
            for (int i = 0; i < 16; ++i)
            {
                bytes[i] = (byte)i;
            }

            writer.Write(bytes);
        }

        stream.Position = 0;
        using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
        {
            Span<byte> bytes = stackalloc byte[16];
            reader.Read(bytes);
            for (int i = 0; i < 16; ++i)
            {
                Assert.AreEqual(bytes[i], (byte)i);
            }
        }
    }

    [MenuItem("Test/Test BinaryReader to byte[]")]
    private static void Test2()
    {
        using var stream = new MemoryStream();

        using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
        {
            Span<byte> bytes = stackalloc byte[16];
            for (int i = 0; i < 16; ++i)
            {
                bytes[i] = (byte)i;
            }

            writer.Write(bytes);
        }

        stream.Position = 0;
        using (var reader = new BinaryReader(stream, Encoding.UTF8, true))
        {
            var bytes = new byte[16];
            reader.Read(bytes, 0, 16);
            for (int i = 0; i < 16; ++i)
            {
                Assert.AreEqual(bytes[i], (byte)i);
            }
        }
    }
}

I add two menu items: ‘Test/Test BinaryReader to Span’ and ‘Test/Test BinaryReader to byte[ ]’.
‘Read to byte[ ]’ always work perfect. But ‘Read to Span’ the result always zero.

I submit a bug report for this: Case 1377375. And attach the test project.
Is it something wrong with my code? Or it is a bug for unity?

7619074–947212–ReadToSpan.zip (19.8 KB)

1 Like

Hi, I have the same issue.

https://issuetracker.unity3d.com/issues/the-binaryreader-read-data-to-a-span-is-always-zero
Now it fixed in 2022.2, which is still in alpha… I am waiting the planned fix for lower version.

2 Likes

thank you watson (?), I will wait with you (I’m using 2021.2.14)
have a nice day.