11package util
22
3- import "strings"
3+ import (
4+ "strings"
5+ "unicode"
6+ "unicode/utf8"
7+ )
48
59type StrEqualFunc func (a , b string ) bool
610
@@ -11,3 +15,47 @@ func IsStrEqualAccurate(a, b string) bool {
1115func IsStrEqualNoCase (a , b string ) bool {
1216 return strings .EqualFold (a , b )
1317}
18+
19+ func EscapeControllingRune (str string ) []byte {
20+ runeBytes := make ([]byte , 4 )
21+ buf := make ([]byte , 0 , len (str ))
22+
23+ for _ , r := range str {
24+ if uint32 (r ) < 32 { // non-printable chars
25+ b := byte (r )
26+ if b == 0 {
27+ buf = append (buf , '\\' , '0' )
28+ } else if b == '\a' {
29+ buf = append (buf , '\\' , 'a' )
30+ } else if b == '\b' {
31+ buf = append (buf , '\\' , 'b' )
32+ } else if b == '\f' {
33+ buf = append (buf , '\\' , 'f' )
34+ } else if b == '\n' {
35+ buf = append (buf , '\\' , 'n' )
36+ } else if b == '\r' {
37+ buf = append (buf , '\\' , 'r' )
38+ } else if b == '\t' {
39+ buf = append (buf , '\\' , 't' )
40+ } else if b == '\v' {
41+ buf = append (buf , '\\' , 'v' )
42+ } else {
43+ h , l := ByteToHex (b )
44+ buf = append (buf , '\\' , 'x' , h , l )
45+ }
46+ continue
47+ }
48+
49+ if unicode .IsControl (r ) {
50+ nBytes := utf8 .EncodeRune (runeBytes , r )
51+ for i := 0 ; i < nBytes ; i ++ {
52+ h , l := ByteToHex (runeBytes [i ])
53+ buf = append (buf , '\\' , 'x' , h , l )
54+ }
55+ } else {
56+ buf = utf8 .AppendRune (buf , r )
57+ }
58+ }
59+
60+ return buf
61+ }
0 commit comments