C
C#3y ago
androidui

BinaryReader and BinaryWriter api behaviour incompatibility

BinaryReader read(span<byte>) does not call read(byte[], int, int) but BinaryWriter write(span<byte>) DOES call write(byte[], int, int) is this expected behaviour?
2 Replies
Klarth
Klarth3y ago
https://github.com/dotnet/runtime/blob/215b39abf947da7a40b0cb137eab4bceb24ad3e3/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs#L386 https://github.com/dotnet/runtime/blob/38ca26b27b9e7a867e6ff69eec3cabbfb4e9e1cf/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs#L336 Write seems to write directly to the underlying stream...unless you've derived from it? In that case, it copies to a rented array and uses the array-writing overload. It seems a bit odd of an implementation to me, but maybe it's there for some backwards compatibility reasons.
androidui
androiduiOP3y ago
hmm alright im using a MemoryStream for both output and input
class MemoryWriter : TypeCheckingBinaryWriter
{
public long Position { get => BaseStream.Position; set => BaseStream.Position = value; }
public long Length => BaseStream.Length;

public MemoryWriter(Stream output) : base(output)
{
}

public MemoryWriter(Stream output, bool leaveOpen) : base(output, Encoding.UTF8, leaveOpen)
{
}

public MemoryWriter() : this(new MemoryStream(), false)
{
}
class MemoryWriter : TypeCheckingBinaryWriter
{
public long Position { get => BaseStream.Position; set => BaseStream.Position = value; }
public long Length => BaseStream.Length;

public MemoryWriter(Stream output) : base(output)
{
}

public MemoryWriter(Stream output, bool leaveOpen) : base(output, Encoding.UTF8, leaveOpen)
{
}

public MemoryWriter() : this(new MemoryStream(), false)
{
}
MemoryWriter memory = new();

var old = memory.BaseStream.Position;
memory.BaseStream.Position = 0;

// keep open
MemoryReader reader = new(memory.BaseStream, true);

while (reader.BaseStream.Position != reader.BaseStream.Length)
{
// ...
}
reader.Dispose();
memory.BaseStream.Position = old;
MemoryWriter memory = new();

var old = memory.BaseStream.Position;
memory.BaseStream.Position = 0;

// keep open
MemoryReader reader = new(memory.BaseStream, true);

while (reader.BaseStream.Position != reader.BaseStream.Length)
{
// ...
}
reader.Dispose();
memory.BaseStream.Position = old;
Want results from more Discord servers?
Add your server