]> git.ipfire.org Git - thirdparty/zlib-ng.git/commitdiff
Added unit test for zng_calloc_aligned to ensure that it always returns 64-byte align...
authorNathan Moinvaziri <nathan@nathanm.com>
Mon, 14 Mar 2022 18:46:02 +0000 (11:46 -0700)
committerHans Kristian Rosbach <hk-github@circlestorm.org>
Tue, 15 Mar 2022 17:32:15 +0000 (18:32 +0100)
test/test_aligned_alloc.cc [new file with mode: 0644]

diff --git a/test/test_aligned_alloc.cc b/test/test_aligned_alloc.cc
new file mode 100644 (file)
index 0000000..43324d3
--- /dev/null
@@ -0,0 +1,44 @@
+/* test_aligned_alloc.cc - Test zng_calloc_aligned and zng_cfree_aligned */
+
+#include <stdlib.h>
+#include <errno.h>
+#include <stdio.h>
+
+extern "C" {
+#  include "zbuild.h"
+#  include "zutil.h"
+}
+
+#include <gtest/gtest.h>
+
+void *zng_calloc_unaligned(void *opaque, unsigned items, unsigned size) {
+    uint8_t *pointer = (uint8_t *)calloc(1, (items * size) + 2);
+    if (pointer == NULL)
+        return pointer;
+    /* Store whether or not our allocation is aligned */
+    *pointer = ((uint64_t)(intptr_t)pointer + 1) % 2 == 0;
+    pointer++;
+    if (*pointer) {
+        /* Return pointer that is off by one */
+        pointer++;
+    }
+    return (void *)pointer;
+}
+
+void zng_cfree_unaligned(void *opaque, void *ptr) {
+    uint8_t *pointer = (uint8_t *)ptr;
+    pointer--;
+    /* Get whether or not our original memory pointer was aligned */
+    if (*pointer) {
+        /* Return original aligned pointer to free() */
+        pointer--;
+    }
+    free(pointer);
+}
+
+TEST(zalloc, aligned_64) {
+    void *return_ptr = zng_calloc_aligned(zng_calloc_unaligned, 0, 1, 100, 64);
+    ASSERT_TRUE(return_ptr != NULL);
+    EXPECT_EQ((intptr_t)return_ptr % 64, 0);
+    zng_cfree_aligned(zng_cfree_unaligned, 0, return_ptr);
+}