-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.go
97 lines (90 loc) · 2.57 KB
/
utils.go
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
// Package jsongen
// Copyright 2024 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//
// https://github.com/tidwall/gjson
package jsongen
import (
"unicode/utf8"
"github.com/fufuok/utils"
"github.com/fufuok/utils/pools/bytespool"
)
// DisableEscapeHTML will disable the automatic escaping of certain
// "problamatic" HTML characters when encoding to JSON.
// These character include '>', '<' and '&', which get escaped to \u003e,
// \u0026, and \u003c respectively.
//
// This is a global flag and will affect all further gjson operations.
// Ideally, if used, it should be set one time before other gjson functions
// are called.
var DisableEscapeHTML = false
var hexchars = [...]byte{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f',
}
// EscapeString 转义 JSON 字符串, 并在前后加上双引号
func EscapeString(s string) string {
dst := bytespool.Make(len(s) + 2)
return utils.B2S(AppendJSONString(dst, s))
}
// AppendJSONString is a convenience function that converts the provided string
// to a valid JSON string and appends it to dst.
//
//nolint:cyclop,nestif
func AppendJSONString(dst []byte, s string) []byte {
dst = append(dst, make([]byte, len(s)+2)...)
dst = append(dst[:len(dst)-len(s)-2], '"')
for i := 0; i < len(s); i++ {
if s[i] < ' ' {
dst = append(dst, '\\')
switch s[i] {
case '\b':
dst = append(dst, 'b')
case '\f':
dst = append(dst, 'f')
case '\n':
dst = append(dst, 'n')
case '\r':
dst = append(dst, 'r')
case '\t':
dst = append(dst, 't')
default:
dst = append(dst, 'u')
dst = appendHex16(dst, uint16(s[i]))
}
} else if !DisableEscapeHTML &&
(s[i] == '>' || s[i] == '<' || s[i] == '&') {
dst = append(dst, '\\', 'u')
dst = appendHex16(dst, uint16(s[i]))
} else if s[i] == '\\' {
dst = append(dst, '\\', '\\')
} else if s[i] == '"' {
dst = append(dst, '\\', '"')
} else if s[i] > 127 {
// read utf8 character
r, n := utf8.DecodeRuneInString(s[i:])
if n == 0 {
break
}
if r == utf8.RuneError && n == 1 {
dst = append(dst, `\ufffd`...)
} else if r == '\u2028' || r == '\u2029' {
dst = append(dst, `\u202`...)
dst = append(dst, hexchars[r&0xF])
} else {
dst = append(dst, s[i:i+n]...)
}
i = i + n - 1
} else {
dst = append(dst, s[i])
}
}
return append(dst, '"')
}
func appendHex16(dst []byte, x uint16) []byte {
return append(dst,
hexchars[x>>12&0xF], hexchars[x>>8&0xF],
hexchars[x>>4&0xF], hexchars[x>>0&0xF],
)
}