#![cfg(any(
feature = "storage",
feature = "wire",
feature = "descriptive",
feature = "json",
feature = "value"
))]
use crate::alloc::{Allocator, String, Vec};
use core::fmt;
#[cfg(not(feature = "simdutf8"))]
#[doc(inline)]
pub use core::str::from_utf8;
#[derive(Debug)]
#[non_exhaustive]
pub struct Utf8Error;
impl core::error::Error for Utf8Error {}
impl fmt::Display for Utf8Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid or incomplete utf-8 sequence")
}
}
#[inline]
#[cfg(not(feature = "simdutf8"))]
pub fn from_utf8_owned<A>(bytes: Vec<u8, A>) -> Result<String<A>, Utf8Error>
where
A: Allocator,
{
match String::from_utf8(bytes) {
Ok(string) => Ok(string),
Err(..) => Err(Utf8Error),
}
}
#[inline]
#[cfg(feature = "simdutf8")]
pub fn from_utf8_owned<A>(bytes: Vec<u8, A>) -> Result<String<A>, Utf8Error>
where
A: Allocator,
{
if simdutf8::basic::from_utf8(&bytes).is_err() {
return Err(Utf8Error);
}
Ok(unsafe { String::from_utf8_unchecked(bytes) })
}
#[inline]
#[cfg(feature = "simdutf8")]
pub fn from_utf8(input: &[u8]) -> Result<&str, Utf8Error> {
simdutf8::basic::from_utf8(input).map_err(|_| Utf8Error)
}