File: stack.go

package info (click to toggle)
golang-github-marstr-collection 0.3.3%2Bgit20171004.e631537-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 152 kB
  • sloc: makefile: 2
file content (76 lines) | stat: -rw-r--r-- 1,737 bytes parent folder | download | duplicates (2)
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
package collection

import (
	"sync"
)

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

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

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

// Enumerate peeks at each element in the stack without mutating it.
func (stack *Stack) Enumerate(cancel <-chan struct{}) Enumerator {
	stack.key.RLock()
	defer stack.key.RUnlock()

	return stack.underlyer.Enumerate(cancel)
}

// IsEmpty tests the Stack to determine if it is populate or not.
func (stack *Stack) 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) Push(entry interface{}) {
	stack.key.Lock()
	defer stack.key.Unlock()

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

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

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

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

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