use std::borrow::Cow;
use super::{Kind, Miss, Node, Record, Typed, Walk};
#[derive(Debug, Clone, Copy)]
pub struct Line<'a> {
text: &'a [u8],
name: &'a str,
}
impl<'a> Line<'a> {
#[must_use]
pub const fn new(text: &'a [u8]) -> Self {
Self::named(text, "message")
}
#[must_use]
pub const fn named(text: &'a [u8], name: &'a str) -> Self {
Self { text, name }
}
}
impl<'a> Record<'a> for Line<'a> {
type At = ();
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<(), Miss> {
match path.split_first() {
Some((first, rest)) if first.as_ref() == self.name => self.find_below((), rest),
_ => Err(Miss::MissingRoot),
}
}
fn find_below<K: AsRef<str>>(self, (): (), path: &[K]) -> Result<(), Miss> {
if path.is_empty() {
Ok(())
} else {
Err(Miss::WrongParentType)
}
}
fn typed(self, (): ()) -> Result<Typed<'a>, Miss> {
self.text(()).map(Typed::Str)
}
fn text(self, (): ()) -> Result<Cow<'a, str>, Miss> {
std::str::from_utf8(self.text)
.map(Cow::Borrowed)
.map_err(|_| Miss::Malformed)
}
}
impl<'a> Walk<'a> for Line<'a> {
fn walk<F: FnMut(Node<'a, ()>)>(self, mut visit: F) -> Result<(), Miss> {
visit(Node {
depth: 0,
key: Some(Cow::Borrowed(self.name)),
kind: Kind::Str,
at: (),
});
Ok(())
}
fn bytes(self, (): ()) -> Result<Cow<'a, [u8]>, Miss> {
Ok(Cow::Borrowed(self.text))
}
}