From d3b0c5dfb079d3140c9494ec3b6309f20c6e7b28 Mon Sep 17 00:00:00 2001 From: YuQing <384681@qq.com> Date: Thu, 26 Mar 2020 15:51:31 +0800 Subject: [PATCH] add function fast_buffer_set_capacity --- src/fast_buffer.c | 32 +++++++++++++++++++++----------- src/fast_buffer.h | 13 ++++++++++++- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/fast_buffer.c b/src/fast_buffer.c index 7efc974..8111025 100644 --- a/src/fast_buffer.c +++ b/src/fast_buffer.c @@ -42,32 +42,42 @@ void fast_buffer_destroy(FastBuffer *buffer) } } -int fast_buffer_check_capacity(FastBuffer *buffer, const int capacity) +int fast_buffer_set_capacity(FastBuffer *buffer, const int capacity) { int alloc_size; + int new_capacity; char *buff; - if (buffer->alloc_size >= capacity) - { - return 0; + new_capacity = (capacity > buffer->length) ? + capacity : (buffer->length + 1); + if (buffer->alloc_size >= new_capacity) { + if (new_capacity > 1024) { + alloc_size = 2048; + } else if (new_capacity > 512) { + alloc_size = 1024; + } else if (new_capacity > 256) { + alloc_size = 512; + } else { + alloc_size = 256; + } + } else { + alloc_size = buffer->alloc_size * 2; } - alloc_size = buffer->alloc_size * 2; - while (alloc_size <= capacity) - { + + while (alloc_size < new_capacity) { alloc_size *= 2; } buff = (char *)malloc(alloc_size); - if (buff == NULL) - { + if (buff == NULL) { logError("file: "__FILE__", line: %d, " "malloc %d bytes fail", __LINE__, alloc_size); return ENOMEM; } - if (buffer->length > 0) - { + if (buffer->length > 0) { memcpy(buff, buffer->data, buffer->length); + *(buff + buffer->length) = '\0'; } free(buffer->data); diff --git a/src/fast_buffer.h b/src/fast_buffer.h index 866b406..f55bf2d 100644 --- a/src/fast_buffer.h +++ b/src/fast_buffer.h @@ -44,7 +44,18 @@ void fast_buffer_destroy(FastBuffer *buffer); #define fast_buffer_check(buffer, inc_len) \ fast_buffer_check_inc_size(buffer, inc_len) -int fast_buffer_check_capacity(FastBuffer *buffer, const int capacity); +int fast_buffer_set_capacity(FastBuffer *buffer, const int capacity); + +static inline int fast_buffer_check_capacity(FastBuffer *buffer, + const int capacity) +{ + if (buffer->alloc_size >= capacity) + { + return 0; + } + + return fast_buffer_set_capacity(buffer, capacity); +} static inline int fast_buffer_check_inc_size(FastBuffer *buffer, const int inc_size)