diff --git a/steam-runtime-tools/glib-backports-internal.h b/steam-runtime-tools/glib-backports-internal.h index 805f2ef099a1584579a12e3c3a835173556968ad..21420ba506f09b06b15b202bef4c082da32f7aa9 100644 --- a/steam-runtime-tools/glib-backports-internal.h +++ b/steam-runtime-tools/glib-backports-internal.h @@ -114,3 +114,9 @@ gpointer *my_g_hash_table_get_keys_as_array (GHashTable *hash, #define G_DBUS_METHOD_INVOCATION_HANDLED TRUE #define G_DBUS_METHOD_INVOCATION_UNHANDLED FALSE #endif + +#if !GLIB_CHECK_VERSION(2, 52, 0) +#define g_utf8_make_valid(s,l) my_g_utf8_make_valid (s, l) +gchar *my_g_utf8_make_valid (const gchar *str, + gssize len); +#endif diff --git a/steam-runtime-tools/glib-backports.c b/steam-runtime-tools/glib-backports.c index 2d637a3e6aef11cd6313693daf7289b49272f635..8b2a5103f2b4b3a02f43046af7cba8d651db3cb1 100644 --- a/steam-runtime-tools/glib-backports.c +++ b/steam-runtime-tools/glib-backports.c @@ -510,3 +510,50 @@ my_g_hash_table_get_keys_as_array (GHashTable *hash, return g_ptr_array_free (arr, FALSE); } #endif + +#if !GLIB_CHECK_VERSION(2, 52, 0) +gchar * +my_g_utf8_make_valid (const gchar *str, + gssize len) +{ + GString *string; + const gchar *remainder, *invalid; + gsize remaining_bytes, valid_bytes; + + g_return_val_if_fail (str != NULL, NULL); + + if (len < 0) + len = strlen (str); + + string = NULL; + remainder = str; + remaining_bytes = len; + + while (remaining_bytes != 0) + { + if (g_utf8_validate (remainder, remaining_bytes, &invalid)) + break; + valid_bytes = invalid - remainder; + + if (string == NULL) + string = g_string_sized_new (remaining_bytes); + + g_string_append_len (string, remainder, valid_bytes); + /* append U+FFFD REPLACEMENT CHARACTER */ + g_string_append (string, "\357\277\275"); + + remaining_bytes -= valid_bytes + 1; + remainder = invalid + 1; + } + + if (string == NULL) + return g_strndup (str, len); + + g_string_append_len (string, remainder, remaining_bytes); + g_string_append_c (string, '\0'); + + g_assert (g_utf8_validate (string->str, -1, NULL)); + + return g_string_free (string, FALSE); +} +#endif