15 #include <wpi/mutex.h>
17 #include "HandlesInternal.h"
18 #include "hal/Types.h"
32 template <
typename THandle,
typename TStruct, int16_t
size,
33 HAL_HandleEnum enumValue>
35 friend class LimitedHandleResourceTest;
43 std::shared_ptr<TStruct> Get(THandle handle);
44 void Free(THandle handle);
45 void ResetHandles()
override;
48 std::array<std::shared_ptr<TStruct>, size> m_structures;
49 std::array<wpi::mutex, size> m_handleMutexes;
50 wpi::mutex m_allocateMutex;
53 template <
typename THandle,
typename TStruct, int16_t size,
54 HAL_HandleEnum enumValue>
57 std::lock_guard<wpi::mutex> lock(m_allocateMutex);
58 for (int16_t i = 0; i < size; i++) {
59 if (m_structures[i] ==
nullptr) {
62 std::lock_guard<wpi::mutex> lock(m_handleMutexes[i]);
63 m_structures[i] = std::make_shared<TStruct>();
64 return static_cast<THandle
>(createHandle(i, enumValue, m_version));
67 return HAL_kInvalidHandle;
70 template <
typename THandle,
typename TStruct, int16_t size,
71 HAL_HandleEnum enumValue>
72 std::shared_ptr<TStruct>
73 LimitedHandleResource<THandle, TStruct, size, enumValue>::Get(THandle handle) {
75 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
76 if (index < 0 || index >= size) {
79 std::lock_guard<wpi::mutex> lock(m_handleMutexes[index]);
82 return m_structures[index];
85 template <
typename THandle,
typename TStruct, int16_t size,
86 HAL_HandleEnum enumValue>
87 void LimitedHandleResource<THandle, TStruct, size, enumValue>::Free(
90 int16_t index = getHandleTypedIndex(handle, enumValue, m_version);
91 if (index < 0 || index >= size)
return;
93 std::lock_guard<wpi::mutex> allocateLock(m_allocateMutex);
94 std::lock_guard<wpi::mutex> handleLock(m_handleMutexes[index]);
95 m_structures[index].reset();
98 template <
typename THandle,
typename TStruct, int16_t size,
99 HAL_HandleEnum enumValue>
100 void LimitedHandleResource<THandle, TStruct, size, enumValue>::ResetHandles() {
102 std::lock_guard<wpi::mutex> allocateLock(m_allocateMutex);
103 for (
int i = 0; i < size; i++) {
104 std::lock_guard<wpi::mutex> handleLock(m_handleMutexes[i]);
105 m_structures[i].reset();
108 HandleBase::ResetHandles();
The LimitedHandleResource class is a way to track handles.
Definition: LimitedHandleResource.h:34
Base for all HAL Handles.
Definition: HandlesInternal.h:29
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