/* * Created by yuuta on 7/19/22. */ #include "helpers.h" #include "log.h" #include "common.h" #include #include #include #include int alloc(void *existing, unsigned int count, unsigned int bytes, bool zero_out, void **out) { const unsigned int size = count * bytes; void *ptr; if (!(ptr = realloc(existing, size))) { const int e = errno; LOGEV("Cannot %sallocate %d bytes of memory: %s (%d).", existing ? "re" : "", size, strerror2(e), e); return AC_E_MEMORY_ALLOCATION; } if (!existing && zero_out) { memset(ptr, 0, size); } *out = ptr; return AC_E_OK; } int strdup2(const char *str, char **out) { char *str2; if (!(str2 = strdup(str))) { const int e = errno; LOGEV("Cannot duplicate string '%s': %s (%d).", str, strerror2(e), e); return AC_E_MEMORY_ALLOCATION; } *out = str2; return AC_E_OK; } static _Thread_local char err_buf[1024]; char *strerror2(int errnum) { #ifdef WIN32 /* Win32 strerror(3) is thread-safe. */ return strerror(errnum); #else int r; if ((strerror_r(errnum, err_buf, sizeof(err_buf) / sizeof(char)))) { snprintf(err_buf, 1024, "%d (%d)", errnum, r); } return err_buf; #endif }