github.com/cosmos/cosmos-sdk@v0.50.10/types/simulation/collections.go (about)

     1  package simulation
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"cosmossdk.io/collections"
     8  	collcodec "cosmossdk.io/collections/codec"
     9  
    10  	"github.com/cosmos/cosmos-sdk/types/kv"
    11  )
    12  
    13  func NewStoreDecoderFuncFromCollectionsSchema(schema collections.Schema) func(kvA, kvB kv.Pair) string {
    14  	colls := schema.ListCollections()
    15  	prefixes := make([][]byte, len(colls))
    16  	valueCodecs := make([]collcodec.UntypedValueCodec, len(colls))
    17  	for i, coll := range colls {
    18  		prefixes[i] = coll.GetPrefix()
    19  		valueCodecs[i] = coll.ValueCodec()
    20  	}
    21  
    22  	return func(kvA, kvB kv.Pair) string {
    23  		for i, prefix := range prefixes {
    24  			if bytes.HasPrefix(kvA.Key, prefix) {
    25  				if !bytes.HasPrefix(kvB.Key, prefix) {
    26  					panic(fmt.Sprintf("prefix mismatch, keyA has prefix %x (%s), but keyB does not %x (%s)", prefix, prefix, kvB.Key, kvB.Key))
    27  				}
    28  				vc := valueCodecs[i]
    29  				// unmarshal kvA.Value to the corresponding type
    30  				vA, err := vc.Decode(kvA.Value)
    31  				if err != nil {
    32  					panic(err)
    33  				}
    34  				// unmarshal kvB.Value to the corresponding type
    35  				vB, err := vc.Decode(kvB.Value)
    36  				if err != nil {
    37  					panic(err)
    38  				}
    39  				vAString, err := vc.Stringify(vA)
    40  				if err != nil {
    41  					panic(err)
    42  				}
    43  				vBString, err := vc.Stringify(vB)
    44  				if err != nil {
    45  					panic(err)
    46  				}
    47  				return vAString + "\n" + vBString
    48  			}
    49  		}
    50  		panic(fmt.Errorf("unexpected key %X (%s)", kvA.Key, kvA.Key))
    51  	}
    52  }