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