runtime/globals/
base64.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use base64::Engine as _;
8use base64::prelude::BASE64_STANDARD;
9use data_url::forgiving_base64::decode_to_vec;
10use ion::string::byte::ByteString;
11use ion::{Context, Error, ErrorKind, Object, Result, function_spec, js_fn};
12use mozjs::jsapi::JSFunctionSpec;
13
14const INVALID_CHARACTER_EXCEPTION: &str = "String contains an invalid character.";
15
16#[js_fn]
17fn btoa(data: ByteString) -> String {
18	BASE64_STANDARD.encode(data.as_bytes())
19}
20
21#[js_fn]
22fn atob(data: ByteString) -> Result<ByteString> {
23	let bytes = decode_to_vec(data.as_bytes());
24	let bytes = bytes.map_err(|_| Error::new(INVALID_CHARACTER_EXCEPTION, ErrorKind::Range))?;
25	Ok(unsafe { ByteString::from_unchecked(bytes) })
26}
27
28const FUNCTIONS: &[JSFunctionSpec] = &[function_spec!(btoa, 1), function_spec!(atob, 1), JSFunctionSpec::ZERO];
29
30pub fn define(cx: &Context, global: &Object) -> bool {
31	unsafe { global.define_methods(cx, FUNCTIONS) }
32}