mem-pool: add convenience functions for strdup and strndup

fast-import had a special mem_pool_strdup() convenience function that I
want to be able to use from the new merge algorithm I am writing.  Move
it from fast-import to mem-pool, and also add a mem_pool_strndup()
while at it that I also want to use.

Signed-off-by: Elijah Newren <newren@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Elijah Newren 2020-08-15 17:37:55 +00:00 коммит произвёл Junio C Hamano
Родитель 2befe97201
Коммит a762c8c1e1
3 изменённых файлов: 26 добавлений и 10 удалений

Просмотреть файл

@ -526,14 +526,6 @@ static unsigned int hc_str(const char *s, size_t len)
return r;
}
static char *pool_strdup(const char *s)
{
size_t len = strlen(s) + 1;
char *r = mem_pool_alloc(&fi_mem_pool, len);
memcpy(r, s, len);
return r;
}
static void insert_mark(struct mark_set *s, uintmax_t idnum, struct object_entry *oe)
{
while ((idnum >> s->shift) >= 1024) {
@ -615,7 +607,7 @@ static struct branch *new_branch(const char *name)
die("Branch name doesn't conform to GIT standards: %s", name);
b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
b->name = pool_strdup(name);
b->name = mem_pool_strdup(&fi_mem_pool, name);
b->table_next_branch = branch_table[hc];
b->branch_tree.versions[0].mode = S_IFDIR;
b->branch_tree.versions[1].mode = S_IFDIR;
@ -2806,7 +2798,7 @@ static void parse_new_tag(const char *arg)
t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
memset(t, 0, sizeof(struct tag));
t->name = pool_strdup(arg);
t->name = mem_pool_strdup(&fi_mem_pool, arg);
if (last_tag)
last_tag->next_tag = t;
else

Просмотреть файл

@ -102,6 +102,24 @@ void *mem_pool_calloc(struct mem_pool *mem_pool, size_t count, size_t size)
return r;
}
char *mem_pool_strdup(struct mem_pool *pool, const char *str)
{
size_t len = strlen(str) + 1;
char *ret = mem_pool_alloc(pool, len);
return memcpy(ret, str, len);
}
char *mem_pool_strndup(struct mem_pool *pool, const char *str, size_t len)
{
char *p = memchr(str, '\0', len);
size_t actual_len = (p ? p - str : len);
char *ret = mem_pool_alloc(pool, actual_len+1);
ret[actual_len] = '\0';
return memcpy(ret, str, actual_len);
}
int mem_pool_contains(struct mem_pool *mem_pool, void *mem)
{
struct mp_block *p;

Просмотреть файл

@ -41,6 +41,12 @@ void *mem_pool_alloc(struct mem_pool *pool, size_t len);
*/
void *mem_pool_calloc(struct mem_pool *pool, size_t count, size_t size);
/*
* Allocate memory from the memory pool and copy str into it.
*/
char *mem_pool_strdup(struct mem_pool *pool, const char *str);
char *mem_pool_strndup(struct mem_pool *pool, const char *str, size_t len);
/*
* Move the memory associated with the 'src' pool to the 'dst' pool. The 'src'
* pool will be empty and not contain any memory. It still needs to be free'd