vec: vec_try_append
Essentially a method to attempt to append data but without doing any reallocation - stay within the bounds of the capacity.
This commit is contained in:
@@ -36,7 +36,10 @@ void vec_init(vec_t *, u64);
|
||||
void vec_free(vec_t *);
|
||||
u8 *vec_data(vec_t *);
|
||||
|
||||
// Append, possibly reallocating memory
|
||||
void vec_append(vec_t *, const void *const, u64);
|
||||
// Try to append without allocating memory
|
||||
bool vec_try_append(vec_t *, const void *const, u64);
|
||||
void vec_ensure_free(vec_t *, u64);
|
||||
void vec_clone(vec_t *, vec_t *);
|
||||
|
||||
|
||||
14
src/vec.c
14
src/vec.c
@@ -81,10 +81,24 @@ void vec_append(vec_t *vec, const void *const ptr, u64 size)
|
||||
if (!vec)
|
||||
return;
|
||||
vec_ensure_free(vec, size);
|
||||
if (ptr)
|
||||
memcpy(vec_data(vec) + vec->size, ptr, size);
|
||||
vec->size += size;
|
||||
}
|
||||
|
||||
bool vec_try_append(vec_t *vec, const void *const ptr, u64 size)
|
||||
{
|
||||
if (!vec || vec->capacity - vec->size < size)
|
||||
return false;
|
||||
if (ptr)
|
||||
{
|
||||
void *newptr = vec_data(vec) + vec->size;
|
||||
memcpy(newptr, ptr, size);
|
||||
}
|
||||
vec->size += size;
|
||||
return true;
|
||||
}
|
||||
|
||||
void vec_clone(vec_t *dest, vec_t *src)
|
||||
{
|
||||
if (!src || !dest)
|
||||
|
||||
Reference in New Issue
Block a user