rusty_common/websocket/utils.rs
1//! WebSocket utility functions
2//!
3//! Provides helper functions for WebSocket operations.
4
5use anyhow::{Result, anyhow};
6use smartstring::alias::String;
7
8// parse_json function removed - was using unsafe simd_json::from_str
9// Use parse_json_bytes instead for safe zero-copy parsing
10
11/// Safe JSON parsing from bytes with UTF-8 validation
12///
13/// This function validates UTF-8 before parsing to prevent undefined behavior
14/// when processing potentially untrusted byte data from WebSocket frames or HTTP responses.
15pub fn parse_json_bytes<T: serde::de::DeserializeOwned>(data: &mut [u8]) -> Result<T> {
16 // Validate UTF-8 first to prevent undefined behavior
17 let _utf8_check =
18 std::str::from_utf8(data).map_err(|e| anyhow!("Invalid UTF-8 in JSON data: {}", e))?;
19
20 // Now safe to use simd_json
21 simd_json::from_slice(data).map_err(|e| anyhow!("JSON parse error: {}", e))
22}
23
24/// Validate that bytes contain valid UTF-8 text
25pub fn validate_utf8(data: &[u8]) -> Result<&str> {
26 std::str::from_utf8(data).map_err(|e| anyhow!("Invalid UTF-8: {}", e))
27}
28
29/// Helper function to serialize data to JSON using simd_json
30pub fn to_json<T: serde::Serialize>(data: &T) -> Result<String> {
31 simd_json::to_string(data)
32 .map(|s| String::from(&s))
33 .map_err(|e| anyhow!("JSON serialization error: {}", e))
34}