Merge pull request #35 from Susko3/add-UTF8GetBytes-helper

Add helper for making null-terminated byte arrays
This commit is contained in:
Dan Balasescu 2024-04-16 03:59:08 +09:00 committed by GitHub
commit 9c89602557
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 0 deletions

View File

@ -14,6 +14,19 @@ namespace SDL3.Tests
{
Console.OutputEncoding = Encoding.UTF8;
unsafe
{
// Encoding.UTF8.GetBytes can churn out null pointers and doesn't guarantee null termination
fixed (byte* badPointer = Encoding.UTF8.GetBytes(""))
Debug.Assert(badPointer == null);
fixed (byte* pointer = UTF8GetBytes(""))
{
Debug.Assert(pointer != null);
Debug.Assert(pointer[0] == '\0');
}
}
SDL_SetHint(SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4, "null byte \0 in string"u8);
Debug.Assert(SDL_GetHint(SDL_HINT_WINDOWS_CLOSE_ON_ALT_F4) == "null byte ");

View File

@ -2,7 +2,9 @@
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace SDL
{
@ -25,5 +27,17 @@ namespace SDL
return s;
}
/// <summary>
/// UTF8 encodes a managed <c>string</c> to a <c>byte</c> array suitable for use in <c>ReadOnlySpan&lt;byte&gt;</c> parameters of SDL functions.
/// </summary>
/// <param name="s">The <c>string</c> to encode.</param>
/// <returns>A null-terminated byte array.</returns>
public static byte[] UTF8GetBytes(string s)
{
byte[] array = Encoding.UTF8.GetBytes(s + '\0');
Debug.Assert(array[^1] == '\0');
return array;
}
}
}