use crate::json::DecodeError;
mod from_impl;
use core::str;
use std::borrow::Cow;
#[derive(Clone)]
pub struct Ctx<'a> {
pub(crate) input: &'a [u8],
pub(crate) error: Option<Cow<'a, str>>,
}
impl<'a> Ctx<'a> {
pub fn new(input: &'a str) -> Self {
Self {
input: input.as_bytes(),
error: None,
}
}
pub fn as_bytes(&self) -> &'a [u8] {
self.input
}
#[inline]
pub fn as_str(&self) -> &'a str {
unsafe { str::from_utf8_unchecked(self.input) }
}
pub fn static_error(&mut self, err: &'static str) {
if self.error.is_none() {
self.error = Some(Cow::Borrowed(err));
}
}
pub fn current_error(&self) -> Option<&str> {
self.error.as_deref()
}
pub fn try_extend_lifetime(&self, text: &str) -> Option<&'a str> {
if self.input.as_ptr_range().contains(&text.as_ptr()) {
Some(unsafe { &*(text as *const str) })
} else {
None
}
}
}
pub trait FromText<'a>: Sized {
fn from_text(ctx: &mut Ctx<'a>, text: &str) -> Result<Self, &'static DecodeError>;
}