Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

rle_test.gno

2.01 Kb · 83 lines
 1package rle
 2
 3import (
 4	"strings"
 5	"testing"
 6
 7	"gno.land/p/nt/uassert/v0"
 8)
 9
10func TestEncode(t *testing.T) {
11	cases := []struct{ in, want string }{
12		{"", ""},
13		{"a", "1a"},
14		{"aaa", "3a"},
15		{"aaabbc", "3a2b1c"},
16		{"abc", "1a1b1c"},
17		{"aabbaa", "2a2b2a"}, // runs, not totals
18	}
19	for _, c := range cases {
20		got, err := Encode(c.in)
21		uassert.NoError(t, err)
22		uassert.Equal(t, c.want, got)
23	}
24}
25
26func TestDecode(t *testing.T) {
27	cases := []struct{ in, want string }{
28		{"", ""},
29		{"3a", "aaa"},
30		{"3a2b1c", "aaabbc"},
31		{"12x", strings.Repeat("x", 12)}, // multi-digit counts
32	}
33	for _, c := range cases {
34		got, err := Decode(c.in)
35		uassert.NoError(t, err)
36		uassert.Equal(t, c.want, got)
37	}
38}
39
40// The property that matters: decode(encode(s)) == s.
41func TestRoundTrip(t *testing.T) {
42	for _, s := range []string{"a", "aaa", "aaabbc", "abcdef", "zzzzzzzzzzzz", "ab"} {
43		enc, err := Encode(s)
44		uassert.NoError(t, err)
45		dec, err2 := Decode(enc)
46		uassert.NoError(t, err2)
47		uassert.Equal(t, s, dec)
48	}
49}
50
51// Digits would be ambiguous with a run count, so they are refused up front.
52func TestEncodeRejectsDigits(t *testing.T) {
53	_, err := Encode("ab3c")
54	uassert.ErrorIs(t, err, ErrDigit)
55}
56
57func TestDecodeMalformed(t *testing.T) {
58	for _, s := range []string{"a", "abc", "3", "3a2", "0a"} {
59		_, err := Decode(s)
60		uassert.Error(t, err)
61	}
62}
63
64// A short encoded input must not be able to blow up memory on decode.
65func TestDecodeExpansionIsBounded(t *testing.T) {
66	_, err := Decode("999999x")
67	uassert.ErrorIs(t, err, ErrTooLong)
68}
69
70func TestEncodeTooLong(t *testing.T) {
71	_, err := Encode(strings.Repeat("a", MaxLen+1))
72	uassert.ErrorIs(t, err, ErrTooLong)
73}
74
75// RLE is a win only on runny data — say so rather than hide it.
76func TestRatioCanExceed100(t *testing.T) {
77	enc, _ := Encode("abcdef")
78	uassert.Equal(t, "1a1b1c1d1e1f", enc)
79	uassert.Equal(t, 200, Ratio("abcdef", enc)) // twice the size!
80	enc2, _ := Encode(strings.Repeat("a", 100))
81	uassert.Equal(t, 4, Ratio(strings.Repeat("a", 100), enc2))
82	uassert.Equal(t, 0, Ratio("", ""))
83}