From 6d73de0679adeffa08bcbd51973ac49f24d8cd68 Mon Sep 17 00:00:00 2001 From: Jeff Vander Stoep Date: Thu, 17 Dec 2020 20:00:13 +0100 Subject: Initial import of form_urlencoded v1.0.0 Test: n/a Change-Id: I0dcac4bfa2e887655063f1b241b9d0f5236cc0e8 --- src/query_encoding.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/query_encoding.rs (limited to 'src/query_encoding.rs') 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 or the MIT license +// , 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 { + 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() + } + } +} -- cgit v1.2.3