Skip to content

Commit

Permalink
util/codec: add EncodedBytesLength (pingcap#15170)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiqiangxu authored Mar 15, 2020
1 parent 0827d77 commit 892dced
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
4 changes: 2 additions & 2 deletions structure/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ func (t *TxStructure) encodeStringDataKey(key []byte) kv.Key {
}

func (t *TxStructure) encodeHashMetaKey(key []byte) kv.Key {
ek := make([]byte, 0, len(t.prefix)+len(key)+24)
ek := make([]byte, 0, len(t.prefix)+codec.EncodedBytesLength(len(key))+8)
ek = append(ek, t.prefix...)
ek = codec.EncodeBytes(ek, key)
return codec.EncodeUint(ek, uint64(HashMeta))
}

func (t *TxStructure) encodeHashDataKey(key []byte, field []byte) kv.Key {
ek := make([]byte, 0, len(t.prefix)+len(key)+len(field)+30)
ek := make([]byte, 0, len(t.prefix)+codec.EncodedBytesLength(len(key))+8+codec.EncodedBytesLength(len(field)))
ek = append(ek, t.prefix...)
ek = codec.EncodeBytes(ek, key)
ek = codec.EncodeUint(ek, uint64(HashData))
Expand Down
7 changes: 7 additions & 0 deletions util/codec/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ func EncodeBytes(b []byte, data []byte) []byte {
return result
}

// EncodedBytesLength returns the length of data after encoded
func EncodedBytesLength(dataLen int) int {
mod := dataLen % encGroupSize
padCount := encGroupSize - mod
return dataLen + padCount + 1 + dataLen/encGroupSize
}

func decodeBytes(b []byte, buf []byte, reverse bool) ([]byte, []byte, error) {
if buf == nil {
buf = make([]byte, 0, len(b))
Expand Down
3 changes: 3 additions & 0 deletions util/codec/bytes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ func (s *testBytesSuite) TestBytesCodec(c *C) {
}

for _, input := range inputs {

c.Assert(EncodedBytesLength(len(input.enc)), Equals, len(input.dec))

if input.desc {
b := EncodeBytesDesc(nil, input.enc)
c.Assert(b, BytesEquals, input.dec)
Expand Down

0 comments on commit 892dced

Please sign in to comment.