Playground
append_test.gno
package varint
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
// Append takes and returns a byte slice rather than a string, so packing a
// sequence reuses one buffer instead of copying the whole prefix per value.
// A string accumulator makes PutUvarints quadratic in the encoded size, which
// on chain is gas a caller pays to produce a result they already had.
func TestAppendReusesOneBuffer(t *testing.T) {
buf := make([]byte, 0, 32)
buf = AppendUvarint(buf, 300)
buf = AppendVarint(buf, -1)
buf = AppendUvarint(buf, 16384)
uassert.Equal(t, "ac020180 8001"[0:0]+hex(string(buf)), "ac0201808001")
// The same bytes the one-shot helpers produce, so the two cannot diverge.
uassert.Equal(t, PutUvarint(300)+PutVarint(-1)+PutUvarint(16384), string(buf))
}
func TestSequenceHelpersMatchAppend(t *testing.T) {
xs := []uint64{0, 1, 127, 128, 300, maxUint64}
buf := []byte{}
for _, x := range xs {
buf = AppendUvarint(buf, x)
}
uassert.Equal(t, string(buf), PutUvarints(xs))
ys := []int64{0, -1, 1, minInt64, maxInt64}
sbuf := []byte{}
for _, y := range ys {
sbuf = AppendVarint(sbuf, y)
}
uassert.Equal(t, string(sbuf), PutVarints(ys))
}
gnomod.toml
module = "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/varint/v0" gno = "0.9" [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 751709 max_deposit = "7000000ugnot"
varint.gno
// Package varint implements LEB128 / protobuf-style variable-length integers
// over strings, with one deliberate restriction: it only accepts the canonical
// encoding of a value.
//
// A varint stores an integer in base 128, least significant group first. Each
// byte carries seven payload bits and a continuation bit in the high position,
// so values below 128 cost one byte, below 16384 two, and a full uint64 at most
// ten. Signed values go through zigzag first, which interleaves positives and
// negatives so that small magnitudes of either sign stay short.
//
// Live demo: [r/moul/x/daily/varintdemo](/r/moul/x/daily/varintdemo/v0).
package varint
import "errors"
// MaxLen is the longest canonical encoding of a uint64: ten groups of seven
// bits covers 70 bits, which is the first multiple of seven past 64.
const MaxLen = 10
var (
// ErrTruncated is returned when the input ends inside a varint, meaning
// the last byte read still had its continuation bit set.
ErrTruncated = errors.New("varint: truncated")
// ErrOverflow is returned when the encoded value does not fit in 64 bits.
ErrOverflow = errors.New("varint: value overflows uint64")
// ErrNotCanonical is returned for an encoding that is longer than it needs
// to be, such as a value padded with trailing continuation groups.
ErrNotCanonical = errors.New("varint: non-canonical encoding")
// ErrTrailing is returned by the all-at-once decoders when bytes remain
// after the last complete value.
ErrTrailing = errors.New("varint: trailing bytes")
)
// PutUvarint returns the canonical encoding of x.
func PutUvarint(x uint64) string {
return string(AppendUvarint(make([]byte, 0, MaxLen), x))
}
// AppendUvarint appends the encoding of x to dst and returns the extended
// slice, the same shape as Go's encoding/binary.
//
// It takes a byte slice and not a string on purpose: a string accumulator
// copies the whole prefix on every append, which makes packing a sequence
// quadratic in the encoded size. On chain that is gas paid to rebuild bytes
// the caller already had.
func AppendUvarint(dst []byte, x uint64) []byte {
for x >= 0x80 {
dst = append(dst, byte(x)|0x80)
x >>= 7
}
return append(dst, byte(x))
}
// PutVarint returns the canonical encoding of x, zigzagged first.
func PutVarint(x int64) string {
return PutUvarint(ZigZag(x))
}
// AppendVarint appends the zigzagged encoding of x to dst.
func AppendVarint(dst []byte, x int64) []byte {
return AppendUvarint(dst, ZigZag(x))
}
// Len reports how many bytes PutUvarint(x) would produce, without encoding it.
func Len(x uint64) int {
n := 1
for x >= 0x80 {
x >>= 7
n++
}
return n
}
// LenVarint reports how many bytes PutVarint(x) would produce.
func LenVarint(x int64) int {
return Len(ZigZag(x))
}
// Uvarint decodes the varint at the start of s and reports how many bytes it
// consumed. The rest of s is ignored, so a stream is read by reslicing.
func Uvarint(s string) (uint64, int, error) {
var x uint64
var shift uint
for i := 0; i < len(s); i++ {
b := s[i]
if i == MaxLen-1 {
// The tenth group may only carry the single bit left over from
// 63; anything above that, continuation included, overflows.
if b > 1 {
return 0, 0, ErrOverflow
}
}
x |= uint64(b&0x7f) << shift
if b < 0x80 {
if i > 0 && b == 0 {
// A zero final group means the value was padded: the same
// number has a shorter encoding, so this one is not canonical.
return 0, 0, ErrNotCanonical
}
return x, i + 1, nil
}
shift += 7
}
return 0, 0, ErrTruncated
}
// Varint decodes the zigzagged varint at the start of s.
func Varint(s string) (int64, int, error) {
u, n, err := Uvarint(s)
if err != nil {
return 0, 0, err
}
return UnZigZag(u), n, nil
}
// ZigZag maps a signed value onto an unsigned one so that small magnitudes of
// either sign stay small: 0, -1, 1, -2, 2 become 0, 1, 2, 3, 4.
func ZigZag(x int64) uint64 {
return uint64(x<<1) ^ uint64(x>>63)
}
// UnZigZag is the inverse of [ZigZag].
func UnZigZag(u uint64) int64 {
return int64(u>>1) ^ -int64(u&1)
}
// PutUvarints encodes every value in xs back to back, into one buffer.
func PutUvarints(xs []uint64) string {
buf := make([]byte, 0, len(xs)+1)
for _, x := range xs {
buf = AppendUvarint(buf, x)
}
return string(buf)
}
// Uvarints decodes a string that is nothing but varints. It fails rather than
// returning a partial result: a trailing fragment is corruption, not a value.
func Uvarints(s string) ([]uint64, error) {
out := []uint64{}
for len(s) > 0 {
x, n, err := Uvarint(s)
if err != nil {
if err == ErrTruncated {
return nil, ErrTrailing
}
return nil, err
}
out = append(out, x)
s = s[n:]
}
return out, nil
}
// PutVarints encodes every value in xs back to back, zigzagged, into one
// buffer.
func PutVarints(xs []int64) string {
buf := make([]byte, 0, len(xs)+1)
for _, x := range xs {
buf = AppendVarint(buf, x)
}
return string(buf)
}
// Varints decodes a string that is nothing but zigzagged varints.
func Varints(s string) ([]int64, error) {
us, err := Uvarints(s)
if err != nil {
return nil, err
}
out := make([]int64, len(us))
for i, u := range us {
out[i] = UnZigZag(u)
}
return out, nil
}
varint_test.gno
package varint
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
const (
minInt64 = -1 << 63
maxInt64 = 1<<63 - 1
maxUint64 = 1<<64 - 1
)
// hex renders a byte string as lowercase hex, so a failing vector prints the
// bytes rather than mojibake.
func hex(s string) string {
const digits = "0123456789abcdef"
var b strings.Builder
for i := 0; i < len(s); i++ {
b.WriteByte(digits[s[i]>>4])
b.WriteByte(digits[s[i]&0x0f])
}
return b.String()
}
// The protobuf base-128 vectors, one per group boundary plus the documented
// 300 example and the full 64-bit maximum.
func TestUvarintVectors(t *testing.T) {
cases := []struct {
in uint64
want string
}{
{0, "00"},
{1, "01"},
{127, "7f"},
{128, "8001"},
{300, "ac02"},
{16383, "ff7f"},
{16384, "808001"},
{maxUint64, "ffffffffffffffffff01"},
}
for _, c := range cases {
got := PutUvarint(c.in)
uassert.Equal(t, c.want, hex(got))
back, n, err := Uvarint(got)
uassert.NoError(t, err)
uassert.Equal(t, c.in, back)
uassert.Equal(t, len(got), n)
}
}
func TestLenAgreesWithEncoding(t *testing.T) {
for _, x := range []uint64{0, 1, 127, 128, 16383, 16384, 2097151, 2097152, maxUint64} {
uassert.Equal(t, len(PutUvarint(x)), Len(x))
}
// The boundary is what the groups are for: one byte up to 127.
uassert.Equal(t, 1, Len(127))
uassert.Equal(t, 2, Len(128))
uassert.Equal(t, MaxLen, Len(maxUint64))
}
func TestZigZagVectors(t *testing.T) {
cases := []struct {
in int64
want uint64
}{
{0, 0},
{-1, 1},
{1, 2},
{-2, 3},
{2, 4},
{maxInt64, maxUint64 - 1},
{minInt64, maxUint64},
}
for _, c := range cases {
uassert.Equal(t, c.want, ZigZag(c.in))
uassert.Equal(t, c.in, UnZigZag(c.want))
}
}
func TestVarintRoundTrip(t *testing.T) {
for _, x := range []int64{0, -1, 1, -64, 63, -1000000, 1000000, minInt64, maxInt64} {
enc := PutVarint(x)
uassert.Equal(t, len(enc), LenVarint(x))
back, n, err := Varint(enc)
uassert.NoError(t, err)
uassert.Equal(t, x, back)
uassert.Equal(t, len(enc), n)
}
}
// Zigzag is the whole reason signed values are not encoded directly: -1 as a
// two's complement uint64 is ten bytes, as a zigzag it is one.
func TestZigZagKeepsSmallNegativesShort(t *testing.T) {
uassert.Equal(t, 1, LenVarint(-1))
uassert.Equal(t, 1, LenVarint(-64))
uassert.Equal(t, 2, LenVarint(-65))
uassert.Equal(t, MaxLen, Len(uint64(0xffffffffffffffff))) // the same -1, unzigzagged
}
func TestRejectsNonCanonical(t *testing.T) {
cases := []struct {
name, in string
}{
{"zero padded once", "\x80\x00"},
{"one padded once", "\x81\x00"},
{"zero padded thrice", "\x80\x80\x80\x00"},
{"full width padding", "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00"},
}
for _, c := range cases {
_, _, err := Uvarint(c.in)
uassert.ErrorIs(t, err, ErrNotCanonical)
}
// A single zero byte is canonical: it is the only encoding of 0.
x, n, err := Uvarint("\x00")
uassert.NoError(t, err)
uassert.Equal(t, uint64(0), x)
uassert.Equal(t, 1, n)
}
func TestRejectsTruncated(t *testing.T) {
for _, s := range []string{"", "\x80", "\xff\xff", strings.Repeat("\xff", 9)} {
_, _, err := Uvarint(s)
uassert.ErrorIs(t, err, ErrTruncated)
}
}
func TestRejectsOverflow(t *testing.T) {
// Ten groups carry 70 bits; the tenth may only hold the one bit left of 64.
_, _, err := Uvarint(strings.Repeat("\xff", 9) + "\x02")
uassert.ErrorIs(t, err, ErrOverflow)
// An eleventh group is unreachable, so it reads as overflow too.
_, _, err = Uvarint(strings.Repeat("\xff", 10) + "\x01")
uassert.ErrorIs(t, err, ErrOverflow)
// Exactly at the limit is fine.
x, n, err := Uvarint(strings.Repeat("\xff", 9) + "\x01")
uassert.NoError(t, err)
uassert.Equal(t, uint64(maxUint64), x)
uassert.Equal(t, MaxLen, n)
}
func TestUvarintReadsOnlyItsOwnPrefix(t *testing.T) {
s := PutUvarint(300) + PutUvarint(1) + "leftover"
x, n, err := Uvarint(s)
uassert.NoError(t, err)
uassert.Equal(t, uint64(300), x)
uassert.Equal(t, 2, n)
x, n, err = Uvarint(s[n:])
uassert.NoError(t, err)
uassert.Equal(t, uint64(1), x)
uassert.Equal(t, 1, n)
}
func TestSequences(t *testing.T) {
in := []uint64{0, 1, 127, 128, 300, maxUint64}
enc := PutUvarints(in)
uassert.Equal(t, 1+1+1+2+2+10, len(enc))
out, err := Uvarints(enc)
uassert.NoError(t, err)
uassert.Equal(t, len(in), len(out))
for i := range in {
uassert.Equal(t, in[i], out[i])
}
signed := []int64{0, -1, 1, minInt64, maxInt64}
back, err := Varints(PutVarints(signed))
uassert.NoError(t, err)
uassert.Equal(t, len(signed), len(back))
for i := range signed {
uassert.Equal(t, signed[i], back[i])
}
}
// A partial value at the end is corruption, and returning the values read so
// far would hand a caller a silently short list.
func TestSequenceRefusesTrailingFragment(t *testing.T) {
_, err := Uvarints(PutUvarint(300) + "\x80")
uassert.ErrorIs(t, err, ErrTrailing)
_, err = Varints(PutVarint(-5) + "\xff")
uassert.ErrorIs(t, err, ErrTrailing)
out, err := Uvarints("")
uassert.NoError(t, err)
uassert.Equal(t, 0, len(out))
}
func TestAppendBuildsInPlace(t *testing.T) {
var buf []byte
buf = AppendUvarint(buf, 300)
buf = AppendVarint(buf, -1)
uassert.Equal(t, "ac0201", hex(string(buf)))
}