github.com/dim4egster/coreth@v0.10.2/core/bounded_buffer.go (about)

     1  // (c) 2022, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package core
     5  
     6  import (
     7  	"github.com/ethereum/go-ethereum/common"
     8  )
     9  
    10  // BoundedBuffer keeps [size] common.Hash entries in a buffer and calls
    11  // [callback] on any item that is evicted. This is typically used for
    12  // dereferencing old roots during block processing.
    13  type BoundedBuffer struct {
    14  	lastPos  int
    15  	size     int
    16  	callback func(common.Hash)
    17  	buffer   []common.Hash
    18  }
    19  
    20  // NewBoundedBuffer creates a new [BoundedBuffer].
    21  func NewBoundedBuffer(size int, callback func(common.Hash)) *BoundedBuffer {
    22  	return &BoundedBuffer{
    23  		size:     size,
    24  		callback: callback,
    25  		buffer:   make([]common.Hash, size),
    26  	}
    27  }
    28  
    29  // Insert adds a new common.Hash to the buffer. If the buffer is full, the
    30  // oldest common.Hash will be evicted and [callback] will be invoked.
    31  //
    32  // WARNING: BoundedBuffer does not support the insertion of empty common.Hash.
    33  // Inserting such data will cause unintended behavior.
    34  func (b *BoundedBuffer) Insert(h common.Hash) {
    35  	nextPos := (b.lastPos + 1) % b.size // the first item added to the buffer will be at position 1
    36  	if b.buffer[nextPos] != (common.Hash{}) {
    37  		b.callback(b.buffer[nextPos])
    38  	}
    39  	b.buffer[nextPos] = h
    40  	b.lastPos = nextPos
    41  }
    42  
    43  // Last retrieves the last item added to the buffer.
    44  // If no items have been added to the buffer, Last returns an empty hash.
    45  func (b *BoundedBuffer) Last() common.Hash {
    46  	return b.buffer[b.lastPos]
    47  }