File: htmlescapewriter.go

package info (click to toggle)
golang-github-valyala-quicktemplate 1.8.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 492 kB
  • sloc: makefile: 16; xml: 15
file content (62 lines) | stat: -rw-r--r-- 994 bytes parent folder | download | duplicates (3)
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
package quicktemplate

import (
	"bytes"
	"io"
)

type htmlEscapeWriter struct {
	w io.Writer
}

func (w *htmlEscapeWriter) Write(b []byte) (int, error) {
	if bytes.IndexByte(b, '<') < 0 &&
		bytes.IndexByte(b, '>') < 0 &&
		bytes.IndexByte(b, '"') < 0 &&
		bytes.IndexByte(b, '\'') < 0 &&
		bytes.IndexByte(b, '&') < 0 {

		// fast path - nothing to escape
		return w.w.Write(b)
	}

	// slow path
	write := w.w.Write
	j := 0
	for i, c := range b {
		switch c {
		case '<':
			write(b[j:i])
			write(strLT)
			j = i + 1
		case '>':
			write(b[j:i])
			write(strGT)
			j = i + 1
		case '"':
			write(b[j:i])
			write(strQuot)
			j = i + 1
		case '\'':
			write(b[j:i])
			write(strApos)
			j = i + 1
		case '&':
			write(b[j:i])
			write(strAmp)
			j = i + 1
		}
	}
	if n, err := write(b[j:]); err != nil {
		return j + n, err
	}
	return len(b), nil
}

var (
	strLT   = []byte("&lt;")
	strGT   = []byte("&gt;")
	strQuot = []byte("&quot;")
	strApos = []byte("&#39;")
	strAmp  = []byte("&amp;")
)