strings: Add apfl_string_blank() and doucment apfl_string_copy()

It's really easy to accidentally pass an uninitialized string as dst into
the copy function, which will result in an free() call to an arbitrary
pointer. Maybe it's a better idea to not deinit the dst string before
copying? The documentation at least makes it more clear and the new
apfl_string_blank() function makes it easy to create an empty string.
This commit is contained in:
Laria 2022-01-02 17:01:51 +01:00
parent 92dc89d3ca
commit eea7e8f840
3 changed files with 20 additions and 6 deletions

View file

@ -50,10 +50,17 @@ int apfl_string_view_cmp(struct apfl_string_view, struct apfl_string_view);
#define apfl_string_cmp(a, b) apfl_string_view_cmp(apfl_string_view_from(a), apfl_string_view_from(b))
#define apfl_string_eq(a, b) (apfl_string_cmp((a), (b)) == 0)
struct apfl_string apfl_string_blank(void);
void apfl_string_deinit(struct apfl_string *);
bool apfl_string_copy(struct apfl_string *dst, struct apfl_string_view src);
struct apfl_string apfl_string_move(struct apfl_string *src);
/**
* Copies a string from src to dst. dst must point to a blank string.
* Returns true on success, false otherwise (if the necessary memory could not
* be allocated).
*/
bool apfl_string_copy(struct apfl_string *dst, struct apfl_string_view src);
struct apfl_string_builder {
char *bytes;
size_t len;

View file

@ -111,7 +111,7 @@ expect_error_of_type(struct parser_test *pt, enum apfl_error_type want)
static struct apfl_string
new_string(struct parser_test *pt, const char *in)
{
struct apfl_string out = { .bytes = NULL, .len = 0 };
struct apfl_string out = apfl_string_blank();
if (!apfl_string_copy(&out, apfl_string_view_from(in))) {
test_fatalf(pt->t, "Failed copying string in new_string");
}

View file

@ -54,12 +54,20 @@ apfl_string_view_cmp(struct apfl_string_view a, struct apfl_string_view b)
return a.len > b.len ? 1 : -1;
}
struct apfl_string
apfl_string_blank(void)
{
return (struct apfl_string) {
.bytes = NULL,
.len = 0,
};
}
void
apfl_string_deinit(struct apfl_string *string)
{
free(string->bytes);
string->len = 0;
string->bytes = NULL;
*string = apfl_string_blank();
}
bool
@ -80,8 +88,7 @@ struct apfl_string
apfl_string_move(struct apfl_string *src)
{
struct apfl_string out = *src;
src->bytes = NULL;
src->len = 0;
*src = apfl_string_blank();
return out;
}