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
26namespace android {
27namespace vintf {
28
29// A XmlFileGroup is a wrapped multimap from name to T, where T
30// must be a subclass of XmlFile.
31template <typename T>
32struct 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:
40    virtual ~XmlFileGroup() {}
41
42    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
51    virtual bool shouldAddXmlFile(const T&) const { return true; }
52
53    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()) { }
57    ConstMultiMapValueIterable<std::string, T> getXmlFiles() const {
58        return ConstMultiMapValueIterable<std::string, T>(mXmlFiles);
59    }
60
61    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 = pair.first;
66                }
67                return false;
68            }
69        }
70        return true;
71    }
72
73   protected:
74    map mXmlFiles;
75};
76
77}  // namespace vintf
78}  // namespace android
79
80#endif  // ANDROID_VINTF_XML_FILE_GROUP_H
81