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