1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! # Serde bridge guide
//!
//! How jshift talks to the **serde** ecosystem without making `serde_json::Value`
//! the spine of your app.
//!
//! Enable:
//!
//! ```toml
//! jshift = { version = "0.7", features = ["derive", "serde"] }
//! ```
//!
//! Related APIs: [`AsJshiftView`](crate::AsJshiftView)(crate::AsJshiftView),
//! [`AsJshiftViewOwned`](crate::AsJshiftViewOwned)(crate::AsJshiftViewOwned),
//! [`JsonView`](crate::JsonView)(crate::JsonView),
//! [`from_value`](crate::from_value)(crate::from_value) / [`to_value`](crate::to_value)(crate::to_value),
//! [`from_str_view`](crate::from_str_view)(crate::from_str_view) / [`from_slice_view`](crate::from_slice_view)(crate::from_slice_view),
//! [`from_raw_value`](crate::from_raw_value)(crate::from_raw_value).
//!
//! //! ---
//!
//! # Why this exists
//!
//! **serde** is the multi-format framework for Rust (JSON, YAML, bincode, …).
//! **serde_json** is the default *JSON* implementation: it builds a typed Rust value
//! (or a full `Value` tree) by walking every token.
//!
//! **jshift** is JSON-only and **byte-level**: schema-guided path reads, open
//! in-place mutate, project/stream — without requiring a `Value` tree for
//! correctness.
//!
//! Teams still hit walls:
//!
//! 1. A framework or library **requires** `T: Deserialize` / `Serialize`.
//! 2. A migration is gradual — half the code is still `serde_json::Value`.
//! 3. Config/tests use `json!` / `Value` at the edge only.
//!
//! The bridge is **not** “reimplement serde.” It is a **boundary adapter**:
//!
//! | Layer | Role |
//! | --- | --- |
//! | serde traits | Satisfy the ecosystem |
//! | `RawValue` text | Carry JSON without a domain `Value` |
//! | [`JsonView::read_from`](crate::JsonView::read_from) / [`JsonView::to_schema_bytes`](crate::JsonView::to_schema_bytes) | Actual app logic on bytes |
//!
//! So you can migrate call sites to jshift views while remaining pluggable into
//! serde-only APIs.
//!
//! ---
//!
//! # The traits (what we implement and why)
//!
//! ## What you already have: `JsonView`
//!
//! jshift’s product trait is **[`JsonView`](crate::JsonView)**, not `Deserialize`:
//!
//! ```rust,ignore
//! pub trait JsonView: Sized {
//! fn read_from(json: &[u8]) -> Result<Self, Error>;
//! fn write_into(&self, json: &mut Vec<u8>) -> Result<(), Error>;
//! fn to_schema_bytes(&self) -> Result<Vec<u8>, Error> { /* default */ }
//! fn project_plan() -> ProjectPlan { /* default */ }
//! // ...
//! }
//! ```
//!
//! | serde / serde_json idea | jshift analogue |
//! | --- | --- |
//! | `Deserialize` full document | [`JsonView::read_from`](crate::JsonView::read_from) (path-selective / open) |
//! | `Serialize` full document | [`to_schema_bytes`](crate::JsonView::to_schema_bytes) (closed card) or open [`write_into`](crate::JsonView::write_into) |
//! | `Value` | Prefer raw `&[u8]` / [`TypedDoc`](crate::TypedDoc); [`RawJson`](crate::RawJson) / maps for dyn pockets |
//! | `#[serde(flatten)]` | `#[json(flatten)]` |
//! | Nested struct | Nested [`JsonView`](crate::JsonView) field (auto) |
//!
//! We did **not** implement `Deserialize`/`Serialize` **on your types directly** by
//! default: that would force a full token walk for every field and blur open vs
//! closed semantics. The adapter types below implement the serde traits instead.
//!
//! ## `AsJshiftView<T>` — zero-copy raw when possible
//!
//! ```rust,ignore
//! pub struct AsJshiftView<T>(pub T);
//! // Deserialize via &'de RawValue → JsonView::read_from
//! // Serialize via to_schema_bytes → RawValue
//! ```
//!
//! | Direction | Mechanism |
//! | --- | --- |
//! | **In** | serde delivers the JSON fragment as text (`&RawValue`); jshift path-scans it |
//! | **Out** | jshift emits schema JSON; serde writes it as raw JSON (not a string-escaped blob) |
//!
//! **Zero-copy (raw text):** `serde_json::from_str` and `from_slice` deserialize
//! `&RawValue` that **borrows** the input buffer — no extra `Box` copy of the JSON
//! text before jshift scans it.
//!
//! **Not zero-copy:** `from_reader` cannot produce `&RawValue` (serde_json requires
//! `Box<RawValue>`). Use [`AsJshiftViewOwned`](crate::AsJshiftViewOwned) or buffer the body and `from_slice`.
//!
//! ## `AsJshiftViewOwned<T>` — owned raw
//!
//! ```rust,ignore
//! pub struct AsJshiftViewOwned<T>(pub T);
//! // Deserialize via Box<RawValue>
//! ```
//!
//! Same jshift decode after the raw text is buffered. Use for streams/readers.
//!
//! ## Boundary helpers
//!
//! | Helper | Use |
//! | --- | --- |
//! | [`from_value`](crate::from_value)`(&Value) -> T` | Edge only: still holding a `Value` |
//! | [`to_value`](crate::to_value)`(&T) -> Value` | Edge only: API returns `Value` |
//! | [`from_str_view`](crate::from_str_view) / [`from_slice_view`](crate::from_slice_view) | Direct jshift (no serde) when you don’t need the trait |
//! | [`from_raw_value`](crate::from_raw_value)`(&RawValue) -> T` | You already have a `RawValue` |
//!
//! [`from_value`](crate::from_value) re-serializes `Value` to text then path-scans — fine for config, not
//! for multi‑MB hot paths.
//!
//! ---
//!
//! # Best practices
//!
//! ## 1. Prefer native jshift when you own the stack
//!
//! ```rust,ignore
//! // Best: no serde in the hot path
//! let card = Card::read_from(body)?;
//! // axum feature: JshiftJson / JshiftDoc
//! ```
//!
//! Use the bridge only at **framework boundaries**.
//!
//! ## 2. Choose the right adapter
//!
//! | Situation | Use |
//! | --- | --- |
//! | `from_str` / `from_slice` / most HTTP frameworks that buffer the body | [`AsJshiftView<T>`](crate::AsJshiftView) |
//! | `from_reader` / streaming deserializer | [`AsJshiftViewOwned<T>`](crate::AsJshiftViewOwned) or read-to-`Vec` then `from_slice` |
//! | You already have `serde_json::Value` | [`from_value`](crate::from_value) / [`to_value`](crate::to_value) |
//! | You control both sides | Drop the bridge; call [`JsonView`](crate::JsonView) directly |
//!
//! ## 3. Know open vs closed on the way out
//!
//! | Encode | Result |
//! | --- | --- |
//! | `Serialize` for [`AsJshiftView`](crate::AsJshiftView) / [`to_schema_bytes`](crate::JsonView::to_schema_bytes) | **Closed card** — only schema fields |
//! | Open [`write_into`](crate::JsonView::write_into) on an original buffer (e.g. axum [`JshiftJson`](crate::JshiftJson) with retained body) | **Unknowns preserved** |
//!
//! Do not expect `serde_json::to_string(&AsJshiftView(view))` to round-trip open
//! unknowns; that path is schema emit by design.
//!
//! ## 4. Sparse views on fat JSON
//!
//! Define partial views (only the fields you need). That is the performance win
//! versus full `Deserialize` of a fat struct or `Value`.
//!
//! ## 5. Measure honestly
//!
//! - Tiny pure objects: serde is already excellent; bridge has a small tax.
//! - Fat objects + sparse fields: jshift wins large.
//! - Prefer **ratios** over absolute ns; re-run benches on your machine.
//!
//! ```bash
//! cargo run --release --example v07_ecosystem_bench --features "derive,serde"
//! cargo run --release --example flatten_bench --features "derive,serde"
//! cargo run --release --example flatten_50mb_bench --features "derive,serde"
//! ```
//!
//! ---
//!
//! # Serde vs jshift: side-by-side examples
//!
//! ## A. Decode a few fields from a fat object
//!
//! **serde** (full typed model or `Value`):
//!
//! ```rust,ignore
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Card {
//! id: u64,
//! title: String,
//! // every other field still paid for if present on a fat struct,
//! // or use Value and index:
//! }
//!
//! // Full deserialize of everything you named + token walk of the whole document
//! let card: Card = serde_json::from_slice(bytes)?;
//!
//! // Or:
//! let v: serde_json::Value = serde_json::from_slice(bytes)?;
//! let id = v["id"].as_u64().unwrap();
//! ```
//!
//! **jshift** (sparse view on bytes):
//!
//! ```rust,ignore
//! use jshift::JsonView;
//!
//! #[derive(JsonView)]
//! struct Card {
//! #[json(path = "id")]
//! id: u64,
//! #[json(path = "title")]
//! title: String,
//! }
//!
//! let card = Card::read_from(bytes)?;
//! // Unknown keys never allocated
//! ```
//!
//! **Via serde trait boundary:**
//!
//! ```rust,ignore
//! use jshift::{AsJshiftView, JsonView};
//!
//! let card: AsJshiftView<Card> = serde_json::from_slice(bytes)?;
//! let card = card.into_inner();
//! // or: let card: Card = jshift::from_slice_view(bytes)?;
//! ```
//!
//! ## B. Nested object + map + flatten
//!
//! **serde:**
//!
//! ```rust,ignore
//! use serde::{Deserialize, Serialize};
//! use std::collections::HashMap;
//!
//! #[derive(Deserialize, Serialize)]
//! struct Meta {
//! rank: u64,
//! sku: String,
//! }
//!
//! #[derive(Deserialize, Serialize)]
//! struct Event {
//! id: u64,
//! meta: Meta, // nested object
//! #[serde(flatten)]
//! extra: HashMap<String, String>, // or flatten a second struct
//! }
//! ```
//!
//! **jshift:**
//!
//! ```rust,ignore
//! use jshift::JsonView;
//! use std::collections::HashMap;
//!
//! #[derive(JsonView)]
//! struct Meta {
//! #[json(path = "rank")]
//! rank: u64,
//! #[json(path = "sku")]
//! sku: String,
//! }
//!
//! #[derive(JsonView)]
//! struct Tags {
//! #[json(path = "env")]
//! env: String,
//! }
//!
//! #[derive(JsonView)]
//! struct Event {
//! #[json(path = "id")]
//! id: u64,
//! #[json(path = "meta")]
//! meta: Meta, // nested → {"meta":{...}}
//! #[json(path = "scores")]
//! scores: HashMap<String, u64>,
//! #[json(flatten)]
//! tags: Tags, // spread env into parent object
//! }
//! ```
//!
//! ## C. Open mutate one field, keep the rest of the body
//!
//! **serde (typical):**
//!
//! ```rust,ignore
//! let mut v: serde_json::Value = serde_json::from_slice(bytes)?;
//! v["status"] = "accepted".into();
//! let out = serde_json::to_vec(&v)?; // full re-serialize
//! ```
//!
//! **jshift:**
//!
//! ```rust,ignore
//! use jshift::{JsonDoc, TypedDoc};
//!
//! let mut doc = TypedDoc::from_vec(bytes.to_vec());
//! doc.mutate().set("status", "accepted")?;
//! let out = doc.into_bytes(); // same buffer, unknowns preserved
//! ```
//!
//! **With a view + open write:**
//!
//! ```rust,ignore
//! let mut buf = bytes.to_vec();
//! let mut card = Card::read_from(&buf)?;
//! card.title = "new".into();
//! card.write_into(&mut buf)?; // upserts schema paths only
//! ```
//!
//! ## D. Plug into a serde-only API
//!
//! **serde-native type:**
//!
//! ```rust,ignore
//! fn publish<T: Serialize>(t: &T) { /* ... */ }
//!
//! #[derive(Serialize)]
//! struct Card { id: u64, title: String }
//!
//! publish(&card);
//! ```
//!
//! **jshift view behind the bridge:**
//!
//! ```rust,ignore
//! use jshift::{AsJshiftView, JsonView};
//!
//! #[derive(JsonView)]
//! struct Card {
//! #[json(path = "id")]
//! id: u64,
//! #[json(path = "title")]
//! title: String,
//! }
//!
//! let card = Card { id: 1, title: "x".into() };
//! publish(&AsJshiftView(card)); // Serialize via schema bytes
//! ```
//!
//! ## E. `from_reader` / owned path
//!
//! ```rust,ignore
//! use jshift::AsJshiftViewOwned;
//! use std::io::Read;
//!
//! // serde_json::from_reader cannot yield &RawValue
//! let v: AsJshiftViewOwned<Card> = serde_json::from_reader(reader)?;
//! let card = v.into_inner();
//!
//! // Or skip the bridge:
//! let mut buf = Vec::new();
//! reader.read_to_end(&mut buf)?;
//! let card = Card::read_from(&buf)?;
//! ```
//!
//! ---
//!
//! # Benchmarks (jshift vs serde-native)
//!
//! Numbers below are **release** timings on a typical developer Linux machine from
//! the 0.7 examples. Prefer **serde/jshift ratios** over absolute times. Re-run:
//!
//! ```bash
//! cargo run --release --example v07_ecosystem_bench --features "derive,serde"
//! cargo run --release --example flatten_bench --features "derive,serde"
//! cargo run --release --example flatten_50mb_bench --features "derive,serde"
//! cargo run --release --example typed_doc_bench
//! ```
//!
//! ## Sparse card / bridge tax (`v07_ecosystem_bench`)
//!
//! | Workload | jshift | serde | serde/jshift |
//! | --- | ---: | ---: | ---: |
//! | Sparse Card on fat object (id+title) | **~141 ns** | ~378 ns | **~2.7×** |
//! | …vs full fat struct deserialize | **~141 ns** | ~741 ns | **~5.3×** |
//! | …vs `Value` + index | **~141 ns** | ~1.5 µs | **~10×** |
//! | `AsJshiftView` sparse via `from_str` | ~448 ns | ~378 ns | **~0.8×** *(bridge tax)* |
//! | Schema emit 2-field card | ~85 ns | ~76 ns | **~0.9×** |
//! | Unit enum decode | ~36 ns | ~38 ns | **~1.1×** |
//!
//! **Reading this:** native jshift sparse decode beats full serde deserialize on fat
//! objects. Wrapping through [`AsJshiftView`](crate::AsJshiftView) + `from_str` pays a **RawValue boundary**
//! (~0.8× vs pure serde sparse struct on small fat cards) — still far cheaper than
//! full `Value` when the document is huge and the view is thin. Prefer native
//! [`read_from`](crate::JsonView::read_from) when you do not need `Deserialize`.
//!
//! ## Flatten (`flatten_bench`)
//!
//! | Workload | jshift | serde | serde/jshift |
//! | --- | ---: | ---: | ---: |
//! | Decode small Event (id + flatten meta) | ~560 ns | ~560 ns | **~1.0×** |
//! | Decode fat (+256 noise keys) | **~560 ns** | ~29 µs | **~51×** |
//! | Open mutate `source` on fat | **~1.1 µs** | ~10 µs | **~9×** |
//! | Encode Event card | ~530 ns | ~140 ns | **~0.3×** *(serde wins)* |
//!
//! ## Flatten on ~50 MiB (`flatten_50mb_bench`)
//!
//! Schema keys first, then ~50 MiB of noise strings.
//!
//! | Workload | jshift | serde | serde/jshift |
//! | --- | ---: | ---: | ---: |
//! | Decode Event (keys first) | **~0.5–1 µs** | ~32 ms | **~30 000–60 000×** |
//! | In-place open `write_into` | **~1 µs** | ~32 ms | **~30 000×** |
//! | Project thin card vs serde roundtrip | **~1.5 µs** | ~18 ms | **~12 000×** |
//! | Encode card only | ~330 ns | ~100 ns | **~0.3×** *(serde wins)* |
//!
//! ## When to use which
//!
//! | You care about… | Prefer |
//! | --- | --- |
//! | Tiny pure JSON, full typed model | **serde** (or jshift near parity) |
//! | Fat JSON, few fields, open patch | **jshift** native |
//! | Must implement `Deserialize`/`Serialize` | **[`AsJshiftView`](crate::AsJshiftView)** / **[`AsJshiftViewOwned`](crate::AsJshiftViewOwned)** at the boundary |
//! | Multi-format (YAML, bincode, …) | **serde** (jshift is JSON-only) |
//! | Closed emit of a small card | Either; serde often slightly faster |
//!
//! ---
//!
//! # Mental model (one paragraph)
//!
//! **serde** asks: “turn this format into my Rust type graph.”
//! **jshift** asks: “which paths in these bytes matter, and can I patch/project without unpacking the rest?”
//! The **serde bridge** answers: “when the ecosystem still asks for serde traits, hand it raw JSON text and let jshift do the path work — without promoting `Value` to your domain type.”
//!
//! ---
//!
//! # See also
//!
//! - Crate README: TypedDoc, flatten tables, axum extractors
//! - Examples: `v07_ecosystem_bench`, `flatten_bench`, `flatten_50mb_bench`, `axum_jshift`
//! - Features: `serde`, `axum`, `derive`
//! - Item docs: [`AsJshiftView`](crate::AsJshiftView), [`AsJshiftViewOwned`](crate::AsJshiftViewOwned), [`JsonView`](crate::JsonView); with feature `axum`: [`JshiftJson`](crate::JshiftJson)
// Doc-only module: the guide lives entirely in the `//!` module docs above.
// This keeps a stable rustdoc URL (`jshift::serde_bridge_guide`) for linking.