Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(ext/web): optimize atob/btoa #13841

Merged
merged 7 commits into from
Mar 5, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ jobs:
~/.cargo/registry/index
~/.cargo/registry/cache
~/.cargo/git/db
key: 4-cargo-home-${{ matrix.os }}-${{ hashFiles('Cargo.lock') }}
key: 5-cargo-home-${{ matrix.os }}-${{ hashFiles('Cargo.lock') }}

# In main branch, always creates fresh cache
- name: Cache build output (main)
Expand All @@ -279,7 +279,7 @@ jobs:
!./target/*/*.zip
!./target/*/*.tar.gz
key: |
4-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-${{ github.sha }}
5-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-${{ github.sha }}

# Restore cache from the latest 'main' branch build.
- name: Cache build output (PR)
Expand All @@ -295,7 +295,7 @@ jobs:
!./target/*/*.tar.gz
key: never_saved
restore-keys: |
4-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-
5-cargo-target-${{ matrix.os }}-${{ matrix.profile }}-

# Don't save cache after building PRs or branches other than 'main'.
- name: Skip save cache (PR)
Expand Down
47 changes: 13 additions & 34 deletions ext/web/05_base64.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,9 @@
"use strict";

((window) => {
const core = Deno.core;
const webidl = window.__bootstrap.webidl;
const {
forgivingBase64Encode,
forgivingBase64Decode,
} = window.__bootstrap.infra;
const { DOMException } = window.__bootstrap.domException;
const {
ArrayPrototypeMap,
StringPrototypeCharCodeAt,
ArrayPrototypeJoin,
SafeArrayIterator,
StringFromCharCode,
TypedArrayFrom,
Uint8Array,
} = window.__bootstrap.primordials;

/**
* @param {string} data
Expand All @@ -36,13 +24,7 @@
prefix,
context: "Argument 1",
});

const uint8Array = forgivingBase64Decode(data);
const result = ArrayPrototypeMap(
[...new SafeArrayIterator(uint8Array)],
(byte) => StringFromCharCode(byte),
);
return ArrayPrototypeJoin(result, "");
return core.opSync("op_base64_atob", data);
}

/**
Expand All @@ -56,20 +38,17 @@
prefix,
context: "Argument 1",
});
const byteArray = ArrayPrototypeMap(
[...new SafeArrayIterator(data)],
(char) => {
const charCode = StringPrototypeCharCodeAt(char, 0);
if (charCode > 0xff) {
throw new DOMException(
"The string to be encoded contains characters outside of the Latin1 range.",
"InvalidCharacterError",
);
}
return charCode;
},
);
return forgivingBase64Encode(TypedArrayFrom(Uint8Array, byteArray));
try {
return core.opSync("op_base64_btoa", data);
} catch (e) {
if (e instanceof TypeError) {
throw new DOMException(
"The string to be encoded contains characters outside of the Latin1 range.",
"InvalidCharacterError",
);
}
throw e;
}
}

window.__bootstrap.base64 = {
Expand Down
82 changes: 55 additions & 27 deletions ext/web/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use deno_core::include_js_files;
use deno_core::op_async;
use deno_core::op_sync;
use deno_core::url::Url;
use deno_core::ByteString;
use deno_core::Extension;
use deno_core::OpState;
use deno_core::Resource;
Expand Down Expand Up @@ -85,6 +86,8 @@ pub fn init<P: TimersPermission + 'static>(
.ops(vec![
("op_base64_decode", op_sync(op_base64_decode)),
("op_base64_encode", op_sync(op_base64_encode)),
("op_base64_atob", op_sync(op_base64_atob)),
("op_base64_btoa", op_sync(op_base64_btoa)),
(
"op_encoding_normalize_label",
op_sync(op_encoding_normalize_label),
Expand Down Expand Up @@ -146,21 +149,41 @@ pub fn init<P: TimersPermission + 'static>(
}

fn op_base64_decode(
_state: &mut OpState,
_: &mut OpState,
input: String,
_: (),
) -> Result<ZeroCopyBuf, AnyError> {
let mut input: &str = &input.replace(|c| char::is_ascii_whitespace(&c), "");
Ok(b64_decode(input, false)?.into())
}

fn op_base64_atob(
_: &mut OpState,
input: String,
_: (),
) -> Result<ByteString, AnyError> {
Ok(ByteString(b64_decode(input, true)?))
}

fn b64_decode(input: String, padding: bool) -> Result<Vec<u8>, AnyError> {
let mut input = input.into_bytes();
AaronO marked this conversation as resolved.
Show resolved Hide resolved
input.retain(|c| !c.is_ascii_whitespace());

// If padding is expected, fail if not 4-byte aligned
// TODO(@AaronO): cleanup
if padding && input.len() % 4 != 0 && (input.ends_with(b"==") || input.ends_with(b"=")) {
return Err(
DomExceptionInvalidCharacterError::new("Failed to decode base64.").into(),
);
}

// "If the length of input divides by 4 leaving no remainder, then:
// if input ends with one or two U+003D EQUALS SIGN (=) characters,
// remove them from input."
if input.len() % 4 == 0 {
if input.ends_with("==") {
input = &input[..input.len() - 2]
} else if input.ends_with('=') {
input = &input[..input.len() - 1]
}
}
let input = match input.len() % 4 == 0 {
true if input.ends_with(b"==") => &input[..input.len() - 2],
true if input.ends_with(b"=") => &input[..input.len() - 1],
_ => &input,
};

// "If the length of input divides by 4 leaving a remainder of 1,
// throw an InvalidCharacterError exception and abort these steps."
Expand All @@ -170,38 +193,43 @@ fn op_base64_decode(
);
}

if input
.chars()
.any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
{
return Err(
let cfg = base64::Config::new(base64::CharacterSet::Standard, true)
.decode_allow_trailing_bits(true);
let out = base64::decode_config(&input, cfg).map_err(|err| match err {
base64::DecodeError::InvalidByte(_, _) => {
DomExceptionInvalidCharacterError::new(
"Failed to decode base64: invalid character",
)
.into(),
);
}

let cfg = base64::Config::new(base64::CharacterSet::Standard, true)
.decode_allow_trailing_bits(true);
let out = base64::decode_config(&input, cfg).map_err(|err| {
DomExceptionInvalidCharacterError::new(&format!(
}
_ => DomExceptionInvalidCharacterError::new(&format!(
"Failed to decode base64: {:?}",
err
))
)),
})?;
Ok(ZeroCopyBuf::from(out))

Ok(out)
}

fn op_base64_encode(
_state: &mut OpState,
_: &mut OpState,
s: ZeroCopyBuf,
_: (),
) -> Result<String, AnyError> {
Ok(b64_encode(&s))
}

fn op_base64_btoa(
_: &mut OpState,
s: ByteString,
_: (),
) -> Result<String, AnyError> {
Ok(b64_encode(&s))
}

fn b64_encode(s: impl AsRef<[u8]>) -> String {
let cfg = base64::Config::new(base64::CharacterSet::Standard, true)
.decode_allow_trailing_bits(true);
let out = base64::encode_config(&s, cfg);
Ok(out)
base64::encode_config(s.as_ref(), cfg)
}

#[derive(Deserialize)]
Expand Down