[dstring] Ignore embedded nulls for appendstr

I don't remember why I thought it was a good idea to respect embedded
nul characters, but doing so makes appendstr O(N) instead of O(1) (or
O(N^2) instead of O(N) for multiple appends of n chars (N = sum(n)).
Also, this makes appendstr consistent with dasprintf.
This commit is contained in:
Bill Currie 2024-09-14 17:05:18 +09:00
parent 4329537b1b
commit edc03c22f9
2 changed files with 10 additions and 4 deletions

View file

@ -140,12 +140,12 @@ void dstring_copystr (dstring_t *dstr, const char *str);
void dstring_copysubstr (dstring_t *dstr, const char *str, size_t len); void dstring_copysubstr (dstring_t *dstr, const char *str, size_t len);
/** Append the null terminated string to the end of the dstring. /** Append the null terminated string to the end of the dstring.
The dstring does not have to be null terminated but will become so. The dstring does not have to be null terminated but will become so.
However, any embedded nulls will be treated as the end of the dstring. \note any embedded nulls will be ignored.
*/ */
void dstring_appendstr (dstring_t *dstr, const char *str); void dstring_appendstr (dstring_t *dstr, const char *str);
/** Append up to len bytes from the string to the end of the dstring. /** Append up to len bytes from the string to the end of the dstring.
The dstring does not have to be null terminated but will become so. The dstring does not have to be null terminated but will become so.
However, any embedded nulls will be treated as the end of the dstring. \note any embedded nulls will be ignored.
*/ */
void dstring_appendsubstr (dstring_t *dstr, const char *str, size_t len); void dstring_appendsubstr (dstring_t *dstr, const char *str, size_t len);
/** Insert the null terminated string into the dstring at pos. The dstring /** Insert the null terminated string into the dstring at pos. The dstring

View file

@ -271,9 +271,12 @@ dstring_copysubstr (dstring_t *dstr, const char *str, size_t len)
VISIBLE void VISIBLE void
dstring_appendstr (dstring_t *dstr, const char *str) dstring_appendstr (dstring_t *dstr, const char *str)
{ {
size_t pos = strnlen (dstr->str, dstr->size); size_t pos = dstr->size;
size_t len = strlen (str); size_t len = strlen (str);
if (pos && !dstr->str[pos - 1]) {
pos--;
}
dstr->size = pos + len + 1; dstr->size = pos + len + 1;
dstring_adjust (dstr); dstring_adjust (dstr);
strcpy (dstr->str + pos, str); strcpy (dstr->str + pos, str);
@ -282,8 +285,11 @@ dstring_appendstr (dstring_t *dstr, const char *str)
VISIBLE void VISIBLE void
dstring_appendsubstr (dstring_t *dstr, const char *str, size_t len) dstring_appendsubstr (dstring_t *dstr, const char *str, size_t len)
{ {
size_t pos = strnlen (dstr->str, dstr->size); size_t pos = dstr->size;
if (pos && !dstr->str[pos - 1]) {
pos--;
}
len = strnlen (str, len); len = strnlen (str, len);
dstr->size = pos + len + 1; dstr->size = pos + len + 1;
dstring_adjust (dstr); dstring_adjust (dstr);