-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencode_test.go
More file actions
236 lines (203 loc) · 5.59 KB
/
Copy pathencode_test.go
File metadata and controls
236 lines (203 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
//go:build go1.24
/*
Copyright 2021-2026 Olivier Mengué.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kittyimg_test
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"iter"
"maps"
"os"
"regexp"
"slices"
"strings"
"testing"
// Note that we are not loading image/png while we have tests that process PNG files.
// The test are still passing because Transcode doesn't decode the PNG but instead just
// send the raw PNG file.
// This can be verified by looking at code coverage for image/png:
// go test -coverpkg=image/png -run TestImage3072
//
// So do not add tests that require image/png in this file.
"github.com/dolmen-go/kittyimg"
)
const (
// Enforce canonical Base64
base64CharRE = `[A-Za-z0-9+/]`
base64CharRE2 = `[AQgw]` // See https://go.dev/play/p/ui8tmhV-YLH
base64CharRE3 = `[AEIMQUYcgkosw048]` // See https://go.dev/play/p/HVF_A6wJcOo
base64REInf = `(?:` + base64CharRE + `{4})*(?:` + base64CharRE + "(?:" + base64CharRE2 + `=|` + base64CharRE + base64CharRE3 + `)=)?`
// Payload is limited to 4096 bytes
// 4096 / 4 = 1024 blocks
// But package regexp has a limit of 250 repetitions (see issue #78222), so we have to split:
// 1024 = 250*4 + 23 + 1
base64Chars4 = `(?:` + base64CharRE + `{4})`
base64Chars250 = base64Chars4 + `{0,250}`
payloadRE = base64Chars250 + base64Chars250 + base64Chars250 + base64Chars250 + base64Chars4 + `{0,23}(?:` + base64CharRE + "(?:" + base64CharRE2 + `==|` + base64CharRE + `(?:` + base64CharRE3 + `=|` + base64CharRE + `{2})))?`
)
var (
blockRE = regexp.MustCompile(`` +
"\033_G" +
"(?<params>(?:[a-zA-Z]=[^,;\033]{1,11}(?:,[a-zA-Z]=[^,;\033]{1,11})*)?)" +
"(?:;(?<payload>" + payloadRE + ")?)" +
"\033\\\\",
)
kvRE = regexp.MustCompile(`^(?:([a-zA-Z])=([^,;\033]+)(?:,|$))+$`)
)
func countBlocks(s string) int {
m := blockRE.FindAllStringIndex(s, -1)
if m == nil {
return 0
}
return len(m)
}
type Params map[byte]string
func (p Params) String() string {
if p == nil || len(p) == 0 {
return ""
}
var sb strings.Builder
for i, k := range slices.Sorted(maps.Keys(p)) {
if i > 0 {
sb.WriteByte(',')
}
sb.WriteByte(k)
sb.WriteByte('=')
sb.WriteString(p[k])
}
return sb.String()
}
type Block struct {
Params Params
Payload []byte
}
func addParam(params *Params, p string) {
if *params == nil {
*params = Params{p[0]: p[2:]}
return
}
(*params)[p[0]] = p[2:]
}
func parseParams(p string) (params Params) {
if p == "" {
return nil
}
for {
i := strings.IndexByte(p, ',')
if i == -1 {
addParam(¶ms, p)
break
}
addParam(¶ms, p[:i])
p = p[i+1:]
}
return
}
func (bl *Block) init(params string, payload string) {
bl.Params = parseParams(params)
if payload != "" {
bl.Payload, _ = base64.StdEncoding.DecodeString(payload)
}
}
func (bl *Block) UnmarshalText(b []byte) error {
m := blockRE.FindSubmatchIndex(b)
if m == nil || m[0] != 0 || m[1] != len(b) {
return errors.New("invalid block")
}
bl.init(string(b[m[2]:m[3]]), string(b[m[4]:m[5]]))
return nil
}
func extractBlocks(s []byte) iter.Seq[*Block] {
matches := blockRE.FindAllSubmatchIndex(s, -1)
if len(matches) == 0 {
// panic("no match")
return func(yield func(*Block) bool) {}
}
anchor := 0
for _, m := range matches {
if m[0] != anchor {
panic("should match contiguously")
}
anchor = m[1]
}
if anchor != len(s) {
panic(fmt.Errorf("should match full string but found %q", s[anchor:]))
}
return func(yield func(*Block) bool) {
for i, m := range matches {
matches[i] = nil // free memory early
//fmt.Printf("Params: %s\n", s[m[2]:m[3]])
//if len(m) > 2 {
// fmt.Printf("Payload: %q\n", s[m[4]:m[5]])
//}
var bl Block
/*
err := bl.UnmarshalText([]byte(s[m[0]:m[1]]))
if err != nil {
panic(err)
}
*/
bl.init(string(s[m[2]:m[3]]), string(s[m[4]:m[5]]))
if !yield(&bl) {
break
}
}
return
}
}
func testDecode(t *testing.T, filepath string, expectedLen int) {
t.Parallel()
f, err := os.Open(filepath)
if err != nil {
t.Fatal(err)
}
defer f.Close()
var buf bytes.Buffer
if err := kittyimg.Transcode(&buf, f); err != nil {
t.Fatal(err)
}
gotLen := buf.Len()
t.Logf("Output: %d bytes", gotLen)
i := 0
for bl := range extractBlocks(buf.Bytes()) {
t.Log("-- Block", i, "--")
t.Log("Params:", bl.Params)
t.Logf("Payload: %d bytes", len(bl.Payload))
i++
}
if i == 0 {
t.Fatal("Decode failure!")
}
if gotLen != expectedLen {
t.Fatalf("Length: got %d, expected %d", gotLen, expectedLen)
}
}
func TestImagePNG3069(t *testing.T) {
testDecode(t, "testdata/go-favicon-3069.png", 4121)
}
func TestImagePNG3070(t *testing.T) {
testDecode(t, "testdata/go-favicon-3070.png", 4125)
}
func TestImagePNG3071(t *testing.T) {
testDecode(t, "testdata/go-favicon-3071.png", 4125)
}
// Test encoding of a PNG image file of 3072 bytes, which is a base64 payload of 4096.
func TestImagePNG3072(t *testing.T) {
testDecode(t, "testdata/go-favicon-3072.png", 4125)
}
// Test encoding of a PNG image file of 3073 bytes, which is two blocks (3072+1 => 4096+4).
func TestImagePNG3073(t *testing.T) {
testDecode(t, "testdata/go-favicon-3073.png", 4142)
}