cosmos-sdk/orm/encoding/ormkv/seq.go
Aaron Craelius c41ac20c6c
feat(orm): add ormkv.EntryCodec and ormkv.IndexCodec's (#10647)
* feat(orm): add KeyCodec

* WIP

* code coverage

* add DefaultValue test

* fix range key check

* revert DefaultValue

* fix range check

* feat(orm): add ormkv.Codec's

* WIP

* add UniqueKeyCodec

* add IndexKeyCodec

* fixes

* add SeqCodec

* add doc comments

* test fields

* refactor field names

* Update orm/encoding/ormkv/index_key.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>

* Update orm/encoding/ormkv/index_key.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>

* Update orm/encoding/ormkv/index_key.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>

* Update orm/encoding/ormkv/unique_key.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>

* add tests for entry strings

* address review comments

* fix non-deterministic string rendering and tests

* Update x/auth/middleware/priority_test.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>

* Update x/auth/middleware/priority_test.go

Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
2021-12-02 22:21:57 -05:00

70 lines
1.4 KiB
Go

package ormkv
import (
"bytes"
"encoding/binary"
"github.com/cosmos/cosmos-sdk/orm/types/ormerrors"
"google.golang.org/protobuf/reflect/protoreflect"
)
// SeqCodec is the codec for auto-incrementing uint64 primary key sequences.
type SeqCodec struct {
tableName protoreflect.FullName
prefix []byte
}
// NewSeqCodec creates a new SeqCodec.
func NewSeqCodec(tableName protoreflect.FullName, prefix []byte) *SeqCodec {
return &SeqCodec{tableName: tableName, prefix: prefix}
}
var _ EntryCodec = &SeqCodec{}
func (s SeqCodec) DecodeEntry(k, v []byte) (Entry, error) {
if !bytes.Equal(k, s.prefix) {
return nil, ormerrors.UnexpectedDecodePrefix
}
x, err := s.DecodeValue(v)
if err != nil {
return nil, err
}
return &SeqEntry{
TableName: s.tableName,
Value: x,
}, nil
}
func (s SeqCodec) EncodeEntry(entry Entry) (k, v []byte, err error) {
seqEntry, ok := entry.(*SeqEntry)
if !ok {
return nil, nil, ormerrors.BadDecodeEntry
}
if seqEntry.TableName != s.tableName {
return nil, nil, ormerrors.BadDecodeEntry
}
return s.prefix, s.EncodeValue(seqEntry.Value), nil
}
func (s SeqCodec) Prefix() []byte {
return s.prefix
}
func (s SeqCodec) EncodeValue(seq uint64) (v []byte) {
bz := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(bz, seq)
return bz[:n]
}
func (s SeqCodec) DecodeValue(v []byte) (uint64, error) {
if len(v) == 0 {
return 0, nil
}
return binary.ReadUvarint(bytes.NewReader(v))
}