github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/core/vm/stack.go (about) 1 // Copyright 2014 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The Spectrum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the Spectrum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package vm 18 19 import ( 20 "fmt" 21 "sync" 22 23 "github.com/holiman/uint256" 24 ) 25 26 var stackPool = sync.Pool{ 27 New: func() interface{} { 28 return &Stack{data: make([]uint256.Int, 0, 16)} 29 }, 30 } 31 32 // Stack is an object for basic stack operations. Items popped to the stack are 33 // expected to be changed and modified. stack does not take care of adding newly 34 // initialised objects. 35 type Stack struct { 36 data []uint256.Int 37 } 38 39 func newstack() *Stack { 40 return stackPool.Get().(*Stack) 41 } 42 43 func returnStack(s *Stack) { 44 s.data = s.data[:0] 45 stackPool.Put(s) 46 } 47 func (st *Stack) require(n int) error { 48 if st.len() < n { 49 return fmt.Errorf("stack underflow (%d <=> %d)", len(st.data), n) 50 } 51 return nil 52 } 53 54 // Data returns the underlying uint256.Int array. 55 func (st *Stack) Data() []uint256.Int { 56 return st.data 57 } 58 59 func (st *Stack) push(d *uint256.Int) { 60 // NOTE push limit (1024) is checked in baseCheck 61 st.data = append(st.data, *d) 62 } 63 func (st *Stack) pushN(ds ...uint256.Int) { 64 // FIXME: Is there a way to pass args by pointers. 65 st.data = append(st.data, ds...) 66 } 67 68 func (st *Stack) pop() (ret uint256.Int) { 69 ret = st.data[len(st.data)-1] 70 st.data = st.data[:len(st.data)-1] 71 return 72 } 73 74 func (st *Stack) len() int { 75 return len(st.data) 76 } 77 78 func (st *Stack) swap(n int) { 79 st.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n] 80 } 81 82 func (st *Stack) dup(n int) { 83 st.push(&st.data[st.len()-n]) 84 } 85 86 func (st *Stack) peek() *uint256.Int { 87 return &st.data[st.len()-1] 88 } 89 90 // Back returns the n'th item in stack 91 func (st *Stack) Back(n int) *uint256.Int { 92 return &st.data[st.len()-n-1] 93 } 94 95 func (st *Stack) Print() { 96 fmt.Println("### stack ###") 97 if len(st.data) > 0 { 98 for i, val := range st.data { 99 fmt.Printf("%-3d %v\n", i, val) 100 } 101 } else { 102 fmt.Println("-- empty --") 103 } 104 fmt.Println("#############") 105 }