memory_allocator.h 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #pragma once
  7. #include "rocksdb/memory_allocator.h"
  8. namespace ROCKSDB_NAMESPACE {
  9. struct CustomDeleter {
  10. CustomDeleter(MemoryAllocator* a = nullptr) : allocator(a) {}
  11. void operator()(char* ptr) const {
  12. if (allocator) {
  13. allocator->Deallocate(reinterpret_cast<void*>(ptr));
  14. } else {
  15. delete[] ptr;
  16. }
  17. }
  18. MemoryAllocator* allocator;
  19. };
  20. using CacheAllocationPtr = std::unique_ptr<char[], CustomDeleter>;
  21. inline CacheAllocationPtr AllocateBlock(size_t size,
  22. MemoryAllocator* allocator) {
  23. if (allocator) {
  24. auto block = reinterpret_cast<char*>(allocator->Allocate(size));
  25. return CacheAllocationPtr(block, allocator);
  26. }
  27. return CacheAllocationPtr(new char[size]);
  28. }
  29. } // namespace ROCKSDB_NAMESPACE