From 231b771ce93955da9425dba99f23299a6bd7c375 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Mon, 12 Oct 2026 20:01:04 +1100 Subject: [PATCH] Avoid per-read char[] allocation in StringStream on older targets --- src/Polyfill/StringStream.cs | 88 ++++++++--- src/Split/net10.0/StringStream.cs | 24 +-- src/Split/net461/StringStream.cs | 67 ++++++-- src/Split/net462/StringStream.cs | 67 ++++++-- src/Split/net47/StringStream.cs | 67 ++++++-- src/Split/net471/StringStream.cs | 67 ++++++-- src/Split/net472/StringStream.cs | 67 ++++++-- src/Split/net48/StringStream.cs | 67 ++++++-- src/Split/net481/StringStream.cs | 67 ++++++-- src/Split/net5.0/StringStream.cs | 24 +-- src/Split/net6.0/StringStream.cs | 24 +-- src/Split/net7.0/StringStream.cs | 24 +-- src/Split/net8.0/StringStream.cs | 24 +-- src/Split/net9.0/StringStream.cs | 24 +-- src/Split/netcoreapp2.0/StringStream.cs | 67 ++++++-- src/Split/netcoreapp2.1/StringStream.cs | 24 +-- src/Split/netcoreapp2.2/StringStream.cs | 24 +-- src/Split/netcoreapp3.0/StringStream.cs | 24 +-- src/Split/netcoreapp3.1/StringStream.cs | 24 +-- src/Split/netstandard2.0/StringStream.cs | 67 ++++++-- src/Split/netstandard2.1/StringStream.cs | 24 +-- src/Split/uap10.0/StringStream.cs | 67 ++++++-- src/Tests/PolyfillTests_StringStream.cs | 192 +++++++++++++++++++++++ 23 files changed, 922 insertions(+), 292 deletions(-) diff --git a/src/Polyfill/StringStream.cs b/src/Polyfill/StringStream.cs index 3e0920df..a7c2f497 100644 --- a/src/Polyfill/StringStream.cs +++ b/src/Polyfill/StringStream.cs @@ -8,8 +8,10 @@ namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -152,7 +154,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -177,7 +179,7 @@ int ReadCore(byte[] buffer, int offset, int count) if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; // If the caller's buffer may be too small for even one encoded scalar, encode into the @@ -186,8 +188,8 @@ int ReadCore(byte[] buffer, int offset, int count) if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); @@ -201,7 +203,7 @@ int ReadCore(byte[] buffer, int offset, int count) { // Encode directly into the caller's buffer. Only flush on the final block so encoder // state is preserved for stateful encodings. - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -215,7 +217,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) @@ -242,31 +244,77 @@ int ReadCore(byte[] buffer, int offset, int count) Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); // Stateless single-shot encode of the whole text into the caller's buffer at byteIndex. - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); #else - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + // The span based Encoding.GetBytes does not exist here, so reach the backing string or array + // rather than copying the text. + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } #endif } - // Stateful incremental encode of chars into bytes[byteIndex..byteIndex+byteCount]. - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + // Stateful incremental encode of text[charIndex..charIndex+charCount] into bytes[byteIndex..byteIndex+byteCount]. + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); #else // The array based Encoder.Convert overload (available on every TFM) requires a char[]. Cap the // slice at byteCount chars: a complete char never encodes to fewer than one byte, so the - // encoder can never consume more chars than there are output bytes, and bounding the copy this - // way keeps a streamed read linear rather than quadratic. - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + // encoder can never consume more chars than there are output bytes, and bounding the slice + // this way keeps a streamed read linear rather than quadratic. + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + + // Array backed text is handed to the encoder as is. + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + + // Otherwise (a string or a MemoryManager) copy the slice into a pooled buffer, so that a + // read does not allocate a char[] of its own. + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } #endif } diff --git a/src/Split/net10.0/StringStream.cs b/src/Split/net10.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net10.0/StringStream.cs +++ b/src/Split/net10.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net461/StringStream.cs b/src/Split/net461/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net461/StringStream.cs +++ b/src/Split/net461/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net462/StringStream.cs b/src/Split/net462/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net462/StringStream.cs +++ b/src/Split/net462/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net47/StringStream.cs b/src/Split/net47/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net47/StringStream.cs +++ b/src/Split/net47/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net471/StringStream.cs b/src/Split/net471/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net471/StringStream.cs +++ b/src/Split/net471/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net472/StringStream.cs b/src/Split/net472/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net472/StringStream.cs +++ b/src/Split/net472/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net48/StringStream.cs b/src/Split/net48/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net48/StringStream.cs +++ b/src/Split/net48/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net481/StringStream.cs b/src/Split/net481/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/net481/StringStream.cs +++ b/src/Split/net481/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net5.0/StringStream.cs b/src/Split/net5.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net5.0/StringStream.cs +++ b/src/Split/net5.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net6.0/StringStream.cs b/src/Split/net6.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net6.0/StringStream.cs +++ b/src/Split/net6.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net7.0/StringStream.cs b/src/Split/net7.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net7.0/StringStream.cs +++ b/src/Split/net7.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net8.0/StringStream.cs b/src/Split/net8.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net8.0/StringStream.cs +++ b/src/Split/net8.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/net9.0/StringStream.cs b/src/Split/net9.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/net9.0/StringStream.cs +++ b/src/Split/net9.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netcoreapp2.0/StringStream.cs b/src/Split/netcoreapp2.0/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/netcoreapp2.0/StringStream.cs +++ b/src/Split/netcoreapp2.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netcoreapp2.1/StringStream.cs b/src/Split/netcoreapp2.1/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/netcoreapp2.1/StringStream.cs +++ b/src/Split/netcoreapp2.1/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netcoreapp2.2/StringStream.cs b/src/Split/netcoreapp2.2/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/netcoreapp2.2/StringStream.cs +++ b/src/Split/netcoreapp2.2/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netcoreapp3.0/StringStream.cs b/src/Split/netcoreapp3.0/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/netcoreapp3.0/StringStream.cs +++ b/src/Split/netcoreapp3.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netcoreapp3.1/StringStream.cs b/src/Split/netcoreapp3.1/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/netcoreapp3.1/StringStream.cs +++ b/src/Split/netcoreapp3.1/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netstandard2.0/StringStream.cs b/src/Split/netstandard2.0/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/netstandard2.0/StringStream.cs +++ b/src/Split/netstandard2.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/netstandard2.1/StringStream.cs b/src/Split/netstandard2.1/StringStream.cs index 272f4c1e..95cb083c 100644 --- a/src/Split/netstandard2.1/StringStream.cs +++ b/src/Split/netstandard2.1/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,15 +184,13 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - return encoding.GetBytes(chars, bytes.AsSpan(byteIndex, byteCount)); + return encoding.GetBytes(text.Span, bytes.AsSpan(byteIndex, byteCount)); } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - GetEncoder().Convert(chars, bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); + GetEncoder().Convert(text.Span.Slice(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), flush, out charsUsed, out bytesUsed, out _); } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Split/uap10.0/StringStream.cs b/src/Split/uap10.0/StringStream.cs index 6742772d..263b0be1 100644 --- a/src/Split/uap10.0/StringStream.cs +++ b/src/Split/uap10.0/StringStream.cs @@ -4,8 +4,10 @@ #if FeatureMemory #pragma warning disable namespace System.IO; +using System.Buffers; using System.Text; using System.Diagnostics; +using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -115,7 +117,7 @@ int ReadCore(byte[] buffer, int offset, int count) text.Length <= (int.MaxValue / maxBytesPerChar) - 1 && count >= encoding.GetMaxByteCount(text.Length)) { - var written = EncodeAll(text.Span, buffer, offset, count); + var written = EncodeAll(buffer, offset, count); charPosition = text.Length; encoderFlushed = true; return written; @@ -135,13 +137,13 @@ int ReadCore(byte[] buffer, int offset, int count) } if (charPosition < text.Length) { - var remaining = text.Span.Slice(charPosition); + var remainingChars = text.Length - charPosition; var availableBytes = count - totalBytesWritten; if (availableBytes < maxBytesPerChar) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - var charsToEncode = Math.Min(2, remaining.Length); - Convert(remaining.Slice(0, charsToEncode), pendingBytes, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); + var charsToEncode = Math.Min(2, remainingChars); + Convert(charPosition, charsToEncode, pendingBytes, 0, pendingBytes.Length, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; var toCopy = Math.Min(bytesUsed, availableBytes); Array.Copy(pendingBytes, 0, buffer, offset + totalBytesWritten, toCopy); @@ -151,7 +153,7 @@ int ReadCore(byte[] buffer, int offset, int count) } else { - Convert(remaining, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); + Convert(charPosition, remainingChars, buffer, offset + totalBytesWritten, availableBytes, flush: false, out var charsUsed, out var bytesUsed); charPosition += charsUsed; totalBytesWritten += bytesUsed; } @@ -161,7 +163,7 @@ int ReadCore(byte[] buffer, int offset, int count) pendingCount == 0) { pendingBytes ??= new byte[encoding.GetMaxByteCount(2)]; - Convert(ReadOnlySpan.Empty, pendingBytes, pendingBytes.Length, flush: true, out _, out var flushBytes); + Convert(text.Length, 0, pendingBytes, 0, pendingBytes.Length, flush: true, out _, out var flushBytes); encoderFlushed = true; if (flushBytes > 0) { @@ -182,17 +184,54 @@ int ReadCore(byte[] buffer, int offset, int count) return totalBytesWritten; } Encoder GetEncoder() => encoder ??= encoding.GetEncoder(); - int EncodeAll(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount) + int EncodeAll(byte[] bytes, int byteIndex, int byteCount) { - var charArray = chars.ToArray(); - return encoding.GetBytes(charArray, 0, charArray.Length, bytes, byteIndex); + if (MemoryMarshal.TryGetString(text, out var value, out var start, out var length)) + { + return encoding.GetBytes(value, start, length, bytes, byteIndex); + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + if (segment.Count == 0) + { + return encoding.GetBytes(Array.Empty(), 0, 0, bytes, byteIndex); + } + return encoding.GetBytes(segment.Array!, segment.Offset, segment.Count, bytes, byteIndex); + } + var rented = ArrayPool.Shared.Rent(text.Length); + try + { + text.Span.CopyTo(rented); + return encoding.GetBytes(rented, 0, text.Length, bytes, byteIndex); + } + finally + { + ArrayPool.Shared.Return(rented); + } } - void Convert(ReadOnlySpan chars, byte[] bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed) => - Convert(chars, bytes, 0, byteCount, flush, out charsUsed, out bytesUsed); - void Convert(ReadOnlySpan chars, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) + void Convert(int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed) { - var charArray = chars.Slice(0, Math.Min(chars.Length, byteCount)).ToArray(); - GetEncoder().Convert(charArray, 0, charArray.Length, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + charCount = Math.Min(charCount, byteCount); + if (charCount == 0) + { + GetEncoder().Convert(Array.Empty(), 0, 0, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + if (MemoryMarshal.TryGetArray(text, out var segment)) + { + GetEncoder().Convert(segment.Array!, segment.Offset + charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + return; + } + var rented = ArrayPool.Shared.Rent(charCount); + try + { + text.Span.Slice(charIndex, charCount).CopyTo(rented); + GetEncoder().Convert(rented, 0, charCount, bytes, byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out _); + } + finally + { + ArrayPool.Shared.Return(rented); + } } /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) diff --git a/src/Tests/PolyfillTests_StringStream.cs b/src/Tests/PolyfillTests_StringStream.cs index 80d4b390..a5312c12 100644 --- a/src/Tests/PolyfillTests_StringStream.cs +++ b/src/Tests/PolyfillTests_StringStream.cs @@ -1,5 +1,6 @@ #if FeatureMemory using System.IO; +using System.Linq; using System.Text; partial class PolyfillTests @@ -342,6 +343,197 @@ await Assert.That(async () => await stream.CopyToAsync(destination, 81920, cance .Throws(); } + // Text mixing one, two and three byte UTF-8 sequences with surrogate pairs, so that every read + // size below splits a multi-byte sequence or a surrogate pair somewhere. + const string stringStreamMixedText = "a\u00e9\u4f60\U0001F30D-\U0001F600\u00fc\u597d z\U00010348\u20ac!"; + + static IEnumerable StringStreamEncodings() + { + yield return new UTF8Encoding(false); + yield return new UnicodeEncoding(false, false); + yield return new UnicodeEncoding(true, false); + yield return new UTF32Encoding(false, false); + yield return Encoding.ASCII; + } + + static readonly int[] stringStreamReadSizes = [1, 2, 3, 4, 5, 7, 16, 61, 4096]; + + static string RepeatStringStreamText() + { + var builder = new StringBuilder(); + for (var index = 0; index < 40; index++) + { + builder.Append(stringStreamMixedText); + } + + return builder.ToString(); + } + + static string? CompareStringStreamReads(Func create, string text) + { + foreach (var encoding in StringStreamEncodings()) + { + var expected = encoding.GetBytes(text); + foreach (var size in stringStreamReadSizes) + { + using var stream = create(encoding); + using var accumulator = new MemoryStream(); + // Read into the middle of a larger buffer so that the offset is honoured too + var buffer = new byte[size + 6]; + int read; + while ((read = stream.Read(buffer, 3, size)) > 0) + { + accumulator.Write(buffer, 3, read); + } + + if (!accumulator.ToArray().SequenceEqual(expected)) + { + return $"{encoding.WebName} with read size {size}"; + } + + if (buffer[0] != 0 || buffer[2] != 0 || buffer[size + 3] != 0 || buffer[size + 5] != 0) + { + return $"{encoding.WebName} with read size {size} wrote outside the requested range"; + } + } + } + + return null; + } + + [Test] + public async Task StringStream_StringBacked_AllReadSizes_MatchGetBytes() + { + var text = RepeatStringStreamText(); + + var failure = CompareStringStreamReads(encoding => new StringStream(text, encoding), text); + + await Assert.That(failure).IsNull(); + } + + [Test] + public async Task StringStream_StringSliceBacked_AllReadSizes_MatchGetBytes() + { + var text = RepeatStringStreamText(); + var padded = "\u4f60xx" + text + "yy\U0001F30D"; + + var failure = CompareStringStreamReads(encoding => new StringStream(padded.AsMemory(3, text.Length), encoding), text); + + await Assert.That(failure).IsNull(); + } + + [Test] + public async Task StringStream_ArrayBacked_AllReadSizes_MatchGetBytes() + { + var text = RepeatStringStreamText(); + var chars = ("\u4f60xx" + text + "yy\U0001F30D").ToCharArray(); + var snapshot = (char[]) chars.Clone(); + + var failure = CompareStringStreamReads(encoding => new StringStream(new ReadOnlyMemory(chars, 3, text.Length), encoding), text); + + await Assert.That(failure).IsNull(); + // The backing array is read in place and must be left untouched + await Assert.That(chars.SequenceEqual(snapshot)).IsTrue(); + } + + [Test] + public async Task StringStream_MemoryManagerBacked_AllReadSizes_MatchGetBytes() + { + var text = RepeatStringStreamText(); + var chars = ("\u4f60xx" + text + "yy\U0001F30D").ToCharArray(); + ReadOnlyMemory memory = new NonArrayCharMemoryManager(chars).Memory.Slice(3, text.Length); + await Assert.That(MemoryMarshal.TryGetArray(memory, out _)).IsFalse(); + await Assert.That(MemoryMarshal.TryGetString(memory, out _, out _, out _)).IsFalse(); + + var failure = CompareStringStreamReads(encoding => new StringStream(memory, encoding), text); + + await Assert.That(failure).IsNull(); + } + + [Test] + public async Task StringStream_SingleShot_AllSources_MatchGetBytes() + { + // A buffer large enough for the whole payload takes the stateless single-shot path + var text = RepeatStringStreamText(); + var chars = ("xx" + text + "yy").ToCharArray(); + var sources = new[] + { + text.AsMemory(), + ("xx" + text + "yy").AsMemory(2, text.Length), + new ReadOnlyMemory(chars, 2, text.Length), + new NonArrayCharMemoryManager(chars).Memory.Slice(2, text.Length) + }; + + foreach (var encoding in StringStreamEncodings()) + { + var expected = encoding.GetBytes(text); + foreach (var source in sources) + { + using var stream = new StringStream(source, encoding); + var buffer = new byte[encoding.GetMaxByteCount(text.Length) + 5]; + + var read = stream.Read(buffer, 5, buffer.Length - 5); + + await Assert.That(read).IsEqualTo(expected.Length); + await Assert.That(buffer.AsSpan(5, read).SequenceEqual(expected)).IsTrue(); + await Assert.That(stream.Read(buffer, 0, buffer.Length)).IsEqualTo(0); + } + } + } + + [Test] + public async Task StringStream_EmptySources_ReadZero() + { + var sources = new[] + { + default, + string.Empty.AsMemory(), + "abc".AsMemory(1, 0), + new ReadOnlyMemory(['a', 'b'], 1, 0), + new NonArrayCharMemoryManager(['a', 'b']).Memory.Slice(1, 0) + }; + + foreach (var source in sources) + { + foreach (var size in new[] {1, 64}) + { + using var stream = new StringStream(source, Encoding.Unicode); + + await Assert.That(stream.Read(new byte[size], 0, size)).IsEqualTo(0); + await Assert.That(stream.ReadByte()).IsEqualTo(-1); + } + } + } + + [Test] + public async Task StringStream_ReadByte_AllSources_MatchGetBytes() + { + var chars = ("xx" + stringStreamMixedText + "yy").ToCharArray(); + var sources = new[] + { + stringStreamMixedText.AsMemory(), + new ReadOnlyMemory(chars, 2, stringStreamMixedText.Length), + new NonArrayCharMemoryManager(chars).Memory.Slice(2, stringStreamMixedText.Length) + }; + + foreach (var encoding in StringStreamEncodings()) + { + var expected = encoding.GetBytes(stringStreamMixedText); + foreach (var source in sources) + { + using var stream = new StringStream(source, encoding); + var actual = new List(); + int value; + while ((value = stream.ReadByte()) != -1) + { + actual.Add((byte) value); + } + + await Assert.That(actual.SequenceEqual(expected)).IsTrue(); + } + } + } + static byte[] ReadToEnd(Stream stream) { using var memory = new MemoryStream();