Blender V5.3
MEM_safe_multiply.h
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#pragma once
6
7#include <cstddef>
8#include <cstdint>
9
11[[nodiscard]] inline bool MEM_size_safe_multiply(size_t a, size_t b, size_t *result)
12{
13 /* A size_t with its high-half bits all set to 1. */
14 const size_t high_bits = SIZE_MAX << (sizeof(size_t) * 8 / 2);
15 const size_t product = a * b;
16
17 if (product == 0) {
18 if (a == 0 || b == 0) {
19 *result = 0;
20 return true;
21 }
22 *result = 0;
23 return false;
24 }
25
26 /* If both A and B fit in N/2 bits, their product fits in N bits without
27 * the possibility of overflow. Otherwise verify with a divide. */
28 if ((high_bits & (a | b)) == 0 || product / b == a) {
29 *result = product;
30 return true;
31 }
32 *result = 0;
33 return false;
34}
35
37[[nodiscard]] inline bool MEM_size_safe_multiply(int64_t a, int64_t b, int64_t *result)
38{
39 /* Fast path for almost all cases. */
40 if ((uint64_t(a) | uint64_t(b)) >> 31 == 0) {
41 *result = a * b;
42 return true;
43 }
44
45 /* Check if resulting size is within range. */
46 *result = 0;
47 if (a < 0 || b < 0) {
48 return false;
49 }
50 if constexpr (sizeof(size_t) < sizeof(int64_t)) {
51 if (uint64_t(a) > SIZE_MAX || uint64_t(b) > SIZE_MAX) {
52 return false;
53 }
54 }
55
56 /* Compute with size_t version. */
57 size_t product;
58 if (!MEM_size_safe_multiply(size_t(a), size_t(b), &product) ||
59 uint64_t(product) > uint64_t(INT64_MAX))
60 {
61 return false;
62 }
63 *result = int64_t(product);
64 return true;
65}
#define SIZE_MAX
#define INT64_MAX
bool MEM_size_safe_multiply(size_t a, size_t b, size_t *result)
long long int int64_t
unsigned long long int uint64_t