@@ -66,6 +66,16 @@ fn encode_unicode(s: Option<&str>) -> char {
66
66
/// assert_eq!(s, "Foo 😊 Bar");
67
67
/// ```
68
68
pub fn unescape_unicode < W > ( w : & mut W , input : & str ) -> fmt:: Result
69
+ where
70
+ W : fmt:: Write ,
71
+ {
72
+ if unescape ( w, input) ? {
73
+ return Ok ( ( ) ) ;
74
+ }
75
+ w. write_str ( input)
76
+ }
77
+
78
+ fn unescape < W > ( w : & mut W , input : & str ) -> Result < bool , std:: fmt:: Error >
69
79
where
70
80
W : fmt:: Write ,
71
81
{
@@ -100,10 +110,15 @@ where
100
110
w. write_char ( new_char) ?;
101
111
start = ptr;
102
112
}
113
+
114
+ if start == 0 {
115
+ return Ok ( false ) ;
116
+ }
117
+
103
118
if start != ptr {
104
119
w. write_str ( & input[ start..ptr] ) ?;
105
120
}
106
- Ok ( ( ) )
121
+ Ok ( true )
107
122
}
108
123
109
124
/// Unescapes to a `Cow<str>` optionally allocating.
@@ -119,41 +134,11 @@ where
119
134
/// );
120
135
/// ```
121
136
pub fn unescape_unicode_to_string ( input : & str ) -> Cow < str > {
122
- let bytes = input. as_bytes ( ) ;
123
- let mut result = Cow :: from ( input) ;
124
-
125
- let mut ptr = 0 ;
126
-
127
- while let Some ( b) = bytes. get ( ptr) {
128
- if b != & b'\\' {
129
- if let Cow :: Owned ( ref mut s) = result {
130
- s. push ( * b as char ) ;
131
- }
132
- ptr += 1 ;
133
- continue ;
134
- }
135
-
136
- if let Cow :: Borrowed ( _) = result {
137
- result = Cow :: from ( & input[ 0 ..ptr] ) ;
138
- }
139
-
140
- ptr += 1 ;
141
-
142
- let new_char = match bytes. get ( ptr) {
143
- Some ( b'\\' ) => '\\' ,
144
- Some ( b'"' ) => '"' ,
145
- Some ( u @ b'u' ) | Some ( u @ b'U' ) => {
146
- let start = ptr + 1 ;
147
- let len = if u == & b'u' { 4 } else { 6 } ;
148
- ptr += len;
149
- input
150
- . get ( start..( start + len) )
151
- . map_or ( UNKNOWN_CHAR , |slice| encode_unicode ( Some ( slice) ) )
152
- }
153
- _ => UNKNOWN_CHAR ,
154
- } ;
155
- result. to_mut ( ) . push ( new_char) ;
156
- ptr += 1 ;
137
+ let mut result = String :: new ( ) ;
138
+ let owned = unescape ( & mut result, input) . expect ( "String write methods don't Err" ) ;
139
+ if owned {
140
+ Cow :: Owned ( result)
141
+ } else {
142
+ Cow :: Borrowed ( input)
157
143
}
158
- result
159
144
}
0 commit comments