Debian Codegraph @

exslices/stack.go

raw
1 // Copyright (c) 2024 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package exslices
8
9 import (
10 "iter"
11 )
12
13 type Stack[T comparable] []T
14
15 func (s *Stack[T]) Push(v ...T) {
16 *s = append(*s, v...)
17 }
18
19 // Peek returns the top item from the stack without removing it.
20 func (s *Stack[T]) Peek() (v T, ok bool) {
21 return s.PeekN(1)
22 }
23
24 // PeekN returns the nth item from the top of the stack (1-based).
25 func (s *Stack[T]) PeekN(n int) (v T, ok bool) {
26 if len(*s) < n {
27 return
28 }
29 v = (*s)[len(*s)-n]
30 ok = true
31 return
32 }
33
34 // Pop removes and returns the top item from the stack.
35 func (s *Stack[T]) Pop() (v T, ok bool) {
36 v, ok = s.Peek()
37 if ok {
38 *s = (*s)[:len(*s)-1]
39 }
40 return
41 }
42
43 func (s *Stack[T]) PeekValue() T {
44 v, _ := s.Peek()
45 return v
46 }
47
48 func (s *Stack[T]) PopValue() T {
49 v, _ := s.Pop()
50 return v
51 }
52
53 // Index returns the highest index of the given value in the stack, or -1 if not found.
54 func (s *Stack[T]) Index(val T) int {
55 for i := len(*s) - 1; i >= 0; i-- {
56 if (*s)[i] == val {
57 return i
58 }
59 }
60 return -1
61 }
62
63 // Has returns whether the given value is in the stack.
64 func (s *Stack[T]) Has(val T) bool {
65 return s.Index(val) != -1
66 }
67
68 func (s *Stack[T]) PopIter() iter.Seq[T] {
69 return func(yield func(T) bool) {
70 for {
71 v, ok := s.Pop()
72 if !ok {
73 return
74 }
75 if !yield(v) {
76 return
77 }
78 }
79 }
80 }