WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
UnlimitedHandleResource.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2008-2017. All Rights Reserved. */
3 /* Open Source Software - may be modified and shared by FRC teams. The code */
4 /* must be accompanied by the FIRST BSD license file in the root directory of */
5 /* the project. */
6 /*----------------------------------------------------------------------------*/
7 
8 #pragma once
9 
10 #include <stdint.h>
11 
12 #include <memory>
13 #include <vector>
14 
15 #include "HAL/Types.h"
16 #include "HAL/cpp/priority_mutex.h"
17 #include "HAL/handles/HandlesInternal.h"
18 
19 namespace hal {
20 
35 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
37  friend class UnlimitedHandleResourceTest;
38 
39  public:
40  UnlimitedHandleResource() = default;
42  UnlimitedHandleResource& operator=(const UnlimitedHandleResource&) = delete;
43 
44  THandle Allocate(std::shared_ptr<TStruct> structure);
45  std::shared_ptr<TStruct> Get(THandle handle);
46  void Free(THandle handle);
47 
48  private:
49  std::vector<std::shared_ptr<TStruct>> m_structures;
50  priority_mutex m_handleMutex;
51 };
52 
53 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
55  std::shared_ptr<TStruct> structure) {
56  std::lock_guard<priority_mutex> sync(m_handleMutex);
57  size_t i;
58  for (i = 0; i < m_structures.size(); i++) {
59  if (m_structures[i] == nullptr) {
60  m_structures[i] = structure;
61  return static_cast<THandle>(createHandle(i, enumValue));
62  }
63  }
64  if (i >= INT16_MAX) return HAL_kInvalidHandle;
65 
66  m_structures.push_back(structure);
67  return static_cast<THandle>(createHandle(static_cast<int16_t>(i), enumValue));
68 }
69 
70 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
71 std::shared_ptr<TStruct>
72 UnlimitedHandleResource<THandle, TStruct, enumValue>::Get(THandle handle) {
73  int16_t index = getHandleTypedIndex(handle, enumValue);
74  std::lock_guard<priority_mutex> sync(m_handleMutex);
75  if (index < 0 || index >= static_cast<int16_t>(m_structures.size()))
76  return nullptr;
77  return m_structures[index];
78 }
79 
80 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
81 void UnlimitedHandleResource<THandle, TStruct, enumValue>::Free(
82  THandle handle) {
83  int16_t index = getHandleTypedIndex(handle, enumValue);
84  std::lock_guard<priority_mutex> sync(m_handleMutex);
85  if (index < 0 || index >= static_cast<int16_t>(m_structures.size())) return;
86  m_structures[index].reset();
87 }
88 } // namespace hal
The UnlimitedHandleResource class is a way to track handles.
Definition: UnlimitedHandleResource.h:36
Definition: priority_mutex.h:53