From 34643b8a8d954b77d1928f39f380e3c09b05e7dc Mon Sep 17 00:00:00 2001 From: XaviDCR92 Date: Sat, 21 Mar 2020 13:14:48 +0100 Subject: Various changes and improvements - Replaced int by specific, more meaningful error codes. - C99 states realloc can be safely called using NULL pointers. - New function dynstr_dup(). --- include/dynstr.h | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) (limited to 'include') diff --git a/include/dynstr.h b/include/dynstr.h index a2e8f41..a545b81 100644 --- a/include/dynstr.h +++ b/include/dynstr.h @@ -45,7 +45,7 @@ /** * Convenience macro that calls dynstr_append and returns its error code if failed. */ -#define dynstr_append_or_ret(d, format, ...) {const int err = dynstr_append(d, format, ## __VA_ARGS__); if (err) return err;} +#define dynstr_append_or_ret(d, format, ...) {const enum dynstr_err err = dynstr_append(d, format, ## __VA_ARGS__); if (err) return err;} /** * Convenience macro that calls dynstr_append and returns zero if failed. @@ -65,6 +65,19 @@ struct dynstr size_t len; /**< String length, null character not included. */ }; +/** + * List of errors that this library might return. + * @note If using GNU C extensions, this errors can be translated into other + * types by using the convenience macros above. + */ +enum dynstr_err +{ + DYNSTR_OK, /**< Operation was successful. */ + DYNSTR_ERR_ALLOC, /**< Alloc operation failed. */ + DYNSTR_ERR_INIT, /**< Dynamic string was not initialized. */ + DYNSTR_ERR_SRC /**< Source string has invalid parameters. */ +}; + /** * Reportedly, it initializes an empty string with zero length. * @attention Always call this function when creating a dynstr instance. @@ -78,9 +91,25 @@ void dynstr_init(struct dynstr *d); * dynamic string. * @param d Dynamic string where new string will be appended. * @param format String literal in printf format. - * @return Returns 0 if successful, 1 if alloc operation failed. + * @return Returns one of the following error codes: + * # DYNSTR_OK if successful. + * # DYNSTR_ERR_ALLOC if no more memory is available. + */ +enum dynstr_err dynstr_append(struct dynstr *d, const char *format, ...); + +/** + * This function duplicates a dynamic string to another instance. + * @attention Destination instance must be initialized before calling + * this function. + * @attention Since this function performs a deep copy, please remember to + * free the source instance if no longer used to avoid memory leaks. + * @return Returns one of the following error codes: + * # DYNSTR_OK if successful. + * # DYNSTR_ERR_ALLOC if no more memory is available. + * # DYNSTR_ERR_INIT if destination dynamic string was not initialized. + * # DYNSTR_ERR_SRC if source dynamic string has no length or data. */ -int dynstr_append(struct dynstr *d, const char *format, ...); +enum dynstr_err dynstr_dup(struct dynstr *dst, const struct dynstr *src); /** * This function frees memory used by the dynamic string. -- cgit v1.2.3