OSSIA
Open Scenario System for Interactive Application
listening.hpp
1 #pragma once
2 #include <ossia/detail/mutex.hpp>
3 #include <ossia/detail/optional.hpp>
4 #include <ossia/detail/small_vector.hpp>
5 #include <ossia/detail/string_algorithms.hpp>
7 
8 namespace ossia
9 {
10 // MOVEME
11 template <typename T>
12 struct locked_map
13 {
14 public:
15  using map_type = T;
16  using key_type = typename map_type::key_type;
17  using mapped_type = typename map_type::mapped_type;
18  using value_type = typename map_type::value_type;
19 
20  template <typename Key>
21  std::optional<mapped_type> find(const Key& path) const
22  {
23  lock_t lock(m_mutex);
24  auto it = m_map.find(path);
25  if(it != m_map.end())
26  {
27  return it->second;
28  }
29  else
30  {
31  return std::nullopt;
32  }
33  }
34 
35  template <typename Key>
36  std::optional<mapped_type> find_and_take(const Key& path)
37  {
38  lock_t lock(m_mutex);
39  auto it = m_map.find(path);
40  if(it != m_map.end())
41  {
42  auto val = std::move(it.value());
43  m_map.erase(it);
44  return std::move(val);
45  }
46  else
47  {
48  return std::nullopt;
49  }
50  }
51 
52  void rename(const key_type& oldk, const key_type& newk)
53  {
54  lock_t lock(m_mutex);
55 
56  ossia::small_vector<std::pair<key_type, mapped_type>, 8> cache;
57 
58  for(auto& [k, v] : m_map)
59  {
60  if(string_starts_with(k, oldk))
61  cache.emplace_back(k, std::move(v));
62  }
63 
64  if(!cache.empty())
65  {
66  for(auto&& e : std::move(cache))
67  {
68  m_map.erase(e.first);
69  e.first.replace(0, oldk.length(), newk);
70  m_map.insert({std::move(e.first), std::move(e.second)});
71  }
72  }
73  }
74 
75  void insert(const value_type& m)
76  {
77  lock_t lock(m_mutex);
78  m_map.insert(m);
79  }
80 
81  void insert(value_type&& m)
82  {
83  lock_t lock(m_mutex);
84  m_map.insert(std::move(m));
85  }
86 
87  void erase(const key_type& m)
88  {
89  lock_t lock(m_mutex);
90  m_map.erase(m);
91  }
92 
93 private:
94  mutable mutex_t m_mutex;
95  map_type m_map TS_GUARDED_BY(m_mutex);
96 };
97 
98 namespace net
99 {
100 class parameter_base;
101 using listened_parameters = locked_map<string_map<ossia::net::parameter_base*>>;
102 }
103 }
Definition: git_info.h:7