twalk.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Implement twalk using twalk_r.
  2. Copyright (C) 2019-2026 Free Software Foundation, Inc.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <https://www.gnu.org/licenses/>.
  13. */
  14. #define _GNU_SOURCE 1
  15. #include <search.h>
  16. struct twalk_with_twalk_r_closure
  17. {
  18. void (*action) (const void *, VISIT, int);
  19. int depth;
  20. };
  21. static void
  22. twalk_with_twalk_r_action (const void *nodep, VISIT which, void *closure0)
  23. {
  24. struct twalk_with_twalk_r_closure *closure = closure0;
  25. switch (which)
  26. {
  27. case leaf:
  28. closure->action (nodep, which, closure->depth);
  29. break;
  30. case preorder:
  31. closure->action (nodep, which, closure->depth);
  32. ++closure->depth;
  33. break;
  34. case postorder:
  35. /* The preorder action incremented the depth. */
  36. closure->action (nodep, which, closure->depth - 1);
  37. break;
  38. case endorder:
  39. --closure->depth;
  40. closure->action (nodep, which, closure->depth);
  41. break;
  42. }
  43. }
  44. void
  45. twalk (const void *root, void (*action) (const void *, VISIT, int))
  46. {
  47. struct twalk_with_twalk_r_closure closure = { action, 0 };
  48. twalk_r (root, twalk_with_twalk_r_action, &closure);
  49. }