diff options
author | Lars Hjemli <hjemli@gmail.com> | 2010-11-10 03:57:18 (JST) |
---|---|---|
committer | Lars Hjemli <hjemli@gmail.com> | 2010-11-10 08:22:41 (JST) |
commit | 958a95b37891098133369e835a2ab687e0dfa9dc (patch) | |
tree | 31bcd62973d381b072b91da15528c48c6fc14a41 | |
parent | 52558a6d39d52e2b2968b622534b0ffa4da285cb (diff) | |
download | cgit-958a95b37891098133369e835a2ab687e0dfa9dc.zip cgit-958a95b37891098133369e835a2ab687e0dfa9dc.tar.gz |
Add vector utility functions
Signed-off-by: Lars Hjemli <hjemli@gmail.com>
-rw-r--r-- | Makefile | 1 | ||||
-rw-r--r-- | vector.c | 38 | ||||
-rw-r--r-- | vector.h | 17 |
3 files changed, 56 insertions, 0 deletions
@@ -103,6 +103,7 @@ OBJECTS += ui-stats.o | |||
103 | OBJECTS += ui-summary.o | 103 | OBJECTS += ui-summary.o |
104 | OBJECTS += ui-tag.o | 104 | OBJECTS += ui-tag.o |
105 | OBJECTS += ui-tree.o | 105 | OBJECTS += ui-tree.o |
106 | OBJECTS += vector.o | ||
106 | 107 | ||
107 | ifdef NEEDS_LIBICONV | 108 | ifdef NEEDS_LIBICONV |
108 | EXTLIBS += -liconv | 109 | EXTLIBS += -liconv |
diff --git a/vector.c b/vector.c new file mode 100644 index 0000000..0863908 --- /dev/null +++ b/vector.c | |||
@@ -0,0 +1,38 @@ | |||
1 | #include <stdio.h> | ||
2 | #include <string.h> | ||
3 | #include <errno.h> | ||
4 | #include "vector.h" | ||
5 | |||
6 | static int grow(struct vector *vec, int gently) | ||
7 | { | ||
8 | size_t new_alloc; | ||
9 | void *new_data; | ||
10 | |||
11 | new_alloc = vec->alloc * 3 / 2; | ||
12 | if (!new_alloc) | ||
13 | new_alloc = 8; | ||
14 | new_data = realloc(vec->data, new_alloc * vec->size); | ||
15 | if (!new_data) { | ||
16 | if (gently) | ||
17 | return ENOMEM; | ||
18 | perror("vector.c:grow()"); | ||
19 | exit(1); | ||
20 | } | ||
21 | vec->data = new_data; | ||
22 | vec->alloc = new_alloc; | ||
23 | return 0; | ||
24 | } | ||
25 | |||
26 | int vector_push(struct vector *vec, const void *data, int gently) | ||
27 | { | ||
28 | int rc; | ||
29 | |||
30 | if (vec->count == vec->alloc && (rc = grow(vec, gently))) | ||
31 | return rc; | ||
32 | if (data) | ||
33 | memmove(vec->data + vec->count * vec->size, data, vec->size); | ||
34 | else | ||
35 | memset(vec->data + vec->count * vec->size, 0, vec->size); | ||
36 | vec->count++; | ||
37 | return 0; | ||
38 | } | ||
diff --git a/vector.h b/vector.h new file mode 100644 index 0000000..c64eb1f --- /dev/null +++ b/vector.h | |||
@@ -0,0 +1,17 @@ | |||
1 | #ifndef CGIT_VECTOR_H | ||
2 | #define CGIT_VECTOR_H | ||
3 | |||
4 | #include <stdlib.h> | ||
5 | |||
6 | struct vector { | ||
7 | size_t size; | ||
8 | size_t count; | ||
9 | size_t alloc; | ||
10 | void *data; | ||
11 | }; | ||
12 | |||
13 | #define VECTOR_INIT(type) {sizeof(type), 0, 0, NULL} | ||
14 | |||
15 | int vector_push(struct vector *vec, const void *data, int gently); | ||
16 | |||
17 | #endif /* CGIT_VECTOR_H */ | ||