15 #include <wpi/mutex.h>
17 #include "hal/Errors.h"
18 #include "hal/Types.h"
19 #include "hal/handles/HandlesInternal.h"
35 template <
typename THandle,
typename TStruct, int16_t
size,
36 HAL_HandleEnum enumValue>
38 friend class IndexedHandleResourceTest;
45 THandle Allocate(int16_t index, int32_t* status);
46 std::shared_ptr<TStruct> Get(THandle handle);
47 void Free(THandle handle);
48 void ResetHandles()
override;
51 std::array<std::shared_ptr<TStruct>, size> m_structures;
52 std::array<wpi::mutex, size> m_handleMutexes;
55 template <
typename THandle,
typename TStruct, int16_t size,
56 HAL_HandleEnum enumValue>
58 int16_t index, int32_t* status) {
60 if (index < 0 || index >= size) {
61 *status = RESOURCE_OUT_OF_RANGE;
62 return HAL_kInvalidHandle;
64 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
66 if (m_structures[index] !=
nullptr) {
67 *status = RESOURCE_IS_ALLOCATED;
68 return HAL_kInvalidHandle;
70 m_structures[index] = std::make_shared<TStruct>();
71 return static_cast<THandle
>(hal::createHandle(index, enumValue, m_version));
74 template <
typename THandle,
typename TStruct, int16_t size,
75 HAL_HandleEnum enumValue>
76 std::shared_ptr<TStruct>
77 IndexedHandleResource<THandle, TStruct, size, enumValue>::Get(THandle handle) {
79 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
80 if (index < 0 || index >= size) {
83 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
86 return m_structures[index];
89 template <
typename THandle,
typename TStruct, int16_t size,
90 HAL_HandleEnum enumValue>
91 void IndexedHandleResource<THandle, TStruct, size, enumValue>::Free(
94 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
95 if (index < 0 || index >= size)
return;
97 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
98 m_structures[index].reset();
101 template <
typename THandle,
typename TStruct, int16_t size,
102 HAL_HandleEnum enumValue>
103 void IndexedHandleResource<THandle, TStruct, size, enumValue>::ResetHandles() {
104 for (
int i = 0; i < size; i++) {
105 std::lock_guard<wpi::mutex> lock(m_handleMutexes[i]);
106 m_structures[i].reset();
108 HandleBase::ResetHandles();
Base for all HAL Handles.
Definition: HandlesInternal.h:29
The IndexedHandleResource class is a way to track handles.
Definition: IndexedHandleResource.h:37
Definition: NotifyListenerVector.h:18
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:999