diff --git a/.jules/bolt.md b/.jules/bolt.md index 362f27c6..fa98a9d6 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -38,3 +38,6 @@ ## 2024-11-20 - Avoid `format!` inside loops for hex string encoding **Learning:** Using `.iter().map(|b| format!("{:02x}", b)).collect::()` to encode a byte array to a hex string incurs a heavy performance penalty because it allocates a new temporary `String` for every single byte processed before concatenating them. The `hex::encode()` function from the `hex` crate performs this conversion directly into a single pre-allocated `String` with zero intermediate allocations. **Action:** Always prefer `hex::encode(bytes)` over iterative `format!` mapping when performing hexadecimal encoding of byte arrays or slices to eliminate intermediate string allocations and significantly boost performance. +## 2026-09-24 - Zero-allocation hex decoding +**Learning:** Using `hex::decode` from the `hex` crate provides a significant performance boost over manually iterating through strings and calling `u8::from_str_radix`, even though `hex::decode` allocates a new `Vec`. It avoids the heavy intermediate allocations and processing overhead of manual string slice iterations. +**Action:** Always prefer `hex::decode` and `hex::encode` when working with hexadecimal encoding/decoding instead of manual iterative string parsing to significantly boost performance. diff --git a/stdlib/src/crypto.rs b/stdlib/src/crypto.rs index 54a9cd19..42210544 100644 --- a/stdlib/src/crypto.rs +++ b/stdlib/src/crypto.rs @@ -78,22 +78,16 @@ impl StdlibRegistry { let hex_ciphertext = args[1].try_into_string()?; // Decode hex string - let mut ciphertext = Vec::new(); - for i in (0..hex_ciphertext.len()).step_by(2) { - if i + 2 <= hex_ciphertext.len() { - if let Ok(byte) = u8::from_str_radix(&hex_ciphertext[i..i + 2], 16) { - ciphertext.push(byte); - } else { - return Err(RuntimeError::new( - RuntimeErrorKind::InvalidOperation( - "Invalid hex ciphertext".to_string(), - ), - None, - None, - )); - } - } - } + // ⚡ Bolt Performance Optimization: Replaced manual hex decoding with hex::decode for zero-allocation decoding. + let ciphertext = hex::decode(&hex_ciphertext).map_err(|_| { + RuntimeError::new( + RuntimeErrorKind::InvalidOperation( + "Invalid hex ciphertext".to_string(), + ), + None, + None, + ) + })?; let mut hasher = sha2::Sha256::new(); hasher.update(key_str.as_bytes());