From 63c984b897f009c07a73c3aaf11a24ecf9876411 Mon Sep 17 00:00:00 2001 From: David Woodhouse Date: Wed, 19 May 2021 10:45:39 +0100 Subject: [PATCH] Add more buf_append_base64() tests... and fix it. Signed-off-by: David Woodhouse --- tests/buftest.c | 15 +++++++++++++++ textbuf.c | 21 +++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/tests/buftest.c b/tests/buftest.c index a15cb2ef..25bd20f7 100644 --- a/tests/buftest.c +++ b/tests/buftest.c @@ -101,6 +101,7 @@ struct oc_text_buf { int error; }; +#define BUFTEST #include "../textbuf.c" #define assert(x) if (!(x)) { \ @@ -133,6 +134,20 @@ int main(void) buf_append_base64(buf, testbytes, -1, 0); assert(buf_error(buf) == -EINVAL); + buf->error = 0; + buf_truncate(buf); + + int ll; + + for (ll = 0; ll < 128; ll += 4) { + for (len = 0; len < 16384; len++) { + buf_truncate(buf); + buf_append_base64(buf, testbytes, len, ll); + assert(!buf_error(buf)); + if (len > 128) + len += len/2; + } + } buf_free(buf); return 0; } diff --git a/textbuf.c b/textbuf.c index a8b22a48..05d0bcc2 100644 --- a/textbuf.c +++ b/textbuf.c @@ -418,14 +418,17 @@ void buf_append_base64(struct oc_text_buf *buf, const void *bytes, int len, if (!buf || buf->error) return; - if (len < 0 || line_len < 0 || (line_len % 3)) { + if (len < 0 || line_len < 0 || (line_len & 3)) { buf->error = -EINVAL; return; } - unsigned int needed = ((len + 2u) / 3) * 4 + 1; - if (line_len) - needed += needed / line_len; + unsigned int needed = ((len + 2u) / 3) * 4; + + /* Line endings, but not for the last line if it reaches line_len */ + if (line_len && needed) + needed += (needed - 1) / line_len; + needed++; /* Allow for the trailing NUL */ if (needed >= (unsigned)(OC_BUF_MAX - buf->pos)) { buf->error = -E2BIG; @@ -435,6 +438,9 @@ void buf_append_base64(struct oc_text_buf *buf, const void *bytes, int len, if (buf_ensure_space(buf, needed)) return; +#ifdef BUFTEST + int orig_len = len, orig_pos = buf->pos; +#endif int ll = 0; while (len > 0) { if (line_len) { @@ -465,5 +471,12 @@ void buf_append_base64(struct oc_text_buf *buf, const void *bytes, int len, in += 3; len -= 3; } +#ifdef BUFTEST + if (buf->pos != orig_pos + needed - 1) { + printf("Used %d instead of calculated %d for %d bytes at line len %d\n", + buf->pos - orig_pos, needed, orig_len, line_len); + buf->error = -EIO; + } +#endif buf->data[buf->pos] = 0; } -- 2.49.0