Skip to content

Instantly share code, notes, and snippets.

@mu578
Last active February 12, 2023 20:40
Show Gist options
  • Save mu578/6c5598e1940e7968c7105b63e61c7d07 to your computer and use it in GitHub Desktop.
Save mu578/6c5598e1940e7968c7105b63e61c7d07 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
# define sys_malloc malloc
# define sys_realloc realloc
# define sys_free free
# define sys_memset memset
# define sys_memmove memmove
# define sys_scope_begin do {
# define sys_scope_end } while (0)
# define sys_cast(_Tp, __var) (_Tp)__var
# define sys_bsize(__n_item, __s_item) \
((sys_cast(const size_t, (__n_item))) * (sys_cast(const size_t, (__s_item))))
# define sys_cksize(__n) \
((__n) > 0 && sys_cast(const size_t, (__n)) < sys_cast(const size_t, (1024 * 16)))
# define sys_ckaddr(__addr_ptr) \
(((__addr_ptr) != NULL) ? 1 : 0)
# define sys_cknull(__addr_ptr) \
(((__addr_ptr) == NULL) ? 1 : 0)
# define sys_dealloc(__addr_ptr) \
sys_scope_begin \
if (sys_ckaddr(__addr_ptr)) { \
sys_free(__addr_ptr); \
(__addr_ptr) = NULL; \
} \
sys_scope_end
# define sys_realloc_type(_Tp, __addr_ptr, __n_item) \
sys_scope_begin \
size_t __n_size = sys_bsize(__n_item, sizeof(_Tp)); \
_Tp * __addr = NULL; \
if (sys_cknull(__addr_ptr) && sys_cksize(__n_size)) { \
__addr = sys_cast(_Tp *, sys_malloc(__n_size)); \
(__addr_ptr) = __addr; \
} else if (sys_ckaddr(__addr_ptr)) && sys_cksize(__n_size)) { \
__addr = sys_cast(_Tp *, sys_realloc((__addr_ptr), __n_size)); \
if (sys_cknull(__addr)) { \
sys_dealloc((__addr_ptr)); \
} else { \
(__addr_ptr) = __addr; \
} \
} else { \
sys_dealloc(__addr_ptr); \
} \
sys_scope_end
# define sys_pad_left_type(_Tp, __addr_ptr, __n_item, __n_pad, __v_pad) \
sys_scope_begin \
sys_realloc_type(_Tp, (__addr_ptr), sys_bsize((__n_item) + (__n_pad), sizeof(_Tp))); \
if (sys_ckaddr(__addr_ptr)) { \
sys_memmove((__addr_ptr) + (__n_pad), (__addr_ptr), sys_bsize((__n_item), sizeof(_Tp))); \
sys_memset((__addr_ptr), (__v_pad), sys_bsize((__n_pad), sizeof(_Tp))); \
} \
sys_scope_end
# define sys_pad_right_type(_Tp, __addr_ptr, __n_item, __n_pad, __v_pad) \
sys_scope_begin \
sys_realloc_type(_Tp, (__addr_ptr), sys_bsize((__n_item) + (__n_pad), sizeof(_Tp))); \
if (sys_ckaddr(__addr_ptr)) { \
sys_memset((__addr_ptr) + (__n_item), (__v_pad), sys_bsize((__n_pad), sizeof(_Tp))); \
} \
sys_scope_end
/* EOF */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment