aboutsummaryrefslogtreecommitdiff
path: root/client/libacron/private/helpers.c
diff options
context:
space:
mode:
Diffstat (limited to 'client/libacron/private/helpers.c')
-rw-r--r--client/libacron/private/helpers.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/client/libacron/private/helpers.c b/client/libacron/private/helpers.c
new file mode 100644
index 0000000..4d4f3c8
--- /dev/null
+++ b/client/libacron/private/helpers.c
@@ -0,0 +1,64 @@
+/*
+ * Created by yuuta on 7/19/22.
+ */
+
+#include "helpers.h"
+#include "log.h"
+#include "common.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+
+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
+} \ No newline at end of file