src/util/vector.h (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#ifndef VECTOR_H
7#define VECTOR_H
8
9#include "util/common.h"
10
11#define DECLARE_VECTOR(NAME, TYPE) \
12 struct NAME { \
13 TYPE* vector; \
14 size_t size; \
15 size_t capacity; \
16 }; \
17 void NAME ## Init(struct NAME* vector, size_t capacity); \
18 void NAME ## Deinit(struct NAME* vector); \
19 TYPE* NAME ## GetPointer(struct NAME* vector, size_t location); \
20 void NAME ## Resize(struct NAME* vector, ssize_t change); \
21 void NAME ## Shift(struct NAME* vector, size_t location, size_t difference); \
22 void NAME ## Unshift(struct NAME* vector, size_t location, size_t difference); \
23 void NAME ## EnsureCapacity(struct NAME* vector, size_t capacity); \
24 size_t NAME ## Size(struct NAME* vector); \
25
26#define DEFINE_VECTOR(NAME, TYPE) \
27 void NAME ## Init(struct NAME* vector, size_t capacity) { \
28 vector->size = 0; \
29 if (capacity == 0) { \
30 capacity = 4; \
31 } \
32 vector->capacity = capacity; \
33 vector->vector = malloc(sizeof(TYPE) * capacity); \
34 } \
35 void NAME ## Deinit(struct NAME* vector) { \
36 free(vector->vector); \
37 vector->vector = 0; \
38 vector->capacity = 0; \
39 } \
40 TYPE* NAME ## GetPointer(struct NAME* vector, size_t location) { \
41 return &vector->vector[location]; \
42 } \
43 void NAME ## Resize(struct NAME* vector, ssize_t change) { \
44 if (change > 0) { \
45 NAME ## EnsureCapacity(vector, vector->size + change); \
46 } \
47 vector->size += change; \
48 } \
49 void NAME ## EnsureCapacity(struct NAME* vector, size_t capacity) { \
50 if (capacity <= vector->capacity) { \
51 return; \
52 } \
53 while (capacity > vector->capacity) { \
54 vector->capacity <<= 1; \
55 } \
56 vector->vector = realloc(vector->vector, vector->capacity * sizeof(TYPE)); \
57 } \
58 void NAME ## Shift(struct NAME* vector, size_t location, size_t difference) { \
59 memmove(&vector->vector[location], &vector->vector[location + difference], (vector->size - location - difference) * sizeof(TYPE)); \
60 vector->size -= difference; \
61 } \
62 void NAME ## Unshift(struct NAME* vector, size_t location, size_t difference) { \
63 NAME ## Resize(vector, difference); \
64 memmove(&vector->vector[location + difference], &vector->vector[location], (vector->size - location - difference) * sizeof(TYPE)); \
65 } \
66 size_t NAME ## Size(struct NAME* vector) { \
67 return vector->size; \
68 } \
69
70#endif