master
  1package gitdiff
  2
  3import (
  4	"bytes"
  5	"testing"
  6)
  7
  8func TestBase85Decode(t *testing.T) {
  9	tests := map[string]struct {
 10		Input  string
 11		Output []byte
 12		Err    bool
 13	}{
 14		"twoBytes": {
 15			Input:  "%KiWV",
 16			Output: []byte{0xCA, 0xFE},
 17		},
 18		"fourBytes": {
 19			Input:  "007GV",
 20			Output: []byte{0x0, 0x0, 0xCA, 0xFE},
 21		},
 22		"sixBytes": {
 23			Input:  "007GV%KiWV",
 24			Output: []byte{0x0, 0x0, 0xCA, 0xFE, 0xCA, 0xFE},
 25		},
 26		"invalidCharacter": {
 27			Input: "00'GV",
 28			Err:   true,
 29		},
 30		"underpaddedSequence": {
 31			Input: "007G",
 32			Err:   true,
 33		},
 34		"dataUnderrun": {
 35			Input:  "007GV",
 36			Output: make([]byte, 8),
 37			Err:    true,
 38		},
 39	}
 40
 41	for name, test := range tests {
 42		t.Run(name, func(t *testing.T) {
 43			dst := make([]byte, len(test.Output))
 44			err := base85Decode(dst, []byte(test.Input))
 45			if test.Err {
 46				if err == nil {
 47					t.Fatalf("expected error decoding base85 data, but got nil")
 48				}
 49				return
 50			}
 51			if err != nil {
 52				t.Fatalf("unexpected error decoding base85 data: %v", err)
 53			}
 54			for i, b := range test.Output {
 55				if dst[i] != b {
 56					t.Errorf("incorrect byte at index %d: expected 0x%X, actual 0x%X", i, b, dst[i])
 57				}
 58			}
 59		})
 60	}
 61}
 62
 63func TestBase85Encode(t *testing.T) {
 64	tests := map[string]struct {
 65		Input  []byte
 66		Output string
 67	}{
 68		"zeroBytes": {
 69			Input:  []byte{},
 70			Output: "",
 71		},
 72		"twoBytes": {
 73			Input:  []byte{0xCA, 0xFE},
 74			Output: "%KiWV",
 75		},
 76		"fourBytes": {
 77			Input:  []byte{0x0, 0x0, 0xCA, 0xFE},
 78			Output: "007GV",
 79		},
 80		"sixBytes": {
 81			Input:  []byte{0x0, 0x0, 0xCA, 0xFE, 0xCA, 0xFE},
 82			Output: "007GV%KiWV",
 83		},
 84	}
 85
 86	for name, test := range tests {
 87		t.Run(name, func(t *testing.T) {
 88			dst := make([]byte, len(test.Output))
 89			base85Encode(dst, test.Input)
 90			for i, b := range test.Output {
 91				if dst[i] != byte(b) {
 92					t.Errorf("incorrect character at index %d: expected '%c', actual '%c'", i, b, dst[i])
 93				}
 94			}
 95		})
 96	}
 97}
 98
 99func FuzzBase85Roundtrip(f *testing.F) {
100	f.Add([]byte{0x2b, 0x0d})
101	f.Add([]byte{0xbc, 0xb4, 0x3f})
102	f.Add([]byte{0xfa, 0x62, 0x05, 0x83, 0x24, 0x39, 0xd5, 0x25})
103	f.Add([]byte{0x31, 0x59, 0x02, 0xa0, 0x61, 0x12, 0xd9, 0x43, 0xb8, 0x23, 0x1a, 0xb4, 0x02, 0xae, 0xfa, 0xcc, 0x22, 0xad, 0x41, 0xb9, 0xb8})
104
105	f.Fuzz(func(t *testing.T, in []byte) {
106		n := len(in)
107		dst := make([]byte, base85Len(n))
108		out := make([]byte, n)
109
110		base85Encode(dst, in)
111		if err := base85Decode(out, dst); err != nil {
112			t.Fatalf("unexpected error decoding base85 data: %v", err)
113		}
114		if !bytes.Equal(in, out) {
115			t.Errorf("decoded data differed from input data:\n   input: %x\n  output: %x\nencoding: %s\n", in, out, string(dst))
116		}
117	})
118}