http_type/utils/utf8.rs
1use crate::*;
2
3/// Checks if the given byte slice is valid UTF-8.
4///
5/// - `data`: The byte slice to validate.
6/// - Returns: `true` if the byte slice is valid UTF-8, otherwise `false`.
7pub fn is_valid_utf8(data: &[u8]) -> bool {
8 std::str::from_utf8(data).is_ok()
9}
10
11/// Converts a byte slice to a UTF-8 string or provides a fallback message.
12///
13/// - `body`: The byte slice to convert.
14/// - Returns: A `Cow<'_, str>` containing the UTF-8 string if valid,
15/// otherwise an owned string indicating the binary data length.
16pub fn body_to_string(body: &[u8]) -> Cow<'_, str> {
17 match std::str::from_utf8(body) {
18 Ok(string_data) => Cow::Borrowed(string_data),
19 Err(_) => Cow::Owned(format!("binary data len: {}", body.len())),
20 }
21}