use serde_json::Value;
pub fn detect_data_type(data_str: &str) -> &'static str {
if data_str
.chars()
.all(|c| !c.is_control() || c == '\n' || c == '\r' || c == '\t')
{
"text"
} else {
"binary"
}
}
pub fn data_to_string(data: &Value) -> String {
match data {
Value::String(s) => {
if detect_data_type(s) == "text" {
s.clone()
} else {
format!("HEX:{}", hex::encode(s.as_bytes()))
}
}
Value::Null => "null".to_string(),
_ => data.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_detect_data_type() {
assert_eq!(detect_data_type("Hello World"), "text");
assert_eq!(detect_data_type("HTTP/1.1 200 OK\r\n"), "text");
assert_eq!(detect_data_type("JSON: {\"key\": \"value\"}\n"), "text");
assert_eq!(detect_data_type("Line1\nLine2\tTabbed"), "text");
assert_eq!(detect_data_type("\x00\x01\x02binary"), "binary");
assert_eq!(detect_data_type("text\x00with\x01null"), "binary");
assert_eq!(detect_data_type("\x1b[31mANSI\x1b[0m"), "binary");
assert_eq!(detect_data_type(""), "text"); assert_eq!(detect_data_type("\r\n\t"), "text"); }
#[test]
fn test_data_to_string() {
let text_value = json!("Hello World");
assert_eq!(data_to_string(&text_value), "Hello World");
let binary_value = json!("\x00\x01\x02binary");
let result = data_to_string(&binary_value);
assert!(result.starts_with("HEX:"));
assert!(result.contains("000102"));
let null_value = json!(null);
assert_eq!(data_to_string(&null_value), "null");
let number_value = json!(42);
assert_eq!(data_to_string(&number_value), "42");
}
#[test]
fn test_edge_cases() {
assert_eq!(detect_data_type(""), "text");
assert_eq!(data_to_string(&json!("")), "");
assert_eq!(detect_data_type("\r\n\t"), "text");
assert_eq!(detect_data_type("\x00"), "binary");
assert_eq!(detect_data_type("Hello\x00World"), "binary");
assert_eq!(detect_data_type("Hello\nWorld"), "text");
}
}