swift.rs (3410B)
1 //! Source-owned observer cancellation over UniFFI's thread-safe cancel ABI. 2 use anyhow::{Result, ensure}; 3 use sha2::{Digest, Sha256}; 4 5 const START: &str = "fileprivate func uniffiRustCallAsync<F, T>("; 6 const END: &str = "// Callback handlers for an async calls."; 7 const UPSTREAM_SHA256: &str = "f05b2a0d1b6d335801874c67de4b25ad50d2995ccdf6650da0562a4b8d943518"; 8 const CANCELLED: &str = 9 " case CALL_CANCELLED:\n fatalError(\"Cancellation not supported yet\")"; 10 11 pub(super) fn cancellation(source: &str, header: &str) -> Result<String> { 12 ensure!( 13 source.matches(START).count() == 1 && source.matches(END).count() == 1, 14 "unexpected Swift async helper layout" 15 ); 16 let start = source.find(START).expect("counted helper"); 17 let end = source.find(END).expect("counted boundary"); 18 ensure!(end > start, "invalid Swift helper boundaries"); 19 let original = &source[start..end]; 20 let initializers: Vec<_> = original 21 .lines() 22 .filter(|line| line.starts_with(" uniffiEnsure") && line.ends_with("Initialized()")) 23 .collect(); 24 ensure!(initializers.len() == 1, "unexpected Swift initializer"); 25 let normalized = original.replace(initializers[0], " {{ ensure_init_fn_name }}()"); 26 ensure!( 27 format!("{:x}", Sha256::digest(normalized.as_bytes())) == UPSTREAM_SHA256, 28 "upstream Swift async helper changed" 29 ); 30 ensure!( 31 source.matches(CANCELLED).count() == 1, 32 "unexpected Swift cancellation error branch" 33 ); 34 let helper = format!("{}\n", include_str!("async.swift")) 35 .replace(" __RADROOTS_ENSURE_INIT__", initializers[0]); 36 let mut output = format!("{}{}{}", &source[..start], helper, &source[end..]); 37 output = output.replacen( 38 CANCELLED, 39 " case CALL_CANCELLED:\n throw CancellationError()", 40 1, 41 ); 42 let mut rewritten = String::with_capacity(output.len()); 43 let mut count = 0; 44 for line in output.split_inclusive('\n') { 45 if let Some(symbol) = line.strip_prefix(" freeFunc: ") { 46 let symbol = symbol 47 .strip_suffix(",\n") 48 .ok_or_else(|| anyhow::anyhow!("unexpected Swift free callback"))?; 49 ensure!( 50 symbol 51 .bytes() 52 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') 53 && symbol.matches("_rust_future_free_").count() == 1, 54 "unexpected Swift callback symbol" 55 ); 56 let cancel = symbol.replacen("_rust_future_free_", "_rust_future_cancel_", 1); 57 ensure!( 58 header 59 .matches(&format!("void {cancel}(uint64_t handle")) 60 .count() 61 == 1, 62 "missing native cancel ABI" 63 ); 64 rewritten.push_str(&format!(" cancelFunc: {cancel},\n")); 65 count += 1; 66 } 67 rewritten.push_str(line); 68 } 69 ensure!(count > 0, "no Swift async calls found"); 70 Ok(rewritten) 71 } 72 73 #[cfg(test)] 74 mod tests { 75 use super::*; 76 #[test] 77 fn refuses_unknown_layout_and_prepatched_input() { 78 assert!(cancellation("", "").is_err()); 79 assert!(cancellation(&format!("{START}\nchanged\n{END}"), "").is_err()); 80 assert!(cancellation(include_str!("async.swift"), "").is_err()); 81 } 82 }