stack.go 955 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package genstack
  2. // stack is a wrapper around an array implementing a stack.
  3. //
  4. // We cannot use slice to represent the stack because append might change the
  5. // pointer value of the slice. That would be an issue in GenStack
  6. // implementation.
  7. type stack[T any] struct {
  8. arr []T
  9. }
  10. // push pushes a new element at the top of a stack.
  11. func (s *stack[T]) push(vs ...T) { s.arr = append(s.arr, vs...) }
  12. // pop pops the stack top-most element.
  13. //
  14. // If stack length is zero, this method panics.
  15. func (s *stack[T]) pop() T {
  16. idx := s.len() - 1
  17. val := s.arr[idx]
  18. // Avoid memory leak
  19. var zero T
  20. s.arr[idx] = zero
  21. s.arr = s.arr[:idx]
  22. return val
  23. }
  24. // takeAll returns all elements in the stack in order as they are stored - i.e.
  25. // the top-most stack element is the last one.
  26. func (s *stack[T]) takeAll() []T {
  27. arr := s.arr
  28. s.arr = nil
  29. return arr
  30. }
  31. // len returns number of elements in the stack.
  32. func (s *stack[T]) len() int { return len(s.arr) }