github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/state/protocol/protocol_state/kvstore/encoding.go (about)

     1  package kvstore
     2  
     3  import (
     4  	"bytes"
     5  
     6  	"github.com/vmihailenco/msgpack/v4"
     7  
     8  	"github.com/onflow/flow-go/module/irrecoverable"
     9  	"github.com/onflow/flow-go/state/protocol/protocol_state"
    10  )
    11  
    12  // versionedEncode is a helper function for implementing VersionedEncodable.
    13  // No errors are expected during normal operation.
    14  func versionedEncode(version uint64, pairs any) (uint64, []byte, error) {
    15  	bz, err := msgpack.Marshal(pairs)
    16  	if err != nil {
    17  		return 0, nil, irrecoverable.NewExceptionf("could not encode kvstore (version=%d): %w", version, err)
    18  	}
    19  	return version, bz, nil
    20  }
    21  
    22  // VersionedDecode decodes a serialized key-value store instance with the given version.
    23  // Errors:
    24  //   - ErrUnsupportedVersion if input version is not supported
    25  func VersionedDecode(version uint64, bz []byte) (protocol_state.KVStoreAPI, error) {
    26  	var target protocol_state.KVStoreAPI
    27  	switch version {
    28  	case 0:
    29  		target = new(Modelv0)
    30  	case 1:
    31  		target = new(Modelv1)
    32  	default:
    33  		return nil, ErrUnsupportedVersion
    34  	}
    35  	err := msgpack.NewDecoder(bytes.NewBuffer(bz)).Decode(&target)
    36  	if err != nil {
    37  		return nil, irrecoverable.NewExceptionf("could not decode kvstore (version=%d): %w", version, err)
    38  	}
    39  	return target, nil
    40  }