gen_stack.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package genstack
  2. // GenStack implements a generational stack.
  3. //
  4. // GenStack works as common stack except for the fact that all elements in the
  5. // older generation are guaranteed to be popped before any element in the newer
  6. // generation. New elements are always pushed to the current (newest)
  7. // generation.
  8. //
  9. // We could also say that GenStack behaves as a stack in case of a single
  10. // generation, but it behaves as a queue of individual generation stacks.
  11. type GenStack[T any] struct {
  12. // We can represent arbitrary number of generations using 2 stacks. The
  13. // new stack stores all new pushes and the old stack serves all reads.
  14. // Old stack can represent multiple generations. If old == new, then all
  15. // elements pushed in previous (not current) generations have already
  16. // been popped.
  17. old *stack[T]
  18. new *stack[T]
  19. }
  20. // NewGenStack creates a new empty GenStack.
  21. func NewGenStack[T any]() *GenStack[T] {
  22. s := &stack[T]{}
  23. return &GenStack[T]{
  24. old: s,
  25. new: s,
  26. }
  27. }
  28. func (s *GenStack[T]) Pop() (T, bool) {
  29. // Pushes always append to the new stack, so if the old once becomes
  30. // empty, it will remail empty forever.
  31. if s.old.len() == 0 && s.old != s.new {
  32. s.old = s.new
  33. }
  34. if s.old.len() == 0 {
  35. var zero T
  36. return zero, false
  37. }
  38. return s.old.pop(), true
  39. }
  40. // Push pushes a new element at the top of the stack.
  41. func (s *GenStack[T]) Push(v T) { s.new.push(v) }
  42. // NextGen starts a new stack generation.
  43. func (s *GenStack[T]) NextGen() {
  44. if s.old == s.new {
  45. s.new = &stack[T]{}
  46. return
  47. }
  48. // We need to pop from the old stack to the top of the new stack. Let's
  49. // have an example:
  50. //
  51. // Old: <bottom> 4 3 2 1
  52. // New: <bottom> 8 7 6 5
  53. // PopOrder: 1 2 3 4 5 6 7 8
  54. //
  55. //
  56. // To preserve pop order, we have to take all elements from the old
  57. // stack and push them to the top of new stack:
  58. //
  59. // New: 8 7 6 5 4 3 2 1
  60. //
  61. s.new.push(s.old.takeAll()...)
  62. // We have the old stack allocated and empty, so why not to reuse it as
  63. // new new stack.
  64. s.old, s.new = s.new, s.old
  65. }
  66. // Len returns number of elements in the stack.
  67. func (s *GenStack[T]) Len() int {
  68. l := s.old.len()
  69. if s.old != s.new {
  70. l += s.new.len()
  71. }
  72. return l
  73. }