Skip to content

Commit 6815e56

Browse files
peffgitster
authored andcommitted
refactor dir_add_name
This is in preparation for keeping two entry lists in the dir object. This patch adds and uses the ALLOC_GROW() macro, which implements the commonly used idiom of growing a dynamic array using the alloc_nr function (not just in dir.c, but everywhere). We also move creation of a dir_entry to dir_entry_new. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 6718f1f commit 6815e56

File tree

2 files changed

+25
-11
lines changed

2 files changed

+25
-11
lines changed

cache.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,21 @@ extern void verify_non_filename(const char *prefix, const char *name);
225225

226226
#define alloc_nr(x) (((x)+16)*3/2)
227227

228+
/*
229+
* Realloc the buffer pointed at by variable 'x' so that it can hold
230+
* at least 'nr' entries; the number of entries currently allocated
231+
* is 'alloc', using the standard growing factor alloc_nr() macro.
232+
*
233+
* DO NOT USE any expression with side-effect for 'x' or 'alloc'.
234+
*/
235+
#define ALLOC_GROW(x, nr, alloc) \
236+
do { \
237+
if ((nr) >= alloc) { \
238+
alloc = alloc_nr(alloc); \
239+
x = xrealloc((x), alloc * sizeof(*(x))); \
240+
} \
241+
} while(0)
242+
228243
/* Initialize and use the cache information */
229244
extern int read_index(struct index_state *);
230245
extern int read_index_from(struct index_state *, const char *path);

dir.c

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -271,27 +271,26 @@ int excluded(struct dir_struct *dir, const char *pathname)
271271
return 0;
272272
}
273273

274-
struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
275-
{
274+
static struct dir_entry *dir_entry_new(const char *pathname, int len) {
276275
struct dir_entry *ent;
277276

278-
if (cache_name_pos(pathname, len) >= 0)
279-
return NULL;
280-
281-
if (dir->nr == dir->alloc) {
282-
int alloc = alloc_nr(dir->alloc);
283-
dir->alloc = alloc;
284-
dir->entries = xrealloc(dir->entries, alloc*sizeof(ent));
285-
}
286277
ent = xmalloc(sizeof(*ent) + len + 1);
287278
ent->ignored = ent->ignored_dir = 0;
288279
ent->len = len;
289280
memcpy(ent->name, pathname, len);
290281
ent->name[len] = 0;
291-
dir->entries[dir->nr++] = ent;
292282
return ent;
293283
}
294284

285+
struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len)
286+
{
287+
if (cache_name_pos(pathname, len) >= 0)
288+
return NULL;
289+
290+
ALLOC_GROW(dir->entries, dir->nr, dir->alloc);
291+
return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
292+
}
293+
295294
enum exist_status {
296295
index_nonexistent = 0,
297296
index_directory,

0 commit comments

Comments
 (0)