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 
7 #pragma once
8 
9 #include "rocksdb/memory_allocator.h"
10 
11 namespace ROCKSDB_NAMESPACE {
12 
13 struct CustomDeleter {
allocatorCustomDeleter14   CustomDeleter(MemoryAllocator* a = nullptr) : allocator(a) {}
15 
operatorCustomDeleter16   void operator()(char* ptr) const {
17     if (allocator) {
18       allocator->Deallocate(reinterpret_cast<void*>(ptr));
19     } else {
20       delete[] ptr;
21     }
22   }
23 
24   MemoryAllocator* allocator;
25 };
26 
27 using CacheAllocationPtr = std::unique_ptr<char[], CustomDeleter>;
28 
AllocateBlock(size_t size,MemoryAllocator * allocator)29 inline CacheAllocationPtr AllocateBlock(size_t size,
30                                         MemoryAllocator* allocator) {
31   if (allocator) {
32     auto block = reinterpret_cast<char*>(allocator->Allocate(size));
33     return CacheAllocationPtr(block, allocator);
34   }
35   return CacheAllocationPtr(new char[size]);
36 }
37 
38 }  // namespace ROCKSDB_NAMESPACE
39