Skip to content

Commit

Permalink
Add array_grow function
Browse files Browse the repository at this point in the history
  • Loading branch information
patperry committed Nov 9, 2011
1 parent 4d668dc commit aa5f843
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 6 deletions.
3 changes: 2 additions & 1 deletion Makefile.am
Expand Up @@ -3,9 +3,10 @@
AM_CPPFLAGS = -Ilib -Isrc

noinst_LIBRARIES = \
libcore.a
libcore.a

libcore_a_SOURCES = \
src/coreutil.c \
src/coreutil.h \
src/hash.h \
src/hashset.c \
Expand Down
19 changes: 19 additions & 0 deletions src/coreutil.c
@@ -0,0 +1,19 @@
#include <assert.h>
#include "coreutil.h"


size_t array_grow(size_t count, size_t capacity, size_t delta,
size_t capacity_max)
{
assert(count <= capacity);
assert(capacity <= capacity_max);
assert(delta <= capacity_max - count);

size_t capacity_min = count + delta;
while (capacity < capacity_min) {
capacity = ARRAY_GROW1(capacity, capacity_max);
}

return capacity;
}

14 changes: 10 additions & 4 deletions src/coreutil.h
@@ -1,6 +1,9 @@
#ifndef CORE_COREUTIL_H
#define CORE_COREUTIL_H

#include <stddef.h>


#define MAX(x,y) ((y) > (x) ? (y) : (x))
#define MIN(x,y) ((y) < (x) ? (y) : (x))

Expand All @@ -9,13 +12,16 @@


/* 0, 5, 11, 20, 34, 55, 86, 133, 203, 308, ... */
#define ARRAY_DELTA(n) \
#define ARRAY_DELTA1(n) \
((n) ? ((n) >> 1) + 4 : 5)

#define ARRAY_GROW(n,nmax) \
(((n) <= (nmax) - ARRAY_DELTA(n)) \
? (n) + ARRAY_DELTA(n) \
#define ARRAY_GROW1(n,nmax) \
(((n) <= (nmax) - ARRAY_DELTA1(n)) \
? (n) + ARRAY_DELTA1(n) \
: (nmax))

size_t array_grow(size_t count, size_t capacity, size_t delta,
size_t capacity_max);


#endif /* CORE_COREUTIL_H */
2 changes: 1 addition & 1 deletion src/pqueue.c
Expand Up @@ -85,7 +85,7 @@ int pqueue_ensure_capacity(struct pqueue *q, size_t n)

static void pqueue_grow(struct pqueue *q)
{
q->capacity = ARRAY_GROW(q->capacity, SIZE_MAX);
q->capacity = ARRAY_GROW1(q->capacity, SIZE_MAX);
q->base = xrealloc(q->base, q->capacity * q->width);
}

Expand Down

0 comments on commit aa5f843

Please sign in to comment.