mirror of
https://github.com/ascii-boxes/boxes.git
synced 2025-01-05 13:38:58 +01:00
Add and use bx_strndup() in 'tools' module for cross-platform compatibility
This commit is contained in:
parent
f620c1b19b
commit
8a6d0d3315
25
src/tools.c
25
src/tools.c
@ -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: */
|
||||
|
11
src/tools.h
11
src/tools.h
@ -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: */
|
||||
|
Loading…
Reference in New Issue
Block a user