1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-07 06:46:59 -05:00

perf(ext/web): avoid reallocations in op_base64_atob (#15018)

This commit is contained in:
Divy Srivastava 2022-06-30 14:18:06 +05:30 committed by David Sherret
parent f9a736372f
commit 2cfda9d8ac

View file

@ -124,25 +124,27 @@ pub fn init<P: TimersPermission + 'static>(
#[op] #[op]
fn op_base64_decode(input: String) -> Result<ZeroCopyBuf, AnyError> { fn op_base64_decode(input: String) -> Result<ZeroCopyBuf, AnyError> {
Ok(forgiving_base64_decode(input.into_bytes())?.into()) let mut s = input.into_bytes();
let decoded_len = forgiving_base64_decode(&mut s)?;
s.truncate(decoded_len);
Ok(s.into())
} }
#[op] #[op]
fn op_base64_atob(s: ByteString) -> Result<ByteString, AnyError> { fn op_base64_atob(mut s: ByteString) -> Result<ByteString, AnyError> {
Ok(forgiving_base64_decode(s.into())?.into()) let decoded_len = forgiving_base64_decode(&mut s)?;
s.truncate(decoded_len);
Ok(s)
} }
/// See <https://infra.spec.whatwg.org/#forgiving-base64> /// See <https://infra.spec.whatwg.org/#forgiving-base64>
fn forgiving_base64_decode(mut input: Vec<u8>) -> Result<Vec<u8>, AnyError> { #[inline]
fn forgiving_base64_decode(input: &mut [u8]) -> Result<usize, AnyError> {
let error: _ = let error: _ =
|| DomExceptionInvalidCharacterError::new("Failed to decode base64"); || DomExceptionInvalidCharacterError::new("Failed to decode base64");
let decoded = base64_simd::Base64::forgiving_decode_inplace(input)
let decoded = base64_simd::Base64::forgiving_decode_inplace(&mut input)
.map_err(|_| error())?; .map_err(|_| error())?;
Ok(decoded.len())
let decoded_len = decoded.len();
input.truncate(decoded_len);
Ok(input)
} }
#[op] #[op]
@ -156,9 +158,10 @@ fn op_base64_btoa(s: ByteString) -> String {
} }
/// See <https://infra.spec.whatwg.org/#forgiving-base64> /// See <https://infra.spec.whatwg.org/#forgiving-base64>
#[inline]
fn forgiving_base64_encode(s: &[u8]) -> String { fn forgiving_base64_encode(s: &[u8]) -> String {
let base64 = base64_simd::Base64::STANDARD; const BASE64_STANDARD: base64_simd::Base64 = base64_simd::Base64::STANDARD;
base64.encode_to_boxed_str(s).into_string() BASE64_STANDARD.encode_to_boxed_str(s).into_string()
} }
#[derive(Deserialize)] #[derive(Deserialize)]