fix: Fixes span reader ReadString (#1539)

This commit is contained in:
Kamron Batman 2023-10-11 13:41:24 -07:00 committed by GitHub
parent 0018901a79
commit 1ebaf5390d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 12 additions and 4 deletions

View file

@ -168,6 +168,11 @@ public ref struct SpanReader
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ReadString(Encoding encoding, bool safeString = false, int fixedLength = -1)
{
if (fixedLength == 0)
{
return "";
}
int byteLength = encoding.GetByteLengthForEncoding();
bool isFixedLength = fixedLength > -1;
@ -191,8 +196,10 @@ public ref struct SpanReader
var span = _buffer.Slice(Position, size);
var index = span.IndexOfTerminator(byteLength);
Position += isFixedLength || index < 0 ? size : index;
return TextEncoding.GetString(span[..index], encoding, safeString);
Position += isFixedLength || index < 0 ? size : index;
// The string is either as long as the first terminator character, remaining buffer size, or fixed length.
return TextEncoding.GetString(span[..(index < 0 ? size : index)], encoding, safeString);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]

View file

@ -277,6 +277,7 @@ public static class StringHelpers
_ => buffer.IndexOf((byte)0)
};
// TODO: If returns -1, do not multiply by the byte length
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfTerminator(this ReadOnlySpan<byte> buffer, int sizeT) =>
sizeT switch