github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/chain/core/vm/intpool.go (about)

     1  package vm
     2  
     3  import (
     4  	"math/big"
     5  	"sync"
     6  )
     7  
     8  var checkVal = big.NewInt(-42)
     9  
    10  const poolLimit = 256
    11  
    12  type intPool struct {
    13  	pool *Stack
    14  }
    15  
    16  func newIntPool() *intPool {
    17  	return &intPool{pool: newstack()}
    18  }
    19  
    20  func (p *intPool) get() *big.Int {
    21  	if p.pool.len() > 0 {
    22  		return p.pool.pop()
    23  	}
    24  	return new(big.Int)
    25  }
    26  
    27  func (p *intPool) getZero() *big.Int {
    28  	if p.pool.len() > 0 {
    29  		return p.pool.pop().SetUint64(0)
    30  	}
    31  	return new(big.Int)
    32  }
    33  
    34  func (p *intPool) put(is ...*big.Int) {
    35  	if len(p.pool.data) > poolLimit {
    36  		return
    37  	}
    38  	for _, i := range is {
    39  
    40  		if verifyPool {
    41  			i.Set(checkVal)
    42  		}
    43  		p.pool.push(i)
    44  	}
    45  }
    46  
    47  const poolDefaultCap = 25
    48  
    49  type intPoolPool struct {
    50  	pools []*intPool
    51  	lock  sync.Mutex
    52  }
    53  
    54  var poolOfIntPools = &intPoolPool{
    55  	pools: make([]*intPool, 0, poolDefaultCap),
    56  }
    57  
    58  func (ipp *intPoolPool) get() *intPool {
    59  	ipp.lock.Lock()
    60  	defer ipp.lock.Unlock()
    61  
    62  	if len(poolOfIntPools.pools) > 0 {
    63  		ip := ipp.pools[len(ipp.pools)-1]
    64  		ipp.pools = ipp.pools[:len(ipp.pools)-1]
    65  		return ip
    66  	}
    67  	return newIntPool()
    68  }
    69  
    70  func (ipp *intPoolPool) put(ip *intPool) {
    71  	ipp.lock.Lock()
    72  	defer ipp.lock.Unlock()
    73  
    74  	if len(ipp.pools) < cap(ipp.pools) {
    75  		ipp.pools = append(ipp.pools, ip)
    76  	}
    77  }