tree-diff: pass whole path string to path_appendnew()

When diffing trees, we'll have a strbuf "base" containing the slash-separted names of our parent trees, and a "path" string representing an entry name from the current tree. We pass these separately to path_appendnew(), which combines them to form a single path string in the combine_diff_path struct. Instead, let's append the path string to our base strbuf ourselves, pass in the result, and then roll it back with strbuf_setlen(). This lets us simplify path_appendnew() a bit, enabling further refactoring. And while it might seem like this causes extra wasted allocations, it does not in practice. We reuse the same strbuf for each tree entry, so we only have to allocate it to match the largest name. Plus, in a recursive diff we'll end up doing this same operation to extend the base for the next level of recursion. So we're really just incurring a small memcpy(). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jan 9, 2025 at 03:49 UTC 8c53354658462aa6783022def86750ab0b79eb6f
1 file changed +6 -5
tree-diff.c
+6 -5
@@ -129,11 +129,10 @@ static int emit_diff_first_parent_only(struct diff_options *opt, struct combine_
129 * and append it to paths list tail.
130 */
131 static struct combine_diff_path *path_appendnew(struct combine_diff_path *last,
132 - int nparent, const struct strbuf *base, const char *path, int pathlen,
132 + int nparent, const char *path, size_t len,
133 unsigned mode, const struct object_id *oid)
134 {
135 struct combine_diff_path *p;
136 - size_t len = st_add(base->len, pathlen);
136 size_t alloclen = combine_diff_path_size(nparent, len);
137
138 p = xmalloc(alloclen);
@@ -141,8 +140,7 @@ static struct combine_diff_path *path_appendnew(struct combine_diff_path *last,
140 last->next = p;
141
142 p->path = (char *)&(p->parent[nparent]);
144 - memcpy(p->path, base->buf, base->len);
145 - memcpy(p->path + base->len, path, pathlen);
143 + memcpy(p->path, path, len);
144 p->path[len] = 0;
145 p->mode = mode;
146 oidcpy(&p->oid, oid ? oid : null_oid());
@@ -206,7 +204,10 @@ static struct combine_diff_path *emit_path(struct combine_diff_path *p,
204 if (emitthis) {
205 int keep;
206 struct combine_diff_path *pprev = p;
209 - p = path_appendnew(p, nparent, base, path, pathlen, mode, oid);
207 +
208 + strbuf_add(base, path, pathlen);
209 + p = path_appendnew(p, nparent, base->buf, base->len, mode, oid);
210 + strbuf_setlen(base, old_baselen);
211
212 for (i = 0; i < nparent; ++i) {
213 /*