facet-json 0.46.1

JSON serialization for facet using the new format architecture
Documentation
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Note: unsafe code is used for lifetime transmutes in from_slice_into/from_str_into
// when BORROW=false, mirroring the approach used in facet-format's FormatDeserializer.

//! JSON parser and serializer using facet-format.
//!
//! This crate provides JSON support via the `FormatParser` trait.

extern crate alloc;

/// Trace-level logging macro that forwards to `tracing::trace!` when the `tracing` feature is enabled.
#[cfg(feature = "tracing")]
#[allow(unused_macros)]
macro_rules! trace {
    ($($arg:tt)*) => {
        ::tracing::trace!($($arg)*)
    };
}

/// Trace-level logging macro (no-op when `tracing` feature is disabled).
#[cfg(not(feature = "tracing"))]
#[allow(unused_macros)]
macro_rules! trace {
    ($($arg:tt)*) => {};
}

/// Debug-level logging macro that forwards to `tracing::debug!` when the `tracing` feature is enabled.
#[cfg(feature = "tracing")]
#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:tt)*) => {
        ::tracing::debug!($($arg)*)
    };
}

/// Debug-level logging macro (no-op when `tracing` feature is disabled).
#[cfg(not(feature = "tracing"))]
#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:tt)*) => {};
}

#[allow(unused_imports)]
pub(crate) use debug;
use facet_reflect::Partial;
#[allow(unused_imports)]
pub(crate) use trace;

mod error;
mod parser;
mod raw_json;
mod scanner;
mod serializer;

#[cfg(feature = "axum")]
mod axum;

#[cfg(feature = "axum")]
pub use axum::{Json, JsonRejection};

pub use error::JsonError;
pub use parser::JsonParser;
pub use raw_json::RawJson;
pub use serializer::{
    BytesFormat, HexBytesOptions, JsonSerializeError, JsonSerializer, SerializeOptions,
    peek_to_string, peek_to_string_pretty, peek_to_string_with_options, peek_to_writer_std,
    peek_to_writer_std_pretty, peek_to_writer_std_with_options, to_string, to_string_pretty,
    to_string_with_options, to_vec, to_vec_pretty, to_vec_with_options, to_writer_std,
    to_writer_std_pretty, to_writer_std_with_options,
};

// Re-export DeserializeError for convenience
pub use facet_format::DeserializeError;

/// Deserialize a value from a JSON string into an owned type.
///
/// This is the recommended default for most use cases. The input does not need
/// to outlive the result, making it suitable for deserializing from temporary
/// buffers (e.g., HTTP request bodies).
///
/// Types containing `&str` fields cannot be deserialized with this function;
/// use `String` or `Cow<str>` instead. For zero-copy deserialization into
/// borrowed types, use [`from_str_borrowed`].
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_str;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
///
/// let json = r#"{"name": "Alice", "age": 30}"#;
/// let person: Person = from_str(json).unwrap();
/// assert_eq!(person.name, "Alice");
/// assert_eq!(person.age, 30);
/// ```
pub fn from_str<T>(input: &str) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'static>,
{
    use facet_format::FormatDeserializer;
    // TRUSTED_UTF8 = true: input came from &str, so it's valid UTF-8
    let mut parser = JsonParser::<true>::new(input.as_bytes());
    let mut de = FormatDeserializer::new_owned(&mut parser);
    de.deserialize_root()
}

/// Deserialize a value from JSON bytes into an owned type.
///
/// This is the recommended default for most use cases. The input does not need
/// to outlive the result, making it suitable for deserializing from temporary
/// buffers (e.g., HTTP request bodies).
///
/// Types containing `&str` fields cannot be deserialized with this function;
/// use `String` or `Cow<str>` instead. For zero-copy deserialization into
/// borrowed types, use [`from_slice_borrowed`].
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_slice;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// let json = br#"{"x": 10, "y": 20}"#;
/// let point: Point = from_slice(json).unwrap();
/// assert_eq!(point.x, 10);
/// assert_eq!(point.y, 20);
/// ```
pub fn from_slice<T>(input: &[u8]) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'static>,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<false>::new(input);
    let mut de = FormatDeserializer::new_owned(&mut parser);
    de.deserialize_root()
}

/// Deserialize a value from a JSON string, allowing zero-copy borrowing.
///
/// This variant requires the input to outlive the result (`'input: 'facet`),
/// enabling zero-copy deserialization of string fields as `&str` or `Cow<str>`.
///
/// Use this when you need maximum performance and can guarantee the input
/// buffer outlives the deserialized value. For most use cases, prefer
/// [`from_str`] which doesn't have lifetime requirements.
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_str_borrowed;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Person<'a> {
///     name: &'a str,
///     age: u32,
/// }
///
/// let json = r#"{"name": "Alice", "age": 30}"#;
/// let person: Person = from_str_borrowed(json).unwrap();
/// assert_eq!(person.name, "Alice");
/// assert_eq!(person.age, 30);
/// ```
pub fn from_str_borrowed<'input, 'facet, T>(input: &'input str) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'facet>,
    'input: 'facet,
{
    use facet_format::FormatDeserializer;
    // TRUSTED_UTF8 = true: input came from &str, so it's valid UTF-8
    let mut parser = JsonParser::<true>::new(input.as_bytes());
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_root()
}

/// Deserialize a value from JSON bytes, allowing zero-copy borrowing.
///
/// This variant requires the input to outlive the result (`'input: 'facet`),
/// enabling zero-copy deserialization of string fields as `&str` or `Cow<str>`.
///
/// Use this when you need maximum performance and can guarantee the input
/// buffer outlives the deserialized value. For most use cases, prefer
/// [`from_slice`] which doesn't have lifetime requirements.
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_slice_borrowed;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Point<'a> {
///     label: &'a str,
///     x: i32,
///     y: i32,
/// }
///
/// let json = br#"{"label": "origin", "x": 0, "y": 0}"#;
/// let point: Point = from_slice_borrowed(json).unwrap();
/// assert_eq!(point.label, "origin");
/// ```
pub fn from_slice_borrowed<'input, 'facet, T>(input: &'input [u8]) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'facet>,
    'input: 'facet,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<false>::new(input);
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_root()
}

/// Deserialize JSON from a string into an existing Partial.
///
/// This is useful for reflection-based deserialization where you don't have
/// a concrete type `T` at compile time, only its Shape metadata. The Partial
/// must already be allocated for the target type.
///
/// This version produces owned strings (no borrowing from input).
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_str_into;
/// use facet_reflect::Partial;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
///
/// let json = r#"{"name": "Alice", "age": 30}"#;
/// let partial = Partial::alloc_owned::<Person>().unwrap();
/// let partial = from_str_into(json, partial).unwrap();
/// let value = partial.build().unwrap();
/// let person: Person = value.materialize().unwrap();
/// assert_eq!(person.name, "Alice");
/// assert_eq!(person.age, 30);
/// ```
pub fn from_str_into<'facet>(
    input: &str,
    partial: Partial<'facet, false>,
) -> Result<Partial<'facet, false>, DeserializeError> {
    use facet_format::{FormatDeserializer, MetaSource};
    // TRUSTED_UTF8 = true: input came from &str, so it's valid UTF-8
    let mut parser = JsonParser::<true>::new(input.as_bytes());
    let mut de = FormatDeserializer::new_owned(&mut parser);

    // SAFETY: The deserializer expects Partial<'input, false> where 'input is the
    // lifetime of the JSON bytes. Since BORROW=false, no data is borrowed from the
    // input, so the actual 'facet lifetime of the Partial is independent of 'input.
    // We transmute to satisfy the type system, then transmute back after deserialization.
    #[allow(unsafe_code)]
    let partial: Partial<'_, false> =
        unsafe { core::mem::transmute::<Partial<'facet, false>, Partial<'_, false>>(partial) };

    let partial = de.deserialize_into(partial, MetaSource::FromEvents)?;

    // SAFETY: Same reasoning - no borrowed data since BORROW=false.
    #[allow(unsafe_code)]
    let partial: Partial<'facet, false> =
        unsafe { core::mem::transmute::<Partial<'_, false>, Partial<'facet, false>>(partial) };

    Ok(partial)
}

/// Deserialize JSON from bytes into an existing Partial.
///
/// This is useful for reflection-based deserialization where you don't have
/// a concrete type `T` at compile time, only its Shape metadata. The Partial
/// must already be allocated for the target type.
///
/// This version produces owned strings (no borrowing from input).
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_slice_into;
/// use facet_reflect::Partial;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// let json = br#"{"x": 10, "y": 20}"#;
/// let partial = Partial::alloc_owned::<Point>().unwrap();
/// let partial = from_slice_into(json, partial).unwrap();
/// let value = partial.build().unwrap();
/// let point: Point = value.materialize().unwrap();
/// assert_eq!(point.x, 10);
/// assert_eq!(point.y, 20);
/// ```
pub fn from_slice_into<'facet>(
    input: &[u8],
    partial: Partial<'facet, false>,
) -> Result<Partial<'facet, false>, DeserializeError> {
    use facet_format::{FormatDeserializer, MetaSource};
    let mut parser = JsonParser::<false>::new(input);
    let mut de = FormatDeserializer::new_owned(&mut parser);

    // SAFETY: The deserializer expects Partial<'input, false> where 'input is the
    // lifetime of the JSON bytes. Since BORROW=false, no data is borrowed from the
    // input, so the actual 'facet lifetime of the Partial is independent of 'input.
    // We transmute to satisfy the type system, then transmute back after deserialization.
    #[allow(unsafe_code)]
    let partial: Partial<'_, false> =
        unsafe { core::mem::transmute::<Partial<'facet, false>, Partial<'_, false>>(partial) };

    let partial = de.deserialize_into(partial, MetaSource::FromEvents)?;

    // SAFETY: Same reasoning - no borrowed data since BORROW=false.
    #[allow(unsafe_code)]
    let partial: Partial<'facet, false> =
        unsafe { core::mem::transmute::<Partial<'_, false>, Partial<'facet, false>>(partial) };

    Ok(partial)
}

/// Deserialize JSON from a string into an existing Partial, allowing zero-copy borrowing.
///
/// This variant requires the input to outlive the Partial's lifetime (`'input: 'facet`),
/// enabling zero-copy deserialization of string fields as `&str` or `Cow<str>`.
///
/// This is useful for reflection-based deserialization where you don't have
/// a concrete type `T` at compile time, only its Shape metadata.
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_str_into_borrowed;
/// use facet_reflect::Partial;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Person<'a> {
///     name: &'a str,
///     age: u32,
/// }
///
/// let json = r#"{"name": "Alice", "age": 30}"#;
/// let partial = Partial::alloc::<Person>().unwrap();
/// let partial = from_str_into_borrowed(json, partial).unwrap();
/// let value = partial.build().unwrap();
/// let person: Person = value.materialize().unwrap();
/// assert_eq!(person.name, "Alice");
/// assert_eq!(person.age, 30);
/// ```
pub fn from_str_into_borrowed<'input, 'facet>(
    input: &'input str,
    partial: Partial<'facet, true>,
) -> Result<Partial<'facet, true>, DeserializeError>
where
    'input: 'facet,
{
    use facet_format::{FormatDeserializer, MetaSource};
    // TRUSTED_UTF8 = true: input came from &str, so it's valid UTF-8
    let mut parser = JsonParser::<true>::new(input.as_bytes());
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_into(partial, MetaSource::FromEvents)
}

/// Deserialize a JSONC string (JSON with `//` and `/* */` comments) into an owned type.
///
/// Identical to [`from_str`] except that comments are allowed anywhere whitespace
/// is allowed. Trailing commas are also accepted (they work in the plain JSON
/// parser too).
pub fn from_str_jsonc<T>(input: &str) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'static>,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<true>::new_jsonc(input.as_bytes());
    let mut de = FormatDeserializer::new_owned(&mut parser);
    de.deserialize_root()
}

/// Deserialize a JSONC byte slice (JSON with `//` and `/* */` comments) into an owned type.
///
/// Identical to [`from_slice`] except that comments are allowed anywhere whitespace
/// is allowed.
pub fn from_slice_jsonc<T>(input: &[u8]) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'static>,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<false>::new_jsonc(input);
    let mut de = FormatDeserializer::new_owned(&mut parser);
    de.deserialize_root()
}

/// Deserialize a JSONC string, allowing zero-copy borrowing.
///
/// Identical to [`from_str_borrowed`] except that comments are allowed.
pub fn from_str_borrowed_jsonc<'input, 'facet, T>(input: &'input str) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'facet>,
    'input: 'facet,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<true>::new_jsonc(input.as_bytes());
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_root()
}

/// Deserialize a JSONC byte slice, allowing zero-copy borrowing.
///
/// Identical to [`from_slice_borrowed`] except that comments are allowed.
pub fn from_slice_borrowed_jsonc<'input, 'facet, T>(
    input: &'input [u8],
) -> Result<T, DeserializeError>
where
    T: facet_core::Facet<'facet>,
    'input: 'facet,
{
    use facet_format::FormatDeserializer;
    let mut parser = JsonParser::<false>::new_jsonc(input);
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_root()
}

/// Deserialize JSON from bytes into an existing Partial, allowing zero-copy borrowing.
///
/// This variant requires the input to outlive the Partial's lifetime (`'input: 'facet`),
/// enabling zero-copy deserialization of string fields as `&str` or `Cow<str>`.
///
/// This is useful for reflection-based deserialization where you don't have
/// a concrete type `T` at compile time, only its Shape metadata.
///
/// # Example
///
/// ```
/// use facet::Facet;
/// use facet_json::from_slice_into_borrowed;
/// use facet_reflect::Partial;
///
/// #[derive(Facet, Debug, PartialEq)]
/// struct Point<'a> {
///     label: &'a str,
///     x: i32,
///     y: i32,
/// }
///
/// let json = br#"{"label": "origin", "x": 0, "y": 0}"#;
/// let partial = Partial::alloc::<Point>().unwrap();
/// let partial = from_slice_into_borrowed(json, partial).unwrap();
/// let value = partial.build().unwrap();
/// let point: Point = value.materialize().unwrap();
/// assert_eq!(point.label, "origin");
/// ```
pub fn from_slice_into_borrowed<'input, 'facet>(
    input: &'input [u8],
    partial: Partial<'facet, true>,
) -> Result<Partial<'facet, true>, DeserializeError>
where
    'input: 'facet,
{
    use facet_format::{FormatDeserializer, MetaSource};
    let mut parser = JsonParser::<false>::new(input);
    let mut de = FormatDeserializer::new(&mut parser);
    de.deserialize_into(partial, MetaSource::FromEvents)
}