arena.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  2. //
  3. // Do small memory allocations on continuous blocks.
  4. //
  5. // Author: Ge,Jun (gejun@baidu.com)
  6. // Date: Fri Jun 5 18:25:40 CST 2015
  7. #ifndef BRPC_BASE_ARENA_H
  8. #define BRPC_BASE_ARENA_H
  9. #include <stdint.h>
  10. #include "base/macros.h"
  11. namespace base {
  12. struct ArenaOptions {
  13. size_t initial_block_size;
  14. size_t max_block_size;
  15. // Constructed with default options.
  16. ArenaOptions();
  17. };
  18. // Just a proof-of-concept, will be refactored in future CI.
  19. class Arena {
  20. public:
  21. explicit Arena(const ArenaOptions& options = ArenaOptions());
  22. ~Arena();
  23. void swap(Arena&);
  24. void* allocate(size_t n);
  25. void* allocate_aligned(size_t n); // not implemented.
  26. void clear();
  27. private:
  28. DISALLOW_COPY_AND_ASSIGN(Arena);
  29. struct Block {
  30. uint32_t left_space() const { return size - alloc_size; }
  31. Block* next;
  32. uint32_t alloc_size;
  33. uint32_t size;
  34. char data[0];
  35. };
  36. void* allocate_in_other_blocks(size_t n);
  37. void* allocate_new_block(size_t n);
  38. Block* pop_block(Block* & head) {
  39. Block* saved_head = head;
  40. head = head->next;
  41. return saved_head;
  42. }
  43. Block* _cur_block;
  44. Block* _isolated_blocks;
  45. size_t _block_size;
  46. ArenaOptions _options;
  47. };
  48. inline void* Arena::allocate(size_t n) {
  49. if (_cur_block != NULL && _cur_block->left_space() >= n) {
  50. void* ret = _cur_block->data + _cur_block->alloc_size;
  51. _cur_block->alloc_size += n;
  52. return ret;
  53. }
  54. return allocate_in_other_blocks(n);
  55. }
  56. } // namespace base
  57. #endif // BRPC_BASE_ARENA_H