libcommunism
Userspace cooperative threading library
AllocImpl.h
Go to the documentation of this file.
1 #ifndef ALLOCIMPL_H
2 #define ALLOCIMPL_H
3 
4 #include <cstddef>
5 #include <cstdint>
6 #include <span>
7 
8 #if defined(PLATFORM_AMD64_SYSV) || defined(PLATFORM_AMD64_WINDOWS)
9 #include "arch/amd64/Common.h"
10 #elif defined(PLATFORM_X86_FASTCALL)
11 #include "arch/x86/Common.h"
12 #elif defined(PLATFORM_AARCH64_AAPCS)
13 #include "arch/aarch64/Common.h"
14 #elif defined(PLATFORM_SETJMP)
15 #include "arch/setjmp/SetJmp.h"
16 #elif defined(PLATFORM_UCONTEXT)
17 #include "arch/ucontext/UContext.h"
18 #endif
19 
20 template <class ImplClass, typename ...Args>
21 static constexpr auto AllocImplHelper(std::span<uintptr_t> buffer, bool &bufferUsed, Args && ...args) {
22  const auto bytes{buffer.size() * sizeof(uintptr_t)};
23 
24  if(sizeof(ImplClass) <= bytes && alignof(ImplClass) <= sizeof(uintptr_t)) {
25  bufferUsed = true;
26  auto mem = reinterpret_cast<ImplClass *>(buffer.data());
27  return new(mem) ImplClass(std::forward<Args>(args)...);
28  } else {
29  bufferUsed = false;
30  return new ImplClass(std::forward<Args>(args)...);
31  }
32 }
33 
37 template <typename ...Args>
38 static constexpr auto AllocImpl(std::span<uintptr_t> buffer, bool &bufferUsed, Args && ...args) {
39  using namespace libcommunism::internal;
40 
41 #if defined(PLATFORM_AMD64_SYSV) || defined(PLATFORM_AMD64_WINDOWS)
42  return AllocImplHelper<Amd64>(buffer, bufferUsed, std::forward<Args>(args)...);
43 #elif defined(PLATFORM_X86_FASTCALL)
44  return AllocImplHelper<x86>(buffer, bufferUsed, std::forward<Args>(args)...);
45 #elif defined(PLATFORM_AARCH64_AAPCS)
46  return AllocImplHelper<Aarch64>(buffer, bufferUsed, std::forward<Args>(args)...);
47 #elif defined(PLATFORM_SETJMP)
48  return AllocImplHelper<SetJmp>(buffer, bufferUsed, std::forward<Args>(args)...);
49 #elif defined(PLATFORM_UCONTEXT)
50  return AllocImplHelper<UContext>(buffer, bufferUsed, std::forward<Args>(args)...);
51 #else
52 #error Do not know how to allocate implementation for current platform!
53 #endif
54 }
55 
56 #endif
Implementation details (including architecture/platform specific code) for the library.
Definition: Common.h:11