1 | /* |
2 | * Copyright 2016-2018 Uber Technologies, Inc. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | /** @file stackAlloc.h |
17 | * @brief Macro to provide cross-platform mechanism for allocating variable |
18 | * length arrays on the stack. |
19 | */ |
20 | |
21 | #ifndef STACKALLOC_H |
22 | #define STACKALLOC_H |
23 | |
24 | #include <assert.h> |
25 | #include <string.h> |
26 | |
27 | #ifdef H3_HAVE_VLA |
28 | |
29 | #define STACK_ARRAY_CALLOC(type, name, numElements) \ |
30 | assert((numElements) > 0); \ |
31 | type name##Buffer[(numElements)]; \ |
32 | memset(name##Buffer, 0, (numElements) * sizeof(type)); \ |
33 | type* name = name##Buffer |
34 | |
35 | #elif defined(H3_HAVE_ALLOCA) |
36 | |
37 | #ifdef _MSC_VER |
38 | |
39 | #include <malloc.h> |
40 | |
41 | #define STACK_ARRAY_CALLOC(type, name, numElements) \ |
42 | assert((numElements) > 0); \ |
43 | type* name = (type*)_alloca(sizeof(type) * (numElements)); \ |
44 | memset(name, 0, sizeof(type) * (numElements)) |
45 | |
46 | #else |
47 | |
48 | #include <alloca.h> |
49 | |
50 | #define STACK_ARRAY_CALLOC(type, name, numElements) \ |
51 | assert((numElements) > 0); \ |
52 | type* name = (type*)alloca(sizeof(type) * (numElements)); \ |
53 | memset(name, 0, sizeof(type) * (numElements)) |
54 | |
55 | #endif |
56 | |
57 | #else |
58 | |
59 | #error \ |
60 | "This platform does not support stack array allocation, please submit an issue on https://github.com/uber/h3 to report this error" |
61 | |
62 | #endif |
63 | |
64 | #endif |
65 | |