Avi Drissman | d387f092 | 2022-09-14 20:51:31 | [diff] [blame] | 1 | // Copyright 2022 The Chromium Authors |
Joe Downing | aacd3e1 | 2022-05-02 16:44:10 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_PROTOBUF_H_ |
| 6 | #define MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_PROTOBUF_H_ |
| 7 | |
| 8 | #include <map> |
| 9 | #include <utility> |
| 10 | |
| 11 | #include "base/logging.h" |
| 12 | #include "mojo/public/cpp/bindings/map_traits.h" |
| 13 | #include "third_party/protobuf/src/google/protobuf/map.h" |
| 14 | |
| 15 | namespace mojo { |
| 16 | |
| 17 | template <typename K, typename V> |
| 18 | struct MapTraits<::google::protobuf::Map<K, V>> { |
| 19 | using Key = K; |
| 20 | using Value = V; |
| 21 | using Iterator = typename ::google::protobuf::Map<K, V>::iterator; |
| 22 | using ConstIterator = typename ::google::protobuf::Map<K, V>::const_iterator; |
| 23 | |
| 24 | static bool IsNull(const ::google::protobuf::Map<K, V>& input) { |
| 25 | // Protobuf Maps are always converted to a non-null mojom map. |
| 26 | return false; |
| 27 | } |
| 28 | |
| 29 | static void SetToNull(::google::protobuf::Map<K, V>* output) { |
| 30 | // Protobuf Maps don't have a null state. Set it to empty instead. |
| 31 | output->clear(); |
| 32 | } |
| 33 | |
| 34 | static size_t GetSize(const ::google::protobuf::Map<K, V>& input) { |
| 35 | return input.size(); |
| 36 | } |
| 37 | |
| 38 | static ConstIterator GetBegin(const ::google::protobuf::Map<K, V>& input) { |
| 39 | return input.begin(); |
| 40 | } |
| 41 | static Iterator GetBegin(::google::protobuf::Map<K, V>& input) { |
| 42 | return input.begin(); |
| 43 | } |
| 44 | |
| 45 | static void AdvanceIterator(ConstIterator& iterator) { iterator++; } |
| 46 | static void AdvanceIterator(Iterator& iterator) { iterator++; } |
| 47 | |
| 48 | static const K& GetKey(Iterator& iterator) { return iterator->first; } |
| 49 | static const K& GetKey(ConstIterator& iterator) { return iterator->first; } |
| 50 | |
| 51 | static V& GetValue(Iterator& iterator) { return iterator->second; } |
| 52 | static const V& GetValue(ConstIterator& iterator) { return iterator->second; } |
| 53 | |
| 54 | template <typename MaybeConstKeyType, typename MaybeConstValueType> |
| 55 | static bool Insert(::google::protobuf::Map<K, V>& input, |
| 56 | MaybeConstKeyType&& key, |
| 57 | MaybeConstValueType&& value) { |
| 58 | input.insert({std::forward<MaybeConstKeyType>(key), |
| 59 | std::forward<MaybeConstValueType>(value)}); |
| 60 | return true; |
| 61 | } |
| 62 | |
| 63 | static void SetToEmpty(::google::protobuf::Map<K, V>* output) { |
| 64 | output->clear(); |
| 65 | } |
| 66 | }; |
| 67 | |
| 68 | } // namespace mojo |
| 69 | |
| 70 | #endif // MOJO_PUBLIC_CPP_BINDINGS_MAP_TRAITS_PROTOBUF_H_ |