append_test.gno
1.14 Kb · 38 lines
1package varint
2
3import (
4 "testing"
5
6 "gno.land/p/nt/uassert/v0"
7)
8
9// Append takes and returns a byte slice rather than a string, so packing a
10// sequence reuses one buffer instead of copying the whole prefix per value.
11// A string accumulator makes PutUvarints quadratic in the encoded size, which
12// on chain is gas a caller pays to produce a result they already had.
13func TestAppendReusesOneBuffer(t *testing.T) {
14 buf := make([]byte, 0, 32)
15 buf = AppendUvarint(buf, 300)
16 buf = AppendVarint(buf, -1)
17 buf = AppendUvarint(buf, 16384)
18 uassert.Equal(t, "ac020180 8001"[0:0]+hex(string(buf)), "ac0201808001")
19
20 // The same bytes the one-shot helpers produce, so the two cannot diverge.
21 uassert.Equal(t, PutUvarint(300)+PutVarint(-1)+PutUvarint(16384), string(buf))
22}
23
24func TestSequenceHelpersMatchAppend(t *testing.T) {
25 xs := []uint64{0, 1, 127, 128, 300, maxUint64}
26 buf := []byte{}
27 for _, x := range xs {
28 buf = AppendUvarint(buf, x)
29 }
30 uassert.Equal(t, string(buf), PutUvarints(xs))
31
32 ys := []int64{0, -1, 1, minInt64, maxInt64}
33 sbuf := []byte{}
34 for _, y := range ys {
35 sbuf = AppendVarint(sbuf, y)
36 }
37 uassert.Equal(t, string(sbuf), PutVarints(ys))
38}