ascii-chat 0.6.0
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
bytes.h
Go to the documentation of this file.
1#pragma once
2
34#include <stdint.h>
35#include <stdbool.h>
36#include <stddef.h>
37#include <limits.h>
38
39/* ============================================================================
40 * Unaligned Memory Access Helpers
41 * ============================================================================
42 * These functions safely read/write multi-byte values from/to potentially
43 * unaligned memory addresses.
44 */
45
63static inline uint16_t bytes_read_u16_unaligned(const void *ptr) {
64 uint16_t value;
65 __builtin_memcpy(&value, ptr, sizeof(value));
66 return value;
67}
68
86static inline uint32_t bytes_read_u32_unaligned(const void *ptr) {
87 uint32_t value;
88 __builtin_memcpy(&value, ptr, sizeof(value));
89 return value;
90}
91
109static inline void bytes_write_u16_unaligned(void *ptr, uint16_t value) {
110 __builtin_memcpy(ptr, &value, sizeof(value));
111}
112
130static inline void bytes_write_u32_unaligned(void *ptr, uint32_t value) {
131 __builtin_memcpy(ptr, &value, sizeof(value));
132}
133
134/* ============================================================================
135 * Big-Endian (Network Byte Order) Access
136 * ============================================================================
137 * These functions read/write values in big-endian byte order, commonly used
138 * for network protocols and SSH agent communication.
139 */
140
155static inline uint32_t read_u32_be(const uint8_t *ptr) {
156 return ((uint32_t)ptr[0] << 24) | ((uint32_t)ptr[1] << 16) | ((uint32_t)ptr[2] << 8) | (uint32_t)ptr[3];
157}
158
174static inline void write_u32_be(uint8_t *ptr, uint32_t value) {
175 ptr[0] = (uint8_t)(value >> 24);
176 ptr[1] = (uint8_t)(value >> 16);
177 ptr[2] = (uint8_t)(value >> 8);
178 ptr[3] = (uint8_t)(value);
179}
180
181/* ============================================================================
182 * Safe Arithmetic Functions
183 * ============================================================================
184 */
185
222static inline bool bytes_safe_size_mul(size_t a, size_t b, size_t *result) {
223 if (result == NULL) {
224 return true; // ERROR: NULL pointer
225 }
226
227 if (a != 0 && b > SIZE_MAX / a) {
228 *result = 0;
229 return true; // ERROR: Overflow detected
230 }
231
232 *result = a * b;
233 return false; // SUCCESS
234}
235
unsigned short uint16_t
Definition common.h:57
unsigned int uint32_t
Definition common.h:58
unsigned char uint8_t
Definition common.h:56
Application limits and constraints.