yum-mirror/slang

Making it easier to work with shaders

git clone https://git.yummers.dev/yum-mirror/slang

Ellie HermaszewskaCorrectly distinguish between windows and MSVC (#5851)48ac6f25f

master
2.0 KiB97 linesraw
1#ifndef SLANG_CORE_ALLOCATOR_H
2#define SLANG_CORE_ALLOCATOR_H
3
4#include "slang-common.h"
5
6#include <stdlib.h>
7#if SLANG_WINDOWS_FAMILY
8#include <malloc.h>
9#endif
10
11#include <type_traits>
12
13namespace Slang
14{
15inline void* alignedAllocate(size_t size, size_t alignment)
16{
17#if SLANG_WINDOWS_FAMILY
18    return _aligned_malloc(size, alignment);
19#elif defined(__CYGWIN__)
20    return aligned_alloc(alignment, size);
21#else
22    void* rs = nullptr;
23    int succ = posix_memalign(&rs, alignment, size);
24    return (succ == 0) ? rs : nullptr;
25#endif
26}
27
28inline void alignedDeallocate(void* ptr)
29{
30#if SLANG_WINDOWS_FAMILY
31    _aligned_free(ptr);
32#else
33    free(ptr);
34#endif
35}
36
37class StandardAllocator
38{
39public:
40    // not really called
41    void* allocate(size_t size) { return ::malloc(size); }
42    void deallocate(void* ptr) { return ::free(ptr); }
43};
44
45template<int ALIGNMENT>
46class AlignedAllocator
47{
48public:
49    void* allocate(size_t size) { return alignedAllocate(size, ALIGNMENT); }
50    void deallocate(void* ptr) { return alignedDeallocate(ptr); }
51};
52
53template<typename T, typename TAllocator>
54class AllocateMethod
55{
56public:
57    static inline T* allocateArray(Index count)
58    {
59        TAllocator allocator;
60        T* rs = (T*)allocator.allocate(count * sizeof(T));
61        if (!std::is_trivially_constructible<T>::value)
62        {
63            for (Index i = 0; i < count; i++)
64                new (rs + i) T();
65        }
66        return rs;
67    }
68    static inline void deallocateArray(T* ptr, Index count)
69    {
70        TAllocator allocator;
71        if (!std::is_trivially_destructible<T>::value)
72        {
73            for (Index i = 0; i < count; i++)
74                ptr[i].~T();
75        }
76        allocator.deallocate(ptr);
77    }
78};
79
80#if 0
81    template<typename T>
82    class AllocateMethod<T, StandardAllocator>
83    {
84    public:
85        static inline T* allocateArray(Index count)
86        {
87            return new T[count];
88        }
89        static inline void deallocateArray(T* ptr, Index /*bufferSize*/)
90        {
91            delete[] ptr;
92        }
93    };
94#endif
95} // namespace Slang
96
97#endif