diff options
author | Nicolas Hillegeer <nicolas@hillegeer.com> | 2014-04-28 21:04:27 +0200 |
---|---|---|
committer | Thiago de Arruda <tpadilha84@gmail.com> | 2014-04-29 09:29:10 -0300 |
commit | 466b73108fa42b9f6b20bf32f5954ab33495a09a (patch) | |
tree | 3ef541f3802fbdb562ab4d23510df1650ea90d0d | |
parent | ce9c49f22234246f18d6e77a34908635bc6e6ece (diff) | |
download | rneovim-466b73108fa42b9f6b20bf32f5954ab33495a09a.tar.gz rneovim-466b73108fa42b9f6b20bf32f5954ab33495a09a.tar.bz2 rneovim-466b73108fa42b9f6b20bf32f5954ab33495a09a.zip |
garray: refactor ga_grow
- xrealloc will call xmalloc if the input pointer is NULL, no need to check
twice.
- use the early-quit idiom to decrease the indentation, which enhances
readability.
-rw-r--r-- | src/garray.c | 29 |
1 files changed, 16 insertions, 13 deletions
diff --git a/src/garray.c b/src/garray.c index d8a674d62d..8ad169b725 100644 --- a/src/garray.c +++ b/src/garray.c @@ -57,20 +57,23 @@ void ga_init(garray_T *gap, int itemsize, int growsize) /// @param n void ga_grow(garray_T *gap, int n) { - if (gap->ga_maxlen - gap->ga_len < n) { - if (n < gap->ga_growsize) { - n = gap->ga_growsize; - } - size_t new_len = (size_t)(gap->ga_itemsize * (gap->ga_len + n)); - char_u *pp = (gap->ga_data == NULL) - ? alloc((unsigned)new_len) - : xrealloc(gap->ga_data, new_len); - - size_t old_len = (size_t)(gap->ga_itemsize * gap->ga_maxlen); - memset(pp + old_len, 0, new_len - old_len); - gap->ga_maxlen = gap->ga_len + n; - gap->ga_data = pp; + if (gap->ga_maxlen - gap->ga_len >= n) { + // the garray still has enough space, do nothing + return; } + + // the garray grows by at least growsize (do we have a MIN macro somewhere?) + n = (n < gap->ga_growsize) ? gap->ga_growsize : n; + + size_t new_size = (size_t)(gap->ga_itemsize * (gap->ga_len + n)); + size_t old_size = (size_t)(gap->ga_itemsize * gap->ga_maxlen); + + // reallocate and clear the new memory + char_u *pp = xrealloc(gap->ga_data, new_size); + memset(pp + old_size, 0, new_size - old_size); + + gap->ga_maxlen = gap->ga_len + n; + gap->ga_data = pp; } /// Sort "gap" and remove duplicate entries. "gap" is expected to contain a |