safe_list.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * safe_list - linked list protected against recursive iteration with deletes
  3. *
  4. * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. /*
  19. * Use this linked list implementation as a replacement for list.h if you
  20. * want to allow deleting arbitrary list entries from within one or more
  21. * recursive iterator calling context
  22. */
  23. #ifndef __LIBUBOX_SAFE_LIST_H
  24. #define __LIBUBOX_SAFE_LIST_H
  25. #include <stdbool.h>
  26. #include "list.h"
  27. #include "utils.h"
  28. struct safe_list;
  29. struct safe_list_iterator;
  30. struct safe_list {
  31. struct list_head list;
  32. struct safe_list_iterator *i;
  33. };
  34. int safe_list_for_each(struct safe_list *list,
  35. int (*cb)(void *ctx, struct safe_list *list),
  36. void *ctx);
  37. void safe_list_add(struct safe_list *list, struct safe_list *head);
  38. void safe_list_add_first(struct safe_list *list, struct safe_list *head);
  39. void safe_list_del(struct safe_list *list);
  40. #define INIT_SAFE_LIST(_head) \
  41. do { \
  42. INIT_LIST_HEAD(_head.list); \
  43. (_head)->i = NULL; \
  44. } while (0)
  45. #define SAFE_LIST_INIT(_name) { LIST_HEAD_INIT(_name.list), NULL }
  46. #define SAFE_LIST(_name) struct safe_list _name = SAFE_LIST_INIT(_name)
  47. static inline bool safe_list_empty(struct safe_list *head)
  48. {
  49. return list_empty(&head->list);
  50. }
  51. #endif