-
Notifications
You must be signed in to change notification settings - Fork 5
/
WriteStringToGolang.go
112 lines (104 loc) · 2.01 KB
/
WriteStringToGolang.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package udwGoTypeMarshal
import (
"bytes"
"unicode/utf8"
)
const lowerhex = "0123456789abcdef"
func WriteStringToGolang(s string) string {
if canUseHereDoc(s) {
return "`" + s + "`"
} else {
return WriteStringToGolangDoubleQuotation(s)
}
}
func WriteStringToGolangDoubleQuotation(s string) string {
outBuf := &bytes.Buffer{}
WriteStringToGolangDoubleQuotationToBuf(s, outBuf)
return outBuf.String()
}
func canUseHereDoc(s string) bool {
l := len(s)
i := 0
for {
if i >= l {
return true
}
result, size := utf8.DecodeRuneInString(s[i:])
if result == utf8.RuneError {
return false
}
if result == '`' {
return false
}
if result == 65279 {
return false
}
if result == 0 {
return false
}
if result == '\r' {
return false
}
i += size
}
}
func WriteStringToGolangToBuf(s string, _buf *bytes.Buffer) {
if canUseHereDoc(s) {
_buf.WriteByte('`')
_buf.WriteString(s)
_buf.WriteByte('`')
return
} else {
WriteStringToGolangDoubleQuotationToBuf(s, _buf)
return
}
}
func WriteStringToGolangDoubleQuotationToBuf(s string, outBuf *bytes.Buffer) {
outBuf.WriteByte('"')
l := len(s)
i := 0
for {
if i >= l {
outBuf.WriteByte('"')
return
}
b := s[i]
switch b {
case '\a':
outBuf.WriteString(`\a`)
case '\b':
outBuf.WriteString(`\b`)
case '\f':
outBuf.WriteString(`\f`)
case '\n':
outBuf.WriteString(`\n`)
case '\r':
outBuf.WriteString(`\r`)
case '\t':
outBuf.WriteString(`\t`)
case '\v':
outBuf.WriteString(`\v`)
case '\\':
outBuf.WriteString(`\\`)
case '"':
outBuf.WriteString(`\"`)
case '\x00':
outBuf.WriteString(`\x00`)
default:
if b >= 0x20 && b <= 0x7e {
outBuf.WriteByte(b)
} else {
result, size := utf8.DecodeRuneInString(s[i:])
if result != utf8.RuneError && result != 65279 && result != 0 {
outBuf.WriteRune(result)
i += size - 1
} else {
outBuf.WriteString(`\x`)
outBuf.WriteByte(lowerhex[s[i]>>4])
outBuf.WriteByte(lowerhex[s[i]&0xF])
}
}
}
i++
}
}