16 #include <wpi/mutex.h>
18 #include "hal/Errors.h"
19 #include "hal/Types.h"
20 #include "hal/handles/HandlesInternal.h"
37 template <
typename THandle,
typename TStruct, int16_t
size,
40 friend class IndexedClassedHandleResourceTest;
48 THandle Allocate(int16_t index, std::shared_ptr<TStruct> toSet,
50 std::shared_ptr<TStruct> Get(THandle handle);
51 void Free(THandle handle);
55 std::array<std::shared_ptr<TStruct>, size> m_structures;
56 std::array<wpi::mutex, size> m_handleMutexes;
59 template <
typename THandle,
typename TStruct, int16_t size,
63 int16_t index, std::shared_ptr<TStruct> toSet, int32_t* status) {
65 if (index < 0 || index >= size) {
66 *status = RESOURCE_OUT_OF_RANGE;
67 return HAL_kInvalidHandle;
69 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
71 if (m_structures[index] !=
nullptr) {
72 *status = RESOURCE_IS_ALLOCATED;
73 return HAL_kInvalidHandle;
75 m_structures[index] = toSet;
79 template <
typename THandle,
typename TStruct, int16_t size,
81 std::shared_ptr<TStruct>
82 IndexedClassedHandleResource<THandle, TStruct, size, enumValue>::Get(
85 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
86 if (index < 0 || index >= size) {
89 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
92 return m_structures[index];
95 template <
typename THandle,
typename TStruct, int16_t size,
97 void IndexedClassedHandleResource<THandle, TStruct, size, enumValue>::Free(
100 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
101 if (index < 0 || index >= size)
return;
103 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
104 m_structures[index].reset();
107 template <
typename THandle,
typename TStruct, int16_t size,
109 void IndexedClassedHandleResource<THandle, TStruct, size,
110 enumValue>::ResetHandles() {
111 for (
int i = 0; i < size; i++) {
112 std::lock_guard<wpi::mutex> lock(m_handleMutexes[i]);
113 m_structures[i].reset();
115 HandleBase::ResetHandles();
HAL_HandleEnum
Enum of HAL handle types.
Definition: HandlesInternal.h:47
Base for all HAL Handles.
Definition: HandlesInternal.h:29
The IndexedClassedHandleResource class is a way to track handles.
Definition: IndexedClassedHandleResource.h:39
WPILib Hardware Abstraction Layer (HAL) namespace.
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
HAL_Handle createHandle(int16_t index, HAL_HandleEnum handleType, int16_t version)
Create a handle for a specific index, type and version.