1 /*
2 * Copyright (c) 2021 Calvin Rose
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to
6 * deal in the Software without restriction, including without limitation the
7 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 * sell copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 * IN THE SOFTWARE.
21 */
22 
23 #ifndef JANET_VECTOR_H_defined
24 #define JANET_VECTOR_H_defined
25 
26 #ifndef JANET_AMALG
27 #include "features.h"
28 #include <janet.h>
29 #endif
30 
31 /*
32  * vector code modified from
33  * https://github.com/nothings/stb/blob/master/stretchy_buffer.h
34 */
35 
36 /* This is mainly used code such as the assembler or compiler, which
37  * need vector like data structures that are only garbage collected in case
38  * of an error, and normally rely on malloc/free. */
39 
40 #define janet_v_free(v)         (((v) != NULL) ? (janet_sfree(janet_v__raw(v)), 0) : 0)
41 #define janet_v_push(v, x)      (janet_v__maybegrow(v, 1), (v)[janet_v__cnt(v)++] = (x))
42 #define janet_v_pop(v)          (janet_v_count(v) ? janet_v__cnt(v)-- : 0)
43 #define janet_v_count(v)        (((v) != NULL) ? janet_v__cnt(v) : 0)
44 #define janet_v_last(v)         ((v)[janet_v__cnt(v) - 1])
45 #define janet_v_empty(v)        (((v) != NULL) ? (janet_v__cnt(v) = 0) : 0)
46 #define janet_v_flatten(v)      (janet_v_flattenmem((v), sizeof(*(v))))
47 
48 #define janet_v__raw(v) ((int32_t *)(v) - 2)
49 #define janet_v__cap(v) janet_v__raw(v)[0]
50 #define janet_v__cnt(v) janet_v__raw(v)[1]
51 
52 #define janet_v__needgrow(v, n)  ((v) == NULL || janet_v__cnt(v) + (n) >= janet_v__cap(v))
53 #define janet_v__maybegrow(v, n) (janet_v__needgrow((v), (n)) ? janet_v__grow((v), (n)) : 0)
54 #define janet_v__grow(v, n)      ((v) = janet_v_grow((v), (n), sizeof(*(v))))
55 
56 /* Actual functions defined in vector.c */
57 void *janet_v_grow(void *v, int32_t increment, int32_t itemsize);
58 void *janet_v_flattenmem(void *v, int32_t itemsize);
59 
60 #endif
61