26 const int MaxInputElementsPerIteration = 1 * 1024 * 1024;
37 public static unsafe
long GetBytes(
this Encoding encoding, ReadOnlySpan<char> chars, IBufferWriter<byte> writer)
40 throw new ArgumentNullException(nameof(encoding));
42 throw new ArgumentNullException(nameof(writer));
44 if (chars.Length <= MaxInputElementsPerIteration)
48 int byteCount = encoding.GetByteCount(chars);
49 Span<byte> scratchBuffer = writer.GetSpan(byteCount);
51 int actualBytesWritten = encoding.GetBytes(chars, scratchBuffer);
53 writer.Advance(actualBytesWritten);
54 return actualBytesWritten;
60 encoding.GetEncoder().Convert(chars, writer, flush:
true, out
long totalBytesWritten, out _);
61 return totalBytesWritten;
65 public static unsafe
int GetBytes(
this Encoding encoding,
string chars, Span<byte> bytes)
67 return encoding.GetBytes(chars.AsSpan(), bytes);
70 public static unsafe
int GetChars(
this Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> chars)
72 fixed (
byte* bytesPtr = bytes)
73 fixed (
char* charsPtr = chars)
74 return encoding.GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length);
77 public static unsafe
int GetCharCount(
this Encoding encoding, ReadOnlySpan<byte> bytes)
79 fixed (
byte* bytesPtr = bytes)
81 return encoding.GetCharCount(bytesPtr, bytes.Length);
85 public static unsafe
int GetByteCount(
this Encoder encoder, ReadOnlySpan<char> chars,
bool flush)
87 fixed (
char* charsPtr = chars)
89 return encoder.GetByteCount(charsPtr, chars.Length, flush);
107 public static void Convert(
this Encoder encoder, ReadOnlySpan<char> chars, IBufferWriter<byte> writer,
bool flush, out
long bytesUsed, out
bool completed)
110 throw new ArgumentNullException(nameof(encoder));
112 throw new ArgumentNullException(nameof(writer));
116 long totalBytesWritten = 0;
127 int byteCountForThisSlice = chars.Length <= MaxInputElementsPerIteration
128 ? encoder.GetByteCount(chars, flush)
129 : encoder.GetByteCount(chars.Slice(0, MaxInputElementsPerIteration), flush:
false );
131 Span<byte> scratchBuffer = writer.GetSpan(byteCountForThisSlice);
133 encoder.Convert(chars, scratchBuffer, flush, out
int charsUsedJustNow, out
int bytesWrittenJustNow, out completed);
135 chars = chars.Slice(charsUsedJustNow);
136 writer.Advance(bytesWrittenJustNow);
137 totalBytesWritten += bytesWrittenJustNow;
138 }
while (!chars.IsEmpty);
140 bytesUsed = totalBytesWritten;
143 public static unsafe
void Convert(
this Encoder encoder, ReadOnlySpan<char> chars, Span<byte> bytes,
bool flush, out
int charsUsed, out
int bytesUsed, out
bool completed)
145 fixed (
char* charsPtr = chars)
146 fixed (
byte* bytesPtr = bytes)
148 encoder.Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed);