summaryrefslogtreecommitdiff
path: root/src/query_encoding.rs
diff options
context:
space:
mode:
authorJeff Vander Stoep <jeffv@google.com>2020-12-21 16:30:52 +0000
committerAutomerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>2020-12-21 16:30:52 +0000
commitf69374e3c35529202aecae8e1026271b9939c27f (patch)
tree0e29682c169c9d673b17bae77494e35b68c3bb5d /src/query_encoding.rs
parentec9391ffbe79d521cb2548c472232d2a215ed51d (diff)
parentda6fecba5f6d2b5fe4d215c290a670469437ca5f (diff)
downloadform_urlencoded-f69374e3c35529202aecae8e1026271b9939c27f.tar.gz
Initial import of form_urlencoded v1.0.0 am: 6d73de0679 am: da6fecba5f
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/form_urlencoded/+/1533346 MUST ONLY BE SUBMITTED BY AUTOMERGER Change-Id: I58c7a7ed808b1d398b5e44e817ca738a234e0f20
Diffstat (limited to 'src/query_encoding.rs')
-rw-r--r--src/query_encoding.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/query_encoding.rs b/src/query_encoding.rs
new file mode 100644
index 0000000..76aed15
--- /dev/null
+++ b/src/query_encoding.rs
@@ -0,0 +1,35 @@
+// Copyright 2019 The rust-url developers.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::borrow::Cow;
+
+pub type EncodingOverride<'a> = Option<&'a dyn Fn(&str) -> Cow<[u8]>>;
+
+pub(crate) fn encode<'a>(encoding_override: EncodingOverride, input: &'a str) -> Cow<'a, [u8]> {
+ if let Some(o) = encoding_override {
+ return o(input);
+ }
+ input.as_bytes().into()
+}
+
+pub(crate) fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
+ match input {
+ Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
+ Cow::Owned(bytes) => {
+ let raw_utf8: *const [u8];
+ match String::from_utf8_lossy(&bytes) {
+ Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
+ Cow::Owned(s) => return s.into(),
+ }
+ // from_utf8_lossy returned a borrow of `bytes` unchanged.
+ debug_assert!(raw_utf8 == &*bytes as *const [u8]);
+ // Reuse the existing `Vec` allocation.
+ unsafe { String::from_utf8_unchecked(bytes) }.into()
+ }
+ }
+}