Commit 74bcc5a0a3e757467b710353e7c6bdfb7277e0a2

Guldoman 2022-05-05T02:23:05

stdlib: Add `SDL_utf8strnlen`

diff --git a/include/SDL_stdinc.h b/include/SDL_stdinc.h
index 6ee15f1..c21e54c 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 76c9e91..1083fd9 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 ddc6557..db4fa1b 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 3125e83..77e0d30 100644
--- a/src/stdlib/SDL_string.c
+++ b/src/stdlib/SDL_string.c
@@ -676,6 +676,23 @@ SDL_utf8strlen(const char *str)
 }
 
 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)
 {
 #if defined(HAVE_STRLCAT)