mirror of
https://github.com/neovim/neovim.git
synced 2025-02-25 18:55:25 -06:00
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.
This commit is contained in:
parent
ce9c49f222
commit
466b73108f
29
src/garray.c
29
src/garray.c
@ -57,20 +57,23 @@ void ga_init(garray_T *gap, int itemsize, int growsize)
|
|||||||
/// @param n
|
/// @param n
|
||||||
void ga_grow(garray_T *gap, int n)
|
void ga_grow(garray_T *gap, int n)
|
||||||
{
|
{
|
||||||
if (gap->ga_maxlen - gap->ga_len < n) {
|
if (gap->ga_maxlen - gap->ga_len >= n) {
|
||||||
if (n < gap->ga_growsize) {
|
// the garray still has enough space, do nothing
|
||||||
n = gap->ga_growsize;
|
return;
|
||||||
}
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
/// Sort "gap" and remove duplicate entries. "gap" is expected to contain a
|
||||||
|
Loading…
Reference in New Issue
Block a user