From 4e92f38d2ced6cbc2c7ed13d79d739dd4ddadb4c Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Thu, 30 Jun 2022 14:18:06 +0530 Subject: [PATCH] perf(ext/web): avoid reallocations in op_base64_atob (#15018) --- ext/web/lib.rs | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/ext/web/lib.rs b/ext/web/lib.rs index 9bc7c1ccec..a80447614f 100644 --- a/ext/web/lib.rs +++ b/ext/web/lib.rs @@ -124,25 +124,27 @@ pub fn init( #[op] fn op_base64_decode(input: String) -> Result { - 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] -fn op_base64_atob(s: ByteString) -> Result { - Ok(forgiving_base64_decode(s.into())?.into()) +fn op_base64_atob(mut s: ByteString) -> Result { + let decoded_len = forgiving_base64_decode(&mut s)?; + s.truncate(decoded_len); + Ok(s) } /// See -fn forgiving_base64_decode(mut input: Vec) -> Result, AnyError> { +#[inline] +fn forgiving_base64_decode(input: &mut [u8]) -> Result { let error: _ = || DomExceptionInvalidCharacterError::new("Failed to decode base64"); - - let decoded = base64_simd::Base64::forgiving_decode_inplace(&mut input) + let decoded = base64_simd::Base64::forgiving_decode_inplace(input) .map_err(|_| error())?; - - let decoded_len = decoded.len(); - input.truncate(decoded_len); - Ok(input) + Ok(decoded.len()) } #[op] @@ -156,9 +158,10 @@ fn op_base64_btoa(s: ByteString) -> String { } /// See +#[inline] fn forgiving_base64_encode(s: &[u8]) -> String { - let base64 = base64_simd::Base64::STANDARD; - base64.encode_to_boxed_str(s).into_string() + const BASE64_STANDARD: base64_simd::Base64 = base64_simd::Base64::STANDARD; + BASE64_STANDARD.encode_to_boxed_str(s).into_string() } #[derive(Deserialize)]