Skip to content

Commit

Permalink
Add WriteByte and optimize ReadByte
Browse files Browse the repository at this point in the history
  • Loading branch information
JimBobSquarePants committed Oct 29, 2024
1 parent 03343c4 commit b74d2e4
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions src/ImageSharp/IO/ChunkedMemoryStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Buffers;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Memory;

namespace SixLabors.ImageSharp.IO;
Expand All @@ -13,11 +14,10 @@ namespace SixLabors.ImageSharp.IO;
/// Chunks are allocated by the <see cref="MemoryAllocator"/> assigned via the constructor
/// and is designed to take advantage of buffer pooling when available.
/// </summary>
/// <summary>Provides an in-memory stream composed of non-contiguous chunks.</summary>
public class ChunkedMemoryStream : Stream
{
private readonly MemoryChunkBuffer memoryChunkBuffer;
private readonly byte[] singleReadBuffer = new byte[1];
private readonly byte[] singleByteBuffer = new byte[1];

private long length;
private long position;
Expand Down Expand Up @@ -101,8 +101,8 @@ public override int ReadByte()
return -1;
}

_ = this.Read(this.singleReadBuffer, 0, 1);
return this.singleReadBuffer[^1];
_ = this.Read(this.singleByteBuffer, 0, 1);
return MemoryMarshal.GetReference<byte>(this.singleByteBuffer);
}

/// <inheritdoc/>
Expand All @@ -129,17 +129,17 @@ public override int Read(Span<byte> buffer)
int count = buffer.Length;

long remaining = this.length - this.position;
if (remaining > count)
{
remaining = count;
}

if (remaining <= 0)
{
// Already at the end of the stream, nothing to read
return 0;
}

if (remaining > count)
{
remaining = count;
}

int bytesToRead = (int)remaining;
int bytesRead = 0;
while (bytesToRead != 0 && this.currentChunk != this.memoryChunkBuffer.Length)
Expand Down Expand Up @@ -175,6 +175,14 @@ public override int Read(Span<byte> buffer)
return bytesRead;
}

/// <inheritdoc/>
public override void WriteByte(byte value)
{
this.EnsureNotDisposed();
MemoryMarshal.Write(this.singleByteBuffer, ref value);
this.Write(this.singleByteBuffer, 0, 1);
}

/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
Expand Down Expand Up @@ -309,7 +317,7 @@ public byte[] ToArray()
byte[] copy = new byte[this.length];

this.Position = 0;
this.Read(copy, 0, copy.Length);
_ = this.Read(copy, 0, copy.Length);
this.Position = position;
return copy;
}
Expand Down

0 comments on commit b74d2e4

Please sign in to comment.