From 302e24671942051d70707586cf8c605a5815edac Mon Sep 17 00:00:00 2001 From: lemon Date: Mon, 15 Dec 2025 22:39:52 +0100 Subject: create distinct interned string type Interned strings are used pervasively, so it's a good idea to add a layer of type safety to differentiate them from general cstrs and avoid potential bugs from comparing non-interned and interned strings. Not that that's happened so far that I can remember, but it could. I'm 90% sure it's legal to alias `struct {char c;}` pointers with `char` pointers. This specific typedef gives type safety but with a simple one-way `internstr -> const char *` typecast (with `&istr->c`). Converting the other way around is more intentional: a straight up cast `(internstr)cstr` which sticks out as unchecked and probably wrong, or calling the intern(cstr) function, which is the right way. --- mem.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'mem.c') diff --git a/mem.c b/mem.c index 6866216..eefe96a 100644 --- a/mem.c +++ b/mem.c @@ -37,12 +37,12 @@ void * } /** string interning **/ -const char * +internstr intern(const char *s) { static uint N, n; static struct ht { - const char *s; + internstr s; size_t h; } *ht; static struct { char m[sizeof(struct arena) + (2<<10)]; struct arena *_a; } amem; @@ -75,7 +75,7 @@ intern(const char *s) N = nnew; i = h; continue; - } else if (h == ht[i].h && !strcmp(s, ht[i].s)) { + } else if (h == ht[i].h && !strcmp(s, &ht[i].s->c)) { return ht[i].s; } ++i; -- cgit v1.2.3