use crate::convert::FromJsonSlice;
use crate::error::Error;
use crate::path::try_parse_path;
use crate::typed_doc::{JsonDoc, TypedDocRef};
use crate::view::JsonView;
use crate::view_list::{ValueList, ViewList};
use crate::map_view::MapView;
#[derive(Clone, Copy, Debug)]
pub struct NestedView<'a> {
bytes: &'a [u8],
}
impl<'a> NestedView<'a> {
#[inline]
pub fn from_span(bytes: &'a [u8]) -> Self {
Self { bytes }
}
pub fn from_doc(doc: &'a impl JsonDoc, path: &str) -> Result<Self, Error> {
let segs = try_parse_path(path)?;
let slice = doc.get_raw_path(&segs)?;
Ok(Self::from_span(slice))
}
#[inline]
pub fn as_bytes(&self) -> &'a [u8] {
self.bytes
}
#[inline]
pub fn as_doc(&self) -> TypedDocRef<'a> {
TypedDocRef::from_slice(self.bytes)
}
#[inline]
pub fn view<T: JsonView>(&self) -> Result<T, Error> {
T::read_from(self.bytes)
}
#[inline]
pub fn get<T: FromJsonSlice>(&self, path: &str) -> Result<T, Error> {
self.as_doc().get(path)
}
#[inline]
pub fn get_raw(&self, path: &str) -> Result<&'a [u8], Error> {
let segs = try_parse_path(path)?;
crate::scan::find_value(self.bytes, &segs)
}
pub fn nest(&self, path: &str) -> Result<NestedView<'a>, Error> {
Ok(NestedView::from_span(self.get_raw(path)?))
}
pub fn view_list<T: JsonView>(&self, path: &str) -> Result<ViewList<'a, T>, Error> {
ViewList::from_array_bytes(self.get_raw(path)?)
}
pub fn value_list<T: FromJsonSlice>(&self, path: &str) -> Result<ValueList<'a, T>, Error> {
ValueList::from_array_bytes(self.get_raw(path)?)
}
pub fn map<T: FromJsonSlice>(&self, path: &str) -> Result<MapView<'a, T>, Error> {
MapView::from_object_bytes(self.get_raw(path)?)
}
pub fn as_map<T: FromJsonSlice>(&self) -> Result<MapView<'a, T>, Error> {
MapView::from_object_bytes(self.bytes)
}
pub fn as_view_list<T: JsonView>(&self) -> Result<ViewList<'a, T>, Error> {
ViewList::from_array_bytes(self.bytes)
}
pub fn as_value_list<T: FromJsonSlice>(&self) -> Result<ValueList<'a, T>, Error> {
ValueList::from_array_bytes(self.bytes)
}
}
impl<'a> JsonDoc for NestedView<'a> {
#[inline]
fn as_json_bytes(&self) -> &[u8] {
self.bytes
}
}
impl<'a> From<TypedDocRef<'a>> for NestedView<'a> {
#[inline]
fn from(d: TypedDocRef<'a>) -> Self {
Self::from_span(d.as_bytes())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::typed_doc::TypedDoc;
#[test]
fn nest_user_tags() {
let doc = TypedDoc::from_slice(br#"{"user":{"id":7,"tags":["a","b"]}}"#);
let user = NestedView::from_doc(&doc, "user").unwrap();
assert_eq!(user.get::<u64>("id").unwrap(), 7);
assert_eq!(
user.value_list::<String>("tags")
.unwrap()
.collect_owned()
.unwrap(),
vec!["a".to_string(), "b".to_string()]
);
let deeper = user.nest("tags").unwrap();
assert_eq!(deeper.as_value_list::<String>().unwrap().get(1).unwrap(), "b");
}
}