15 #include <wpi/mutex.h>
17 #include "hal/Types.h"
18 #include "hal/handles/HandlesInternal.h"
33 template <
typename THandle,
typename TStruct, int16_t
size,
36 friend class LimitedClassedHandleResourceTest;
44 THandle Allocate(std::shared_ptr<TStruct> toSet);
45 std::shared_ptr<TStruct> Get(THandle handle);
46 void Free(THandle handle);
47 void ResetHandles()
override;
50 std::array<std::shared_ptr<TStruct>, size> m_structures;
51 std::array<wpi::mutex, size> m_handleMutexes;
52 wpi::mutex m_allocateMutex;
55 template <
typename THandle,
typename TStruct, int16_t size,
59 std::shared_ptr<TStruct> toSet) {
61 std::lock_guard<wpi::mutex> lock(m_allocateMutex);
62 for (int16_t i = 0; i < size; i++) {
63 if (m_structures[i] ==
nullptr) {
66 std::lock_guard<wpi::mutex> lock(m_handleMutexes[i]);
67 m_structures[i] = toSet;
68 return static_cast<THandle
>(
createHandle(i, enumValue, m_version));
71 return HAL_kInvalidHandle;
74 template <
typename THandle,
typename TStruct, int16_t size,
76 std::shared_ptr<TStruct>
77 LimitedClassedHandleResource<THandle, TStruct, size, enumValue>::Get(
80 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
81 if (index < 0 || index >= size) {
84 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
87 return m_structures[index];
90 template <
typename THandle,
typename TStruct, int16_t size,
92 void LimitedClassedHandleResource<THandle, TStruct, size, enumValue>::Free(
95 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
96 if (index < 0 || index >= size)
return;
98 std::lock_guard<wpi::mutex> allocateLock(m_allocateMutex);
99 std::lock_guard<wpi::mutex> handleLock(m_handleMutexes[index]);
100 m_structures[index].reset();
103 template <
typename THandle,
typename TStruct, int16_t size,
105 void LimitedClassedHandleResource<THandle, TStruct, size,
106 enumValue>::ResetHandles() {
108 std::lock_guard<wpi::mutex> allocateLock(m_allocateMutex);
109 for (
int i = 0; i < size; i++) {
110 std::lock_guard<wpi::mutex> handleLock(m_handleMutexes[i]);
111 m_structures[i].reset();
114 HandleBase::ResetHandles();
HAL_HandleEnum
Enum of HAL handle types.
Definition: HandlesInternal.h:47
Base for all HAL Handles.
Definition: HandlesInternal.h:29
WPILib Hardware Abstraction Layer (HAL) namespace.
Definition: NotifyListenerVector.h:18
The LimitedClassedHandleResource class is a way to track handles.
Definition: LimitedClassedHandleResource.h:35
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.