canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
//! Internal JSON helpers.
//!
//! This module provides minimal JSON string escaping used by sinks
//! that serialize events without a full JSON library.

/// Escapes a string for safe inclusion in a JSON string literal.
///
/// Handles `"`, `\`, and control characters below `0x20`.
pub(crate) fn json_escape(input: &str) -> String {
    use core::fmt::Write as _;

    let mut output = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            ch if (ch as u32) < 0x20 => {
                let _ = write!(output, "\\u{:04x}", ch as u32);
            }
            ch => output.push(ch),
        }
    }
    output
}

#[cfg(test)]
mod tests {
    use super::json_escape;

    #[test]
    fn escapes_quotes_and_backslashes() {
        assert_eq!(json_escape(r#"he said "hi""#), r#"he said \"hi\""#);
        assert_eq!(json_escape(r"back\slash"), r"back\\slash");
    }

    #[test]
    fn escapes_control_characters() {
        assert_eq!(json_escape("line\nnew"), "line\\nnew");
        assert_eq!(json_escape("tab\there"), "tab\\there");
        assert_eq!(json_escape("cr\rhere"), "cr\\rhere");
    }

    #[test]
    fn escapes_other_control_as_unicode() {
        assert_eq!(json_escape("\x01"), "\\u0001");
        assert_eq!(json_escape("\x1f"), "\\u001f");
    }

    #[test]
    fn leaves_normal_text_unchanged() {
        assert_eq!(json_escape("hello world 123"), "hello world 123");
    }

    #[test]
    fn empty_string() {
        assert_eq!(json_escape(""), "");
    }
}