ascii-chat 0.6.0
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
overflow.h
Go to the documentation of this file.
1#pragma once
2
42#include <stddef.h>
43#include <stdint.h>
44#include <stdbool.h>
45#include <limits.h>
46
47#include "../common.h"
48
49/* ============================================================================
50 * Overflow Prediction Functions
51 * ============================================================================
52 */
53
73static inline bool size_mul_would_overflow(size_t a, size_t b) {
74 // Handle zero case (no overflow)
75 if (a == 0 || b == 0)
76 return false;
77
78 // Check if a * b would exceed SIZE_MAX
79 // This is safe: if a != 0, we can divide
80 return b > SIZE_MAX / a;
81}
82
101static inline bool size_add_would_overflow(size_t a, size_t b) {
102 return b > SIZE_MAX - a;
103}
104
105/* ============================================================================
106 * Checked Arithmetic Operations
107 * ============================================================================
108 */
109
134static inline asciichat_error_t checked_size_mul(size_t a, size_t b, size_t *result) {
135 if (size_mul_would_overflow(a, b)) {
136 return 1; // ERROR_OVERFLOW - see asciichat_errno.h for exact value
137 }
138 *result = a * b;
139 return 0; // ASCIICHAT_OK
140}
141
163static inline asciichat_error_t checked_size_add(size_t a, size_t b, size_t *result) {
164 if (size_add_would_overflow(a, b)) {
165 return 1; // ERROR_OVERFLOW
166 }
167 *result = a + b;
168 return 0; // ASCIICHAT_OK
169}
170
195static inline asciichat_error_t checked_size_mul3(size_t width, size_t height, size_t depth, size_t *result) {
196 // First multiply width * height
197 if (size_mul_would_overflow(width, height)) {
198 return 1; // ERROR_OVERFLOW
199 }
200 size_t intermediate = width * height;
201
202 // Then multiply result * depth
203 if (size_mul_would_overflow(intermediate, depth)) {
204 return 1; // ERROR_OVERFLOW
205 }
206 *result = intermediate * depth;
207 return 0; // ASCIICHAT_OK
208}
209
210/* ============================================================================
211 * Unchecked Variants (For Performance-Critical Code)
212 * ============================================================================
213 */
214
229#define SIZE_MUL_SAFE(a, b) (size_mul_would_overflow(a, b) ? SIZE_MAX : (a) * (b))
230
244#define SIZE_ADD_SAFE(a, b) (size_add_would_overflow(a, b) ? SIZE_MAX : (a) + (b))
245
asciichat_error_t
Error and exit codes - unified status values (0-255)
Definition error_codes.h:46
Application limits and constraints.