github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/iavl/fast_node.go (about)

     1  package iavl
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/pkg/errors"
     7  	"github.com/tendermint/go-amino"
     8  )
     9  
    10  // NOTE: This file favors int64 as opposed to int for size/counts.
    11  // The Tree on the other hand favors int.  This is intentional.
    12  
    13  type FastNode struct {
    14  	key                  []byte
    15  	versionLastUpdatedAt int64
    16  	value                []byte
    17  }
    18  
    19  // NewFastNode returns a new fast node from a value and version.
    20  func NewFastNode(key []byte, value []byte, version int64) *FastNode {
    21  	return &FastNode{
    22  		key:                  key,
    23  		versionLastUpdatedAt: version,
    24  		value:                value,
    25  	}
    26  }
    27  
    28  // DeserializeFastNode constructs an *FastNode from an encoded byte slice.
    29  func DeserializeFastNode(key []byte, buf []byte) (*FastNode, error) {
    30  	ver, n, cause := amino.DecodeVarint(buf)
    31  	if cause != nil {
    32  		return nil, errors.Wrap(cause, "decoding fastnode.version")
    33  	}
    34  	buf = buf[n:]
    35  
    36  	val, _, cause := amino.DecodeByteSlice(buf)
    37  	if cause != nil {
    38  		return nil, errors.Wrap(cause, "decoding fastnode.value")
    39  	}
    40  
    41  	fastNode := &FastNode{
    42  		key:                  key,
    43  		versionLastUpdatedAt: ver,
    44  		value:                val,
    45  	}
    46  
    47  	return fastNode, nil
    48  }
    49  
    50  func (node *FastNode) encodedSize() int {
    51  	n := amino.VarintSize(node.versionLastUpdatedAt) + amino.ByteSliceSize(node.value)
    52  	return n
    53  }
    54  
    55  // writeBytes writes the FastNode as a serialized byte slice to the supplied io.Writer.
    56  func (node *FastNode) writeBytes(w io.Writer) error {
    57  	if node == nil {
    58  		return errors.New("cannot write nil node")
    59  	}
    60  	cause := amino.EncodeVarint(w, node.versionLastUpdatedAt)
    61  	if cause != nil {
    62  		return errors.Wrap(cause, "writing version last updated at")
    63  	}
    64  	cause = amino.EncodeByteSlice(w, node.value)
    65  	if cause != nil {
    66  		return errors.Wrap(cause, "writing value")
    67  	}
    68  	return nil
    69  }