1 /*
2 * Copyright © 2021 Valve Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Mike Blumenkrantz <[email protected]>
25 */
26
27 #pragma once
28
29 #include <stdlib.h>
30 #include <inttypes.h>
31 #include <stdbool.h>
32 #include "macros.h"
33
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
37
38 static inline void *
ptralloc(size_t base_size,unsigned member_count,size_t * member_sizes,void *** members)39 ptralloc(size_t base_size, unsigned member_count, size_t *member_sizes, void ***members)
40 {
41 size_t size = base_size;
42 for (unsigned i = 0; i < member_count; i++)
43 size += member_sizes[i];
44
45 uint8_t *ptr = (uint8_t*)malloc(size);
46 if (!ptr)
47 return NULL;
48
49 size_t accum = base_size;
50 for (unsigned i = 0; i < member_count; i++) {
51 *members[i] = (void*)(ptr + accum);
52 accum += member_sizes[i];
53 }
54 return (void*)ptr;
55 }
56
57 static inline void *
ptrzalloc(size_t base_size,unsigned member_count,size_t * member_sizes,void *** members)58 ptrzalloc(size_t base_size, unsigned member_count, size_t *member_sizes, void ***members)
59 {
60 size_t size = base_size;
61 for (unsigned i = 0; i < member_count; i++)
62 size += member_sizes[i];
63
64 uint8_t *ptr = (uint8_t*)calloc(1, size);
65 if (!ptr)
66 return NULL;
67
68 size_t accum = base_size;
69 for (unsigned i = 0; i < member_count; i++) {
70 *members[i] = (void*)(ptr + accum);
71 accum += member_sizes[i];
72 }
73 return (void*)ptr;
74 }
75
76 #ifdef __cplusplus
77 }
78 #endif
79