xref: /freebsd-src/contrib/libcbor/src/cbor/internal/memory_utils.h (revision abd872540f24cfc7dbd1ea29b6918c7082a22108)
110ff414cSEd Maste /*
210ff414cSEd Maste  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
310ff414cSEd Maste  *
410ff414cSEd Maste  * libcbor is free software; you can redistribute it and/or modify
510ff414cSEd Maste  * it under the terms of the MIT license. See LICENSE for details.
610ff414cSEd Maste  */
710ff414cSEd Maste 
810ff414cSEd Maste #ifndef LIBCBOR_MEMORY_UTILS_H
910ff414cSEd Maste #define LIBCBOR_MEMORY_UTILS_H
1010ff414cSEd Maste 
1110ff414cSEd Maste #include <stdbool.h>
1210ff414cSEd Maste #include <string.h>
1310ff414cSEd Maste 
145d3e7166SEd Maste #include "cbor/common.h"
155d3e7166SEd Maste 
165d3e7166SEd Maste /** Can `a` and `b` be multiplied without overflowing size_t? */
175d3e7166SEd Maste _CBOR_NODISCARD
1810ff414cSEd Maste bool _cbor_safe_to_multiply(size_t a, size_t b);
1910ff414cSEd Maste 
205d3e7166SEd Maste /** Can `a` and `b` be added without overflowing size_t? */
215d3e7166SEd Maste _CBOR_NODISCARD
225d3e7166SEd Maste bool _cbor_safe_to_add(size_t a, size_t b);
235d3e7166SEd Maste 
24*abd87254SEd Maste /** Adds `a` and `b`, propagating zeros and returning 0 on overflow. */
255d3e7166SEd Maste _CBOR_NODISCARD
265d3e7166SEd Maste size_t _cbor_safe_signaling_add(size_t a, size_t b);
275d3e7166SEd Maste 
2810ff414cSEd Maste /** Overflow-proof contiguous array allocation
2910ff414cSEd Maste  *
3010ff414cSEd Maste  * @param item_size
3110ff414cSEd Maste  * @param item_count
3210ff414cSEd Maste  * @return Region of item_size * item_count bytes, or NULL if the total size
3310ff414cSEd Maste  * overflows size_t or the underlying allocator failed
3410ff414cSEd Maste  */
3510ff414cSEd Maste void* _cbor_alloc_multiple(size_t item_size, size_t item_count);
3610ff414cSEd Maste 
3710ff414cSEd Maste /** Overflow-proof contiguous array reallocation
3810ff414cSEd Maste  *
3910ff414cSEd Maste  * This implements the OpenBSD `reallocarray` functionality.
4010ff414cSEd Maste  *
4110ff414cSEd Maste  * @param pointer
4210ff414cSEd Maste  * @param item_size
4310ff414cSEd Maste  * @param item_count
4410ff414cSEd Maste  * @return Realloc'd of item_size * item_count bytes, or NULL if the total size
4510ff414cSEd Maste  * overflows size_t or the underlying allocator failed
4610ff414cSEd Maste  */
4710ff414cSEd Maste void* _cbor_realloc_multiple(void* pointer, size_t item_size,
4810ff414cSEd Maste                              size_t item_count);
4910ff414cSEd Maste 
5010ff414cSEd Maste #endif  // LIBCBOR_MEMORY_UTILS_H
51