← Back to C-Kernel-Engine Docs Doxygen Source Documentation
Loading...
Searching...
No Matches
expand_group_row_indices_checked.c
Go to the documentation of this file.
1#include <stdint.h>
2#include <stddef.h>
3
4static int region_ok(const void *ptr, size_t count, size_t element_bytes) {
5 return ptr && (uintptr_t)ptr % element_bytes == 0 &&
6 count <= SIZE_MAX / element_bytes &&
7 (uintptr_t)ptr <= UINTPTR_MAX - count * element_bytes;
8}
9
10static int overlaps(const void *a, size_t a_bytes,
11 const void *b, size_t b_bytes) {
12 uintptr_t x = (uintptr_t)a, y = (uintptr_t)b;
13 return x < y + b_bytes && y < x + a_bytes;
14}
15
16/* Turn ordered group sizes into an identity row index and its owning group.
17 * All counts are validated before either output is written. */
19 const int32_t *group_counts, size_t group_count_elements,
20 size_t groups, size_t rows,
21 int32_t *row_indices, size_t row_index_elements,
22 int32_t *owner_indices, size_t owner_index_elements) {
23 if (!groups || !rows || groups > INT32_MAX || rows > INT32_MAX ||
24 group_count_elements < groups || row_index_elements < rows ||
25 owner_index_elements < rows)
26 return -2;
27 if (!region_ok(group_counts, group_count_elements, sizeof(int32_t)) ||
28 !region_ok(row_indices, row_index_elements, sizeof(int32_t)) ||
29 !region_ok(owner_indices, owner_index_elements, sizeof(int32_t)))
30 return -1;
31 if (overlaps(group_counts, group_count_elements * sizeof(int32_t),
32 row_indices, row_index_elements * sizeof(int32_t)) ||
33 overlaps(group_counts, group_count_elements * sizeof(int32_t),
34 owner_indices, owner_index_elements * sizeof(int32_t)) ||
35 overlaps(row_indices, row_index_elements * sizeof(int32_t),
36 owner_indices, owner_index_elements * sizeof(int32_t)))
37 return -1;
38 size_t total = 0;
39 for (size_t group = 0; group < groups; ++group) {
40 int32_t count = group_counts[group];
41 if (count <= 0 || (size_t)count > rows - total) return -2;
42 total += (size_t)count;
43 }
44 if (total != rows) return -2;
45 size_t row = 0;
46 for (size_t group = 0; group < groups; ++group) {
47 for (int32_t item = 0; item < group_counts[group]; ++item, ++row) {
48 row_indices[row] = (int32_t)row;
49 owner_indices[row] = (int32_t)group;
50 }
51 }
52 return 0;
53}
int ck_expand_group_row_indices_checked_i32(const int32_t *group_counts, size_t group_count_elements, size_t groups, size_t rows, int32_t *row_indices, size_t row_index_elements, int32_t *owner_indices, size_t owner_index_elements)
static int region_ok(const void *ptr, size_t count, size_t element_bytes)
static int overlaps(const void *a, size_t a_bytes, const void *b, size_t b_bytes)
const uint8_t size_t count
Definition true_bpe.h:211