diff --git a/.changes/change-pr-14340.md b/.changes/change-pr-14340.md new file mode 100644 index 000000000000..7b3ec4f02095 --- /dev/null +++ b/.changes/change-pr-14340.md @@ -0,0 +1,5 @@ +--- +"tauri": "patch:perf" +--- + +perf: optimize CSP nonce generation diff --git a/crates/tauri/src/manager/mod.rs b/crates/tauri/src/manager/mod.rs index 2126dd8957ce..3e1f9707b0cd 100644 --- a/crates/tauri/src/manager/mod.rs +++ b/crates/tauri/src/manager/mod.rs @@ -6,6 +6,7 @@ use std::{ borrow::Cow, collections::HashMap, fmt, + fmt::Write, sync::{atomic::AtomicBool, Arc, Mutex, MutexGuard}, }; @@ -127,7 +128,7 @@ fn replace_csp_nonce( directive: &str, hashes: Vec, ) { - let mut nonces = Vec::new(); + let mut nonces = Vec::with_capacity(asset.matches(token).count()); *asset = replace_with_callback(asset, token, || { #[cfg(target_pointer_width = "64")] let mut raw = [0u8; 8]; @@ -141,17 +142,23 @@ fn replace_csp_nonce( nonce.to_string() }); - if !(nonces.is_empty() && hashes.is_empty()) { - let nonce_sources = nonces - .into_iter() - .map(|n| format!("'nonce-{n}'")) - .collect::>(); + if !nonces.is_empty() || !hashes.is_empty() { let sources = csp.entry(directive.into()).or_default(); - let self_source = "'self'".to_string(); - if !sources.contains(&self_source) { + let self_source = "'self'"; + if !sources.contains(self_source) { sources.push(self_source); } - sources.extend(nonce_sources); + #[cfg(target_pointer_width = "64")] + let mut buf = String::with_capacity(28); + #[cfg(target_pointer_width = "32")] + let mut buf = String::with_capacity(20); + #[cfg(target_pointer_width = "16")] + let mut buf = String::with_capacity(14); + for nonce in nonces { + buf.clear(); + write!(&mut buf, "'nonce-{}'", nonce).unwrap(); + sources.push(buf.clone()); + } sources.extend(hashes); } }