Debian Codegraph @

internal/markup/markup.go

raw symbols SCIP
1 // Package markup implements functions for extracting info from
2 // HTML and XML documents.
3 package markup
4
5 import (
6 "bytes"
7
8 "github.com/gabriel-vasile/mimetype/internal/scan"
9 )
10
11 // GetAnAttribute assumes we passed over an SGML tag and extracts first
12 // attribute and its value.
13 //
14 // Initially, this code existed inside charset/charset.go, because it was part of
15 // implementing the https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding
16 // algorithm. But because extracting an attribute from a tag is the same for
17 // both HTML and XML, then the code was moved here.
18 func GetAnAttribute(s *scan.Bytes) (name, val []byte, hasMore bool) {
19 for scan.ByteIsWS(s.Peek()) || s.Peek() == '/' {
20 s.Advance(1)
21 }
22 if s.Peek() == '>' {
23 return nil, nil, false
24 }
25 origS, end := *s, 0
26 // step 4 and 5
27 for {
28 // bap means byte at position in the specification.
29 bap := s.Pop()
30 if bap == 0 {
31 return nil, nil, false
32 }
33 if bap == '=' && end > 0 {
34 val, hasMore := getAValue(s)
35 return origS[:end], val, hasMore
36 } else if scan.ByteIsWS(bap) {
37 for scan.ByteIsWS(s.Peek()) {
38 s.Advance(1)
39 }
40 if s.Peek() != '=' {
41 return origS[:end], nil, true
42 }
43 s.Advance(1)
44 for scan.ByteIsWS(s.Peek()) {
45 s.Advance(1)
46 }
47 val, hasMore := getAValue(s)
48 return origS[:end], val, hasMore
49 } else if bap == '/' || bap == '>' {
50 return origS[:end], nil, false
51 } else { // for any ASCII, non-ASCII, just advance
52 end++
53 }
54 }
55 }
56
57 func getAValue(s *scan.Bytes) (_ []byte, hasMore bool) {
58 for scan.ByteIsWS(s.Peek()) {
59 s.Advance(1)
60 }
61 origS, end := *s, 0
62 bap := s.Pop()
63 if bap == 0 {
64 return nil, false
65 }
66 end++
67 // Step 10
68 switch bap {
69 case '"', '\'':
70 val := s.PopUntil(bap)
71 if s.Pop() != bap {
72 return nil, false
73 }
74 return val, s.Peek() != 0 && s.Peek() != '>'
75 case '>':
76 return nil, false
77 }
78
79 // Step 11
80 for {
81 bap = s.Pop()
82 if bap == 0 {
83 return nil, false
84 }
85 switch {
86 case scan.ByteIsWS(bap):
87 return origS[:end], true
88 case bap == '>':
89 return origS[:end], false
90 default:
91 end++
92 }
93 }
94 }
95
96 func SkipAComment(s *scan.Bytes) (skipped bool) {
97 if bytes.HasPrefix(*s, []byte("<!--")) {
98 // Offset by 2 len(<!) because the starting and ending -- can be the same.
99 if i := bytes.Index((*s)[2:], []byte("-->")); i != -1 {
100 s.Advance(i + 2 + 3) // 2 comes from len(<!) and 3 comes from len(-->).
101 return true
102 }
103 }
104 return false
105 }