tlv: add MakeBigSizeRecord to save space

This commit adds a pair of encoder/decoder to take the advantage of the
BigSize format when encoding an uint64 and possibly an uint32.

Often the time an uint64 value is not big enough to fill all the 8
bytes, thus using BigSize can save extra bytes when save it to db. And
for uint32, if we know most of the values do not exceed 65536, we can
also save at least 1 byte using BigSize format.

This commit introduces `MakeBigSizeRecord` that can be used optionally
where db space is a concern.
This commit is contained in:
yyforyongyu committed 2022-04-16 12:05:23 +08:00
1 parent 02d17bb81a
commit 4ddb5c586b
4 files changed
+257

No files matched your search

+37
View File
@@ -249,3 +249,40 @@ func SortRecords(records []Record) {
return records[i].Type() < records[j].Type()
})
}
// MakeBigSizeRecord creates a tlv record using the BigSize format. The only
// allowed values are uint64 and uint32.
//
// NOTE: for uint32, we would only gain space reduction if the encoded value is
// no greater than 65535, which requires at most 3 bytes to encode.
func MakeBigSizeRecord(typ Type, val interface{}) Record {
var (
staticSize uint64
sizeFunc SizeFunc
encoder Encoder
decoder Decoder
)
switch val.(type) {
case *uint32:
sizeFunc = SizeBigSize(val)
encoder = EBigSize
decoder = DBigSize
case *uint64:
sizeFunc = SizeBigSize(val)
encoder = EBigSize
decoder = DBigSize
default:
panic(fmt.Sprintf("unknown supported compact type: %T", val))
}
return Record{
value: val,
typ: typ,
staticSize: staticSize,
sizeFunc: sizeFunc,
encoder: encoder,
decoder: decoder,
}
}