| // SPF Smart Gateway - UTF-8 Safety Utilities | |
| // Copyright 2026 Joseph Stone - All Rights Reserved | |
| // | |
| // Three failure modes addressed here: | |
| // A. read_to_string() on binary files → CRASH (Err propagated) | |
| // B. from_utf8_lossy() on binary data → SILENT CORRUPTION (? replaces bytes) | |
| // C. &s[..n] byte-offset slice → PANIC (mid-multibyte boundary) | |
| // | |
| // Usage: | |
| // read_file_safe() → replaces std::fs::read_to_string (Mode A) | |
| // binary_info() → formats fingerprint for MCP text response | |
| // process_output_safe() → replaces from_utf8_lossy on process stdout/stderr (Mode B) | |
| // encode_for_lmdb() → replaces from_utf8_lossy before LMDB storage (Mode B) | |
| // safe_truncate() → replaces &s[..n] byte slices (Mode C) | |
| use sha2::{Digest, Sha256}; | |
| // ─── Mode A: Binary-safe file reading ──────────────────────────────────────── | |
| /// Read a file and detect whether it is valid UTF-8 text or binary. | |
| /// | |
| /// Returns: | |
| /// Ok(Ok(String)) — valid UTF-8 text content | |
| /// Ok(Err((bytes, sha256))) — binary content: raw bytes + hex SHA-256 | |
| /// Err(io::Error) — file could not be read | |
| pub fn read_file_safe( | |
| path: &std::path::Path, | |
| ) -> std::io::Result<Result<String, (Vec<u8>, String)>> { | |
| let bytes = std::fs::read(path)?; | |
| match String::from_utf8(bytes.clone()) { | |
| Ok(text) => Ok(Ok(text)), | |
| Err(_) => { | |
| let sha = sha256_hex(&bytes); | |
| Ok(Err((bytes, sha))) | |
| } | |
| } | |
| } | |
| /// Format binary file info for an MCP text response. | |
| /// Shows byte count + first 16 hex chars of SHA-256. | |
| pub fn binary_info(bytes: &[u8]) -> String { | |
| let sha = sha256_hex(bytes); | |
| format!("[Binary file: {} bytes | SHA-256: {}…]", bytes.len(), &sha[..16]) | |
| } | |
| // ─── Mode B: Binary-safe process output ────────────────────────────────────── | |
| /// Convert process stdout/stderr bytes to a String safely. | |
| /// | |
| /// Valid UTF-8 → returned as-is (zero-copy if possible). | |
| /// Binary output → "[Binary output: N bytes | hex: ...]" | |
| pub fn process_output_safe(bytes: &[u8]) -> String { | |
| match std::str::from_utf8(bytes) { | |
| Ok(s) => s.to_string(), | |
| Err(_) => { | |
| let preview_len = bytes.len().min(32); | |
| format!( | |
| "[Binary output: {} bytes | hex: {}…]", | |
| bytes.len(), | |
| hex::encode(&bytes[..preview_len]) | |
| ) | |
| } | |
| } | |
| } | |
| /// Encode content for LMDB state storage. | |
| /// | |
| /// Valid UTF-8 text → stored as-is. | |
| /// Binary data → "__HEX__:<hex-encoded>" (fully reversible, no data loss). | |
| pub fn encode_for_lmdb(data: &[u8]) -> String { | |
| match std::str::from_utf8(data) { | |
| Ok(s) => s.to_string(), | |
| Err(_) => format!("__HEX__:{}", hex::encode(data)), | |
| } | |
| } | |
| // ─── Mode C: Safe string truncation ────────────────────────────────────────── | |
| /// Truncate a UTF-8 string at a safe character boundary. | |
| /// | |
| /// `&s[..n]` panics if `n` falls inside a multi-byte sequence. | |
| /// This function walks backward from `max_bytes` to the nearest valid boundary. | |
| /// Never panics. Returns the original string if shorter than `max_bytes`. | |
| pub fn safe_truncate(s: &str, max_bytes: usize) -> &str { | |
| if s.len() <= max_bytes { | |
| return s; | |
| } | |
| let mut cut = max_bytes; | |
| while !s.is_char_boundary(cut) { | |
| cut -= 1; | |
| } | |
| &s[..cut] | |
| } | |
| // ─── Internal ───────────────────────────────────────────────────────────────── | |
| fn sha256_hex(data: &[u8]) -> String { | |
| let mut h = Sha256::new(); | |
| h.update(data); | |
| hex::encode(h.finalize()) | |
| } | |