From ded2b9429c5399c9d6b3b5f125d36826211fde16 Mon Sep 17 00:00:00 2001 From: Ozan Tezcan Date: Sun, 4 Apr 2021 12:58:07 +0300 Subject: [PATCH] sc_buf set_rpos and set_wpos checks. Don't compact on reserve. (#65) * sc_buf set_rpos and set_wpos checks. Don't compact on reserve. --- buffer/buf_test.c | 9 +++++++++ buffer/sc_buf.c | 44 ++++++++++++++++++++++++-------------------- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/buffer/buf_test.c b/buffer/buf_test.c index 0bc4c08..c9cb091 100644 --- a/buffer/buf_test.c +++ b/buffer/buf_test.c @@ -10,6 +10,15 @@ void test1() const char* xstr; struct sc_buf buf, buf2; + sc_buf_init(&buf, 100); + sc_buf_set_rpos(&buf, 1); + assert(sc_buf_valid(&buf) == false); + sc_buf_clear(&buf); + assert(sc_buf_valid(&buf) == true); + sc_buf_set_wpos(&buf, 101); + assert(sc_buf_valid(&buf) == false); + sc_buf_term(&buf); + sc_buf_init(&buf, 100); sc_buf_init(&buf2, 100); sc_buf_put_str(&buf, "s"); diff --git a/buffer/sc_buf.c b/buffer/sc_buf.c index 0c55933..4010b2f 100644 --- a/buffer/sc_buf.c +++ b/buffer/sc_buf.c @@ -93,30 +93,28 @@ bool sc_buf_reserve(struct sc_buf *buf, uint32_t len) if (buf->wpos + len > buf->cap) { if (buf->ref) { - return false; + goto error; } - sc_buf_compact(buf); - - if (buf->wpos + len > buf->cap) { - size = ((buf->cap + len + 4095) / 4096) * 4096; - if (size > buf->limit || buf->cap >= SC_BUF_SIZE_MAX - 4096) { - buf->error |= SC_BUF_OOM; - return false; - } - - tmp = sc_buf_realloc(buf->mem, size); - if (tmp == NULL) { - buf->error |= SC_BUF_OOM; - return false; - } - - buf->cap = size; - buf->mem = tmp; + size = ((buf->cap + len + 4095) / 4096) * 4096; + if (size > buf->limit || buf->cap >= SC_BUF_SIZE_MAX - 4096) { + goto error; } + + tmp = sc_buf_realloc(buf->mem, size); + if (tmp == NULL) { + goto error; + } + + buf->cap = size; + buf->mem = tmp; } return true; + +error: + buf->error |= SC_BUF_OOM; + return false; } bool sc_buf_shrink(struct sc_buf *buf, uint32_t len) @@ -182,13 +180,19 @@ uint32_t sc_buf_rpos(struct sc_buf *buf) void sc_buf_set_rpos(struct sc_buf *buf, uint32_t pos) { - assert(buf->wpos >= pos); + if (pos > buf->wpos) { + buf->error |= SC_BUF_CORRUPT; + } + buf->rpos = pos; } void sc_buf_set_wpos(struct sc_buf *buf, uint32_t pos) { - assert(pos <= buf->cap); + if (pos > buf->cap) { + buf->error |= SC_BUF_CORRUPT; + } + buf->wpos = pos; }