traverse.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * traverse.h - node traversing
  3. * Copyright (C) 2017 caryoscelus
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef CORE_NODE_TRAVERSE_H_CC85EE3C_3B5E_5268_9929_8FC36285B95C
  19. #define CORE_NODE_TRAVERSE_H_CC85EE3C_3B5E_5268_9929_8FC36285B95C
  20. #include <list>
  21. #include <core/std/set.h>
  22. #include "abstract_list.h"
  23. namespace rainynite::core {
  24. enum class TraverseDepth {
  25. Once,
  26. Deeper
  27. };
  28. template <typename T>
  29. T traverse_once(AbstractReference root, std::function<optional<T>(AbstractReference)> f, TraverseDepth depth = TraverseDepth::Once) {
  30. set<AbstractReference> traversed;
  31. std::list<AbstractReference> to_traverse;
  32. to_traverse.push_back(root);
  33. while (!to_traverse.empty()) {
  34. auto i = to_traverse.begin();
  35. auto node = *i;
  36. to_traverse.erase(i);
  37. if (traversed.count(node) > 0 && depth == TraverseDepth::Once)
  38. continue;
  39. if (optional<T> result = f(node))
  40. return *result;
  41. if (traversed.count(node) == 0) {
  42. if (auto linked_node = list_cast(node)) {
  43. auto links = linked_node->get_links();
  44. std::copy_if(
  45. links.begin(),
  46. links.end(),
  47. std::back_inserter(to_traverse),
  48. [&traversed, depth](AbstractReference ref) {
  49. return depth == TraverseDepth::Deeper
  50. || traversed.count(ref) == 0;
  51. }
  52. );
  53. }
  54. }
  55. traversed.insert(node);
  56. }
  57. return {};
  58. }
  59. } // namespace rainynite::core
  60. #endif