Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

varintdemo.gno

5.00 Kb · 136 lines
  1// Package varintdemo is a small gnoweb demo of the
  2// [p/moul/x/daily/varint](/p/moul/x/daily/varint/v0) library: it shows what the
  3// group boundaries cost, what zigzag buys on negative numbers, and which
  4// encodings the decoder refuses.
  5//
  6// It contains no codec logic of its own. Stateless, so Render is deterministic.
  7package varintdemo
  8
  9import (
 10	"strconv"
 11	"strings"
 12
 13	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
 14	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
 15	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/varint/v0"
 16)
 17
 18// Fixed inputs, never chain state: a demo whose output moves with the block
 19// height cannot be pinned by an example test.
 20var (
 21	unsigned = []uint64{0, 1, 127, 128, 300, 16383, 16384, 1 << 32, 1<<64 - 1}
 22	signed   = []int64{0, -1, 1, -64, 64, -1 << 63, 1<<63 - 1}
 23	rejected = []struct{ label, in string }{
 24		{"`80 00`, zero with one padding group", "\x80\x00"},
 25		{"`81 00`, one with one padding group", "\x81\x00"},
 26		{"`80`, continuation bit then nothing", "\x80"},
 27		{"`ff ... ff 02`, ten groups, eleven bits too many", "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x02"},
 28	}
 29)
 30
 31// Render renders the demo for gnoweb.
 32//
 33//	Render("") / Render("/")  -> the vector tables and the refusals
 34//	Render("/<integer>")      -> encode that integer both ways
 35func Render(path string) string {
 36	var b strings.Builder
 37	b.WriteString("# Varint\n\n")
 38	b.WriteString("LEB128 base-128 integers, demoing the ")
 39	b.WriteString("[`p/moul/x/daily/varint`](/p/moul/x/daily/varint/v0) library.\n\n")
 40
 41	if arg := parseArg(path); arg != "" {
 42		b.WriteString(renderOne(arg))
 43		return b.String()
 44	}
 45
 46	b.WriteString("## Unsigned\n\n")
 47	b.WriteString("Seven payload bits per byte, so the length steps at every power of 128.\n\n")
 48	t := ui.NewTable("value", "encoding", "bytes")
 49	for _, x := range unsigned {
 50		t.Row("`"+strconv.FormatUint(x, 10)+"`", "`"+hex(varint.PutUvarint(x))+"`", strconv.Itoa(varint.Len(x)))
 51	}
 52	b.WriteString(t.String())
 53
 54	b.WriteString("\n## Signed, through zigzag\n\n")
 55	b.WriteString("Encoding a negative directly would sign-extend it to ten bytes. ")
 56	b.WriteString("Zigzag interleaves the signs first, so `-1` costs one byte and not ten.\n\n")
 57	t = ui.NewTable("value", "zigzag", "encoding", "bytes")
 58	for _, x := range signed {
 59		t.Row(
 60			"`"+strconv.FormatInt(x, 10)+"`",
 61			"`"+strconv.FormatUint(varint.ZigZag(x), 10)+"`",
 62			"`"+hex(varint.PutVarint(x))+"`",
 63			strconv.Itoa(varint.LenVarint(x)),
 64		)
 65	}
 66	b.WriteString(t.String())
 67
 68	b.WriteString("\n## Only the canonical encoding decodes\n\n")
 69	b.WriteString("A padded varint means the same number has two spellings, which is a ")
 70	b.WriteString("different hash for the same state. The decoder refuses them.\n\n")
 71	t = ui.NewTable("input", "result")
 72	for _, c := range rejected {
 73		_, _, err := varint.Uvarint(c.in)
 74		t.Row(c.label, "`"+err.Error()+"`")
 75	}
 76	b.WriteString(t.String())
 77
 78	b.WriteString("\n> Try another value: append it to the path, for instance ")
 79	b.WriteString("[`/-300`](/r/moul/x/daily/varintdemo/v0:/-300).\n")
 80	return b.String()
 81}
 82
 83// renderOne encodes a single integer supplied in the path.
 84//
 85// The argument is the visitor's text and it is shown inside a code span, so
 86// it goes through md.InlineCode and not ui.Cell: a cell escaper backslashes
 87// a backtick, and a backslash does not close a backtick inside a span. Only
 88// a fence wider than anything in the argument does, which is what
 89// md.InlineCode picks.
 90func renderOne(arg string) string {
 91	var b strings.Builder
 92	b.WriteString("## ")
 93	b.WriteString(md.InlineCode(arg))
 94	b.WriteString("\n\n")
 95
 96	unsigned := false
 97	if u, err := strconv.ParseUint(arg, 10, 64); err == nil {
 98		unsigned = true
 99		b.WriteString("- unsigned: `" + hex(varint.PutUvarint(u)) + "` (" + strconv.Itoa(varint.Len(u)) + " bytes)\n")
100	}
101	i, err := strconv.ParseInt(arg, 10, 64)
102	if err != nil {
103		// Above MaxInt64 the unsigned line above is the whole answer: the
104		// codec carries the value, only the signed form cannot hold it.
105		if !unsigned {
106			b.WriteString("Not an integer this codec can carry: 64 bits, signed or unsigned.\n")
107		}
108		return b.String()
109	}
110	b.WriteString("- zigzag: `" + strconv.FormatUint(varint.ZigZag(i), 10) + "`\n")
111	b.WriteString("- signed: `" + hex(varint.PutVarint(i)) + "` (" + strconv.Itoa(varint.LenVarint(i)) + " bytes)\n")
112	return b.String()
113}
114
115// hex renders a byte string as lowercase hex pairs. Presentation only: the
116// library deals in bytes and says nothing about how they are shown.
117func hex(s string) string {
118	const digits = "0123456789abcdef"
119	var b strings.Builder
120	for i := 0; i < len(s); i++ {
121		if i > 0 {
122			b.WriteByte(' ')
123		}
124		b.WriteByte(digits[s[i]>>4])
125		b.WriteByte(digits[s[i]&0x0f])
126	}
127	return b.String()
128}
129
130// parseArg takes the one routing slash off and nothing else. It does not cut
131// at a later slash and it does not trim: a page that offers to encode what
132// the caller typed either encodes that string or says it refused it, and
133// never quietly substitutes a shorter or tidier one.
134func parseArg(path string) string {
135	return strings.TrimPrefix(path, "/")
136}