CellAllocator.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Badge.h>
  7. #include <LibJS/Heap/BlockAllocator.h>
  8. #include <LibJS/Heap/CellAllocator.h>
  9. #include <LibJS/Heap/Heap.h>
  10. #include <LibJS/Heap/HeapBlock.h>
  11. namespace JS {
  12. CellAllocator::CellAllocator(size_t cell_size)
  13. : m_cell_size(cell_size)
  14. {
  15. }
  16. CellAllocator::~CellAllocator()
  17. {
  18. }
  19. Cell* CellAllocator::allocate_cell(Heap& heap)
  20. {
  21. if (m_usable_blocks.is_empty()) {
  22. auto block = HeapBlock::create_with_cell_size(heap, m_cell_size);
  23. m_usable_blocks.append(*block.leak_ptr());
  24. }
  25. auto& block = *m_usable_blocks.last();
  26. auto* cell = block.allocate();
  27. VERIFY(cell);
  28. if (block.is_full())
  29. m_full_blocks.append(*m_usable_blocks.last());
  30. return cell;
  31. }
  32. void CellAllocator::block_did_become_empty(Badge<Heap>, HeapBlock& block)
  33. {
  34. auto& heap = block.heap();
  35. block.m_list_node.remove();
  36. // NOTE: HeapBlocks are managed by the BlockAllocator, so we don't want to `delete` the block here.
  37. block.~HeapBlock();
  38. heap.block_allocator().deallocate_block(&block);
  39. }
  40. void CellAllocator::block_did_become_usable(Badge<Heap>, HeapBlock& block)
  41. {
  42. VERIFY(!block.is_full());
  43. m_usable_blocks.append(block);
  44. }
  45. }