diff --git a/Cargo.lock b/Cargo.lock index e60b33bbe5..01400750b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7331,6 +7331,7 @@ dependencies = [ "chrono", "craft-font-catalog", "craft-font-store", + "craft-mime", "craft-proof", "craft-zip", "encoding_rs", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 8c3c48ed2f..ad546f0b86 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -15,6 +15,7 @@ workspace = true test-support = [] [dependencies] +craft-mime.workspace = true wordcraft-geom = { workspace = true, features = ["image"] } wordcraft-doc = { workspace = true } wordcraft-fonts = { workspace = true } diff --git a/crates/engine/src/cmd/insert/objects.rs b/crates/engine/src/cmd/insert/objects.rs index 43267af36d..59d2e13cd1 100644 --- a/crates/engine/src/cmd/insert/objects.rs +++ b/crates/engine/src/cmd/insert/objects.rs @@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option> { Some(out) } -pub fn base64_encode(b: &[u8]) -> String { - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = String::with_capacity(b.len().div_ceil(3) * 4); - for ch in b.chunks(3) { - let n = - (ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32; - for i in 0..4 { - if i <= ch.len() { - out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out -} +pub use craft_mime::transfer::base64 as base64_encode; pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult { let bytes = if let Some(d) = p::str(v, "data") { diff --git a/crates/engine/src/cmd/insert/tests.rs b/crates/engine/src/cmd/insert/tests.rs index 8ab29ddd28..de38fe91fa 100644 --- a/crates/engine/src/cmd/insert/tests.rs +++ b/crates/engine/src/cmd/insert/tests.rs @@ -415,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() { assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600); } } + +#[test] +fn shared_base64_preserves_command_payload_bytes() { + for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] { + assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded); + } + let bytes: Vec = (0..513).map(|i| (i % 256) as u8).collect(); + for len in 0..=bytes.len() { + let encoded = super::objects::base64_encode(&bytes[..len]); + assert_eq!(encoded.len(), len.div_ceil(3) * 4); + assert!(!encoded.contains(['\r', '\n'])); + assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec())); + } + assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///"); + // The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding. + assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255])); + assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec())); + assert_eq!(super::objects::base64_decode("!!!!"), None); +}