@@ -43,6 +43,14 @@ func _UnHex(p string, r, l int) (v int, ok bool) {
43
43
return v , true ;
44
44
}
45
45
46
+ func _ToHex (b []byte , rune int ) {
47
+ const hexDigits = "0123456789abcdef" ;
48
+ b [0 ] = hexDigits [rune >> 12 & 0xf ];
49
+ b [1 ] = hexDigits [rune >> 8 & 0xf ];
50
+ b [2 ] = hexDigits [rune >> 4 & 0xf ];
51
+ b [3 ] = hexDigits [rune & 0xf ];
52
+ }
53
+
46
54
// Unquote unquotes the JSON-quoted string s,
47
55
// returning a raw string t. If s is not a valid
48
56
// JSON-quoted string, Unquote returns with ok set to false.
@@ -88,7 +96,7 @@ func Unquote(s string) (t string, ok bool) {
88
96
w ++ ;
89
97
case 'u' :
90
98
r ++ ;
91
- rune , ok := _UnHex (s , r , 4 );
99
+ rune , ok := _UnHex (s , r , r + 4 );
92
100
if ! ok {
93
101
return
94
102
}
@@ -122,46 +130,53 @@ func Unquote(s string) (t string, ok bool) {
122
130
// Quote quotes the raw string s using JSON syntax,
123
131
// so that Unquote(Quote(s)) = s, true.
124
132
func Quote (s string ) string {
125
- chr := make ([]byte , utf8 . UTFMax );
133
+ chr := make ([]byte , 6 );
126
134
chr0 := chr [0 :1 ];
127
135
b := new (bytes.Buffer );
128
136
chr [0 ] = '"' ;
129
137
b .Write (chr0 );
130
- for i := 0 ; i < len (s ); i ++ {
138
+
139
+ for _ , rune := range s {
131
140
switch {
132
- case s [ i ] == '"' || s [ i ] == '\\' :
141
+ case rune == '"' || rune == '\\' :
133
142
chr [0 ] = '\\' ;
134
- chr [1 ] = s [ i ] ;
143
+ chr [1 ] = byte ( rune ) ;
135
144
b .Write (chr [0 :2 ]);
136
145
137
- case s [ i ] == '\b' :
146
+ case rune == '\b' :
138
147
chr [0 ] = '\\' ;
139
148
chr [1 ] = 'b' ;
140
149
b .Write (chr [0 :2 ]);
141
150
142
- case s [ i ] == '\f' :
151
+ case rune == '\f' :
143
152
chr [0 ] = '\\' ;
144
153
chr [1 ] = 'f' ;
145
154
b .Write (chr [0 :2 ]);
146
155
147
- case s [ i ] == '\n' :
156
+ case rune == '\n' :
148
157
chr [0 ] = '\\' ;
149
158
chr [1 ] = 'n' ;
150
159
b .Write (chr [0 :2 ]);
151
160
152
- case s [ i ] == '\r' :
161
+ case rune == '\r' :
153
162
chr [0 ] = '\\' ;
154
163
chr [1 ] = 'r' ;
155
164
b .Write (chr [0 :2 ]);
156
165
157
- case s [ i ] == '\t' :
166
+ case rune == '\t' :
158
167
chr [0 ] = '\\' ;
159
168
chr [1 ] = 't' ;
160
169
b .Write (chr [0 :2 ]);
161
170
162
- case 0x20 <= s [ i ] && s [ i ] < utf8 .RuneSelf :
163
- chr [0 ] = s [ i ] ;
171
+ case 0x20 <= rune && rune < utf8 .RuneSelf :
172
+ chr [0 ] = byte ( rune ) ;
164
173
b .Write (chr0 );
174
+
175
+ default :
176
+ chr [0 ] = '\\' ;
177
+ chr [1 ] = 'u' ;
178
+ _ToHex (chr [2 :6 ], rune );
179
+ b .Write (chr );
165
180
}
166
181
}
167
182
chr [0 ] = '"' ;
0 commit comments