ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
overflow.h
Go to the documentation of this file.
1#pragma once
2
41
42#include <limits.h>
43#include <stdbool.h>
44#include <stddef.h>
45#include <stdint.h>
46
47#include "../common.h"
48
49#ifdef __cplusplus
50extern "C" {
51#endif
52
53/* ============================================================================
54 * Overflow Prediction Functions
55 * ============================================================================
56 */
57
77static inline bool size_mul_would_overflow(size_t a, size_t b) {
78 // Handle zero case (no overflow)
79 if (a == 0 || b == 0)
80 return false;
81
82 // Check if a * b would exceed SIZE_MAX
83 // This is safe: if a != 0, we can divide
84 return b > SIZE_MAX / a;
85}
86
105static inline bool size_add_would_overflow(size_t a, size_t b) {
106 return b > SIZE_MAX - a;
107}
108
109/* ============================================================================
110 * Checked Arithmetic Operations
111 * ============================================================================
112 */
113
140static inline asciichat_error_t checked_size_mul(size_t a, size_t b,
141 size_t *result) {
142 if (size_mul_would_overflow(a, b)) {
143 return 1; // ERROR_OVERFLOW - see asciichat_errno.h for exact value
144 }
145 *result = a * b;
146 return 0; // ASCIICHAT_OK
147}
148
170static inline asciichat_error_t checked_size_add(size_t a, size_t b,
171 size_t *result) {
172 if (size_add_would_overflow(a, b)) {
173 return 1; // ERROR_OVERFLOW
174 }
175 *result = a + b;
176 return 0; // ASCIICHAT_OK
177}
178
205static inline asciichat_error_t
206checked_size_mul3(size_t width, size_t height, size_t depth, size_t *result) {
207 // First multiply width * height
208 if (size_mul_would_overflow(width, height)) {
209 return 1; // ERROR_OVERFLOW
210 }
211 size_t intermediate = width * height;
212
213 // Then multiply result * depth
214 if (size_mul_would_overflow(intermediate, depth)) {
215 return 1; // ERROR_OVERFLOW
216 }
217 *result = intermediate * depth;
218 return 0; // ASCIICHAT_OK
219}
220
221/* ============================================================================
222 * Unchecked Variants (For Performance-Critical Code)
223 * ============================================================================
224 */
225
240#define SIZE_MUL_SAFE(a, b) \
241 (size_mul_would_overflow(a, b) ? SIZE_MAX : (a) * (b))
242
256#define SIZE_ADD_SAFE(a, b) \
257 (size_add_would_overflow(a, b) ? SIZE_MAX : (a) + (b))
258
260
261#ifdef __cplusplus
262}
263#endif
unsigned int height
Definition fft.c:24
unsigned int width
Definition fft.c:24
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
⚙️ Common definitions, error codes, macros, and types shared throughout the application