| 1 | // Licensed to the .NET Foundation under one or more agreements. |
|---|---|
| 2 | // The .NET Foundation licenses this file to you under the MIT license. |
| 3 | // See the LICENSE file in the project root for more information. |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | class HostAllocator final |
| 8 | { |
| 9 | private: |
| 10 | HostAllocator() |
| 11 | { |
| 12 | } |
| 13 | |
| 14 | public: |
| 15 | template <typename T> |
| 16 | T* allocate(size_t count) |
| 17 | { |
| 18 | ClrSafeInt<size_t> safeElemSize(sizeof(T)); |
| 19 | ClrSafeInt<size_t> safeCount(count); |
| 20 | ClrSafeInt<size_t> size = safeElemSize * safeCount; |
| 21 | if (size.IsOverflow()) |
| 22 | { |
| 23 | return nullptr; |
| 24 | } |
| 25 | |
| 26 | return static_cast<T*>(allocateHostMemory(size.Value())); |
| 27 | } |
| 28 | |
| 29 | void deallocate(void* p) |
| 30 | { |
| 31 | freeHostMemory(p); |
| 32 | } |
| 33 | |
| 34 | static HostAllocator getHostAllocator() |
| 35 | { |
| 36 | return HostAllocator(); |
| 37 | } |
| 38 | |
| 39 | private: |
| 40 | void* allocateHostMemory(size_t size); |
| 41 | void freeHostMemory(void* p); |
| 42 | }; |
| 43 | |
| 44 | // Global operator new overloads that work with HostAllocator |
| 45 | |
| 46 | inline void* __cdecl operator new(size_t n, HostAllocator alloc) |
| 47 | { |
| 48 | return alloc.allocate<char>(n); |
| 49 | } |
| 50 | |
| 51 | inline void* __cdecl operator new[](size_t n, HostAllocator alloc) |
| 52 | { |
| 53 | return alloc.allocate<char>(n); |
| 54 | } |
| 55 |