map.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_WIN_MAP_H_
  5. #define BASE_WIN_MAP_H_
  6. #include <windows.foundation.collections.h>
  7. #include <wrl/implements.h>
  8. #include <map>
  9. #include "base/logging.h"
  10. #include "base/stl_util.h"
  11. #include "base/win/vector.h"
  12. #include "base/win/winrt_foundation_helpers.h"
  13. namespace base {
  14. namespace win {
  15. template <typename K, typename V>
  16. class Map;
  17. namespace internal {
  18. // Template tricks needed to dispatch to the correct implementation.
  19. // See base/win/winrt_foundation_helpers.h for explanation.
  20. template <typename K, typename V>
  21. using ComplexK =
  22. typename ABI::Windows::Foundation::Collections::IMap<K, V>::K_complex;
  23. template <typename K, typename V>
  24. using ComplexV =
  25. typename ABI::Windows::Foundation::Collections::IMap<K, V>::V_complex;
  26. template <typename K, typename V>
  27. using LogicalK = LogicalType<ComplexK<K, V>>;
  28. template <typename K, typename V>
  29. using LogicalV = LogicalType<ComplexV<K, V>>;
  30. template <typename K, typename V>
  31. using AbiK = AbiType<ComplexK<K, V>>;
  32. template <typename K, typename V>
  33. using AbiV = AbiType<ComplexV<K, V>>;
  34. template <typename K, typename V>
  35. using StorageK = StorageType<ComplexK<K, V>>;
  36. template <typename K, typename V>
  37. using StorageV = StorageType<ComplexV<K, V>>;
  38. template <typename K, typename V>
  39. class KeyValuePair : public Microsoft::WRL::RuntimeClass<
  40. Microsoft::WRL::RuntimeClassFlags<
  41. Microsoft::WRL::WinRtClassicComMix |
  42. Microsoft::WRL::InhibitRoOriginateError>,
  43. ABI::Windows::Foundation::Collections::
  44. IKeyValuePair<LogicalK<K, V>, LogicalV<K, V>>> {
  45. public:
  46. using AbiK = AbiK<K, V>;
  47. using AbiV = AbiV<K, V>;
  48. using StorageK = StorageK<K, V>;
  49. using StorageV = StorageV<K, V>;
  50. KeyValuePair(StorageK key, StorageV value)
  51. : key_(std::move(key)), value_(std::move(value)) {}
  52. // ABI::Windows::Foundation::Collections::IKeyValuePair:
  53. IFACEMETHODIMP get_Key(AbiK* key) { return CopyTo(key_, key); }
  54. IFACEMETHODIMP get_Value(AbiV* value) { return CopyTo(value_, value); }
  55. private:
  56. StorageK key_;
  57. StorageV value_;
  58. };
  59. template <typename K>
  60. class MapChangedEventArgs
  61. : public Microsoft::WRL::RuntimeClass<
  62. Microsoft::WRL::RuntimeClassFlags<
  63. Microsoft::WRL::WinRtClassicComMix |
  64. Microsoft::WRL::InhibitRoOriginateError>,
  65. ABI::Windows::Foundation::Collections::IMapChangedEventArgs<K>> {
  66. public:
  67. MapChangedEventArgs(
  68. ABI::Windows::Foundation::Collections::CollectionChange change,
  69. K key)
  70. : change_(change), key_(std::move(key)) {}
  71. ~MapChangedEventArgs() override = default;
  72. // ABI::Windows::Foundation::Collections::IMapChangedEventArgs:
  73. IFACEMETHODIMP get_CollectionChange(
  74. ABI::Windows::Foundation::Collections::CollectionChange* value) override {
  75. *value = change_;
  76. return S_OK;
  77. }
  78. IFACEMETHODIMP get_Key(K* value) override {
  79. *value = key_;
  80. return S_OK;
  81. }
  82. private:
  83. const ABI::Windows::Foundation::Collections::CollectionChange change_;
  84. K key_;
  85. };
  86. } // namespace internal
  87. // This file provides an implementation of Windows::Foundation::IMap. It
  88. // functions as a thin wrapper around an std::map, and dispatches
  89. // method calls to either the corresponding std::map API or
  90. // appropriate std algorithms. Furthermore, it notifies its observers whenever
  91. // its observable state changes, and is iterable. Please notice also that if the
  92. // map is modified while iterating over it, iterator methods will return
  93. // E_CHANGED_STATE. A base::win::Map can be constructed for any types <K,V>, and
  94. // is implicitly constructible from a std::map. In the case where K or V is a
  95. // pointer derived from IUnknown, the std::map needs to be of type
  96. // Microsoft::WRL::ComPtr<K> or Microsoft::WRL::ComPtr<V>. This enforces proper
  97. // reference counting and improves safety.
  98. template <typename K, typename V>
  99. class Map
  100. : public Microsoft::WRL::RuntimeClass<
  101. Microsoft::WRL::RuntimeClassFlags<
  102. Microsoft::WRL::WinRt | Microsoft::WRL::InhibitRoOriginateError>,
  103. ABI::Windows::Foundation::Collections::IMap<internal::LogicalK<K, V>,
  104. internal::LogicalV<K, V>>,
  105. ABI::Windows::Foundation::Collections::IObservableMap<
  106. internal::LogicalK<K, V>,
  107. internal::LogicalV<K, V>>,
  108. ABI::Windows::Foundation::Collections::IIterable<
  109. ABI::Windows::Foundation::Collections::IKeyValuePair<
  110. internal::LogicalK<K, V>,
  111. internal::LogicalV<K, V>>*>> {
  112. public:
  113. using LogicalK = internal::LogicalK<K, V>;
  114. using LogicalV = internal::LogicalV<K, V>;
  115. using AbiK = internal::AbiK<K, V>;
  116. using AbiV = internal::AbiV<K, V>;
  117. using StorageK = internal::StorageK<K, V>;
  118. using StorageV = internal::StorageV<K, V>;
  119. private:
  120. class MapView;
  121. // Iterates over base::win::Map.
  122. // Its methods return E_CHANGED_STATE is the map is modified.
  123. // TODO(https://crbug.com/987533): Refactor MapIterator to leverage
  124. // std::map::iterator.
  125. class MapIterator
  126. : public Microsoft::WRL::RuntimeClass<
  127. Microsoft::WRL::RuntimeClassFlags<
  128. Microsoft::WRL::WinRtClassicComMix |
  129. Microsoft::WRL::InhibitRoOriginateError>,
  130. ABI::Windows::Foundation::Collections::IIterator<
  131. ABI::Windows::Foundation::Collections::IKeyValuePair<
  132. internal::LogicalK<K, V>,
  133. internal::LogicalV<K, V>>*>> {
  134. public:
  135. explicit MapIterator(Microsoft::WRL::ComPtr<MapView> view)
  136. : view_(std::move(view)) {
  137. DCHECK(view_->ValidState());
  138. ConvertMapToVectorIterator();
  139. }
  140. // ABI::Windows::Foundation::Collections::IIterator:
  141. IFACEMETHODIMP get_Current(
  142. ABI::Windows::Foundation::Collections::IKeyValuePair<LogicalK,
  143. LogicalV>**
  144. current) override {
  145. return view_->ValidState() ? iterator_->get_Current(current)
  146. : E_CHANGED_STATE;
  147. }
  148. IFACEMETHODIMP get_HasCurrent(boolean* has_current) override {
  149. return view_->ValidState() ? iterator_->get_HasCurrent(has_current)
  150. : E_CHANGED_STATE;
  151. }
  152. IFACEMETHODIMP MoveNext(boolean* has_current) override {
  153. return view_->ValidState() ? iterator_->MoveNext(has_current)
  154. : E_CHANGED_STATE;
  155. }
  156. IFACEMETHODIMP GetMany(
  157. unsigned capacity,
  158. ABI::Windows::Foundation::Collections::IKeyValuePair<LogicalK,
  159. LogicalV>** value,
  160. unsigned* actual) override {
  161. return view_->ValidState() ? iterator_->GetMany(capacity, value, actual)
  162. : E_CHANGED_STATE;
  163. }
  164. private:
  165. // Helper for iteration:
  166. void ConvertMapToVectorIterator() {
  167. // Create a vector that will hold Map's key-value pairs.
  168. auto vector = Microsoft::WRL::Make<
  169. Vector<ABI::Windows::Foundation::Collections::IKeyValuePair<
  170. LogicalK, LogicalV>*>>();
  171. // Fill the vector with container data.
  172. for (const auto& pair : view_->get_map()) {
  173. auto key_value_pair =
  174. Microsoft::WRL::Make<internal::KeyValuePair<AbiK, AbiV>>(
  175. pair.first, pair.second);
  176. vector->Append(key_value_pair.Get());
  177. }
  178. // Return an iterator to that vector.
  179. // Iterator is immutable (wraps an IVectorView) and Vector's lifecycle is
  180. // ensured cause the view holds a reference to the vector, and iterator
  181. // holds a reference to the view.
  182. HRESULT hr = vector->First(&iterator_);
  183. DCHECK(SUCCEEDED(hr));
  184. }
  185. Microsoft::WRL::ComPtr<MapView> view_;
  186. Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<
  187. ABI::Windows::Foundation::Collections::IKeyValuePair<LogicalK,
  188. LogicalV>*>>
  189. iterator_;
  190. };
  191. class MapView
  192. : public Microsoft::WRL::RuntimeClass<
  193. Microsoft::WRL::RuntimeClassFlags<
  194. Microsoft::WRL::WinRtClassicComMix |
  195. Microsoft::WRL::InhibitRoOriginateError>,
  196. ABI::Windows::Foundation::Collections::
  197. IMapView<internal::LogicalK<K, V>, internal::LogicalV<K, V>>,
  198. ABI::Windows::Foundation::Collections::IIterable<
  199. ABI::Windows::Foundation::Collections::IKeyValuePair<
  200. internal::LogicalK<K, V>,
  201. internal::LogicalV<K, V>>*>,
  202. ABI::Windows::Foundation::Collections::MapChangedEventHandler<
  203. internal::LogicalK<K, V>,
  204. internal::LogicalV<K, V>>> {
  205. public:
  206. explicit MapView(Microsoft::WRL::ComPtr<Map<LogicalK, LogicalV>> map)
  207. : map_(std::move(map)) {
  208. map_->add_MapChanged(this, &map_changed_token_);
  209. }
  210. ~MapView() override {
  211. if (map_)
  212. map_->remove_MapChanged(map_changed_token_);
  213. }
  214. // ABI::Windows::Foundation::Collections::IMapView:
  215. IFACEMETHODIMP Lookup(AbiK key, AbiV* value) override {
  216. return map_ ? map_->Lookup(key, value) : E_CHANGED_STATE;
  217. }
  218. IFACEMETHODIMP get_Size(unsigned int* size) override {
  219. return map_ ? map_->get_Size(size) : E_CHANGED_STATE;
  220. }
  221. IFACEMETHODIMP HasKey(AbiK key, boolean* found) override {
  222. return map_ ? map_->HasKey(key, found) : E_CHANGED_STATE;
  223. }
  224. IFACEMETHODIMP Split(
  225. ABI::Windows::Foundation::Collections::IMapView<LogicalK, LogicalV>**
  226. first_partition,
  227. ABI::Windows::Foundation::Collections::IMapView<LogicalK, LogicalV>**
  228. second_partition) override {
  229. NOTIMPLEMENTED();
  230. return E_NOTIMPL;
  231. }
  232. // ABI::Windows::Foundation::Collections::IIterable:
  233. IFACEMETHODIMP First(
  234. ABI::Windows::Foundation::Collections::IIterator<
  235. ABI::Windows::Foundation::Collections::IKeyValuePair<LogicalK,
  236. LogicalV>*>**
  237. first) override {
  238. return map_ ? map_->First(first) : E_CHANGED_STATE;
  239. }
  240. // ABI::Windows::Foundation::Collections::MapChangedEventHandler:
  241. IFACEMETHODIMP Invoke(
  242. ABI::Windows::Foundation::Collections::IObservableMap<LogicalK,
  243. LogicalV>* sender,
  244. ABI::Windows::Foundation::Collections::IMapChangedEventArgs<LogicalK>*
  245. e) override {
  246. DCHECK_EQ(map_.Get(), sender);
  247. map_.Reset();
  248. sender->remove_MapChanged(map_changed_token_);
  249. return S_OK;
  250. }
  251. // Accessor used in MapIterator for iterating over Map's container.
  252. // Will remain valid during the entire iteration.
  253. const std::map<StorageK, StorageV, internal::Less>& get_map() {
  254. DCHECK(map_);
  255. return map_->map_;
  256. }
  257. bool ValidState() const { return map_; }
  258. private:
  259. Microsoft::WRL::ComPtr<Map<LogicalK, LogicalV>> map_;
  260. EventRegistrationToken map_changed_token_;
  261. };
  262. public:
  263. Map() = default;
  264. explicit Map(const std::map<StorageK, StorageV, internal::Less>& map)
  265. : map_(map) {}
  266. explicit Map(std::map<StorageK, StorageV, internal::Less>&& map)
  267. : map_(std::move(map)) {}
  268. // ABI::Windows::Foundation::Collections::IMap:
  269. IFACEMETHODIMP Lookup(AbiK key, AbiV* value) override {
  270. auto it = map_.find(key);
  271. if (it == map_.cend())
  272. return E_BOUNDS;
  273. return internal::CopyTo(it->second, value);
  274. }
  275. IFACEMETHODIMP get_Size(unsigned int* size) override {
  276. *size = map_.size();
  277. return S_OK;
  278. }
  279. IFACEMETHODIMP HasKey(AbiK key, boolean* found) override {
  280. *found = Contains(map_, key);
  281. return S_OK;
  282. }
  283. IFACEMETHODIMP GetView(
  284. ABI::Windows::Foundation::Collections::IMapView<LogicalK, LogicalV>**
  285. view) override {
  286. return Microsoft::WRL::Make<MapView>(this).CopyTo(view);
  287. }
  288. IFACEMETHODIMP Insert(AbiK key, AbiV value, boolean* replaced) override {
  289. *replaced = !InsertOrAssign(map_, key, std::move(value)).second;
  290. NotifyMapChanged(*replaced ? ABI::Windows::Foundation::Collections::
  291. CollectionChange_ItemChanged
  292. : ABI::Windows::Foundation::Collections::
  293. CollectionChange_ItemInserted,
  294. key);
  295. return S_OK;
  296. }
  297. IFACEMETHODIMP Remove(AbiK key) override {
  298. if (!map_.erase(key))
  299. return E_BOUNDS;
  300. NotifyMapChanged(
  301. ABI::Windows::Foundation::Collections::CollectionChange_ItemRemoved,
  302. key);
  303. return S_OK;
  304. }
  305. IFACEMETHODIMP Clear() override {
  306. map_.clear();
  307. NotifyMapChanged(
  308. ABI::Windows::Foundation::Collections::CollectionChange_Reset,
  309. 0); // NOLINT(modernize-use-nullptr): AbiK may not be a pointer.
  310. return S_OK;
  311. }
  312. // ABI::Windows::Foundation::Collections::IObservableMap:
  313. IFACEMETHODIMP add_MapChanged(
  314. ABI::Windows::Foundation::Collections::MapChangedEventHandler<LogicalK,
  315. LogicalV>*
  316. handler,
  317. EventRegistrationToken* token) override {
  318. token->value = handler_id_++;
  319. handlers_.emplace_hint(handlers_.end(), token->value, handler);
  320. return S_OK;
  321. }
  322. IFACEMETHODIMP remove_MapChanged(EventRegistrationToken token) override {
  323. return handlers_.erase(token.value) ? S_OK : E_BOUNDS;
  324. }
  325. // ABI::Windows::Foundation::Collections::IIterable:
  326. IFACEMETHODIMP First(
  327. ABI::Windows::Foundation::Collections::IIterator<
  328. ABI::Windows::Foundation::Collections::IKeyValuePair<LogicalK,
  329. LogicalV>*>**
  330. first) override {
  331. return Microsoft::WRL::Make<MapIterator>(
  332. Microsoft::WRL::Make<MapView>(this))
  333. .CopyTo(first);
  334. }
  335. private:
  336. ~Map() override {
  337. // Handlers should not outlive the Map. Furthermore, they must ensure
  338. // they are unregistered before the the handler is destroyed. This implies
  339. // there should be no handlers left when the Map is destructed.
  340. DCHECK(handlers_.empty());
  341. }
  342. void NotifyMapChanged(
  343. ABI::Windows::Foundation::Collections::CollectionChange change,
  344. AbiK key) {
  345. auto args =
  346. Microsoft::WRL::Make<internal::MapChangedEventArgs<AbiK>>(change, key);
  347. // Invoking the handlers could result in mutations to the map, thus we make
  348. // a copy beforehand.
  349. auto handlers = handlers_;
  350. for (auto& handler : handlers)
  351. handler.second->Invoke(this, args.Get());
  352. }
  353. std::map<StorageK, StorageV, internal::Less> map_;
  354. base::flat_map<int64_t,
  355. ABI::Windows::Foundation::Collections::
  356. MapChangedEventHandler<LogicalK, LogicalV>*>
  357. handlers_;
  358. int64_t handler_id_ = 0;
  359. };
  360. } // namespace win
  361. } // namespace base
  362. #endif // BASE_WIN_MAP_H_