use super::super::{Memory, MemoryError, OwnedVec, TextErrorKind, Work};
pub(in super::super) struct ValidatedText<W: Work = Memory> {
bytes: OwnedVec<u8, W>,
}
impl<W: Work> ValidatedText<W> {
pub(in super::super) fn from_utf8(
bytes: OwnedVec<u8, W>,
) -> Result<Self, (TextErrorKind, OwnedVec<u8, W>)> {
if let Err(cause) = bytes
.values
.allocator()
.work()
.charge_work(bytes.len() as u64)
{
return Err((TextErrorKind::Resource(cause), bytes));
}
if let Err(cause) = core::str::from_utf8(&bytes) {
return Err((TextErrorKind::Utf8(cause), bytes));
}
Ok(Self { bytes })
}
pub(in super::super) fn from_str(text: &str, execution: &W) -> Result<Self, MemoryError> {
let mut bytes = execution.vector();
bytes.try_extend_from_slice(text.as_bytes())?;
Ok(Self { bytes })
}
pub(in super::super) fn bytes(&self) -> &OwnedVec<u8, W> {
&self.bytes
}
pub(in super::super) fn try_push_str(&mut self, suffix: &str) -> Result<(), MemoryError> {
self.bytes.try_extend_from_slice(suffix.as_bytes())
}
pub(in super::super) fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), MemoryError> {
self.bytes.try_reserve_exact(additional)
}
pub(in super::super) fn as_str(&self) -> &str {
unsafe { core::str::from_utf8_unchecked(&self.bytes) }
}
pub(in super::super) fn into_owned(self) -> ValidatedText {
ValidatedText {
bytes: self.bytes.into_owned(),
}
}
pub(in super::super) fn into_bytes(self) -> OwnedVec<u8, W> {
self.bytes
}
}