chains.nim 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2016 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Template based implementation of singly and doubly linked lists.
  10. ## The involved types should have 'prev' or 'next' fields and the
  11. ## list header should have 'head' or 'tail' fields.
  12. template prepend*(header, node) =
  13. when compiles(header.head):
  14. when compiles(node.prev):
  15. if header.head != nil:
  16. header.head.prev = node
  17. node.next = header.head
  18. header.head = node
  19. when compiles(header.tail):
  20. if header.tail == nil:
  21. header.tail = node
  22. template append*(header, node) =
  23. when compiles(header.head):
  24. if header.head == nil:
  25. header.head = node
  26. when compiles(header.tail):
  27. when compiles(node.prev):
  28. node.prev = header.tail
  29. if header.tail != nil:
  30. header.tail.next = node
  31. header.tail = node
  32. template unlink*(header, node) =
  33. if node.next != nil:
  34. node.next.prev = node.prev
  35. if node.prev != nil:
  36. node.prev.next = node.next
  37. if header.head == node:
  38. header.head = node.prev
  39. if header.tail == node:
  40. header.tail = node.next