| 1 | /* |
| 2 | * Copyright (c) 2014-2020 Pavel Kalvoda <[email protected]> |
| 3 | * |
| 4 | * libcbor is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the MIT license. See LICENSE for details. |
| 6 | */ |
| 7 | |
| 8 | #ifndef LIBCBOR_MEMORY_UTILS_H |
| 9 | #define LIBCBOR_MEMORY_UTILS_H |
| 10 | |
| 11 | #include <stdbool.h> |
| 12 | #include <string.h> |
| 13 | |
| 14 | #include "cbor/common.h" |
| 15 | |
| 16 | /** Can `a` and `b` be multiplied without overflowing size_t? */ |
| 17 | _CBOR_NODISCARD |
| 18 | bool _cbor_safe_to_multiply(size_t a, size_t b); |
| 19 | |
| 20 | /** Can `a` and `b` be added without overflowing size_t? */ |
| 21 | _CBOR_NODISCARD |
| 22 | bool _cbor_safe_to_add(size_t a, size_t b); |
| 23 | |
| 24 | /** Adds `a` and `b`, propagating zeros and returning 0 on overflow. */ |
| 25 | _CBOR_NODISCARD |
| 26 | size_t _cbor_safe_signaling_add(size_t a, size_t b); |
| 27 | |
| 28 | /** Overflow-proof contiguous array allocation |
| 29 | * |
| 30 | * @param item_size |
| 31 | * @param item_count |
| 32 | * @return Region of item_size * item_count bytes, or NULL if the total size |
| 33 | * overflows size_t or the underlying allocator failed |
| 34 | */ |
| 35 | void* _cbor_alloc_multiple(size_t item_size, size_t item_count); |
| 36 | |
| 37 | /** Overflow-proof contiguous array reallocation |
| 38 | * |
| 39 | * This implements the OpenBSD `reallocarray` functionality. |
| 40 | * |
| 41 | * @param pointer |
| 42 | * @param item_size |
| 43 | * @param item_count |
| 44 | * @return Realloc'd of item_size * item_count bytes, or NULL if the total size |
| 45 | * overflows size_t or the underlying allocator failed |
| 46 | */ |
| 47 | void* _cbor_realloc_multiple(void* pointer, size_t item_size, |
| 48 | size_t item_count); |
| 49 | |
| 50 | #endif // LIBCBOR_MEMORY_UTILS_H |