]> git.kaiwu.me - klib.git/commitdiff
Only canonicalise if there is room, and add docs
authorJohn Marshall <jm18@sanger.ac.uk>
Wed, 24 Jul 2013 13:08:25 +0000 (14:08 +0100)
committerJohn Marshall <jm18@sanger.ac.uk>
Wed, 24 Jul 2013 13:08:25 +0000 (14:08 +0100)
We could increment SIZE to ensure there would be room, but that would
disadvantage people using kstrings for binary data in power-of-2-sized
blocks.  Instead document that SIZE=KS.l+1 will ensure NUL-termination.

This fixes a bug in the previous version when the l<m invariant does not
hold (kputc_()/etc and manual manipulation only maintain the weaker l<=m);
hattip Rob Davies.

kstring.h

index 4c803b81560daa5d3b549d768c60641f8f14fd46..360a5987a77fb7099a964dcb17b8f262a64dee4f 100644 (file)
--- a/kstring.h
+++ b/kstring.h
@@ -78,6 +78,9 @@ extern "C" {
 }
 #endif
 
+/* Ensures that the string has space for at least SIZE bytes, and ensures that
+ * it is NUL-terminated if there is room.  Thus ks_resize(&s,s.l+1) can be used
+ * to make sure that a kstring_t is both allocated and NUL-terminated.  */
 static inline int ks_resize(kstring_t *s, size_t size)
 {
        if (s->m < size) {
@@ -89,7 +92,7 @@ static inline int ks_resize(kstring_t *s, size_t size)
                else
                        return -1;
        }
-       s->s[s->l] = '\0';
+       if (s->l < s->m) s->s[s->l] = '\0';
        return 0;
 }