summaryrefslogtreecommitdiffstats
path: root/source/core/slang-allocator.h
blob: 38d46c9bdd1439a62a25e816d3596c11174181b3 (plain)
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
#ifndef SLANG_CORE_ALLOCATOR_H
#define SLANG_CORE_ALLOCATOR_H

#include "slang-common.h"

#include <stdlib.h>
#if SLANG_WINDOWS_FAMILY
#include <malloc.h>
#endif

#include <type_traits>

namespace Slang
{
inline void* alignedAllocate(size_t size, size_t alignment)
{
#if SLANG_WINDOWS_FAMILY
    return _aligned_malloc(size, alignment);
#elif defined(__CYGWIN__)
    return aligned_alloc(alignment, size);
#else
    void* rs = nullptr;
    int succ = posix_memalign(&rs, alignment, size);
    return (succ == 0) ? rs : nullptr;
#endif
}

inline void alignedDeallocate(void* ptr)
{
#if SLANG_WINDOWS_FAMILY
    _aligned_free(ptr);
#else
    free(ptr);
#endif
}

class StandardAllocator
{
public:
    // not really called
    void* allocate(size_t size) { return ::malloc(size); }
    void deallocate(void* ptr) { return ::free(ptr); }
};

template<int ALIGNMENT>
class AlignedAllocator
{
public:
    void* allocate(size_t size) { return alignedAllocate(size, ALIGNMENT); }
    void deallocate(void* ptr) { return alignedDeallocate(ptr); }
};

template<typename T, typename TAllocator>
class AllocateMethod
{
public:
    static inline T* allocateArray(Index count)
    {
        TAllocator allocator;
        T* rs = (T*)allocator.allocate(count * sizeof(T));
        if (!std::is_trivially_constructible<T>::value)
        {
            for (Index i = 0; i < count; i++)
                new (rs + i) T();
        }
        return rs;
    }
    static inline void deallocateArray(T* ptr, Index count)
    {
        TAllocator allocator;
        if (!std::is_trivially_destructible<T>::value)
        {
            for (Index i = 0; i < count; i++)
                ptr[i].~T();
        }
        allocator.deallocate(ptr);
    }
};

#if 0
    template<typename T>
    class AllocateMethod<T, StandardAllocator>
    {
    public:
        static inline T* allocateArray(Index count)
        {
            return new T[count];
        }
        static inline void deallocateArray(T* ptr, Index /*bufferSize*/)
        {
            delete[] ptr;
        }
    };
#endif
} // namespace Slang

#endif