From c968fe9e4be1cf62295e19434f55cc0243568071 Mon Sep 17 00:00:00 2001 From: Likhita Polavarapu <78951027+likhita-809@users.noreply.github.com> Date: Mon, 7 Aug 2023 15:16:26 +0530 Subject: [PATCH] feat: Add legacy format key codec for bytes in collections (#17104) --- types/collections.go | 28 ++++++++++++++++++++++++++++ types/collections_test.go | 4 ++++ 2 files changed, 32 insertions(+) diff --git a/types/collections.go b/types/collections.go index a0c8ad4005..eb3146222b 100644 --- a/types/collections.go +++ b/types/collections.go @@ -44,6 +44,12 @@ var ( // state backwards compatibility. // Deprecated: use collections.Uint64Key instead. LEUint64Key collcodec.KeyCodec[uint64] = leUint64Key{} + + // LengthPrefixedBytesKey is a collections KeyCodec to work with []byte. + // Deprecated: exists only for state compatibility reasons, should not be + // used for new storage keys using []byte. Please use the BytesKey provided + // in the collections package. + LengthPrefixedBytesKey collcodec.KeyCodec[[]byte] = lengthPrefixedBytesKey{collections.BytesKey} ) type addressUnion interface { @@ -135,6 +141,28 @@ func LengthPrefixedAddressKey[T addressUnion](keyCodec collcodec.KeyCodec[T]) co } } +// Deprecated: lengthPrefixedBytesKey is a special key codec used to retain state backwards compatibility +// when a bytes key is used as an index key. +type lengthPrefixedBytesKey struct { + collcodec.KeyCodec[[]byte] +} + +func (g lengthPrefixedBytesKey) Encode(buffer, key []byte) (int, error) { + return g.EncodeNonTerminal(buffer, key) +} + +func (g lengthPrefixedBytesKey) Decode(buffer []byte) (int, []byte, error) { + return g.DecodeNonTerminal(buffer) +} + +func (g lengthPrefixedBytesKey) Size(key []byte) int { + return g.SizeNonTerminal(key) +} + +func (g lengthPrefixedBytesKey) KeyType() string { + return "index_key/" + g.KeyCodec.KeyType() +} + // Collection Codecs type intValueCodec struct{} diff --git a/types/collections_test.go b/types/collections_test.go index 75a19f03fa..d8e919cb7c 100644 --- a/types/collections_test.go +++ b/types/collections_test.go @@ -30,6 +30,10 @@ func TestCollectionsCorrectness(t *testing.T) { t.Run("Time", func(t *testing.T) { colltest.TestKeyCodec(t, TimeKey, time.Time{}) }) + + t.Run("BytesIndexingKey", func(t *testing.T) { + colltest.TestKeyCodec(t, LengthPrefixedBytesKey, []byte{}) + }) } func TestLEUint64Key(t *testing.T) {