memory_allocator_impl.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 <algorithm>
  8. #include "rocksdb/memory_allocator.h"
  9. namespace ROCKSDB_NAMESPACE {
  10. struct CacheAllocationDeleter {
  11. CacheAllocationDeleter(MemoryAllocator* a = nullptr) : allocator(a) {}
  12. void operator()(char* ptr) const {
  13. if (allocator) {
  14. allocator->Deallocate(ptr);
  15. } else {
  16. delete[] ptr;
  17. }
  18. }
  19. MemoryAllocator* allocator;
  20. };
  21. using CacheAllocationPtr = std::unique_ptr<char[], CacheAllocationDeleter>;
  22. inline CacheAllocationPtr AllocateBlock(size_t size,
  23. MemoryAllocator* allocator) {
  24. if (allocator) {
  25. auto block = static_cast<char*>(allocator->Allocate(size));
  26. return CacheAllocationPtr(block, allocator);
  27. }
  28. return CacheAllocationPtr(new char[size]);
  29. }
  30. inline CacheAllocationPtr AllocateAndCopyBlock(const Slice& data,
  31. MemoryAllocator* allocator) {
  32. CacheAllocationPtr cap = AllocateBlock(data.size(), allocator);
  33. std::copy_n(data.data(), data.size(), cap.get());
  34. return cap;
  35. }
  36. } // namespace ROCKSDB_NAMESPACE