CellAllocator.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/IntrusiveList.h>
  8. #include <AK/NeverDestroyed.h>
  9. #include <AK/NonnullOwnPtr.h>
  10. #include <LibJS/Forward.h>
  11. #include <LibJS/Heap/BlockAllocator.h>
  12. #include <LibJS/Heap/HeapBlock.h>
  13. #define JS_DECLARE_ALLOCATOR(ClassName) \
  14. static JS::TypeIsolatingCellAllocator<ClassName> cell_allocator;
  15. #define JS_DEFINE_ALLOCATOR(ClassName) \
  16. JS::TypeIsolatingCellAllocator<ClassName> ClassName::cell_allocator { #ClassName };
  17. namespace JS {
  18. class CellAllocator {
  19. public:
  20. CellAllocator(size_t cell_size, char const* class_name = nullptr);
  21. ~CellAllocator() = default;
  22. size_t cell_size() const { return m_cell_size; }
  23. Cell* allocate_cell(Heap&);
  24. template<typename Callback>
  25. IterationDecision for_each_block(Callback callback)
  26. {
  27. for (auto& block : m_full_blocks) {
  28. if (callback(block) == IterationDecision::Break)
  29. return IterationDecision::Break;
  30. }
  31. for (auto& block : m_usable_blocks) {
  32. if (callback(block) == IterationDecision::Break)
  33. return IterationDecision::Break;
  34. }
  35. return IterationDecision::Continue;
  36. }
  37. void block_did_become_empty(Badge<Heap>, HeapBlock&);
  38. void block_did_become_usable(Badge<Heap>, HeapBlock&);
  39. IntrusiveListNode<CellAllocator> m_list_node;
  40. using List = IntrusiveList<&CellAllocator::m_list_node>;
  41. BlockAllocator& block_allocator() { return m_block_allocator; }
  42. private:
  43. char const* const m_class_name { nullptr };
  44. size_t const m_cell_size;
  45. BlockAllocator m_block_allocator;
  46. using BlockList = IntrusiveList<&HeapBlock::m_list_node>;
  47. BlockList m_full_blocks;
  48. BlockList m_usable_blocks;
  49. };
  50. template<typename T>
  51. class TypeIsolatingCellAllocator {
  52. public:
  53. using CellType = T;
  54. TypeIsolatingCellAllocator(char const* class_name)
  55. : allocator(sizeof(T), class_name)
  56. {
  57. }
  58. NeverDestroyed<CellAllocator> allocator;
  59. };
  60. }