t/helper/test-hashmap.c: avoid using `strtok()`
Avoid using the non-reentrant `strtok()` to separate the parts of each incoming command. Instead of replacing it with `strtok_r()`, let's instead use the more friendly pair of `string_list_split_in_place()` and `string_list_remove_empty_items()`. Signed-off-by: Taylor Blau <me@ttaylorr.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Taylor Blau committed
Apr 24, 2023 at 18:20 UTC
826f0e33ab0cbe976af02dd487303e4d1a0b3017
1 file changed
+15
-7
t/helper/test-hashmap.c
+15
-7
@@ -2,6 +2,7 @@
2
#include "git-compat-util.h"
3
#include "hashmap.h"
4
#include "strbuf.h"
5
+#include "string-list.h"
6
7
struct test_entry
8
{
@@ -150,6 +151,7 @@ static void perf_hashmap(unsigned int method, unsigned int rounds)
151
*/
152
int cmd__hashmap(int argc, const char **argv)
153
{
154
+ struct string_list parts = STRING_LIST_INIT_NODUP;
155
struct strbuf line = STRBUF_INIT;
156
int icase;
157
struct hashmap map = HASHMAP_INIT(test_entry_cmp, &icase);
@@ -159,21 +161,26 @@ int cmd__hashmap(int argc, const char **argv)
161
162
/* process commands from stdin */
163
while (strbuf_getline(&line, stdin) != EOF) {
162
- char *cmd, *p1 = NULL, *p2 = NULL;
164
+ char *cmd, *p1, *p2;
165
unsigned int hash = 0;
166
struct test_entry *entry;
167
168
/* break line into command and up to two parameters */
167
- cmd = strtok(line.buf, DELIM);
169
+ string_list_setlen(&parts, 0);
170
+ string_list_split_in_place(&parts, line.buf, DELIM, 2);
171
+ string_list_remove_empty_items(&parts, 0);
172
+
173
/* ignore empty lines */
169
- if (!cmd || *cmd == '#')
174
+ if (!parts.nr)
175
+ continue;
176
+ if (!*parts.items[0].string || *parts.items[0].string == '#')
177
continue;
178
172
- p1 = strtok(NULL, DELIM);
173
- if (p1) {
179
+ cmd = parts.items[0].string;
180
+ p1 = parts.nr >= 1 ? parts.items[1].string : NULL;
181
+ p2 = parts.nr >= 2 ? parts.items[2].string : NULL;
182
+ if (p1)
183
hash = icase ? strihash(p1) : strhash(p1);
175
- p2 = strtok(NULL, DELIM);
176
- }
184
185
if (!strcmp("add", cmd) && p1 && p2) {
186
@@ -260,6 +267,7 @@ int cmd__hashmap(int argc, const char **argv)
267
}
268
}
269
270
+ string_list_clear(&parts, 0);
271
strbuf_release(&line);
272
hashmap_clear_and_free(&map, struct test_entry, ent);
273
return 0;