allocator.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #pragma once
  2. #include <kernel/mem.h>
  3. #include <types/cplusplus.hpp>
  4. #include <types/types.h>
  5. inline void* operator new(size_t, void* ptr)
  6. {
  7. return ptr;
  8. }
  9. namespace types {
  10. template <typename Allocator>
  11. class allocator_traits;
  12. template <typename T>
  13. class kernel_allocator {
  14. public:
  15. using value_type = T;
  16. static value_type* allocate_memory(size_t count)
  17. {
  18. return static_cast<value_type*>(::k_malloc(count));
  19. }
  20. static void deallocate_memory(value_type* ptr)
  21. {
  22. ::k_free(ptr);
  23. }
  24. };
  25. template <typename T>
  26. class kernel_ident_allocator {
  27. public:
  28. using value_type = T;
  29. static value_type* allocate_memory(size_t count)
  30. {
  31. return static_cast<value_type*>(::ki_malloc(count));
  32. }
  33. static void deallocate_memory(value_type* ptr)
  34. {
  35. ::ki_free(ptr);
  36. }
  37. };
  38. template <typename T, typename... Args>
  39. T* kernel_allocator_new(Args&&... args)
  40. {
  41. return allocator_traits<kernel_allocator<T>>::allocate_and_construct(forward<Args>(args)...);
  42. }
  43. template <typename T, typename... Args>
  44. T* kernel_ident_allocator_new(Args&&... args)
  45. {
  46. return allocator_traits<kernel_ident_allocator<T>>::allocate_and_construct(forward<Args>(args)...);
  47. }
  48. template <typename Allocator>
  49. class allocator_traits {
  50. public:
  51. using value_type = typename Allocator::value_type;
  52. static value_type* allocate(size_t count)
  53. {
  54. if (count == 0)
  55. return nullptr;
  56. return Allocator::allocate_memory(sizeof(value_type) * count);
  57. }
  58. template <typename... Args>
  59. static value_type* construct(value_type* ptr, Args&&... args)
  60. {
  61. new (ptr) value_type(forward<Args>(args)...);
  62. return ptr;
  63. }
  64. template <typename... Args>
  65. static value_type* allocate_and_construct(Args&&... args)
  66. {
  67. auto* ptr = allocate(1);
  68. construct(ptr, forward<Args>(args)...);
  69. return ptr;
  70. }
  71. static void deconstruct(value_type* ptr)
  72. {
  73. if (!ptr)
  74. return;
  75. ptr->~value_type();
  76. }
  77. static void deallocate(value_type* ptr)
  78. {
  79. if (!ptr)
  80. return;
  81. Allocator::deallocate_memory(ptr);
  82. }
  83. static void deconstruct_and_deallocate(value_type* ptr)
  84. {
  85. if (!ptr)
  86. return;
  87. deconstruct(ptr);
  88. deallocate(ptr);
  89. }
  90. };
  91. } // namespace types