Merge pull request #207 from SaxxonPike/Utf8String-Allocations

Allocate string memory only once in Utf8String when input lacks null terminator
This commit is contained in:
Dan Balasescu 2025-06-05 13:38:25 +09:00 committed by GitHub
commit c61b11ee5d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 14 additions and 10 deletions

View File

@ -24,10 +24,16 @@ namespace SDL
if (str == null)
return new Utf8String(null);
if (str.EndsWith('\0'))
if (str.Length == 0)
return new Utf8String("\0"u8);
if (str[^1] == '\0')
return new Utf8String(Encoding.UTF8.GetBytes(str));
return new Utf8String(Encoding.UTF8.GetBytes(str + '\0'));
int len = Encoding.UTF8.GetByteCount(str);
byte[] bytes = new byte[len + 1];
Encoding.UTF8.GetBytes(str, bytes);
return new Utf8String(bytes);
}
public static implicit operator Utf8String(ReadOnlySpan<byte> raw)
@ -36,16 +42,14 @@ namespace SDL
return new Utf8String(null);
if (raw.Length == 0)
return new Utf8String(new ReadOnlySpan<byte>([0]));
return new Utf8String("\0"u8);
if (raw[^1] != 0)
{
byte[] copy = new byte[raw.Length + 1];
raw.CopyTo(copy);
raw = copy;
}
if (raw[^1] == 0)
return new Utf8String(raw);
return new Utf8String(raw);
byte[] copy = new byte[raw.Length + 1];
raw.CopyTo(copy);
return new Utf8String(copy);
}
internal ref readonly byte GetPinnableReference() => ref Raw.GetPinnableReference();