Skip to content

Commit

Permalink
text: introduce text_bytes_alloc0 utility function
Browse files Browse the repository at this point in the history
Heap allocates a zero terminated string of the given range.
Freeing is the caller's responsibility.

Checks for unsigned integer overflow i.e. passing SIZE_MAX
as len will always fail because there is no room for the
terminating NUL byte. This is important as EPOS is defined
to be SIZE_MAX.
  • Loading branch information
martanne committed Jan 10, 2016
1 parent 713f90f commit e6e077c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
12 changes: 12 additions & 0 deletions text.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <fcntl.h>
#include <errno.h>
#include <wchar.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
Expand Down Expand Up @@ -1441,6 +1442,17 @@ size_t text_bytes_get(Text *txt, size_t pos, size_t len, char *buf) {
return len - rem;
}

char *text_bytes_alloc0(Text *txt, size_t pos, size_t len) {
if (len == SIZE_MAX)
return NULL;
char *buf = malloc(len+1);
if (!buf)
return NULL;
len = text_bytes_get(txt, pos, len, buf);
buf[len] = '\0';
return buf;
}

size_t text_size(Text *txt) {
return txt->size;
}
Expand Down
3 changes: 3 additions & 0 deletions text.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ bool text_byte_get(Text*, size_t pos, char *buf);
* indicates how many bytes were copied into `buf'. WARNING buf will not be
* NUL terminated. */
size_t text_bytes_get(Text*, size_t pos, size_t len, char *buf);
/* allocate a NUL terminated buffer and fill at most `len' bytes
* starting at `pos'. Freeing is the caller's responsibility! */
char *text_bytes_alloc0(Text*, size_t pos, size_t len);

Iterator text_iterator_get(Text*, size_t pos);
bool text_iterator_valid(const Iterator*);
Expand Down

0 comments on commit e6e077c

Please sign in to comment.