44using System . Buffers ;
55using System . Collections ;
66using System . Runtime . CompilerServices ;
7+ using System . Runtime . InteropServices ;
78using SixLabors . ImageSharp . Memory ;
89
910namespace SixLabors . ImageSharp . IO ;
@@ -13,11 +14,10 @@ namespace SixLabors.ImageSharp.IO;
1314/// Chunks are allocated by the <see cref="MemoryAllocator"/> assigned via the constructor
1415/// and is designed to take advantage of buffer pooling when available.
1516/// </summary>
16- /// <summary>Provides an in-memory stream composed of non-contiguous chunks.</summary>
1717public class ChunkedMemoryStream : Stream
1818{
1919 private readonly MemoryChunkBuffer memoryChunkBuffer ;
20- private readonly byte [ ] singleReadBuffer = new byte [ 1 ] ;
20+ private readonly byte [ ] singleByteBuffer = new byte [ 1 ] ;
2121
2222 private long length ;
2323 private long position ;
@@ -101,8 +101,8 @@ public override int ReadByte()
101101 return - 1 ;
102102 }
103103
104- _ = this . Read ( this . singleReadBuffer , 0 , 1 ) ;
105- return this . singleReadBuffer [ ^ 1 ] ;
104+ _ = this . Read ( this . singleByteBuffer , 0 , 1 ) ;
105+ return MemoryMarshal . GetReference < byte > ( this . singleByteBuffer ) ;
106106 }
107107
108108 /// <inheritdoc/>
@@ -129,17 +129,17 @@ public override int Read(Span<byte> buffer)
129129 int count = buffer . Length ;
130130
131131 long remaining = this . length - this . position ;
132- if ( remaining > count )
133- {
134- remaining = count ;
135- }
136-
137132 if ( remaining <= 0 )
138133 {
139134 // Already at the end of the stream, nothing to read
140135 return 0 ;
141136 }
142137
138+ if ( remaining > count )
139+ {
140+ remaining = count ;
141+ }
142+
143143 int bytesToRead = ( int ) remaining ;
144144 int bytesRead = 0 ;
145145 while ( bytesToRead != 0 && this . currentChunk != this . memoryChunkBuffer . Length )
@@ -175,6 +175,14 @@ public override int Read(Span<byte> buffer)
175175 return bytesRead ;
176176 }
177177
178+ /// <inheritdoc/>
179+ public override void WriteByte ( byte value )
180+ {
181+ this . EnsureNotDisposed ( ) ;
182+ MemoryMarshal . Write ( this . singleByteBuffer , ref value ) ;
183+ this . Write ( this . singleByteBuffer , 0 , 1 ) ;
184+ }
185+
178186 /// <inheritdoc/>
179187 public override void Write ( byte [ ] buffer , int offset , int count )
180188 {
@@ -309,7 +317,7 @@ public byte[] ToArray()
309317 byte [ ] copy = new byte [ this . length ] ;
310318
311319 this . Position = 0 ;
312- this . Read ( copy , 0 , copy . Length ) ;
320+ _ = this . Read ( copy , 0 , copy . Length ) ;
313321 this . Position = position ;
314322 return copy ;
315323 }
0 commit comments