{"thread":{"id":"58636","subject":"[PATCH] path.c: do not alloc for .contents in the trie","startedAt":"2022-10-17T06:15:08Z","lastAt":"2022-10-17T06:15:08Z","messageCount":1,"participants":["Rubén Justo"],"isPatch":true,"patchVersion":1,"patchTotal":null},"messages":[{"id":"465068","messageId":"4db3d1ed-d530-2429-f578-33196ff71fb1@gmail.com","threadId":"58636","inReplyTo":null,"subject":"[PATCH] path.c: do not alloc for .contents in the trie","fromName":"Rubén Justo","fromEmail":"rjusto@gmail.com","sentAt":"2022-10-17T06:14:59Z","receivedAt":"2022-10-17T06:15:08Z","isPatch":true,"sender":{"key":"rjusto@gmail.com","avatar":"https://avatars.githubusercontent.com/u/5685487?v=4"},"body":"In 4e09cf2ac (path: optimize common dir checking, 2015-08-31) a trie was\nintroduced to search non-linearly over common_list.  The nodes in the\ntrie are constructed from the values in that static variable.  Each of\nthose nodes can have in .contents a heap allocated string with the\ncharacters to be considered for the node, and in .len the count of this\ncharacters.  Having this .len there is no need to have a local copy of\nthe string, we can just have in .contents a pointer to a specific\nposition in the specific string in the specific value in common_list.\nOnly .len characters will be considered.\n\nLet's make .contents const and remove that unneeded xstrndups.\n\nSigned-off-by: Rubén Justo <rjusto@gmail.com>\n---\n path.c | 14 +++++---------\n 1 file changed, 5 insertions(+), 9 deletions(-)\n\ndiff --git a/path.c b/path.c\nindex a3cfcd8a6e..94483d98f9 100644\n--- a/path.c\n+++ b/path.c\n@@ -159,7 +159,7 @@ static struct common_dir common_list[] = {\n struct trie {\n \tstruct trie *children[256];\n \tint len;\n-\tchar *contents;\n+\tconst char *contents;\n \tvoid *value;\n };\n \n@@ -167,10 +167,8 @@ static struct trie *make_trie_node(const char *key, void *value)\n {\n \tstruct trie *new_node = xcalloc(1, sizeof(*new_node));\n \tnew_node->len = strlen(key);\n-\tif (new_node->len) {\n-\t\tnew_node->contents = xmalloc(new_node->len);\n-\t\tmemcpy(new_node->contents, key, new_node->len);\n-\t}\n+\tif (new_node->len)\n+\t\tnew_node->contents = key;\n \tnew_node->value = value;\n \treturn new_node;\n }\n@@ -204,10 +202,8 @@ static void *add_to_trie(struct trie *root, const char *key, void *value)\n \t\tmemcpy(child->children, root->children, sizeof(root->children));\n \n \t\tchild->len = root->len - i - 1;\n-\t\tif (child->len) {\n-\t\t\tchild->contents = xstrndup(root->contents + i + 1,\n-\t\t\t\t\t\t   child->len);\n-\t\t}\n+\t\tif (child->len)\n+\t\t\tchild->contents = root->contents + i + 1;\n \t\tchild->value = root->value;\n \t\troot->value = NULL;\n \t\troot->len = i;\n-- \n2.36.1\n"}]}