jshift 0.7.0

Schema-guided typed JSON on raw bytes: path get/mutate, open views, project — without a Value tree.
Documentation
//! Optional **serde** bridge for gradual migration (feature `serde`).
//!
//! Frameworks and APIs that still demand `Deserialize` / `Serialize` can wrap a
//! [`JsonView`] in [`AsJshiftView`]. The app type stays a jshift view; serde only
//! carries the **raw JSON text** across the boundary.
//!
//! **Full guide** (long essay: why the bridge exists, best practices, benches,
//! serde vs jshift examples): [`crate::serde_bridge_guide`].
//!
//! # How it works
//!
//! | Direction | Mechanism |
//! | --- | --- |
//! | Deserialize | Borrowed [`serde_json::value::RawValue`] (`&RawValue`) when the deserializer allows it — **zero-copy** for `from_str` / `from_slice`; then [`JsonView::read_from`] path-decodes (no `Value` tree). |
//! | Serialize | [`JsonView::to_schema_bytes`] → `String::from_utf8` reuses the buffer → `RawValue` so the serializer emits raw JSON. |
//!
//! Prefer **native** jshift (`JsonView::read_from`, [`crate::JshiftJson`] with feature
//! `axum`) when you control the stack. Use this bridge when a third party still
//! requires serde traits.
//!
//! # Borrowing vs owned deserializers
//!
//! | Entry point | [`AsJshiftView`] (`&RawValue`) | Notes |
//! | --- | --- | --- |
//! | `serde_json::from_str` | **Zero-copy** raw text | Prefer this / `from_slice` |
//! | `serde_json::from_slice` | **Zero-copy** raw text | Same |
//! | `serde_json::from_reader` | **Not supported** by `&RawValue` | Buffer first, then `from_slice` / [`from_slice_view`], or use [`AsJshiftViewOwned`] |
//! | `serde_json::from_value` | Prefer [`from_value`] helper | Avoids fighting `Value`’s owned tree |
//!
//! # Example
//!
//! ```
//! # #[cfg(all(feature = "serde", feature = "derive"))]
//! # {
//! use jshift::{AsJshiftView, JsonView};
//!
//! #[derive(JsonView)]
//! struct Card {
//!     #[json(path = "id")]
//!     id: u64,
//! }
//!
//! let raw = r#"{"id":7,"noise":true}"#;
//! let v: AsJshiftView<Card> = serde_json::from_str(raw).unwrap();
//! assert_eq!(v.id, 7);
//! // Schema emit drops noise:
//! let out = serde_json::to_string(&v).unwrap();
//! assert!(out.contains(r#""id":7"#));
//! assert!(!out.contains("noise"));
//! # }
//! ```
//!
//! # Boundary helpers
//!
//! [`from_value`] / [`to_value`] convert at the edge of code that still holds a
//! `serde_json::Value`. They serialize/parse **text** once — fine for config and
//! tests; avoid on hot multi‑MB paths (prefer bytes end-to-end).

use std::fmt;
use std::ops::{Deref, DerefMut};

use crate::error::Error;
use crate::view::JsonView;
use serde::de::Error as DeError;
use serde::ser::Error as SerError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::value::RawValue;

/// Newtype: serde ↔ [`JsonView`] via raw JSON text (not a `Value` tree).
///
/// # Ergonomics
///
/// * Public field `0` for pattern matching / construction.
/// * [`Deref`] / [`DerefMut`] to `T` so `view.id` works without `.0`.
/// * [`From<T>`] / [`into_inner`](Self::into_inner) for explicit wrapping.
///
/// # Performance
///
/// * **Deserialize** uses **`&'de RawValue`**: for `serde_json::from_str` /
///   `from_slice`, the JSON text is **not copied** into a `Box`; jshift only
///   path-scans those bytes. See module docs for `from_reader` / owned paths.
/// * **Serialize** reuses the schema-byte `Vec` as a `String` (`from_utf8`) before
///   handing it to `RawValue` (one buffer, no extra UTF-8 copy of the content).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AsJshiftView<T>(pub T);

impl<T> AsJshiftView<T> {
    /// Wrap a view value.
    #[inline]
    pub const fn new(value: T) -> Self {
        Self(value)
    }

    /// Unwrap into the inner [`JsonView`] value.
    #[inline]
    pub fn into_inner(self) -> T {
        self.0
    }

    /// Borrow the inner value.
    #[inline]
    pub fn get(&self) -> &T {
        &self.0
    }

    /// Mutably borrow the inner value.
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.0
    }

    /// Decode from a [`RawValue`] (borrowed or behind `Box` via `raw.get()`).
    ///
    /// Useful when you already hold a `RawValue` from another API without going
    /// through [`Deserialize`] again.
    #[inline]
    pub fn from_raw_value(raw: &RawValue) -> Result<Self, Error>
    where
        T: JsonView,
    {
        Ok(Self(T::read_from(raw.get().as_bytes())?))
    }
}

impl<T> From<T> for AsJshiftView<T> {
    #[inline]
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T> Deref for AsJshiftView<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for AsJshiftView<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T: fmt::Display> fmt::Display for AsJshiftView<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<'de, T: JsonView> Deserialize<'de> for AsJshiftView<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Borrowed form: zero-copy when the deserializer is from_str / from_slice
        // (serde_json buffers the input and RawValue points into it).
        // Does not work for from_reader — use AsJshiftViewOwned or buffer + from_slice.
        let raw = <&'de RawValue>::deserialize(deserializer)?;
        let t = T::read_from(raw.get().as_bytes()).map_err(|e| D::Error::custom(e.to_string()))?;
        Ok(AsJshiftView(t))
    }
}

impl<T: JsonView> Serialize for AsJshiftView<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serialize_view(&self.0, serializer)
    }
}

fn serialize_view<T: JsonView, S: Serializer>(view: &T, serializer: S) -> Result<S::Ok, S::Error> {
    let bytes = view
        .to_schema_bytes()
        .map_err(|e| S::Error::custom(e.to_string()))?;
    // Reuse allocation: Vec<u8> → String without re-copying UTF-8 payload.
    let s = String::from_utf8(bytes).map_err(|e| S::Error::custom(e.to_string()))?;
    let raw = RawValue::from_string(s).map_err(|e| S::Error::custom(e.to_string()))?;
    raw.serialize(serializer)
}

/// Like [`AsJshiftView`], but deserializes via **`Box<RawValue>`** (owned buffer).
///
/// Use when the deserializer cannot borrow (`serde_json::from_reader`, some
/// adapters). Prefer [`AsJshiftView`] for `from_str` / `from_slice` (zero-copy raw).
///
/// Serialize path matches [`AsJshiftView`] (schema bytes → raw JSON).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AsJshiftViewOwned<T>(pub T);

impl<T> AsJshiftViewOwned<T> {
    #[inline]
    pub const fn new(value: T) -> Self {
        Self(value)
    }

    #[inline]
    pub fn into_inner(self) -> T {
        self.0
    }

    #[inline]
    pub fn into_borrowed(self) -> AsJshiftView<T> {
        AsJshiftView(self.0)
    }
}

impl<T> From<T> for AsJshiftViewOwned<T> {
    #[inline]
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T> From<AsJshiftView<T>> for AsJshiftViewOwned<T> {
    #[inline]
    fn from(value: AsJshiftView<T>) -> Self {
        Self(value.0)
    }
}

impl<T> Deref for AsJshiftViewOwned<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for AsJshiftViewOwned<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'de, T: JsonView> Deserialize<'de> for AsJshiftViewOwned<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = Box::<RawValue>::deserialize(deserializer)?;
        let t = T::read_from(raw.get().as_bytes()).map_err(|e| D::Error::custom(e.to_string()))?;
        Ok(AsJshiftViewOwned(t))
    }
}

impl<T: JsonView> Serialize for AsJshiftViewOwned<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serialize_view(&self.0, serializer)
    }
}

/// Boundary: `serde_json::Value` → `T: JsonView` (text intermediate).
///
/// Prefer [`JsonView::read_from`] on original bytes when you still have them.
/// Prefer this over `serde_json::from_value::<AsJshiftView<T>>` (borrowed
/// `RawValue` cannot attach to an owned `Value` tree).
pub fn from_value<T: JsonView>(value: &serde_json::Value) -> Result<T, Error> {
    let bytes = serde_json::to_vec(value).map_err(|_| Error::InvalidJsonSyntax {
        pos: 0,
        msg: "serde_json failed to serialize Value for jshift",
    })?;
    T::read_from(&bytes)
}

/// Boundary: `T: JsonView` → `serde_json::Value` via schema bytes.
///
/// Use only at edges (APIs that still return `Value`). Schema emit is closed
/// (named fields only) — open unknowns from an original buffer are not preserved.
pub fn to_value<T: JsonView>(view: &T) -> Result<serde_json::Value, Error> {
    let bytes = view.to_schema_bytes()?;
    serde_json::from_slice(&bytes).map_err(|_| Error::InvalidJsonSyntax {
        pos: 0,
        msg: "serde_json failed to parse jshift schema bytes",
    })
}

/// Decode `T` from a JSON text string (direct jshift; no serde intermediate).
///
/// Prefer this over `serde_json::from_str::<AsJshiftView<T>>` when you do not
/// need the `Deserialize` trait — same path scan, one less layer.
#[inline]
pub fn from_str_view<T: JsonView>(s: &str) -> Result<T, Error> {
    T::read_from(s.as_bytes())
}

/// Decode `T` from JSON bytes (direct jshift; no serde).
#[inline]
pub fn from_slice_view<T: JsonView>(json: &[u8]) -> Result<T, Error> {
    T::read_from(json)
}

/// Decode `T` from a [`RawValue`] (works for borrowed or boxed).
#[inline]
pub fn from_raw_value<T: JsonView>(raw: &RawValue) -> Result<T, Error> {
    T::read_from(raw.get().as_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{find_value, parse_path, upsert_at_path, FromJsonSlice, ToJsonBytes};

    struct IdOnly {
        id: u64,
    }

    impl JsonView for IdOnly {
        fn read_from(json: &[u8]) -> Result<Self, Error> {
            let slice = find_value(json, &parse_path("id"))?;
            Ok(Self {
                id: u64::from_json_slice(slice).ok_or(Error::TypeMismatch {
                    expected: "u64",
                    found: "bad",
                })?,
            })
        }
        fn write_into(&self, json: &mut Vec<u8>) -> Result<(), Error> {
            upsert_at_path(json, &parse_path("id"), &self.id.to_json_bytes())
        }
        fn project_plan() -> crate::ProjectPlan {
            crate::ProjectPlan::from_paths(&["id"]).unwrap()
        }
    }

    #[test]
    fn as_jshift_view_roundtrip_json() {
        let raw = r#"{"id":7,"noise":true}"#;
        let v: AsJshiftView<IdOnly> = serde_json::from_str(raw).unwrap();
        assert_eq!(v.id, 7); // Deref
        let out = serde_json::to_string(&v).unwrap();
        assert!(out.contains("\"id\":7"));
        assert!(!out.contains("noise"));
    }

    #[test]
    fn from_str_and_slice_use_borrowed_raw() {
        let raw = r#"{"id":7,"noise":true}"#;
        let v: AsJshiftView<IdOnly> = serde_json::from_str(raw).unwrap();
        assert_eq!(v.id, 7);

        let v2: AsJshiftView<IdOnly> = serde_json::from_slice(raw.as_bytes()).unwrap();
        assert_eq!(v2.id, 7);

        // Explicit RawValue borrow path (same as Deserialize internals).
        let rv: &RawValue = serde_json::from_str(raw).unwrap();
        // Pointer into `raw` — proves RawValue did not own a separate buffer.
        let rv_addr = rv.get().as_ptr() as usize;
        let start = raw.as_ptr() as usize;
        let end = start + raw.len();
        assert!(
            rv_addr >= start && rv_addr < end,
            "RawValue text should borrow from input string"
        );
        let v3 = AsJshiftView::<IdOnly>::from_raw_value(rv).unwrap();
        assert_eq!(v3.id, 7);
    }

    #[test]
    fn owned_form_from_reader_path() {
        use std::io::Cursor;
        let raw = br#"{"id":42,"x":1}"#;
        let cur = Cursor::new(raw);
        // from_reader cannot produce &RawValue; AsJshiftViewOwned uses Box.
        let v: AsJshiftViewOwned<IdOnly> = serde_json::from_reader(cur).unwrap();
        assert_eq!(v.id, 42);
        assert_eq!(v.into_borrowed().id, 42);
    }

    #[test]
    fn from_to_value_boundary() {
        let val = serde_json::json!({"id": 3, "x": 1});
        let t: IdOnly = from_value(&val).unwrap();
        assert_eq!(t.id, 3);
        let back = to_value(&t).unwrap();
        assert_eq!(back["id"], 3);
        assert!(back.get("x").is_none());
    }

    #[test]
    fn from_slice_view_direct() {
        let t = from_slice_view::<IdOnly>(br#"{"id":11}"#).unwrap();
        assert_eq!(t.id, 11);
    }

    #[test]
    fn into_inner_and_from() {
        let v = AsJshiftView::from(IdOnly { id: 1 });
        assert_eq!(v.into_inner().id, 1);
    }
}