1package escape
2
3import (
4	"bytes"
5	"reflect"
6	"strings"
7	"testing"
8)
9
10var result []byte
11
12func BenchmarkBytesEscapeNoEscapes(b *testing.B) {
13	buf := []byte(`no_escapes`)
14	for i := 0; i < b.N; i++ {
15		result = Bytes(buf)
16	}
17}
18
19func BenchmarkUnescapeNoEscapes(b *testing.B) {
20	buf := []byte(`no_escapes`)
21	for i := 0; i < b.N; i++ {
22		result = Unescape(buf)
23	}
24}
25
26func BenchmarkBytesEscapeMany(b *testing.B) {
27	tests := [][]byte{
28		[]byte("this is my special string"),
29		[]byte("a field w=i th == tons of escapes"),
30		[]byte("some,commas,here"),
31	}
32	for n := 0; n < b.N; n++ {
33		for _, test := range tests {
34			result = Bytes(test)
35		}
36	}
37}
38
39func BenchmarkUnescapeMany(b *testing.B) {
40	tests := [][]byte{
41		[]byte(`this\ is\ my\ special\ string`),
42		[]byte(`a\ field\ w\=i\ th\ \=\=\ tons\ of\ escapes`),
43		[]byte(`some\,commas\,here`),
44	}
45	for i := 0; i < b.N; i++ {
46		for _, test := range tests {
47			result = Unescape(test)
48		}
49	}
50}
51
52var boolResult bool
53
54func BenchmarkIsEscaped(b *testing.B) {
55	tests := [][]byte{
56		[]byte(`no_escapes`),
57		[]byte(`a\ field\ w\=i\ th\ \=\=\ tons\ of\ escapes`),
58		[]byte(`some\,commas\,here`),
59	}
60	for i := 0; i < b.N; i++ {
61		for _, test := range tests {
62			boolResult = IsEscaped(test)
63		}
64	}
65}
66
67func BenchmarkAppendUnescaped(b *testing.B) {
68	tests := [][]byte{
69		[]byte(`this\ is\ my\ special\ string`),
70		[]byte(`a\ field\ w\=i\ th\ \=\=\ tons\ of\ escapes`),
71		[]byte(`some\,commas\,here`),
72	}
73	for i := 0; i < b.N; i++ {
74		result = nil
75		for _, test := range tests {
76			result = AppendUnescaped(result, test)
77		}
78	}
79}
80
81func TestUnescape(t *testing.T) {
82	tests := []struct {
83		in  []byte
84		out []byte
85	}{
86		{
87			[]byte(nil),
88			[]byte(nil),
89		},
90
91		{
92			[]byte(""),
93			[]byte(nil),
94		},
95
96		{
97			[]byte("\\,\\\"\\ \\="),
98			[]byte(",\" ="),
99		},
100
101		{
102			[]byte("\\\\"),
103			[]byte("\\\\"),
104		},
105
106		{
107			[]byte("plain and simple"),
108			[]byte("plain and simple"),
109		},
110	}
111
112	for ii, tt := range tests {
113		got := Unescape(tt.in)
114		if !reflect.DeepEqual(got, tt.out) {
115			t.Errorf("[%d] Unescape(%#v) = %#v, expected %#v", ii, string(tt.in), string(got), string(tt.out))
116		}
117	}
118}
119
120func TestAppendUnescaped(t *testing.T) {
121	cases := strings.Split(strings.TrimSpace(`
122normal
123inv\alid
124goo\"d
125sp\ ace
126\,\"\ \=
127f\\\ x
128`), "\n")
129
130	for _, c := range cases {
131		exp := Unescape([]byte(c))
132		got := AppendUnescaped(nil, []byte(c))
133
134		if !bytes.Equal(got, exp) {
135			t.Errorf("AppendUnescaped failed for %#q: got %#q, exp %#q", c, got, exp)
136		}
137	}
138
139}
140