Debian Codegraph @

internal/util/stack.go

raw symbols SCIP
1 //Copyright 2013 Vastech SA (PTY) LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package util
16
17 type Stack struct {
18 stack []interface{}
19 }
20
21 // NewStack will return a new, initialized stack.
22 func NewStack(capacity int) *Stack {
23 return &Stack{make([]interface{}, 0, capacity)}
24 }
25
26 // Len returns the number of items on the stack, or 0 if it is empty.
27 func (this *Stack) Len() int {
28 return len(this.stack)
29 }
30
31 // Peek will return the item at `index` in the stack, where 0 is the bottom. Returns
32 // nil if the index exceeds the length of the stack.
33 func (this *Stack) Peek(index int) interface{} {
34 if index > len(this.stack)-1 {
35 return nil
36 }
37 return this.stack[index]
38 }
39
40 // Pop removes and returns the item at the top of the stack or nil.
41 func (this *Stack) Pop() (item interface{}) {
42 if len(this.stack) == 0 {
43 return nil
44 }
45 item = this.stack[len(this.stack)-1]
46 this.stack = this.stack[:len(this.stack)-1]
47 return
48 }
49
50 // Push places an item at the top of the stack or panics if item is nil.
51 func (this *Stack) Push(items ...interface{}) *Stack {
52 for _, item := range items {
53 if item == nil {
54 panic("nil item may not be pushed")
55 }
56 this.stack = append(this.stack, item)
57 }
58 return this
59 }
60
61 // Top returns the item at the top of the stack without altering the stack.
62 func (this *Stack) Top() interface{} {
63 return this.stack[len(this.stack)-1]
64 }