Created
May 4, 2024 02:57
-
-
Save m1lkweed/31630bf36535a72daadf40808b712a85 to your computer and use it in GitHub Desktop.
Handy memory-manipulation functions that don't exist in the standard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <string.h> | |
// Copy a byte pattern into memory, repeating src if dest_len > src_len | |
void *memwrap(void *dest, const void *src, size_t dest_len, size_t src_len){ | |
if((dest == NULL) || (src == NULL) || (dest_len == 0U) || | |
(src_len == 0U) || (dest == src)){ | |
goto return_early; | |
} | |
if(dest_len <= src_len){ | |
memmove(dest, src, dest_len); | |
}else{ | |
size_t i; | |
uint8_t *dest_bytes = dest; | |
for(i = 0; i < (dest_len - src_len); i += src_len){ | |
memmove(&dest_bytes[i], src, src_len); | |
} | |
memmove(&dest_bytes[i], src, dest_len - i); | |
} | |
return_early: | |
return dest; | |
} | |
#define vd_idx(a, sz, x) ((void*)((uint8_t*)(a) + (sz) * (x))) | |
// Swap two regions of memory that are each at least num_bytes bytes long | |
void memswap(void *a, void *b, size_t num_bytes){ | |
if((a == NULL) || (b == NULL) || (num_bytes == 0U)) | |
goto return_early; | |
for(size_t i = 0; i < num_bytes; ++i){ | |
uint8_t tmp = *(uint8_t*)vd_idx(a, 1, i); | |
memcpy(vd_idx(a, 1, i), vd_idx(b, 1, i), 1); | |
memcpy(vd_idx(b, 1, i), &tmp, 1); | |
} | |
return_early: | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment