aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/memory.cpp
blob: a0d911786a7fdd44bcd3c021def18ad155cc494f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/except.h>
#include <zencore/fmtutils.h>
#include <zencore/intmath.h>
#include <zencore/memory.h>
#include <zencore/testing.h>
#include <zencore/zencore.h>

#include <cstdlib>

#if ZEN_USE_MIMALLOC
ZEN_THIRD_PARTY_INCLUDES_START
#	include <mimalloc.h>
ZEN_THIRD_PARTY_INCLUDES_END
#endif

namespace zen {

//////////////////////////////////////////////////////////////////////////

static void*
AlignedAllocImpl(size_t Size, size_t Alignment)
{
	// aligned_alloc() states that size must be a multiple of alignment. Some
	// platforms return null if this requirement isn't met.
	Size = (Size + Alignment - 1) & ~(Alignment - 1);

#if ZEN_USE_MIMALLOC
	return mi_aligned_alloc(Alignment, Size);
#elif ZEN_PLATFORM_WINDOWS
	return _aligned_malloc(Size, Alignment);
#else
	return std::aligned_alloc(Alignment, Size);
#endif
}

void
AlignedFreeImpl(void* ptr)
{
	if (ptr == nullptr)
		return;

#if ZEN_USE_MIMALLOC
	return mi_free(ptr);
#elif ZEN_PLATFORM_WINDOWS
	_aligned_free(ptr);
#else
	std::free(ptr);
#endif
}

//////////////////////////////////////////////////////////////////////////

void*
Memory::Alloc(size_t Size, size_t Alignment)
{
	return AlignedAllocImpl(Size, Alignment);
}

void
Memory::Free(void* ptr)
{
	AlignedFreeImpl(ptr);
}

//////////////////////////////////////////////////////////////////////////
//
// Unit tests
//

#if ZEN_WITH_TESTS

TEST_CASE("MemoryView")
{
	{
		uint8_t	   Array1[16] = {};
		MemoryView View1	  = MakeMemoryView(Array1);
		CHECK(View1.GetSize() == 16);
	}

	{
		uint32_t   Array2[16] = {};
		MemoryView View2	  = MakeMemoryView(Array2);
		CHECK(View2.GetSize() == 64);
	}

	CHECK(MakeMemoryView<float>({1.0f, 1.2f}).GetSize() == 8);
}

void
memory_forcelink()
{
}

#endif

}  // namespace zen