diff --git a/src/apfl.h b/src/apfl.h index 2428b20..a27557f 100644 --- a/src/apfl.h +++ b/src/apfl.h @@ -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; diff --git a/src/parser_test.c b/src/parser_test.c index f42f3de..bd2fd9e 100644 --- a/src/parser_test.c +++ b/src/parser_test.c @@ -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"); } diff --git a/src/strings.c b/src/strings.c index 5246077..b2228c7 100644 --- a/src/strings.c +++ b/src/strings.c @@ -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; }