ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
bytes.h
Go to the documentation of this file.
1#pragma once
2
33
34#include <limits.h>
35#include <stdbool.h>
36#include <stddef.h>
37#include <stdint.h>
38#include <string.h>
39
40#ifdef __cplusplus
41extern "C" {
42#endif
43
44/* ============================================================================
45 * Unaligned Memory Access Helpers
46 * ============================================================================
47 * These functions safely read/write multi-byte values from/to potentially
48 * unaligned memory addresses.
49 */
50
68static inline uint16_t bytes_read_u16_unaligned(const void *ptr) {
69 uint16_t value;
70 memcpy(&value, ptr, sizeof(value));
71 return value;
72}
73
91static inline uint32_t bytes_read_u32_unaligned(const void *ptr) {
92 uint32_t value;
93 memcpy(&value, ptr, sizeof(value));
94 return value;
95}
96
114static inline void bytes_write_u16_unaligned(void *ptr, uint16_t value) {
115 memcpy(ptr, &value, sizeof(value));
116}
117
135static inline void bytes_write_u32_unaligned(void *ptr, uint32_t value) {
136 memcpy(ptr, &value, sizeof(value));
137}
138
139/* ============================================================================
140 * Big-Endian (Network Byte Order) Access
141 * ============================================================================
142 * These functions read/write values in big-endian byte order, commonly used
143 * for network protocols and SSH agent communication.
144 */
145
160static inline uint32_t read_u32_be(const uint8_t *ptr) {
161 return ((uint32_t)ptr[0] << 24) | ((uint32_t)ptr[1] << 16) |
162 ((uint32_t)ptr[2] << 8) | (uint32_t)ptr[3];
163}
164
181static inline void write_u32_be(uint8_t *ptr, uint32_t value) {
182 ptr[0] = (uint8_t)(value >> 24);
183 ptr[1] = (uint8_t)(value >> 16);
184 ptr[2] = (uint8_t)(value >> 8);
185 ptr[3] = (uint8_t)(value);
186}
187
188/* ============================================================================
189 * Safe Arithmetic Functions
190 * ============================================================================
191 */
192
229static inline bool bytes_safe_size_mul(size_t a, size_t b, size_t *result) {
230 if (result == NULL) {
231 return true; // ERROR: NULL pointer
232 }
233
234 if (a != 0 && b > SIZE_MAX / a) {
235 *result = 0;
236 return true; // ERROR: Overflow detected
237 }
238
239 *result = a * b;
240 return false; // SUCCESS
241}
242
244
245#ifdef __cplusplus
246}
247#endif
unsigned short uint16_t
unsigned int uint32_t
unsigned char uint8_t
🔤 String Manipulation and Shell Escaping Utilities