Răsfoiți Sursa

Simplify and document the signature of EncodingOverride::encode.

Simon Sapin 12 ani în urmă
părinte
comite
4e30f965cc
3 a modificat fișierele cu 14 adăugiri și 9 ștergeri
  1. 10 5
      src/encoding.rs
  2. 2 2
      src/form_urlencoded.rs
  3. 2 2
      src/parser.rs

+ 10 - 5
src/encoding.rs

@@ -62,8 +62,14 @@ impl EncodingOverride {
         }
     }
 
-    pub fn encode<'a>(&self, pair: &'a mut (&str, Vec<u8>)) -> &'a [u8] {
-        let &(ref input, ref mut tmp) = pair;
+    // For UTF-8, we want to return the &[u8] bytes of the &str input strings without copying
+    // But for other encodings we have to allocate a new Vec<u8>.
+    // To return &[u8] in that case, the vector has to be kept somewhere
+    // that lives at least as long as the return value.
+    // Therefore, the caller provides a temporary Vec<u8> as scratch space.
+    //
+    // FIXME: Return std::borrow::Cow<'a, Vec<u8>, [u8]> instead.
+    pub fn encode<'a>(&self, input: &'a str, tmp: &'a mut Vec<u8>) -> &'a [u8] {
         match self.encoding {
             Some(encoding) => {
                 *tmp = encoding.encode(input.as_slice(), EncoderTrap::NcrEscape).unwrap();
@@ -96,8 +102,7 @@ impl EncodingOverride {
         String::from_utf8_lossy(input).into_string()
     }
 
-    pub fn encode<'a>(&self, pair: &'a mut (&str, Vec<u8>)) -> &'a [u8] {
-        let &(ref query, _) = pair;
-        query.as_bytes()
+    pub fn encode<'a>(&self, input: &'a str, _: &'a mut Vec<u8>) -> &'a [u8] {
+        input.as_bytes()
     }
 }

+ 2 - 2
src/form_urlencoded.rs

@@ -123,8 +123,8 @@ fn serialize_internal<'a, I>(mut pairs: I, encoding_override: EncodingOverride)
     #[inline]
     fn byte_serialize(input: &str, output: &mut String,
                       encoding_override: EncodingOverride) {
-        let mut pair = (input, vec![]);
-        for &byte in encoding_override.encode(&mut pair).iter() {
+        let tmp = &mut vec![];
+        for &byte in encoding_override.encode(input, tmp).iter() {
             if byte == b' ' {
                 output.push_str("+")
             } else {

+ 2 - 2
src/parser.rs

@@ -644,8 +644,8 @@ pub fn parse_query<'a>(input: &'a str, context: Context, parser: &UrlParser)
         }
     }
 
-    let mut pair = (query.as_slice(), vec![]);
-    let query_bytes = parser.query_encoding_override.encode(&mut pair);
+    let tmp = &mut vec![];
+    let query_bytes = parser.query_encoding_override.encode(query.as_slice(), tmp);
     Ok((percent_encode(query_bytes.as_slice(), QUERY_ENCODE_SET), remaining))
 }