github.com/jackc/puddle/v2@v2.2.2-0.20240301145809-72b022bcfc59/internal/genstack/stack.go (about)

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