| 1 |
package xml |
| 2 |
|
| 3 |
var ( |
| 4 |
ltEntityBytes = []byte("<") |
| 5 |
ampEntityBytes = []byte("&") |
| 6 |
singleQuoteEntityBytes = []byte("'") |
| 7 |
doubleQuoteEntityBytes = []byte(""") |
| 8 |
) |
| 9 |
|
| 10 |
// EscapeAttrVal returns the escape attribute value bytes without quotes. |
| 11 |
func EscapeAttrVal(buf *[]byte, b []byte) []byte { |
| 12 |
singles := 0 |
| 13 |
doubles := 0 |
| 14 |
for _, c := range b { |
| 15 |
if c == '"' { |
| 16 |
doubles++ |
| 17 |
} else if c == '\'' { |
| 18 |
singles++ |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
n := len(b) + 2 |
| 23 |
var quote byte |
| 24 |
var escapedQuote []byte |
| 25 |
if doubles > singles { |
| 26 |
n += singles * 4 |
| 27 |
quote = '\'' |
| 28 |
escapedQuote = singleQuoteEntityBytes |
| 29 |
} else { |
| 30 |
n += doubles * 4 |
| 31 |
quote = '"' |
| 32 |
escapedQuote = doubleQuoteEntityBytes |
| 33 |
} |
| 34 |
if n > cap(*buf) { |
| 35 |
*buf = make([]byte, 0, n) // maximum size, not actual size |
| 36 |
} |
| 37 |
t := (*buf)[:n] // maximum size, not actual size |
| 38 |
t[0] = quote |
| 39 |
j := 1 |
| 40 |
start := 0 |
| 41 |
for i, c := range b { |
| 42 |
if c == quote { |
| 43 |
j += copy(t[j:], b[start:i]) |
| 44 |
j += copy(t[j:], escapedQuote) |
| 45 |
start = i + 1 |
| 46 |
} |
| 47 |
} |
| 48 |
j += copy(t[j:], b[start:]) |
| 49 |
t[j] = quote |
| 50 |
return t[:j+1] |
| 51 |
} |
| 52 |
|
| 53 |
// EscapeCDATAVal returns the escaped text bytes. |
| 54 |
func EscapeCDATAVal(buf *[]byte, b []byte) ([]byte, bool) { |
| 55 |
n := 0 |
| 56 |
for _, c := range b { |
| 57 |
if c == '<' || c == '&' { |
| 58 |
if c == '<' { |
| 59 |
n += 3 // < |
| 60 |
} else { |
| 61 |
n += 4 // & |
| 62 |
} |
| 63 |
if n > len("<![CDATA[]]>") { |
| 64 |
return b, false |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
if len(b)+n > cap(*buf) { |
| 69 |
*buf = make([]byte, 0, len(b)+n) |
| 70 |
} |
| 71 |
t := (*buf)[:len(b)+n] |
| 72 |
j := 0 |
| 73 |
start := 0 |
| 74 |
for i, c := range b { |
| 75 |
if c == '<' { |
| 76 |
j += copy(t[j:], b[start:i]) |
| 77 |
j += copy(t[j:], ltEntityBytes) |
| 78 |
start = i + 1 |
| 79 |
} else if c == '&' { |
| 80 |
j += copy(t[j:], b[start:i]) |
| 81 |
j += copy(t[j:], ampEntityBytes) |
| 82 |
start = i + 1 |
| 83 |
} |
| 84 |
} |
| 85 |
j += copy(t[j:], b[start:]) |
| 86 |
return t[:j], true |
| 87 |
} |