File: vector.h

package info (click to toggle)
libnbd 1.22.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,636 kB
  • sloc: ansic: 53,855; ml: 12,311; sh: 8,499; python: 4,595; makefile: 2,902; perl: 165; cpp: 24
file content (305 lines) | stat: -rw-r--r-- 17,820 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/* nbdkit
 * Copyright Red Hat
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Red Hat nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/* Simple implementation of a vector.  It can be cheaply appended, and
 * more expensively inserted.  There are two main use-cases we
 * consider: lists of strings (either with a defined length, or
 * NULL-terminated), and lists of numbers.  It is generic so could be
 * used for lists of anything (eg. structs) where being able to append
 * easily is important.
 */

#ifndef NBDKIT_VECTOR_H
#define NBDKIT_VECTOR_H

#include <stdbool.h>
#include <assert.h>
#include <string.h>

#include "compiler-macros.h"
#include "static-assert.h"

#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wduplicate-decl-specifier"
#endif

/* Use of this macro defines a new type called ‘name’ containing an
 * extensible vector of ‘type’ elements.  For example:
 *
 *   DEFINE_VECTOR_TYPE (string_vector, char *);
 *
 * defines a new type called ‘string_vector’ as a vector of ‘char *’.
 * You can create variables of this type:
 *
 *   string_vector names = empty_vector;
 *
 * or
 *
 *   string_vector names;
 *   names = (string_vector)empty_vector;
 *
 * where ‘names.ptr[]’ will be an array of strings and ‘names.len’
 * will be the number of strings.  There are no get/set accessors.  To
 * iterate over the strings you can use the ‘.ptr’ field directly:
 *
 *   for (size_t i = 0; i < names.len; ++i)
 *     printf ("%s\n", names.ptr[i]);
 *
 * Initializing with ‘empty_vector’, or assigning the compound literal
 * ‘(string_vector)empty_vector’, sets ‘.ptr = NULL’ and ‘.len = 0’.
 *
 * DEFINE_VECTOR_TYPE also defines utility functions.  For the full
 * list see the definition below, but useful functions include:
 *
 * ‘name’_append  (eg. ‘string_vector_append’)
 *   - Append a new element at the end.  This operation is cheap.
 *
 * ‘name’_insert  (eg. ‘string_vector_insert’)
 *   - Insert a new element at the beginning, middle or end.  This
 *     operation is more expensive because existing elements may need
 *     to be copied around.
 *
 * Both functions extend the vector if required, and so both may fail
 * (returning -1) which you must check for.
 */
#define DEFINE_VECTOR_TYPE(name, type)                                  \
  struct name {                                                         \
    type *ptr;              /* Pointer to array of items. */            \
    size_t len;             /* Number of valid items in the array. */   \
    size_t cap;             /* Maximum number of items. */              \
  };                                                                    \
  typedef struct name name;                                             \
                                                                        \
  /* Reserve n elements at the end of the vector.  Note space is        \
   * allocated and capacity is increased, but the vector length is      \
   * not increased and the new elements are not initialized.            \
   */                                                                   \
  static inline int __attribute__ ((__unused__))                        \
  name##_reserve (name *v, size_t n)                                    \
  {                                                                     \
    return generic_vector_reserve ((struct generic_vector *)v, n,       \
                                   sizeof (type), false);               \
  }                                                                     \
                                                                        \
  /* Same as _reserve, but reserve exactly this number of elements      \
   * without any overhead.  Useful if you know ahead of time that you   \
   * will never need to extend the vector.                              \
   */                                                                   \
  static inline int __attribute__ ((__unused__))                        \
  name##_reserve_exactly (name *v, size_t n)                            \
  {                                                                     \
    return generic_vector_reserve ((struct generic_vector *)v,          \
                                   n, sizeof (type), true);             \
  }                                                                     \
                                                                        \
  /* Same as _reserve, but the allocation will be page aligned.  Note   \
   * that the machine page size must be divisible by sizeof (type).     \
   */                                                                   \
  static inline int __attribute__ ((__unused__))                        \
  name##_reserve_page_aligned (name *v, size_t n)                       \
  {                                                                     \
    return generic_vector_reserve_page_aligned ((struct generic_vector *)v, \
                                                n, sizeof (type));      \
  }                                                                     \
                                                                        \
  /* Insert list at i'th element.  i=0 => beginning  i=len => append */ \
  static inline int __attribute__ ((__unused__))                        \
  name##_insert_array (name *v, type *elems, size_t nr_elems, size_t i) \
  {                                                                     \
    assert (i <= v->len);                                               \
    if (v->len+nr_elems > v->cap) {                                     \
      if (name##_reserve (v, nr_elems) == -1) return -1;                \
    }                                                                   \
    memmove (&v->ptr[i+nr_elems], &v->ptr[i],                           \
             (v->len-i) * sizeof (elems[0]));                           \
    memcpy (&v->ptr[i], elems, nr_elems * sizeof (elems[0]));           \
    v->len += nr_elems;                                                 \
    return 0;                                                           \
  }                                                                     \
                                                                        \
  /* Insert at i'th element.  i=0 => beginning  i=len => append */      \
  static inline int __attribute__ ((__unused__))                        \
  name##_insert (name *v, type elem, size_t i)                          \
  {                                                                     \
    return name##_insert_array (v, &elem, 1, i);                        \
  }                                                                     \
                                                                        \
  /* Append a new element to the end of the vector. */                  \
  static inline int __attribute__ ((__unused__))                        \
  name##_append (name *v, type elem)                                    \
  {                                                                     \
    return name##_insert (v, elem, v->len);                             \
  }                                                                     \
                                                                        \
  /* Append list of new elements to the end of the vector. */           \
  static inline int __attribute__ ((__unused__))                        \
  name##_append_array (name *v, type *elems, size_t nr_elems)           \
  {                                                                     \
    return name##_insert_array (v, elems, nr_elems, v->len);            \
  }                                                                     \
                                                                        \
  /* Remove [i..i+nr-1] elements.  i=0 => beginning  i=len-1 => end */  \
  static inline void __attribute__ ((__unused__))                       \
  name##_remove_range (name *v, size_t nr, size_t i)                    \
  {                                                                     \
    assert (i < v->len);                                                \
    memmove (&v->ptr[i], &v->ptr[i+nr], (v->len-i-nr) * sizeof (type)); \
    v->len -= nr;                                                       \
  }                                                                     \
                                                                        \
  /* Remove i'th element.  i=0 => beginning  i=len-1 => end */          \
  static inline void __attribute__ ((__unused__))                       \
  name##_remove (name *v, size_t i)                                     \
  {                                                                     \
    name##_remove_range (v, 1, i);                                      \
  }                                                                     \
                                                                        \
  /* Remove all elements and deallocate the vector. */                  \
  static inline void __attribute__ ((__unused__))                       \
  name##_reset (name *v)                                                \
  {                                                                     \
    free (v->ptr);                                                      \
    v->ptr = NULL;                                                      \
    v->len = v->cap = 0;                                                \
  }                                                                     \
                                                                        \
  /* Iterate over the vector, calling f() on each element. */           \
  static inline void __attribute__ ((__unused__))                       \
  name##_iter (name *v, void (*f) (type elem))                          \
  {                                                                     \
    size_t i;                                                           \
    for (i = 0; i < v->len; ++i)                                        \
      f (v->ptr[i]);                                                    \
  }                                                                     \
                                                                        \
  /* Sort the elements of the vector. */                                \
  static inline void __attribute__ ((__unused__))                       \
  name##_sort (name *v,                                                 \
               int (*compare) (const type *p1, const type *p2))         \
  {                                                                     \
    qsort (v->ptr, v->len, sizeof (type), (void *)compare);             \
  }                                                                     \
                                                                        \
  /* Remove duplicate adjacent elements (uniq). */                      \
  static inline void __attribute__ ((__unused__))                       \
  name##_uniq (name *v,                                                 \
               int (*compare) (type const *p1, type const *p2))         \
  {                                                                     \
    size_t i;                                                           \
    for (i = 0; i < v->len - 1; ++i) {                                  \
      if (compare (&v->ptr[i], &v->ptr[i+1]) == 0) {                    \
        name##_remove (v, i);                                           \
        i--;                                                            \
      }                                                                 \
    }                                                                   \
  }                                                                     \
                                                                        \
  /* Search for an exactly matching element in the vector using a       \
   * binary search.  Returns a pointer to the element or NULL.          \
   */                                                                   \
  static inline type * __attribute__ ((__unused__))                     \
  name##_search (const name *v, const void *key,                        \
                 int (*compare) (const void *key, const type *v))       \
  {                                                                     \
    return bsearch (key, v->ptr, v->len, sizeof (type),                 \
                    (void *)compare);                                   \
  }                                                                     \
                                                                        \
  /* Make a new vector with the same elements. */                       \
  static inline int __attribute__ ((__unused__))                        \
  name##_duplicate (name *v, name *copy)                                \
  {                                                                     \
    /* Note it's allowed for v and copy to be the same pointer. */      \
    type const *vptr = v->ptr;                                          \
    type *newptr;                                                       \
    const size_t len = v->len * sizeof (type);                          \
                                                                        \
    newptr = malloc (len);                                              \
    if (newptr == NULL) return -1;                                      \
    memcpy (newptr, vptr, len);                                         \
    copy->ptr = newptr;                                                 \
    copy->len = copy->cap = v->len;                                     \
    return 0;                                                           \
  }                                                                     \
                                                                        \
  /* End with duplicate declaration, so callers must supply ';'. */     \
  struct name

#define empty_vector { .ptr = NULL, .len = 0, .cap = 0 }

/* This macro should only be used if:
 * - the vector contains pointers, and
 * - the pointed-to objects are:
 *   - neither const- nor volatile-qualified, and
 *   - allocated with malloc() or equivalent.
 */
#define ADD_VECTOR_EMPTY_METHOD(name)                                  \
  /* Call free() on each element of the vector, then reset the vector. \
   */                                                                  \
  static inline void __attribute__ ((__unused__))                      \
  name##_empty (name *v)                                               \
  {                                                                    \
    size_t i;                                                          \
    for (i = 0; i < v->len; ++i) {                                     \
      STATIC_ASSERT (TYPE_IS_POINTER (v->ptr[i]),                      \
                     _vector_contains_pointers);                       \
      free (v->ptr[i]);                                                \
    }                                                                  \
    name##_reset (v);                                                  \
  }                                                                    \
                                                                       \
  /* Force callers to supply ';'. */                                   \
  struct name

/* Convenience macro tying together DEFINE_VECTOR_TYPE() and
 * ADD_VECTOR_EMPTY_METHOD(). Inherit and forward the requirement for a
 * trailing semicolon from ADD_VECTOR_EMPTY_METHOD() to the caller.
 */
#define DEFINE_POINTER_VECTOR_TYPE(name, type) \
  DEFINE_VECTOR_TYPE (name, type);             \
  ADD_VECTOR_EMPTY_METHOD (name)

struct generic_vector {
  void *ptr;
  size_t len;
  size_t cap;
};

extern int generic_vector_reserve (struct generic_vector *v,
                                   size_t n, size_t itemsize,
                                   bool exactly);

extern int generic_vector_reserve_page_aligned (struct generic_vector *v,
                                                size_t n, size_t itemsize);

#endif /* NBDKIT_VECTOR_H */