cosmos-sdk/codec/collections.go
testinginprod ed17f2d437
feat: add collections key encoders and value encoders for common types. (#14760)
Co-authored-by: testinginprod <testinginprod@somewhere.idk>
2023-01-27 11:10:54 +01:00

45 lines
1.0 KiB
Go

package codec
import (
"cosmossdk.io/collections"
"github.com/cosmos/gogoproto/proto"
)
type protoMessage[T any] interface {
*T
proto.Message
}
// CollValue inits a collections.ValueCodec for a generic gogo protobuf message.
func CollValue[T any, PT protoMessage[T]](cdc BinaryCodec) collections.ValueCodec[T] {
return &collValue[T, PT]{cdc.(Codec)}
}
type collValue[T any, PT protoMessage[T]] struct{ cdc Codec }
func (c collValue[T, PT]) Encode(value T) ([]byte, error) {
return c.cdc.Marshal(PT(&value))
}
func (c collValue[T, PT]) Decode(b []byte) (value T, err error) {
err = c.cdc.Unmarshal(b, PT(&value))
return value, err
}
func (c collValue[T, PT]) EncodeJSON(value T) ([]byte, error) {
return c.cdc.MarshalJSON(PT(&value))
}
func (c collValue[T, PT]) DecodeJSON(b []byte) (value T, err error) {
err = c.cdc.UnmarshalJSON(b, PT(&value))
return
}
func (c collValue[T, PT]) Stringify(value T) string {
return PT(&value).String()
}
func (c collValue[T, PT]) ValueType() string {
return "gogoproto/" + proto.MessageName(PT(new(T)))
}