use crate::error::Error;
use crate::index::IndexedDocument;
use crate::project::{project, ProjectPlan};
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be used as a nested jshift JSON field",
label = "`JsonView` is not implemented for `{Self}`",
note = "serde users: nested structs need `#[derive(JsonView)]` on the nested type (like `Deserialize`). \
Wire shape is `{{\"field\": {{...}} }}`. For flatten into the parent object use `#[json(flatten)]`. \
For a custom scalar newtype implementing `FromJsonSlice`, mark the field `#[json(from_slice)]`. \
Built-in scalars (`String`, integers, `bool`, …) and `HashMap`/`BTreeMap<String, V>` are not nested views."
)]
pub trait JsonView: Sized {
fn read_from(json: &[u8]) -> Result<Self, Error>;
fn read_from_indexed(json: &[u8]) -> Result<Self, Error> {
Self::read_from(json)
}
fn read_from_doc(doc: &IndexedDocument<'_>) -> Result<Self, Error> {
Self::read_from(doc.as_bytes())
}
fn write_into(&self, json: &mut Vec<u8>) -> Result<(), Error>;
fn project_plan() -> ProjectPlan {
ProjectPlan::from_paths(&[]).unwrap_or_else(|_| ProjectPlan::identity())
}
fn project_bytes(json: &[u8]) -> Result<Vec<u8>, Error> {
project(json, &Self::project_plan())
}
fn to_schema_bytes(&self) -> Result<Vec<u8>, Error> {
let mut buf = Vec::with_capacity(64);
buf.extend_from_slice(br#"{"#);
buf.push(b'}');
self.write_into(&mut buf)?;
Self::project_bytes(&buf)
}
fn to_schema_doc(&self) -> Result<crate::typed_doc::TypedDoc, Error> {
Ok(crate::typed_doc::TypedDoc::from_vec(self.to_schema_bytes()?))
}
}
#[inline]
pub fn build_schema_bytes<T: JsonView>(view: &T) -> Result<Vec<u8>, Error> {
view.to_schema_bytes()
}
pub fn project_view_each<T, F>(json: &[u8], array_path: &str, mut f: F) -> Result<(), Error>
where
T: JsonView,
F: FnMut(T) -> Result<(), Error>,
{
use crate::view_list::ViewList;
let doc = crate::typed_doc::TypedDocRef::from_slice(json);
let list = ViewList::<T>::from_doc(&doc, array_path)?;
list.each(|v| f(v))
}
#[inline]
pub fn project_view_collect<T: JsonView>(json: &[u8], array_path: &str) -> Result<Vec<T>, Error> {
let mut out = Vec::new();
project_view_each(json, array_path, |v| {
out.push(v);
Ok(())
})?;
Ok(out)
}
#[inline]
pub fn read_view<T: JsonView>(json: &[u8]) -> Result<T, Error> {
T::read_from(json)
}
#[inline]
pub fn read_view_at<T: JsonView>(
json: &[u8],
path: &[crate::path::PathSegment],
) -> Result<T, Error> {
let slice = crate::scan::find_value(json, path)?;
T::read_from(slice)
}
pub fn read_view_at_opt<T: JsonView>(
json: &[u8],
path: &[crate::path::PathSegment],
) -> Result<Option<T>, Error> {
match crate::scan::find_value(json, path) {
Ok(slice) => {
if is_json_null(slice) {
return Ok(None);
}
Ok(Some(T::read_from(slice)?))
}
Err(Error::PathNotFound) => Ok(None),
Err(e) => Err(e),
}
}
pub fn write_view_at<T: JsonView>(
json: &mut Vec<u8>,
path: &[crate::path::PathSegment],
view: &T,
) -> Result<(), Error> {
write_view_at_open(json, path, view)
}
#[inline]
pub fn write_view_at_opt<T: JsonView>(
json: &mut Vec<u8>,
path: &[crate::path::PathSegment],
view: Option<&T>,
) -> Result<(), Error> {
if let Some(v) = view {
write_view_at_open(json, path, v)?;
}
Ok(())
}
pub fn write_view_at_open<T: JsonView>(
json: &mut Vec<u8>,
path: &[crate::path::PathSegment],
view: &T,
) -> Result<(), Error> {
use crate::mutate::upsert_at_path;
use crate::scan::{find_value_offsets, skip_whitespace};
if find_value_offsets(json, path).is_err() {
upsert_at_path(json, path, b"{}")?;
}
let (start, end) = find_value_offsets(json, path)?;
let s = skip_whitespace(&json[start..end], 0);
let mut nested = if s < (end - start) && json[start + s] == b'{' {
json[start..end].to_vec()
} else {
b"{}".to_vec()
};
view.write_into(&mut nested)?;
json.splice(start..end, nested);
Ok(())
}
#[inline]
pub fn write_view_at_closed<T: JsonView>(
json: &mut Vec<u8>,
path: &[crate::path::PathSegment],
view: &T,
) -> Result<(), Error> {
let bytes = view.to_schema_bytes()?;
crate::mutate::upsert_at_path(json, path, &bytes)
}
#[inline]
pub fn write_view_at_closed_opt<T: JsonView>(
json: &mut Vec<u8>,
path: &[crate::path::PathSegment],
view: Option<&T>,
) -> Result<(), Error> {
if let Some(v) = view {
write_view_at_closed(json, path, v)?;
}
Ok(())
}
#[inline]
fn is_json_null(slice: &[u8]) -> bool {
use crate::scan::skip_whitespace;
let s = skip_whitespace(slice, 0);
let mut e = slice.len();
while e > s && matches!(slice[e - 1], b' ' | b'\t' | b'\n' | b'\r') {
e -= 1;
}
&slice[s..e] == b"null"
}
#[inline]
pub fn from_jshift_bytes<T: JsonView>(json: &[u8]) -> Result<T, Error> {
T::read_from(json)
}
#[inline]
pub fn project_as_view<T: JsonView>(json: &[u8]) -> Result<T, Error> {
let thin = T::project_bytes(json)?;
T::read_from(&thin)
}
#[inline]
pub fn write_view<T: JsonView>(view: &T, json: &mut Vec<u8>) -> Result<(), Error> {
view.write_into(json)
}