ie_pre_allocator.hpp
Go to the documentation of this file.
1 // Copyright (C) 2018-2020 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4 
5 /**
6  * @brief The header file defines utility PreAllocator class
7  *
8  * @file ie_pre_allocator.hpp
9  */
10 #pragma once
11 
12 #include <details/ie_exception.hpp>
13 #include <memory>
14 
15 #include "ie_allocator.hpp"
16 
17 namespace InferenceEngine {
18 namespace details {
19 /*
20  * @brief This is a helper class to wrap external memory
21  */
22 class PreAllocator : public IAllocator {
23  void* _actualData;
24  size_t _sizeInBytes;
25 
26 public:
27  PreAllocator(void* ptr, size_t bytes_size): _actualData(ptr), _sizeInBytes(bytes_size) {}
28  /**
29  * @brief Locks a handle to heap memory accessible by any memory manipulation routines
30  * @return The generic pointer to a memory buffer
31  */
32  void* lock(void* handle, LockOp = LOCK_FOR_WRITE) noexcept override {
33  if (handle != _actualData) {
34  return nullptr;
35  }
36  return handle;
37  }
38  /**
39  * @brief The PreAllocator class does not utilize this function
40  */
41  void unlock(void*) noexcept override {} // NOLINT
42 
43  /**
44  * @brief Returns a pointer to preallocated memory
45  * @param size Size in bytes
46  * @return A handle to the preallocated memory or nullptr
47  */
48  void* alloc(size_t size) noexcept override {
49  if (size <= _sizeInBytes) {
50  return _actualData;
51  }
52 
53  return nullptr;
54  }
55  /**
56  * @brief The PreAllocator class cannot release the handle
57  * @return false
58  */
59  bool free(void*) noexcept override { // NOLINT
60  return false;
61  }
62 
63  /**
64  * @brief Deletes current allocator.
65  * Can be used if a shared_from_irelease pointer is used
66  */
67  void Release() noexcept override {
68  delete this;
69  }
70 
71 protected:
72  virtual ~PreAllocator() = default;
73 };
74 
75 /**
76  * @brief Creates a special allocator that only works on external memory
77  * @param ptr Pointer to preallocated memory
78  * @param size Number of elements allocated
79  * @return A new allocator
80  */
81 template <class T>
82 std::shared_ptr<IAllocator> make_pre_allocator(T* ptr, size_t size) {
83  return shared_from_irelease(new PreAllocator(ptr, size * sizeof(T)));
84 }
85 
86 } // namespace details
87 } // namespace InferenceEngine
Definition: cldnn_config.hpp:16
virtual bool free(void *handle) noexcept=0
Releases the handle and all associated memory resources which invalidates the handle.
A header file that provides Allocator interface.
virtual void * alloc(size_t size) noexcept=0
Allocates memory.
virtual void unlock(void *handle) noexcept=0
Unmaps memory by handle with multiple sequential mappings of the same handle.
virtual void * lock(void *handle, LockOp op=LOCK_FOR_WRITE) noexcept=0
Maps handle to heap memory accessible by any memory manipulation routines.
A header file for the main Inference Engine exception.