Do not build decode table for base85 until it is actually needed

Also make the tests actual tests
This commit is contained in:
Kovid Goyal
2023-09-04 21:32:25 +05:30
parent 0107d1cb89
commit 541c0cdde4
2 changed files with 75 additions and 66 deletions

View File

@@ -1,60 +1,54 @@
package base85
import (
"testing"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestChunked (t *testing.T) {
a := []byte("M")
fmt.Printf("a %#v\n", a)
b := make([]byte, EncodedLen(len(a)))
encodeChunk(b, a)
fmt.Printf("b %#v\n", b)
c := make([]byte, DecodedLen(len(b)))
decodeChunk(c, b)
fmt.Printf("c %#v\n", c)
var _ = fmt.Print
a = []byte("Ma")
fmt.Printf("a %#v\n", a)
b = make([]byte, EncodedLen(len(a)))
encodeChunk(b, a)
fmt.Printf("b %#v\n", b)
c = make([]byte, DecodedLen(len(b)))
decodeChunk(c, b)
fmt.Printf("c %#v\n", c)
a = []byte("Man")
fmt.Printf("a %#v\n", a)
b = make([]byte, EncodedLen(len(a)))
encodeChunk(b, a)
fmt.Printf("b %#v\n", b)
c = make([]byte, DecodedLen(len(b)))
decodeChunk(c, b)
fmt.Printf("c %#v\n", c)
a = []byte("Man ")
fmt.Printf("a %#v\n", a)
b = make([]byte, EncodedLen(len(a)))
encodeChunk(b, a)
fmt.Printf("b %#v\n", b)
c = make([]byte, DecodedLen(len(b)))
decodeChunk(c, b)
fmt.Printf("c %#v\n", c)
a = []byte("Manual")
fmt.Printf("a %#v\n", a)
b = make([]byte, EncodedLen(len(a)))
n := Encode(b, a)
fmt.Printf("b %#v %d\n", b, n)
c = make([]byte, DecodedLen(len(b)))
n, _ = Decode(c, b)
fmt.Printf("c %#v %d\n", c, n)
a = []byte("Manual")
fmt.Printf("a %s\n", a)
sb := EncodeToString(a) + "\""
fmt.Printf("b %#v\n", sb)
sc, err := DecodeString(sb)
fmt.Printf("c %s %s\n", sc, err)
type pair struct {
src, encoded string
}
func TestBase85(t *testing.T) {
dst, dst2 := [8]byte{}, [8]byte{}
decode := decoder_array()
var el int
for _, x := range []string{"M", "Ma", "Man", "Man "} {
a := []byte(x)
if el = encodeChunk(dst[:], a); el != EncodedLen(len(a)) {
t.Fatalf("Encoded len for %#v wrong: %d != %d", x, el, EncodedLen(len(a)))
}
encoded := dst[:el]
dl, bad_idx := decodeChunk(&decode, dst2[:], encoded)
if bad_idx != 0 {
t.Fatalf("Decode for %#v returned bad data at: %d (%#v)", x, bad_idx, encoded)
}
if dl != DecodedLen(len(encoded)) {
t.Fatalf("Decoded len for %#v wrong: %d != %d", x, dl, DecodedLen(len(a)))
}
decoded := string(dst2[:dl])
if diff := cmp.Diff(x, decoded); diff != "" {
t.Fatalf("Roundtrip failed for %#v: %s", x, diff)
}
}
for _, p := range []pair{
{"M", "O#"},
{"Manual", "O<`_zVQc"},
} {
q := EncodeToString([]byte(p.src))
if diff := cmp.Diff(p.encoded, q); diff != "" {
t.Fatalf("Incorrect encoding of: %#v\n%s", p.src, diff)
}
sc, err := DecodeString(q)
if err != nil {
t.Fatalf("Failed to decode %#v with error: %s", p.src, err)
}
if diff := cmp.Diff(p.src, string(sc)); diff != "" {
t.Fatalf("Failed to roundtrip %#v\n%s", p.src, diff)
}
}
}