WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
UnlimitedHandleResource.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2008-2016. 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:
41  UnlimitedHandleResource operator=(const UnlimitedHandleResource&) = delete;
42  UnlimitedHandleResource() = default;
43  THandle Allocate(std::shared_ptr<TStruct> structure);
44  std::shared_ptr<TStruct> Get(THandle handle);
45  void Free(THandle handle);
46 
47  private:
48  std::vector<std::shared_ptr<TStruct>> m_structures;
49  priority_mutex m_handleMutex;
50 };
51 
52 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
54  std::shared_ptr<TStruct> structure) {
55  std::lock_guard<priority_mutex> sync(m_handleMutex);
56  size_t i;
57  for (i = 0; i < m_structures.size(); i++) {
58  if (m_structures[i] == nullptr) {
59  m_structures[i] = structure;
60  return static_cast<THandle>(createHandle(i, enumValue));
61  }
62  }
63  if (i >= INT16_MAX) return HAL_kInvalidHandle;
64 
65  m_structures.push_back(structure);
66  return static_cast<THandle>(createHandle(static_cast<int16_t>(i), enumValue));
67 }
68 
69 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
70 std::shared_ptr<TStruct>
71 UnlimitedHandleResource<THandle, TStruct, enumValue>::Get(THandle handle) {
72  int16_t index = getHandleTypedIndex(handle, enumValue);
73  std::lock_guard<priority_mutex> sync(m_handleMutex);
74  if (index < 0 || index >= static_cast<int16_t>(m_structures.size()))
75  return nullptr;
76  return m_structures[index];
77 }
78 
79 template <typename THandle, typename TStruct, HAL_HandleEnum enumValue>
80 void UnlimitedHandleResource<THandle, TStruct, enumValue>::Free(
81  THandle handle) {
82  int16_t index = getHandleTypedIndex(handle, enumValue);
83  std::lock_guard<priority_mutex> sync(m_handleMutex);
84  if (index < 0 || index >= static_cast<int16_t>(m_structures.size())) return;
85  m_structures[index].reset();
86 }
87 } // namespace hal
The UnlimitedHandleResource class is a way to track handles.
Definition: UnlimitedHandleResource.h:36
Definition: priority_mutex.h:53