File size: 3,976 Bytes
1269259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// 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())
}