Skip to content

Commit beba25a

Browse files
committed
revision.c: update show_object_with_name() without using malloc()
Allocating and then immediately freeing temporary memory a million times when listing a million objects is distasteful. Signed-off-by: Junio C Hamano <[email protected]>
1 parent 91f1751 commit beba25a

File tree

1 file changed

+36
-14
lines changed

1 file changed

+36
-14
lines changed

revision.c

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,45 @@ char *path_name(const struct name_path *path, const char *name)
4040
return n;
4141
}
4242

43+
static int show_path_component_truncated(FILE *out, const char *name, int len)
44+
{
45+
int cnt;
46+
for (cnt = 0; cnt < len; cnt++) {
47+
int ch = name[cnt];
48+
if (!ch || ch == '\n')
49+
return -1;
50+
fputc(ch, out);
51+
}
52+
return len;
53+
}
54+
55+
static int show_path_truncated(FILE *out, const struct name_path *path)
56+
{
57+
int emitted, ours;
58+
59+
if (!path)
60+
return 0;
61+
emitted = show_path_truncated(out, path->up);
62+
if (emitted < 0)
63+
return emitted;
64+
if (emitted)
65+
fputc('/', out);
66+
ours = show_path_component_truncated(out, path->elem, path->elem_len);
67+
if (ours < 0)
68+
return ours;
69+
return ours || emitted;
70+
}
71+
4372
void show_object_with_name(FILE *out, struct object *obj, const struct name_path *path, const char *component)
4473
{
45-
char *name = path_name(path, component);
46-
const char *ep = strchr(name, '\n');
74+
struct name_path leaf;
75+
leaf.up = (struct name_path *)path;
76+
leaf.elem = component;
77+
leaf.elem_len = strlen(component);
4778

48-
/*
49-
* An object with name "foo\n0000000..." can be used to
50-
* confuse downstream "git pack-objects" very badly.
51-
*/
52-
if (ep) {
53-
fprintf(out, "%s %.*s\n", sha1_to_hex(obj->sha1),
54-
(int) (ep - name),
55-
name);
56-
}
57-
else
58-
fprintf(out, "%s %s\n", sha1_to_hex(obj->sha1), name);
59-
free(name);
79+
fprintf(out, "%s ", sha1_to_hex(obj->sha1));
80+
show_path_truncated(out, &leaf);
81+
fputc('\n', out);
6082
}
6183

6284
void add_object(struct object *obj,

0 commit comments

Comments
 (0)