stack.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package vm
  17. import (
  18. "fmt"
  19. "math/big"
  20. )
  21. // Stack is an object for basic stack operations. Items popped to the stack are
  22. // expected to be changed and modified. stack does not take care of adding newly
  23. // initialised objects.
  24. type Stack struct {
  25. data []*big.Int
  26. }
  27. func newstack() *Stack {
  28. return &Stack{data: make([]*big.Int, 0, 1024)}
  29. }
  30. // Data returns the underlying big.Int array.
  31. func (st *Stack) Data() []*big.Int {
  32. return st.data
  33. }
  34. func (st *Stack) push(d *big.Int) {
  35. // NOTE push limit (1024) is checked in baseCheck
  36. //stackItem := new(big.Int).Set(d)
  37. //st.data = append(st.data, stackItem)
  38. st.data = append(st.data, d)
  39. }
  40. func (st *Stack) pushN(ds ...*big.Int) {
  41. st.data = append(st.data, ds...)
  42. }
  43. func (st *Stack) pop() (ret *big.Int) {
  44. ret = st.data[len(st.data)-1]
  45. st.data = st.data[:len(st.data)-1]
  46. return
  47. }
  48. func (st *Stack) len() int {
  49. return len(st.data)
  50. }
  51. func (st *Stack) swap(n int) {
  52. st.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]
  53. }
  54. func (st *Stack) dup(pool *intPool, n int) {
  55. st.push(pool.get().Set(st.data[st.len()-n]))
  56. }
  57. func (st *Stack) peek() *big.Int {
  58. return st.data[st.len()-1]
  59. }
  60. // Back returns the n'th item in stack
  61. func (st *Stack) Back(n int) *big.Int {
  62. return st.data[st.len()-n-1]
  63. }
  64. // Print dumps the content of the stack
  65. func (st *Stack) Print() {
  66. fmt.Println("### stack ###")
  67. if len(st.data) > 0 {
  68. for i, val := range st.data {
  69. fmt.Printf("%-3d %v\n", i, val)
  70. }
  71. } else {
  72. fmt.Println("-- empty --")
  73. }
  74. fmt.Println("#############")
  75. }