allocator.hpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include <memory>
  3. #include <new>
  4. #include <utility>
  5. #include <type_traits>
  6. #include <cstddef>
  7. #include <stdint.h>
  8. #include <types/cplusplus.hpp>
  9. #include <types/types.h>
  10. #include <kernel/async/lock.hpp>
  11. namespace kernel::kinit {
  12. void init_kernel_heap(void* start, std::size_t size);
  13. } // namespace kernel::kinit
  14. namespace types::memory {
  15. class brk_memory_allocator {
  16. public:
  17. using byte = std::byte;
  18. using size_type = std::size_t;
  19. private:
  20. byte* p_start;
  21. byte* p_limit;
  22. byte* p_break;
  23. kernel::async::mutex mtx;
  24. constexpr byte* brk(byte* addr)
  25. {
  26. if (addr >= p_limit) [[unlikely]]
  27. return nullptr;
  28. return p_break = addr;
  29. }
  30. constexpr byte* sbrk(size_type increment)
  31. { return brk(p_break + increment); }
  32. public:
  33. explicit brk_memory_allocator(byte* start, size_type size);
  34. brk_memory_allocator(const brk_memory_allocator&) = delete;
  35. void* allocate(size_type size);
  36. void deallocate(void* ptr);
  37. };
  38. void* kimalloc(std::size_t size);
  39. void kifree(void* ptr);
  40. template <typename T>
  41. struct ident_allocator {
  42. using value_type = T;
  43. using propagate_on_container_move_assignment = std::true_type;
  44. constexpr ident_allocator() = default;
  45. template <typename U>
  46. constexpr ident_allocator(const ident_allocator<U>&) noexcept {}
  47. inline T* allocate(std::size_t n)
  48. { return (T*)kimalloc(n * sizeof(T)); }
  49. inline void deallocate(T* ptr, std::size_t) { return kifree(ptr); }
  50. };
  51. template <typename T, typename... Args>
  52. constexpr T* kinew(Args&&... args)
  53. {
  54. ident_allocator<T> alloc { };
  55. T* ptr = std::allocator_traits<ident_allocator<T>>::allocate(alloc, 1);
  56. std::allocator_traits<ident_allocator<T>>::construct(alloc, ptr, std::forward<Args>(args)...);
  57. return ptr;
  58. }
  59. template <typename T>
  60. constexpr void kidelete(T* ptr)
  61. {
  62. ident_allocator<T> alloc { };
  63. std::allocator_traits<ident_allocator<T>>::destroy(alloc, ptr);
  64. std::allocator_traits<ident_allocator<T>>::deallocate(alloc, ptr, 1);
  65. }
  66. } // namespace types::memory