File: stack.go

package info (click to toggle)
golang-github-marstr-collection 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 208 kB
  • sloc: makefile: 2
file content (77 lines) | stat: -rw-r--r-- 1,756 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package collection

import (
	"context"
	"sync"
)

// Stack implements a basic FILO structure.
type Stack[T any] struct {
	underlyer *LinkedList[T]
	key       sync.RWMutex
}

// NewStack instantiates a new FILO structure.
func NewStack[T any](entries ...T) *Stack[T] {
	retval := &Stack[T]{}
	retval.underlyer = NewLinkedList[T]()

	for _, entry := range entries {
		retval.Push(entry)
	}
	return retval
}

// Enumerate peeks at each element in the stack without mutating it.
func (stack *Stack[T]) Enumerate(ctx context.Context) Enumerator[T] {
	stack.key.RLock()
	defer stack.key.RUnlock()

	return stack.underlyer.Enumerate(ctx)
}

// IsEmpty tests the Stack to determine if it is populate or not.
func (stack *Stack[T]) IsEmpty() bool {
	stack.key.RLock()
	defer stack.key.RUnlock()
	return stack.underlyer == nil || stack.underlyer.IsEmpty()
}

// Push adds an entry to the top of the Stack.
func (stack *Stack[T]) Push(entry T) {
	stack.key.Lock()
	defer stack.key.Unlock()

	if nil == stack.underlyer {
		stack.underlyer = NewLinkedList[T]()
	}
	stack.underlyer.AddFront(entry)
}

// Pop returns the entry at the top of the Stack then removes it.
func (stack *Stack[T]) Pop() (T, bool) {
	stack.key.Lock()
	defer stack.key.Unlock()

	if nil == stack.underlyer {
		return *new(T), false
	}
	return stack.underlyer.RemoveFront()
}

// Peek returns the entry at the top of the Stack without removing it.
func (stack *Stack[T]) Peek() (T, bool) {
	stack.key.RLock()
	defer stack.key.RUnlock()
	return stack.underlyer.PeekFront()
}

// Size returns the number of entries populating the Stack.
func (stack *Stack[T]) Size() uint {
	stack.key.RLock()
	defer stack.key.RUnlock()
	if stack.underlyer == nil {
		return 0
	}
	return stack.underlyer.Length()
}