XmlFileGroup.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #ifndef ANDROID_VINTF_XML_FILE_GROUP_H
  17. #define ANDROID_VINTF_XML_FILE_GROUP_H
  18. #include <map>
  19. #include <type_traits>
  20. #include "MapValueIterator.h"
  21. #include "XmlFile.h"
  22. namespace android {
  23. namespace vintf {
  24. // A XmlFileGroup is a wrapped multimap from name to T, where T
  25. // must be a subclass of XmlFile.
  26. template <typename T>
  27. struct XmlFileGroup {
  28. static_assert(std::is_base_of<XmlFile, T>::value, "T must be a subclass of XmlFile");
  29. private:
  30. using map = std::multimap<std::string, T>;
  31. using const_range = std::pair<typename map::const_iterator, typename map::const_iterator>;
  32. public:
  33. virtual ~XmlFileGroup() {}
  34. bool addXmlFile(T&& t) {
  35. if (!shouldAddXmlFile(t)) {
  36. return false;
  37. }
  38. std::string name = t.name();
  39. mXmlFiles.emplace(std::move(name), std::move(t));
  40. return true;
  41. }
  42. virtual bool shouldAddXmlFile(const T&) const { return true; }
  43. const_range getXmlFiles(const std::string& key) const { return mXmlFiles.equal_range(key); }
  44. // Return an iterable to all T objects. Call it as follows:
  45. // for (const auto& e : vm.getXmlFiles()) { }
  46. ConstMultiMapValueIterable<std::string, T> getXmlFiles() const {
  47. return ConstMultiMapValueIterable<std::string, T>(mXmlFiles);
  48. }
  49. bool addAllXmlFiles(XmlFileGroup* other, std::string* error) {
  50. for (auto& pair : other->mXmlFiles) {
  51. if (!addXmlFile(std::move(pair.second))) {
  52. if (error) {
  53. *error = "XML File \"" + pair.first + "\" has a conflict.";
  54. }
  55. return false;
  56. }
  57. }
  58. other->mXmlFiles.clear();
  59. return true;
  60. }
  61. protected:
  62. map mXmlFiles;
  63. };
  64. } // namespace vintf
  65. } // namespace android
  66. #endif // ANDROID_VINTF_XML_FILE_GROUP_H