git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] path.c: do not alloc for .contents in the trie

From
Rubén Justo <rjusto@gmail.com>
Date
Oct 17, 2022, 06:14 UTC
Message-ID
<4db3d1ed-d530-2429-f578-33196ff71fb1@gmail.com>

In 4e09cf2ac (path: optimize common dir checking, 2015-08-31) a trie was introduced to search non-linearly over common_list. The nodes in the trie are constructed from the values in that static variable. Each of those nodes can have in .contents a heap allocated string with the characters to be considered for the node, and in .len the count of this characters. Having this .len there is no need to have a local copy of the string, we can just have in .contents a pointer to a specific position in the specific string in the specific value in common_list. Only .len characters will be considered.

Let's make .contents const and remove that unneeded xstrndups.
Signed-off-by: Rubén Justo <rjusto@gmail.com>
---
 path.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
diff --git a/path.c b/path.c
index a3cfcd8a6e..94483d98f9 100644
--- a/path.c
+++ b/path.c
@@ -159,7 +159,7 @@ static struct common_dir common_list[] = {
 struct trie {
 	struct trie *children[256];
 	int len;
-	char *contents;
+	const char *contents;
 	void *value;
 };
 
@@ -167,10 +167,8 @@ static struct trie *make_trie_node(const char *key, void *value)
 {
 	struct trie *new_node = xcalloc(1, sizeof(*new_node));
 	new_node->len = strlen(key);
-	if (new_node->len) {
-		new_node->contents = xmalloc(new_node->len);
-		memcpy(new_node->contents, key, new_node->len);
-	}
+	if (new_node->len)
+		new_node->contents = key;
 	new_node->value = value;
 	return new_node;
 }
@@ -204,10 +202,8 @@ static void *add_to_trie(struct trie *root, const char *key, void *value)
 		memcpy(child->children, root->children, sizeof(root->children));
 
 		child->len = root->len - i - 1;
-		if (child->len) {
-			child->contents = xstrndup(root->contents + i + 1,
-						   child->len);
-		}
+		if (child->len)
+			child->contents = root->contents + i + 1;
 		child->value = root->value;
 		root->value = NULL;
 		root->len = i;
-- 
2.36.1
Message 1 of 1 in “path.c: do not alloc for .contents in the trie”
  1. path.c: do not alloc for .contents in the trieRubén Justo, Oct 17, 2022

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.