Add and use bx_strndup() in 'tools' module for cross-platform compatibility

This commit is contained in:
Thomas Jensen 2021-04-07 21:21:44 +02:00
parent f620c1b19b
commit 8a6d0d3315
No known key found for this signature in database
GPG Key ID: A4ACEE270D0FB7DB
2 changed files with 34 additions and 2 deletions

View File

@ -694,12 +694,11 @@ char *trimdup(char *s, char *e)
while (e > s && (*e == ' ' || *e == '\t')) {
--e;
}
return strndup(s, e - s + 1);
return bx_strndup(s, e - s + 1);
}
int tag_is_valid(char *tag)
{
if (tag == NULL) {
@ -715,4 +714,26 @@ int tag_is_valid(char *tag)
}
char *bx_strndup(const char *s, size_t n)
{
if (s == NULL) {
return NULL;
}
size_t len = strlen(s);
if (n < len) {
len = n;
}
char *result = (char *) malloc(len + 1);
if (result == NULL) {
return NULL;
}
result[len] = '\0';
return (char *) memcpy(result, s, len);
}
/*EOF*/ /* vim: set sw=4: */

View File

@ -115,6 +115,17 @@ char *trimdup(char *s, char *e);
int tag_is_valid(char *tag);
/**
* Duplicate at most `n` bytes from the given string `s`. Memory for the new string is obtained with `malloc()`, and
* can be freed with `free()`. A terminating null byte is added. We include this implementation because the libc's
* `strndup()` is not consistently available across all platforms.
* @param s a string
* @param n maximum number of characters to copy (excluding the null byte)
* @returns a new string, or `NULL` if either `s` was also `NULL`, or out of memory
*/
char *bx_strndup(const char *s, size_t n);
#endif
/*EOF*/ /* vim: set cindent sw=4: */