trpc.group/trpc-go/trpc-go@v1.0.3/internal/stack/stack.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 // Package stack provides a non-thread-safe stack. 15 package stack 16 17 // Stack is a non-thread-safe stack. 18 type Stack[T any] struct { 19 top *node[T] 20 size int 21 } 22 23 type node[T any] struct { 24 value T 25 prev *node[T] 26 } 27 28 // New creates a stack. 29 func New[T any]() *Stack[T] { 30 return &Stack[T]{} 31 } 32 33 // Size returns the stack size. 34 func (st *Stack[T]) Size() int { 35 return st.size 36 } 37 38 // Reset resets the stack. 39 func (st *Stack[T]) Reset() { 40 st.top = nil 41 st.size = 0 42 } 43 44 // Push pushes an element onto the stack. 45 func (st *Stack[T]) Push(value T) { 46 newNode := &node[T]{ 47 value: value, 48 prev: st.top, 49 } 50 st.top = newNode 51 st.size++ 52 } 53 54 // Pop pops an element from the stack. 55 func (st *Stack[T]) Pop() (T, bool) { 56 if st.size == 0 { 57 var zero T 58 return zero, false 59 } 60 topNode := st.top 61 st.top = topNode.prev 62 topNode.prev = nil 63 st.size-- 64 return topNode.value, true 65 } 66 67 // Peek looks at the top element of the stack. 68 func (st *Stack[T]) Peek() (T, bool) { 69 if st.size == 0 { 70 var zero T 71 return zero, false 72 } 73 return st.top.value, true 74 }