Skip to content

Commit 4796c91

Browse files
committed
buffer: return errors for git_buf_init and git_buf_attach
Both the `git_buf_init` and `git_buf_attach` functions may call `git_buf_grow` in case they were given an allocation length as parameter. As such, it is possible for these functions to fail when we run out of memory. While it won't probably be used anytime soon, it does indeed make sense to also record this fact by returning an error code from both functions. As they belong to the internal API only, this change does not break our interface.
1 parent 9a8386a commit 4796c91

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

src/buffer.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,15 @@ char git_buf__oom[1];
2222
return -1;
2323

2424

25-
void git_buf_init(git_buf *buf, size_t initial_size)
25+
int git_buf_init(git_buf *buf, size_t initial_size)
2626
{
2727
buf->asize = 0;
2828
buf->size = 0;
2929
buf->ptr = git_buf__initbuf;
3030

31-
if (initial_size)
32-
git_buf_grow(buf, initial_size);
31+
ENSURE_SIZE(buf, initial_size);
32+
33+
return 0;
3334
}
3435

3536
int git_buf_try_grow(
@@ -577,7 +578,7 @@ char *git_buf_detach(git_buf *buf)
577578
return data;
578579
}
579580

580-
void git_buf_attach(git_buf *buf, char *ptr, size_t asize)
581+
int git_buf_attach(git_buf *buf, char *ptr, size_t asize)
581582
{
582583
git_buf_free(buf);
583584

@@ -588,9 +589,10 @@ void git_buf_attach(git_buf *buf, char *ptr, size_t asize)
588589
buf->asize = (asize < buf->size) ? buf->size + 1 : asize;
589590
else /* pass 0 to fall back on strlen + 1 */
590591
buf->asize = buf->size + 1;
591-
} else {
592-
git_buf_grow(buf, asize);
593592
}
593+
594+
ENSURE_SIZE(buf, asize);
595+
return 0;
594596
}
595597

596598
void git_buf_attach_notowned(git_buf *buf, const char *ptr, size_t size)

src/buffer.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ GIT_INLINE(bool) git_buf_is_allocated(const git_buf *buf)
3434
* For the cases where GIT_BUF_INIT cannot be used to do static
3535
* initialization.
3636
*/
37-
extern void git_buf_init(git_buf *buf, size_t initial_size);
37+
extern int git_buf_init(git_buf *buf, size_t initial_size);
3838

3939
/**
4040
* Resize the buffer allocation to make more space.
@@ -73,7 +73,7 @@ extern void git_buf_sanitize(git_buf *buf);
7373

7474
extern void git_buf_swap(git_buf *buf_a, git_buf *buf_b);
7575
extern char *git_buf_detach(git_buf *buf);
76-
extern void git_buf_attach(git_buf *buf, char *ptr, size_t asize);
76+
extern int git_buf_attach(git_buf *buf, char *ptr, size_t asize);
7777

7878
/* Populates a `git_buf` where the contents are not "owned" by the
7979
* buffer, and calls to `git_buf_free` will not free the given buf.

0 commit comments

Comments
 (0)