Skip to content

Commit dfcec18

Browse files
authored
gtk.cfg: Remove pure annotation from g_str_has_prefix/suffix (#8788)
`g_str_has_prefix` and `g_str_has_suffix` are not technically pure because they can log to the console if a precondition fails. This partially reverts commit 7cc7c0b. --- Some notes: The original `gtk.cfg` change hasn't been released yet, so the revert shouldn't cause any churn for users. GLib has code like this: ```c gboolean (g_str_has_prefix) (const gchar *str, const gchar *prefix) { g_return_val_if_fail (str != NULL, FALSE); g_return_val_if_fail (prefix != NULL, FALSE); return strncmp (str, prefix, strlen (prefix)) == 0; } ``` Most real-world code is treating this function as safe to call inside of an assert, even though it could technically have side effects if one of the preconditions fails. I removed the pure annotation to err on the side of correctness and pedantry, even though most projects would view the warnings as "false positives" from a practical perspective. Here is example usage from QEMU: ```c char *qemu_chr_get_filename(Chardev *chr) { ChardevClass *cc = CHARDEV_GET_CLASS(chr); const char *typename; if (cc->chr_get_filename) { return cc->chr_get_filename(chr); } typename = object_get_typename(OBJECT(chr)); assert(g_str_has_prefix(typename, "chardev-")); return g_strdup(typename + 8); } ```
1 parent b1b7e3c commit dfcec18

2 files changed

Lines changed: 6 additions & 1 deletion

File tree

cfg/gtk.cfg

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5221,7 +5221,6 @@
52215221
<!-- gboolean g_str_has_prefix (const gchar* str, const gchar* prefix); -->
52225222
<!-- gboolean g_str_has_suffix (const gchar* str, const gchar* prefix); -->
52235223
<function name="g_str_has_prefix,g_str_has_suffix">
5224-
<pure/>
52255224
<leak-ignore/>
52265225
<noreturn>false</noreturn>
52275226
<returnValue type="gboolean"/>

test/cfg/gtk.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,14 @@ void validCode(int argInt, GHashTableIter * hash_table_iter, GHashTable * hash_t
5959
g_string_free(pGStr1, TRUE);
6060

6161
gchar * pGchar1 = g_strconcat("a", "b", NULL);
62+
63+
// g_str_has_prefix and g_str_has_suffix can have side effects because they use
64+
// g_return_val_if_fail, which logs to the console upon failure
65+
// cppcheck-suppress assertWithSideEffect
6266
g_assert_true(g_str_has_prefix(pGchar1, "a"));
67+
// cppcheck-suppress assertWithSideEffect
6368
g_assert_true(g_str_has_suffix(pGchar1, "b"));
69+
6470
printf("%s", pGchar1);
6571
g_free(pGchar1);
6672

0 commit comments

Comments
 (0)