Skip to content

Commit 23dd6f8

Browse files
derrickstoleegitster
authored andcommitted
sparse-index: use strbuf in path_found()
The path_found() method previously reused strings from the cache entries the calling methods were using. This prevents string manipulation in place and causes some odd reallocation before the final lstat() call in the method. Refactor the method to use strbufs and copy the path into the strbuf, but also only the parent directory and not the whole path. This looks like extra copying when assigning the path to the strbuf, but we save an allocation by dropping the 'tmp' string, and we are "reusing" the copy from 'tmp' to put the data in the strbuf. Signed-off-by: Derrick Stolee <[email protected]> Reviewed-by: Elijah Newren <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent b746a85 commit 23dd6f8

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

sparse-index.c

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -440,31 +440,30 @@ void ensure_correct_sparsity(struct index_state *istate)
440440
}
441441

442442
struct path_found_data {
443-
const char *dirname;
444-
size_t dir_len;
443+
struct strbuf dir;
445444
int dir_found;
446445
};
447446

448447
#define PATH_FOUND_DATA_INIT { \
448+
.dir = STRBUF_INIT, \
449449
.dir_found = 1 \
450450
}
451451

452452
static void clear_path_found_data(struct path_found_data *data)
453453
{
454-
return;
454+
strbuf_release(&data->dir);
455455
}
456456

457457
static int path_found(const char *path, struct path_found_data *data)
458458
{
459459
struct stat st;
460460
char *newdir;
461-
char *tmp;
462461

463462
/*
464463
* If dirname corresponds to a directory that doesn't exist, and this
465464
* path starts with dirname, then path can't exist.
466465
*/
467-
if (!data->dir_found && !memcmp(path, data->dirname, data->dir_len))
466+
if (!data->dir_found && !memcmp(path, data->dir.buf, data->dir.len))
468467
return 0;
469468

470469
/*
@@ -486,17 +485,15 @@ static int path_found(const char *path, struct path_found_data *data)
486485
* If path starts with directory (which we already lstat'ed and found),
487486
* then no need to lstat parent directory again.
488487
*/
489-
if (data->dir_found && data->dirname &&
490-
memcmp(path, data->dirname, data->dir_len))
488+
if (data->dir_found && data->dir.buf &&
489+
memcmp(path, data->dir.buf, data->dir.len))
491490
return 0;
492491

493492
/* Free previous dirname, and cache path's dirname */
494-
data->dirname = path;
495-
data->dir_len = newdir - path + 1;
493+
strbuf_reset(&data->dir);
494+
strbuf_add(&data->dir, path, newdir - path + 1);
496495

497-
tmp = xstrndup(path, data->dir_len);
498-
data->dir_found = !lstat(tmp, &st);
499-
free(tmp);
496+
data->dir_found = !lstat(data->dir.buf, &st);
500497

501498
return 0;
502499
}

0 commit comments

Comments
 (0)