use crate::BeBytesError;
#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned, string::String};
#[doc(hidden)]
pub trait StringInterpreter {
fn from_bytes(bytes: &[u8]) -> Result<String, BeBytesError>;
fn to_bytes(s: &str) -> &[u8];
}
#[doc(hidden)]
pub struct Utf8;
impl StringInterpreter for Utf8 {
fn from_bytes(bytes: &[u8]) -> Result<String, BeBytesError> {
core::str::from_utf8(bytes)
.map(str::to_owned)
.map_err(|_| BeBytesError::InvalidUtf8 { field: "string" })
}
fn to_bytes(s: &str) -> &[u8] {
s.as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_utf8_valid() {
let bytes = b"Hello, world!";
let result = Utf8::from_bytes(bytes);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "Hello, world!");
}
#[test]
fn test_utf8_invalid() {
let bytes = &[0xFF, 0xFE, 0xFD]; let result = Utf8::from_bytes(bytes);
assert!(result.is_err());
}
#[test]
fn test_utf8_to_bytes() {
let s = "Hello, world!";
let bytes = Utf8::to_bytes(s);
assert_eq!(bytes, b"Hello, world!");
}
}