1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_VINTF_XML_FILE_GROUP_H
18 #define ANDROID_VINTF_XML_FILE_GROUP_H
19 
20 #include <map>
21 #include <type_traits>
22 
23 #include "MapValueIterator.h"
24 #include "XmlFile.h"
25 
26 namespace android {
27 namespace vintf {
28 
29 // A XmlFileGroup is a wrapped multimap from name to T, where T
30 // must be a subclass of XmlFile.
31 template <typename T>
32 struct XmlFileGroup {
33     static_assert(std::is_base_of<XmlFile, T>::value, "T must be a subclass of XmlFile");
34 
35    private:
36     using map = std::multimap<std::string, T>;
37     using const_range = std::pair<typename map::const_iterator, typename map::const_iterator>;
38 
39    public:
~XmlFileGroupXmlFileGroup40     virtual ~XmlFileGroup() {}
41 
addXmlFileXmlFileGroup42     bool addXmlFile(T&& t) {
43         if (!shouldAddXmlFile(t)) {
44             return false;
45         }
46         std::string name = t.name();
47         mXmlFiles.emplace(std::move(name), std::move(t));
48         return true;
49     }
50 
shouldAddXmlFileXmlFileGroup51     virtual bool shouldAddXmlFile(const T&) const { return true; }
52 
getXmlFilesXmlFileGroup53     const_range getXmlFiles(const std::string& key) const { return mXmlFiles.equal_range(key); }
54 
55     // Return an iterable to all T objects. Call it as follows:
56     // for (const auto& e : vm.getXmlFiles()) { }
getXmlFilesXmlFileGroup57     ConstMultiMapValueIterable<std::string, T> getXmlFiles() const {
58         return ConstMultiMapValueIterable<std::string, T>(mXmlFiles);
59     }
60 
addAllXmlFilesXmlFileGroup61     bool addAllXmlFiles(XmlFileGroup* other, std::string* error) {
62         for (auto& pair : other->mXmlFiles) {
63             if (!addXmlFile(std::move(pair.second))) {
64                 if (error) {
65                     *error = "XML File \"" + pair.first + "\" has a conflict.";
66                 }
67                 return false;
68             }
69         }
70         other->mXmlFiles.clear();
71         return true;
72     }
73 
74    protected:
75     map mXmlFiles;
76 };
77 
78 }  // namespace vintf
79 }  // namespace android
80 
81 #endif  // ANDROID_VINTF_XML_FILE_GROUP_H
82