stack.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package vm
  17. import (
  18. "fmt"
  19. "math/big"
  20. )
  21. func newstack() *stack {
  22. return &stack{}
  23. }
  24. type stack struct {
  25. data []*big.Int
  26. ptr int
  27. }
  28. func (st *stack) Data() []*big.Int {
  29. return st.data[:st.ptr]
  30. }
  31. func (st *stack) push(d *big.Int) {
  32. // NOTE push limit (1024) is checked in baseCheck
  33. stackItem := new(big.Int).Set(d)
  34. if len(st.data) > st.ptr {
  35. st.data[st.ptr] = stackItem
  36. } else {
  37. st.data = append(st.data, stackItem)
  38. }
  39. st.ptr++
  40. }
  41. func (st *stack) pop() (ret *big.Int) {
  42. st.ptr--
  43. ret = st.data[st.ptr]
  44. return
  45. }
  46. func (st *stack) len() int {
  47. return st.ptr
  48. }
  49. func (st *stack) swap(n int) {
  50. st.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]
  51. }
  52. func (st *stack) dup(n int) {
  53. st.push(st.data[st.len()-n])
  54. }
  55. func (st *stack) peek() *big.Int {
  56. return st.data[st.len()-1]
  57. }
  58. func (st *stack) require(n int) error {
  59. if st.len() < n {
  60. return fmt.Errorf("stack underflow (%d <=> %d)", len(st.data), n)
  61. }
  62. return nil
  63. }
  64. func (st *stack) Print() {
  65. fmt.Println("### stack ###")
  66. if len(st.data) > 0 {
  67. for i, val := range st.data {
  68. fmt.Printf("%-3d %v\n", i, val)
  69. }
  70. } else {
  71. fmt.Println("-- empty --")
  72. }
  73. fmt.Println("#############")
  74. }