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`.
7#[inline]
8pub fn is_valid_utf8(data: &[u8]) -> bool {
9 std::str::from_utf8(data).is_ok()
10}
11
12/// Converts a byte slice to a UTF-8 string or provides a fallback message.
13///
14/// - `body`: The byte slice to convert.
15/// - Returns: A `Cow<'_, str>` containing the UTF-8 string if valid,
16/// otherwise an owned string indicating the binary data length.
17#[inline]
18pub fn body_to_string(body: &[u8]) -> Cow<'_, str> {
19 match std::str::from_utf8(body) {
20 Ok(string_data) => Cow::Borrowed(string_data),
21 Err(_) => Cow::Owned(format!("binary data len: {}", body.len())),
22 }
23}