Skip to content

Commit

Permalink
Add functions to alloc/free aligned memory
Browse files Browse the repository at this point in the history
  • Loading branch information
dacap committed Aug 1, 2023
1 parent 56ebc35 commit 5838e40
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
18 changes: 18 additions & 0 deletions base/memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,21 @@ void operator delete[](void* ptr) LAF_NOEXCEPT
}

#endif

void* base_aligned_alloc(std::size_t bytes, std::size_t alignment)
{
#if LAF_WINDOWS
return _aligned_malloc(bytes, alignment);
#else
return aligned_malloc(alignment, bytes);
#endif
}

void base_aligned_free(void* mem)
{
#if LAF_WINDOWS
_aligned_free(mem);
#else
free(mem);
#endif
}
25 changes: 25 additions & 0 deletions base/memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,37 @@

#include <cstddef>

#ifdef __cplusplus
#ifdef __STDCPP_DEFAULT_NEW_ALIGNMENT__
static constexpr size_t base_alignment = __STDCPP_DEFAULT_NEW_ALIGNMENT__;
#else
static constexpr size_t base_alignment = 1;
#endif

constexpr size_t base_align_size(const size_t n,
const size_t alignment = base_alignment) {
size_t remaining = (n % alignment);
size_t aligned_n = n + (remaining ? (alignment - remaining): 0);
if (aligned_n > alignment)
return aligned_n;
else
return alignment;
}
#endif

void* base_malloc (std::size_t bytes);
void* base_malloc0(std::size_t bytes);
void* base_realloc(void* mem, std::size_t bytes);
void base_free (void* mem);
char* base_strdup (const char* string);

#ifdef __cplusplus
void* base_aligned_alloc(std::size_t bytes, std::size_t alignment = base_alignment);
#else
void* base_aligned_alloc(std::size_t bytes, std::size_t alignment);
#endif
void base_aligned_free(void* mem);

#ifdef LAF_MEMLEAK
void base_memleak_init();
void base_memleak_exit();
Expand Down
34 changes: 34 additions & 0 deletions base/memory_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// LAF Base Library
// Copyright (c) 2023 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include <gtest/gtest.h>

#include "base/memory.h"

TEST(Memory, AlignedAlloc)
{
void* a = base_aligned_alloc(9, 8);
void* b = base_aligned_alloc(1, 16);
void* c = base_aligned_alloc(16, 16);
void* d = base_aligned_alloc(17, 16);
void* e = base_aligned_alloc(33, 32);
EXPECT_EQ(0, (((size_t)a) % 8));
EXPECT_EQ(0, (((size_t)b) % 16));
EXPECT_EQ(0, (((size_t)c) % 16));
EXPECT_EQ(0, (((size_t)d) % 16));
EXPECT_EQ(0, (((size_t)e) % 32));
base_aligned_free(a);
base_aligned_free(b);
base_aligned_free(c);
base_aligned_free(d);
base_aligned_free(e);
}

int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

0 comments on commit 5838e40

Please sign in to comment.