SDL: stdlib: Add `SDL_utf8strnlen`

From 74bcc5a0a3e757467b710353e7c6bdfb7277e0a2 Mon Sep 17 00:00:00 2001
From: Guldoman <[EMAIL REDACTED]>
Date: Thu, 5 May 2022 02:23:05 +0200
Subject: [PATCH] stdlib: Add `SDL_utf8strnlen`

---
 include/SDL_stdinc.h              |  1 +
 src/dynapi/SDL_dynapi_overrides.h |  1 +
 src/dynapi/SDL_dynapi_procs.h     |  1 +
 src/stdlib/SDL_string.c           | 17 +++++++++++++++++
 4 files changed, 20 insertions(+)

diff --git a/include/SDL_stdinc.h b/include/SDL_stdinc.h
index 6ee15f1444a..c21e54c0671 100644
--- a/include/SDL_stdinc.h
+++ b/include/SDL_stdinc.h
@@ -561,6 +561,7 @@ extern DECLSPEC char *SDLCALL SDL_strrchr(const char *str, int c);
 extern DECLSPEC char *SDLCALL SDL_strstr(const char *haystack, const char *needle);
 extern DECLSPEC char *SDLCALL SDL_strtokr(char *s1, const char *s2, char **saveptr);
 extern DECLSPEC size_t SDLCALL SDL_utf8strlen(const char *str);
+extern DECLSPEC size_t SDLCALL SDL_utf8strnlen(const char *str, size_t bytes);
 
 extern DECLSPEC char *SDLCALL SDL_itoa(int value, char *str, int radix);
 extern DECLSPEC char *SDLCALL SDL_uitoa(unsigned int value, char *str, int radix);
diff --git a/src/dynapi/SDL_dynapi_overrides.h b/src/dynapi/SDL_dynapi_overrides.h
index 76c9e91998c..1083fd9adbc 100644
--- a/src/dynapi/SDL_dynapi_overrides.h
+++ b/src/dynapi/SDL_dynapi_overrides.h
@@ -874,3 +874,4 @@
 #define SDL_HasLSX SDL_HasLSX_REAL
 #define SDL_HasLASX SDL_HasLASX_REAL
 #define SDL_RenderGetD3D12Device SDL_RenderGetD3D12Device_REAL
+#define SDL_utf8strnlen SDL_utf8strnlen_REAL
diff --git a/src/dynapi/SDL_dynapi_procs.h b/src/dynapi/SDL_dynapi_procs.h
index ddc655760bc..db4fa1bb9b1 100644
--- a/src/dynapi/SDL_dynapi_procs.h
+++ b/src/dynapi/SDL_dynapi_procs.h
@@ -951,3 +951,4 @@ SDL_DYNAPI_PROC(SDL_bool,SDL_HasLASX,(void),(),return)
 #ifdef __WIN32__
 SDL_DYNAPI_PROC(ID3D12Device*,SDL_RenderGetD3D12Device,(SDL_Renderer *a),(a),return)
 #endif
+SDL_DYNAPI_PROC(size_t,SDL_utf8strnlen,(const char *a, size_t b),(a,b),return)
diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c
index 3125e839054..77e0d30f5a5 100644
--- a/src/stdlib/SDL_string.c
+++ b/src/stdlib/SDL_string.c
@@ -675,6 +675,23 @@ SDL_utf8strlen(const char *str)
     return retval;
 }
 
+size_t
+SDL_utf8strnlen(const char *str, size_t bytes)
+{
+    size_t retval = 0;
+    const char *p = str;
+    unsigned char ch;
+
+    while ((ch = *(p++)) != 0 && bytes-- > 0) {
+        /* if top two bits are 1 and 0, it's a continuation byte. */
+        if ((ch & 0xc0) != 0x80) {
+            retval++;
+        }
+    }
+
+    return retval;
+}
+
 size_t
 SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen)
 {