From e18e833799b3ea3f2ad143a5c894a37b215dc708 Mon Sep 17 00:00:00 2001 From: Anthony Konzel Date: Wed, 4 Jun 2025 16:40:37 -0500 Subject: [PATCH 1/2] Reduce the number of string allocations in Utf8String when input strings do not contain a null terminator --- SDL3-CS/Utf8String.cs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/SDL3-CS/Utf8String.cs b/SDL3-CS/Utf8String.cs index 832b44f..2eef006 100644 --- a/SDL3-CS/Utf8String.cs +++ b/SDL3-CS/Utf8String.cs @@ -24,10 +24,18 @@ 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')); + ReadOnlySpan chars = str.AsSpan(); + int len = Encoding.UTF8.GetByteCount(chars); + byte[] bytes = new byte[len + 1]; + Encoding.UTF8.GetBytes(chars, bytes); + + return new Utf8String(bytes); } public static implicit operator Utf8String(ReadOnlySpan raw) @@ -36,14 +44,14 @@ namespace SDL return new Utf8String(null); if (raw.Length == 0) - return new Utf8String(new ReadOnlySpan([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); + + byte[] copy = new byte[raw.Length + 1]; + raw.CopyTo(copy); + raw = copy; return new Utf8String(raw); } From e4a0124bfcff4f492c5a3ddb91c7fa716fd29597 Mon Sep 17 00:00:00 2001 From: Susko3 Date: Thu, 5 Jun 2025 02:16:48 +0200 Subject: [PATCH 2/2] Clean up code --- SDL3-CS/Utf8String.cs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/SDL3-CS/Utf8String.cs b/SDL3-CS/Utf8String.cs index 2eef006..8754bfb 100644 --- a/SDL3-CS/Utf8String.cs +++ b/SDL3-CS/Utf8String.cs @@ -30,11 +30,9 @@ namespace SDL if (str[^1] == '\0') return new Utf8String(Encoding.UTF8.GetBytes(str)); - ReadOnlySpan chars = str.AsSpan(); - int len = Encoding.UTF8.GetByteCount(chars); + int len = Encoding.UTF8.GetByteCount(str); byte[] bytes = new byte[len + 1]; - Encoding.UTF8.GetBytes(chars, bytes); - + Encoding.UTF8.GetBytes(str, bytes); return new Utf8String(bytes); } @@ -51,9 +49,7 @@ namespace SDL byte[] copy = new byte[raw.Length + 1]; raw.CopyTo(copy); - raw = copy; - - return new Utf8String(raw); + return new Utf8String(copy); } internal ref readonly byte GetPinnableReference() => ref Raw.GetPinnableReference();