Debian Codegraph @

common.go

raw
1 // Package parse contains a collection of parsers for various formats in its subpackages.
2 package parse
3
4 import (
5 "bytes"
6 "encoding/base64"
7 "errors"
8 "strconv"
9 )
10
11 var (
12 dataSchemeBytes = []byte("data:")
13 base64Bytes = []byte("base64")
14 textMimeBytes = []byte("text/plain")
15 )
16
17 // ErrBadDataURI is returned by DataURI when the byte slice does not start with 'data:' or is too short.
18 var ErrBadDataURI = errors.New("not a data URI")
19
20 // Number returns the number of bytes that parse as a number of the regex format (+|-)?([0-9]+(\.[0-9]+)?|\.[0-9]+)((e|E)(+|-)?[0-9]+)?.
21 func Number(b []byte) int {
22 if len(b) == 0 {
23 return 0
24 }
25 i := 0
26 if b[i] == '+' || b[i] == '-' {
27 i++
28 if i >= len(b) {
29 return 0
30 }
31 }
32 firstDigit := (b[i] >= '0' && b[i] <= '9')
33 if firstDigit {
34 i++
35 for i < len(b) && b[i] >= '0' && b[i] <= '9' {
36 i++
37 }
38 }
39 if i < len(b) && b[i] == '.' {
40 i++
41 if i < len(b) && b[i] >= '0' && b[i] <= '9' {
42 i++
43 for i < len(b) && b[i] >= '0' && b[i] <= '9' {
44 i++
45 }
46 } else if firstDigit {
47 // . could belong to the next token
48 i--
49 return i
50 } else {
51 return 0
52 }
53 } else if !firstDigit {
54 return 0
55 }
56 iOld := i
57 if i < len(b) && (b[i] == 'e' || b[i] == 'E') {
58 i++
59 if i < len(b) && (b[i] == '+' || b[i] == '-') {
60 i++
61 }
62 if i >= len(b) || b[i] < '0' || b[i] > '9' {
63 // e could belong to next token
64 return iOld
65 }
66 for i < len(b) && b[i] >= '0' && b[i] <= '9' {
67 i++
68 }
69 }
70 return i
71 }
72
73 // Dimension parses a byte-slice and returns the length of the number and its unit.
74 func Dimension(b []byte) (int, int) {
75 num := Number(b)
76 if num == 0 || num == len(b) {
77 return num, 0
78 } else if b[num] == '%' {
79 return num, 1
80 } else if b[num] >= 'a' && b[num] <= 'z' || b[num] >= 'A' && b[num] <= 'Z' {
81 i := num + 1
82 for i < len(b) && (b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z') {
83 i++
84 }
85 return num, i - num
86 }
87 return num, 0
88 }
89
90 // Mediatype parses a given mediatype and splits the mimetype from the parameters.
91 // It works similar to mime.ParseMediaType but is faster.
92 func Mediatype(b []byte) ([]byte, map[string]string) {
93 i := 0
94 for i < len(b) && b[i] == ' ' {
95 i++
96 }
97 b = b[i:]
98 n := len(b)
99 mimetype := b
100 var params map[string]string
101 for i := 3; i < n; i++ { // mimetype is at least three characters long
102 if b[i] == ';' || b[i] == ' ' {
103 mimetype = b[:i]
104 if b[i] == ' ' {
105 i++ // space
106 for i < n && b[i] == ' ' {
107 i++
108 }
109 if n <= i || b[i] != ';' {
110 break
111 }
112 }
113 params = map[string]string{}
114 s := string(b)
115 PARAM:
116 i++ // semicolon
117 for i < n && s[i] == ' ' {
118 i++
119 }
120 start := i
121 for i < n && s[i] != '=' && s[i] != ';' && s[i] != ' ' {
122 i++
123 }
124 key := s[start:i]
125 for i < n && s[i] == ' ' {
126 i++
127 }
128 if i < n && s[i] == '=' {
129 i++
130 for i < n && s[i] == ' ' {
131 i++
132 }
133 start = i
134 for i < n && s[i] != ';' && s[i] != ' ' {
135 i++
136 }
137 } else {
138 start = i
139 }
140 params[key] = s[start:i]
141 for i < n && s[i] == ' ' {
142 i++
143 }
144 if i < n && s[i] == ';' {
145 goto PARAM
146 }
147 break
148 }
149 }
150 return mimetype, params
151 }
152
153 // DataURI parses the given data URI and returns the mediatype, data and ok.
154 func DataURI(dataURI []byte) ([]byte, []byte, error) {
155 if len(dataURI) > 5 && bytes.Equal(dataURI[:5], dataSchemeBytes) {
156 dataURI = dataURI[5:]
157 inBase64 := false
158 var mediatype []byte
159 i := 0
160 for j := 0; j < len(dataURI); j++ {
161 c := dataURI[j]
162 if c == '=' || c == ';' || c == ',' {
163 if c != '=' && bytes.Equal(TrimWhitespace(dataURI[i:j]), base64Bytes) {
164 if len(mediatype) > 0 {
165 mediatype = mediatype[:len(mediatype)-1]
166 }
167 inBase64 = true
168 i = j
169 } else if c != ',' {
170 mediatype = append(append(mediatype, TrimWhitespace(dataURI[i:j])...), c)
171 i = j + 1
172 } else {
173 mediatype = append(mediatype, TrimWhitespace(dataURI[i:j])...)
174 }
175 if c == ',' {
176 if len(mediatype) == 0 || mediatype[0] == ';' {
177 mediatype = textMimeBytes
178 }
179 data := dataURI[j+1:]
180 if inBase64 {
181 decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
182 n, err := base64.StdEncoding.Decode(decoded, data)
183 if err != nil {
184 return nil, nil, err
185 }
186 data = decoded[:n]
187 } else {
188 data = DecodeURL(data)
189 }
190 return mediatype, data, nil
191 }
192 }
193 }
194 }
195 return nil, nil, ErrBadDataURI
196 }
197
198 // QuoteEntity parses the given byte slice and returns the quote that got matched (' or ") and its entity length.
199 // TODO: deprecated
200 func QuoteEntity(b []byte) (quote byte, n int) {
201 if len(b) < 5 || b[0] != '&' {
202 return 0, 0
203 }
204 if b[1] == '#' {
205 if b[2] == 'x' {
206 i := 3
207 for i < len(b) && b[i] == '0' {
208 i++
209 }
210 if i+2 < len(b) && b[i] == '2' && b[i+2] == ';' {
211 if b[i+1] == '2' {
212 return '"', i + 3 // &#x22;
213 } else if b[i+1] == '7' {
214 return '\'', i + 3 // &#x27;
215 }
216 }
217 } else {
218 i := 2
219 for i < len(b) && b[i] == '0' {
220 i++
221 }
222 if i+2 < len(b) && b[i] == '3' && b[i+2] == ';' {
223 if b[i+1] == '4' {
224 return '"', i + 3 // &#34;
225 } else if b[i+1] == '9' {
226 return '\'', i + 3 // &#39;
227 }
228 }
229 }
230 } else if len(b) >= 6 && b[5] == ';' {
231 if bytes.Equal(b[1:5], []byte{'q', 'u', 'o', 't'}) {
232 return '"', 6 // &quot;
233 } else if bytes.Equal(b[1:5], []byte{'a', 'p', 'o', 's'}) {
234 return '\'', 6 // &apos;
235 }
236 }
237 return 0, 0
238 }
239
240 // ReplaceMultipleWhitespace replaces character series of space, \n, \t, \f, \r into a single space or newline (when the serie contained a \n or \r).
241 func ReplaceMultipleWhitespace(b []byte) []byte {
242 j, k := 0, 0 // j is write position, k is start of next text section
243 for i := 0; i < len(b); i++ {
244 if IsWhitespace(b[i]) {
245 start := i
246 newline := IsNewline(b[i])
247 i++
248 for ; i < len(b) && IsWhitespace(b[i]); i++ {
249 if IsNewline(b[i]) {
250 newline = true
251 }
252 }
253 if newline {
254 b[start] = '\n'
255 } else {
256 b[start] = ' '
257 }
258 if 1 < i-start { // more than one whitespace
259 if j == 0 {
260 j = start + 1
261 } else {
262 j += copy(b[j:], b[k:start+1])
263 }
264 k = i
265 }
266 }
267 }
268 if j == 0 {
269 return b
270 } else if j == 1 { // only if starts with whitespace
271 b[k-1] = b[0]
272 return b[k-1:]
273 } else if k < len(b) {
274 j += copy(b[j:], b[k:])
275 }
276 return b[:j]
277 }
278
279 // replaceEntities will replace in b at index i, assuming that b[i] == '&' and that i+3<len(b). The returned int will be the last character of the entity, so that the next iteration can safely do i++ to continue and not miss any entitites.
280 func replaceEntities(b []byte, i int, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) ([]byte, int) {
281 const MaxEntityLength = 31 // longest HTML entity: CounterClockwiseContourIntegral
282 var r []byte
283 j := i + 1
284 if b[j] == '#' {
285 j++
286 if b[j] == 'x' {
287 j++
288 c := 0
289 for ; j < len(b) && (b[j] >= '0' && b[j] <= '9' || b[j] >= 'a' && b[j] <= 'f' || b[j] >= 'A' && b[j] <= 'F'); j++ {
290 if b[j] <= '9' {
291 c = c<<4 + int(b[j]-'0')
292 } else if b[j] <= 'F' {
293 c = c<<4 + int(b[j]-'A') + 10
294 } else if b[j] <= 'f' {
295 c = c<<4 + int(b[j]-'a') + 10
296 }
297 }
298 if j <= i+3 || 10000 <= c {
299 return b, j - 1
300 }
301 if c < 128 {
302 r = []byte{byte(c)}
303 } else {
304 r = append(r, '&', '#')
305 r = strconv.AppendInt(r, int64(c), 10)
306 r = append(r, ';')
307 }
308 } else {
309 c := 0
310 for ; j < len(b) && c < 128 && b[j] >= '0' && b[j] <= '9'; j++ {
311 c = c*10 + int(b[j]-'0')
312 }
313 if j <= i+2 || 128 <= c {
314 return b, j - 1
315 }
316 r = []byte{byte(c)}
317 }
318 } else {
319 for ; j < len(b) && j-i-1 <= MaxEntityLength && b[j] != ';'; j++ {
320 if !(b[j] >= '0' && b[j] <= '9' || b[j] >= 'a' && b[j] <= 'z' || b[j] >= 'A' && b[j] <= 'Z') {
321 // invalid character reference character
322 break
323 }
324 }
325 if len(b) <= j || j == i+1 || b[j] != ';' {
326 return b, i
327 }
328
329 var ok bool
330 r, ok = entitiesMap[string(b[i+1:j])]
331 if !ok {
332 return b, j
333 }
334 }
335
336 // j is at semicolon
337 n := j + 1 - i
338 if j < len(b) && b[j] == ';' && 2 < n {
339 if len(r) == 1 {
340 if q, ok := revEntitiesMap[r[0]]; ok {
341 if len(q) == len(b[i:j+1]) && bytes.Equal(q, b[i:j+1]) {
342 return b, j
343 }
344 r = q
345 } else if r[0] == '&' {
346 // check if for example &amp; is followed by something that could potentially be an entity
347 k := j + 1
348 if k < len(b) && (b[k] >= '0' && b[k] <= '9' || b[k] >= 'a' && b[k] <= 'z' || b[k] >= 'A' && b[k] <= 'Z' || b[k] == '#') {
349 return b, k
350 }
351 }
352 }
353
354 copy(b[i:], r)
355 copy(b[i+len(r):], b[j+1:])
356 b = b[:len(b)-n+len(r)]
357 return b, i + len(r) - 1
358 }
359 return b, i
360 }
361
362 // ReplaceEntities replaces all occurrences of entites (such as &quot;) to their respective unencoded bytes.
363 func ReplaceEntities(b []byte, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) []byte {
364 for i := 0; i < len(b); i++ {
365 if b[i] == '&' && i+3 < len(b) {
366 b, i = replaceEntities(b, i, entitiesMap, revEntitiesMap)
367 }
368 }
369 return b
370 }
371
372 // ReplaceMultipleWhitespaceAndEntities is a combination of ReplaceMultipleWhitespace and ReplaceEntities. It is faster than executing both sequentially.
373 func ReplaceMultipleWhitespaceAndEntities(b []byte, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) []byte {
374 j, k := 0, 0 // j is write position, k is start of next text section
375 for i := 0; i < len(b); i++ {
376 if IsWhitespace(b[i]) {
377 start := i
378 newline := IsNewline(b[i])
379 i++
380 for ; i < len(b) && IsWhitespace(b[i]); i++ {
381 if IsNewline(b[i]) {
382 newline = true
383 }
384 }
385 if newline {
386 b[start] = '\n'
387 } else {
388 b[start] = ' '
389 }
390 if 1 < i-start { // more than one whitespace
391 if j == 0 {
392 j = start + 1
393 } else {
394 j += copy(b[j:], b[k:start+1])
395 }
396 k = i
397 }
398 }
399 if i+3 < len(b) && b[i] == '&' {
400 b, i = replaceEntities(b, i, entitiesMap, revEntitiesMap)
401 }
402 }
403 if j == 0 {
404 return b
405 } else if j == 1 { // only if starts with whitespace
406 b[k-1] = b[0] // move newline to end of whitespace
407 return b[k-1:]
408 } else if k < len(b) {
409 j += copy(b[j:], b[k:])
410 }
411 return b[:j]
412 }
413
414 // URLEncodingTable is a charmap for which characters need escaping in the URL encoding scheme
415 var URLEncodingTable = [256]bool{
416 // ASCII
417 true, true, true, true, true, true, true, true,
418 true, true, true, true, true, true, true, true,
419 true, true, true, true, true, true, true, true,
420 true, true, true, true, true, true, true, true,
421
422 true, false, true, true, true, true, true, false, // space, ", #, $, %, &
423 false, false, false, true, true, false, false, true, // +, comma, /
424 false, false, false, false, false, false, false, false,
425 false, false, true, true, true, true, true, true, // :, ;, <, =, >, ?
426
427 true, false, false, false, false, false, false, false, // @
428 false, false, false, false, false, false, false, false,
429 false, false, false, false, false, false, false, false,
430 false, false, false, true, true, true, true, false, // [, \, ], ^
431
432 true, false, false, false, false, false, false, false, // `
433 false, false, false, false, false, false, false, false,
434 false, false, false, false, false, false, false, false,
435 false, false, false, true, true, true, false, true, // {, |, }, DEL
436
437 // non-ASCII
438 true, true, true, true, true, true, true, true,
439 true, true, true, true, true, true, true, true,
440 true, true, true, true, true, true, true, true,
441 true, true, true, true, true, true, true, true,
442
443 true, true, true, true, true, true, true, true,
444 true, true, true, true, true, true, true, true,
445 true, true, true, true, true, true, true, true,
446 true, true, true, true, true, true, true, true,
447
448 true, true, true, true, true, true, true, true,
449 true, true, true, true, true, true, true, true,
450 true, true, true, true, true, true, true, true,
451 true, true, true, true, true, true, true, true,
452
453 true, true, true, true, true, true, true, true,
454 true, true, true, true, true, true, true, true,
455 true, true, true, true, true, true, true, true,
456 true, true, true, true, true, true, true, true,
457 }
458
459 // DataURIEncodingTable is a charmap for which characters need escaping in the Data URI encoding scheme
460 // Escape only non-printable characters, unicode and %, #, &.
461 // IE11 additionally requires encoding of \, [, ], ", <, >, `, {, }, |, ^ which is not required by Chrome, Firefox, Opera, Edge, Safari, Yandex
462 // To pass the HTML validator, restricted URL characters must be escaped: non-printable characters, space, <, >, #, %, "
463 var DataURIEncodingTable = [256]bool{
464 // ASCII
465 true, true, true, true, true, true, true, true,
466 true, true, true, true, true, true, true, true,
467 true, true, true, true, true, true, true, true,
468 true, true, true, true, true, true, true, true,
469
470 true, false, true, true, false, true, true, false, // space, ", #, %, &
471 false, false, false, false, false, false, false, false,
472 false, false, false, false, false, false, false, false,
473 false, false, false, false, true, false, true, false, // <, >
474
475 false, false, false, false, false, false, false, false,
476 false, false, false, false, false, false, false, false,
477 false, false, false, false, false, false, false, false,
478 false, false, false, true, true, true, true, false, // [, \, ], ^
479
480 true, false, false, false, false, false, false, false, // `
481 false, false, false, false, false, false, false, false,
482 false, false, false, false, false, false, false, false,
483 false, false, false, true, true, true, false, true, // {, |, }, DEL
484
485 // non-ASCII
486 true, true, true, true, true, true, true, true,
487 true, true, true, true, true, true, true, true,
488 true, true, true, true, true, true, true, true,
489 true, true, true, true, true, true, true, true,
490
491 true, true, true, true, true, true, true, true,
492 true, true, true, true, true, true, true, true,
493 true, true, true, true, true, true, true, true,
494 true, true, true, true, true, true, true, true,
495
496 true, true, true, true, true, true, true, true,
497 true, true, true, true, true, true, true, true,
498 true, true, true, true, true, true, true, true,
499 true, true, true, true, true, true, true, true,
500
501 true, true, true, true, true, true, true, true,
502 true, true, true, true, true, true, true, true,
503 true, true, true, true, true, true, true, true,
504 true, true, true, true, true, true, true, true,
505 }
506
507 // EncodeURL encodes bytes using the URL encoding scheme
508 func EncodeURL(b []byte, table [256]bool) []byte {
509 for i := 0; i < len(b); i++ {
510 c := b[i]
511 if table[c] {
512 b = append(b, 0, 0)
513 copy(b[i+3:], b[i+1:])
514 b[i+0] = '%'
515 b[i+1] = "0123456789ABCDEF"[c>>4]
516 b[i+2] = "0123456789ABCDEF"[c&15]
517 }
518 }
519 return b
520 }
521
522 // DecodeURL decodes an URL encoded using the URL encoding scheme
523 func DecodeURL(b []byte) []byte {
524 for i := 0; i < len(b); i++ {
525 if b[i] == '%' && i+2 < len(b) {
526 j := i + 1
527 c := 0
528 for ; j < i+3 && (b[j] >= '0' && b[j] <= '9' || b[j] >= 'a' && b[j] <= 'f' || b[j] >= 'A' && b[j] <= 'F'); j++ {
529 if b[j] <= '9' {
530 c = c<<4 + int(b[j]-'0')
531 } else if b[j] <= 'F' {
532 c = c<<4 + int(b[j]-'A') + 10
533 } else if b[j] <= 'f' {
534 c = c<<4 + int(b[j]-'a') + 10
535 }
536 }
537 if j == i+3 {
538 b[i] = byte(c)
539 b = append(b[:i+1], b[i+3:]...)
540 }
541 } else if b[i] == '+' {
542 b[i] = ' '
543 }
544 }
545 return b
546 }
547
548 func AppendEscape(b, str, chars []byte, escape byte) []byte {
549 i := 0
550 for j := 0; j < len(str); j++ {
551 has := false
552 for _, c := range chars {
553 if c == str[j] {
554 has = true
555 break
556 }
557 }
558 if has || str[j] == escape {
559 if i < j {
560 b = append(b, str[i:j]...)
561 }
562 b = append(b, escape)
563 i = j
564 }
565 }
566 if i < len(str) {
567 b = append(b, str[i:]...)
568 }
569 return b
570 }