jsony 0.1.10

An experimental fast compiling serialization and deserialization library for JSON like formats.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! # Jsony
//! An ergonomic and performant (at runtime & compile time) serialization framework
//! for the following formats:
//! - [JSON](json) (with optional extensions: trailing commas, comments, unquoted keys)
//! - [Custom Binary Encoding](crate::binary)
//!
//! ### Decoding/Encoding JSON with strongly typed data structures
//!
//! The Jsony derive macro can automatically implement the encoding and decoding
//! for a number of formats.
//! ```
//! use jsony::Jsony;
//!
//! #[derive(Jsony)]
//! #[jsony(Json)]
//! struct Player {
//!     name: String,
//!     health: u32,
//!     inventory: Vec<String>
//! }
//!
//! fn main() -> Result<(), jsony::JsonError> {
//!     let input: String = jsony::object!{
//!         name: "Jimmy",
//!         health: 100,
//!         inventory: [
//!             "Rock",
//!             "Helmet"
//!         ]
//!     };
//!
//!     let mut player: Player = jsony::from_json(&input)?;
//!     player.health -= 10;
//!
//!     let output: String = jsony::to_json(&player);
//!
//!     println!("generated json:\n {}", output);
//!
//!     Ok(())
//! }
//! ```
//! Here we choose to implement `ToJson` and `FromJson` automatically via the `Json` attribute.
//!
//! When deriving a format trait, all fields in the struct/enum need to implement the same
//! trait or have an implementation specified by a field attribute.
//!
//! #### Feature Documentation
//! - [Jsony derive macro](crate::Jsony): Declaratively specify how your Rust types map to various formats.
//! - [Flexible JSON decoder](crate::JsonParserConfig): Enable extensions for comments, trailing comments and more.
//! - [JSON template macros](crate::object): Flexibly generate a JSON string directly.
//! - [Binary format](crate::binary): Encode data in a fast, compact binary representation.
//! - [Lazy JSON Parsing](crate::drill): Dynamically parse only what you need.
//! - [Flexible encode destination](crate::to_json_into): Encode to a file or stack-allocating buffer.

#![allow(
    clippy::question_mark,
    reason = "? introduces extra code bloat slowing down compile times"
)]
#![allow(elided_lifetimes_in_paths)]
use std::ptr::NonNull;
#[doc(hidden)]
pub mod __internal;
pub mod binary;
mod byte_writer;
pub mod helper;
pub mod json;
mod lazy_parser;
pub mod parser;
mod rewriter;
mod strings;
pub mod text;
mod text_writer;
pub use rewriter::{PrettifyConfig, prettify};

mod third_party;

pub use byte_writer::BytesWriter;
use parser::JsonParentContext;
pub use text_writer::TextWriter;

/// Error definitions
pub mod error;

use binary::{Decoder, FromBinaryError};
use json::DecodeError;
use json::JsonValueKind;
use parser::Parser;

/// Templating macro for creating JSON Arrays
///
/// See [object] template macro for more details.
///
/// Works that sames `object!{}` except produces an array.
#[cfg(feature = "macros")]
pub use jsony_macros::array;

pub use byte_writer::IntoByteWriter;
#[cfg(feature = "macros")]
pub use jsony_macros::{Jsony, object};
pub use text_writer::IntoTextWriter;

/// A trait for parsing a value from a compact binary representation.
///
/// # Safety
///
/// This trait is safe to implement if you only override `decode_binary` and leave
/// other methods as default. However, setting `POD = true` requires additional
/// safety considerations.
///
/// # Usage
///
/// Given a decoder, `decode_binary` will attempt to decode `Self` from the prefix
/// of the decoder. This method always returns a value, even in case of an error.
/// When an error occurs, a default value is returned. This approach is primarily
/// an optimization but can also be used to extract partial values when parsing
/// as a whole has failed.
///
/// # Error Handling
///
/// Errors are stored in the decoder rather than being returned directly by
/// `decode_binary`.
///
/// # Plain Old Data (POD)
///
/// Setting `POD = true` indicates that this type can be directly memory-copied
/// from the input and maintains the same representation as if it was encoded
/// field-by-field in the binary decoder.
///
/// ## Requirements for `POD = true`:
/// - Every bit must be valid for the type and layout.
/// - There must be no padding between fields.
/// - Fields must be laid out in the same order as they are encoded and decoded
///   by `decode_binary`.
pub unsafe trait FromBinary<'a>: Sized {
    /// Indicates whether this type is Plain Old Data (POD).
    const POD: bool = false;

    /// Decodes `Self` from the given decoder.
    fn decode_binary(decoder: &mut Decoder<'a>) -> Self;

    /// Hidden method for endian transformation.
    ///
    /// This method is only defined for non-little-endian targets.
    #[doc(hidden)]
    #[cfg(not(target_endian = "little"))]
    fn endian_transform(&mut self) {}
}

/// A trait for converting a value to a compact binary representation.
///
/// This trait is used to append the binary encoding of a type to the end of a provided encoder.
/// For more details on the specific binary implementation, see the `binary` module.
///
/// # Safety
///
/// If you use the default implementation (i.e., `POD = false`), this trait is always safe to implement.
/// When `POD` is set to `true`, it indicates that this type can be directly memory-copied
/// to the output, maintaining the same representation as if it were encoded field-by-field.
///
/// ## Constraints for `POD = true`:
///
/// 1. Every bit pattern must be valid for the type and layout.
/// 2. There must be no padding between fields.
/// 3. Fields must be laid out in the same order as they would be encoded and decoded via the `encode_binary` function.
///
/// # Notes
///
/// - The `encode_binary` function should always write a value, even in error cases.
///   There is no error return;
pub unsafe trait ToBinary {
    /// Indicates whether the type is Plain Old Data (POD).
    ///
    /// When `true`, the type can be safely memory-copied.
    /// Default is `false`.
    const POD: bool = false;

    /// Encodes the type into its binary representation.
    ///
    /// This function should append the binary encoding of `self` to the provided `encoder`.
    fn encode_binary(&self, encoder: &mut BytesWriter);

    /// Hidden method for endian transformation.
    ///
    /// This method is only available on non-little-endian targets.
    #[doc(hidden)]
    #[cfg(not(target_endian = "little"))]
    fn endian_transform(&mut self) {}
}

/// A trait for types that can be parsed from JSON.
///
/// Either `emplace_for_json` or `decode_json` should be implemented.
///
/// # Safety
///
/// This trait is unsafe to implement. Implementors must ensure that the
/// `emplace_from_json` method properly initializes the memory at `dest`
/// when it returns `Ok(())`.
pub unsafe trait FromJson<'a>: Sized + 'a {
    /// Parses a JSON value and writes it directly to the given memory location.
    /// If Ok(()) is returned `dest` is guaranteed to be initialized
    ///
    /// # Safety
    ///
    /// dest, must be a pointer to Self although possilibly uninitialized
    /// and be valid for writes.
    ///
    /// If this method returns `Ok(())`, it must have properly initialized the
    /// memory at `dest` with a valid instance of `Self`. There is no such
    /// constraint if an error is returned.
    ///
    /// # Arguments
    ///
    /// * `dest` - A pointer to the memory where the parsed value should be written.
    /// * `parser` - The JSON parser to read from.
    #[inline]
    unsafe fn emplace_from_json(
        dest: NonNull<()>,
        parser: &mut Parser<'a>,
    ) -> Result<(), &'static DecodeError> {
        match Self::decode_json(parser) {
            Ok(value) => {
                // SAFETY: the caller of `emplace_from_json` guarantees `dest`
                // is valid writable storage for `Self`.
                unsafe {
                    dest.cast::<Self>().write(value);
                }
                Ok(())
            }
            Err(err) => Err(err),
        }
    }

    /// Decodes a JSON value from the parser.
    ///
    /// This method reads JSON data from the current position of the parser,
    /// ignoring anything after the parsed value. It may add error context
    /// to the parser on failure.
    ///
    /// # Arguments
    ///
    /// * `parser` - The JSON parser to read from.
    ///
    /// # Returns
    ///
    /// The parsed value if successful, or an error if parsing failed.
    #[inline]
    fn decode_json(parser: &mut Parser<'a>) -> Result<Self, &'static DecodeError> {
        let mut value = std::mem::MaybeUninit::<Self>::uninit();
        // SAFETY: `value.as_mut_ptr()` is non-null, correctly aligned storage
        // for `Self`. By the `FromJson` contract, `emplace_from_json`
        // initializes it exactly when it returns `Ok(())`.
        if let Err(err) = unsafe {
            Self::emplace_from_json(NonNull::new_unchecked(value.as_mut_ptr()).cast(), parser)
        } {
            Err(err)
        } else {
            // SAFETY: the successful `emplace_from_json` call initialized
            // `value` per the trait contract.
            Ok(unsafe { value.assume_init() })
        }
    }
}

mod __private {
    pub trait Sealed {}
}

/// A trait for converting a value into JSON.
pub trait ToJson {
    /// Represents the kind of JSON value that will be produced.
    ///
    /// This can be a string, object, array, or any value that could be
    /// one of those or a scalar (e.g., number).
    type Kind: JsonValueKind;

    /// Converts `self` to JSON and appends it to the given `TextWriter`.
    /// Note: this method is prefixed to avoid collisions in macros that
    /// that invoke it via method resolution.
    #[allow(non_snake_case)]
    fn encode_json__jsony(&self, output: &mut TextWriter) -> Self::Kind;
}

/// A validated JSON string slice.
#[repr(transparent)]
pub struct RawJson {
    pub(crate) raw: str,
}

impl RawJson {
    pub fn as_str(&self) -> &str {
        &self.raw
    }
}

impl RawJson {
    pub(crate) fn new_unchecked(raw: &str) -> &RawJson {
        if raw.is_empty() {
            // SAFETY: `RawJson` is `repr(transparent)` over `str`, and the
            // string literal is valid for the returned lifetime. The caller is
            // responsible for the semantic invariant that the text is JSON;
            // empty input is normalized to the valid JSON literal `null`.
            unsafe { &*("null" as *const str as *const RawJson) }
        } else {
            // SAFETY: `RawJson` is `repr(transparent)` over `str`, so a `str`
            // reference has the same layout. JSON validity is this unchecked
            // constructor's semantic precondition.
            unsafe { &*(raw as *const str as *const RawJson) }
        }
    }
    pub(crate) fn new_boxed_unchecked(raw: Box<str>) -> Box<RawJson> {
        if raw.is_empty() {
            Self::new_boxed_unchecked("null".into())
        } else {
            // SAFETY: `RawJson` is `repr(transparent)` over `str`, so the boxed
            // allocation layout and metadata are identical to `Box<str>`.
            // `Box::into_raw` transfers ownership and `Box::from_raw` rebuilds
            // it with the transparent wrapper type.
            unsafe { Box::from_raw(Box::into_raw(raw) as *mut RawJson) }
        }
    }
}

impl std::fmt::Debug for RawJson {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (**self).fmt(f)
    }
}

impl std::ops::Deref for RawJson {
    type Target = MaybeJson;

    fn deref(&self) -> &Self::Target {
        // SAFETY: both `RawJson` and `MaybeJson` are `repr(transparent)` over
        // `str`, so their reference layouts are identical.
        unsafe { &*(self as *const RawJson as *const MaybeJson) }
    }
}

/// Either a JSON string slice or an error state.
///
/// `MaybeJson` provides lazy JSON parsing capabilities through index operators, allowing you to
/// traverse JSON structures while deferring actual parsing until necessary. Conceptually, it's
/// similar to the following enum:
///
/// ```
/// # use jsony::json::DecodeError;
/// enum MaybeJsonEnum<'a> {
///    UnvalidatedJsonPrefix(&'a str),
///    DecodeError(&'static DecodeError),
///    ObjectKeyIndexError{ key: &'static str },
/// }
/// ```
///
/// See: [RawJson] which is similar to `MaybeJson` except is known to valid JSON.
///
/// The type implements index operators that allow traversal through JSON structures, automatically
/// handling error propagation during navigation.
///
/// ### Example
/// ```rust
/// # use jsony::MaybeJson;
/// let json = MaybeJson::new(r#"{"key": [{"inner": 42}]}"#);
/// assert_eq!(42, json["key"][0]["inner"].parse::<u32>().unwrap());
///
/// // When indexing with a `&'static str`, missing object keys are tracked
/// assert_eq!(json[&"key_typo"][0][&"inner"].key_error(), Some("key_typo"));
/// ```
#[repr(transparent)]
pub struct MaybeJson {
    /// The raw string to be parsed as a JSON value, possibly including leading whitespace.
    /// Empty strings are used to represent errors through pointer tagging.
    pub(crate) raw: str,
}

/// # Lazy JSON parser
///
/// Interpret the given string as a JSON value to lazily parse. Particular useful,
/// when you need to extract a single deeply nested value out of larger JSON object.
///
///
/// See [MaybeJson] for more info.
///
/// ## Example
/// ```
/// let object = jsony::drill(stringify![{
///     "key": {"inner": [0, false]},
/// }]);
/// let value: bool = object["key"]["inner"][1].parse().unwrap();
/// assert_eq!(value, false);
/// ```
pub fn drill(input: &str) -> &MaybeJson {
    MaybeJson::new(input)
}

struct JsonErrorInner {
    error: &'static DecodeError,
    context: Option<String>,
    parent_context: JsonParentContext,
    index: usize,
    surrounding: [u8; 24],
}

impl JsonErrorInner {
    fn near_by_input(&self) -> &[u8] {
        &self.surrounding[0..self.surrounding[23] as usize]
    }
}

/// The error type for JSON decoding failure with context.
///
/// See [DecodeError] for the contextless errors used during decoding.
pub struct JsonError {
    inner: Box<JsonErrorInner>,
}

impl JsonError {
    pub fn index(&self) -> usize {
        self.inner.index
    }
    pub fn decoding_error(&self) -> &'static DecodeError {
        self.inner.error
    }

    #[cold]
    fn trailing() -> JsonError {
        JsonError {
            inner: Box::new(JsonErrorInner {
                error: &DecodeError {
                    message: "Trailing characters",
                },
                context: None,
                parent_context: JsonParentContext::None,
                index: 0,
                surrounding: [0; 24],
            }),
        }
    }

    pub fn new(error: &'static DecodeError, context: Option<String>) -> JsonError {
        JsonError {
            inner: Box::new(JsonErrorInner {
                error,
                context,
                parent_context: JsonParentContext::None,
                index: 0,
                surrounding: [0; 24],
            }),
        }
    }

    pub fn extract(error: &'static DecodeError, parser: &mut Parser) -> JsonError {
        fn surrounding(at: usize, text: &[u8]) -> [u8; 24] {
            let mut s: [u8; 24] = [0; 24];
            let end = (at + 12).min(text.len());
            let start = end.saturating_sub(23);
            let ctx = &text[start..end];
            s[23] = ctx.len() as u8;
            s[0..ctx.len()].copy_from_slice(ctx);
            s
        }
        JsonError {
            inner: Box::new(JsonErrorInner {
                error,
                context: parser.at.ctx.error.take().map(|x| x.to_string()),
                parent_context: parser.parent_context,
                index: parser.at.index,
                surrounding: surrounding(parser.at.index, parser.at.ctx.input),
            }),
        }
    }
}
impl std::error::Error for JsonError {}

impl std::fmt::Debug for JsonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <JsonError as std::fmt::Display>::fmt(self, f)
    }
}

impl std::fmt::Display for JsonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.inner.error.message)?;
        if let Some(context) = &self.inner.context {
            f.write_str(": ")?;
            f.write_str(context)?;
        }

        match &self.inner.parent_context {
            JsonParentContext::ObjectKey(key) => {
                write!(f, " @ key {:?}", key)?;
            }
            JsonParentContext::Schema { schema, mask } => {
                if std::ptr::eq(self.inner.error, &crate::error::MISSING_REQUIRED_FIELDS) {
                    write!(f, ": ")?;
                    let mut first = true;
                    for (index, field) in schema.fields.iter().enumerate() {
                        if mask & (1 << index) != 0 {
                            if !first {
                                f.write_str(", ")?;
                            }
                            first = false;
                            write!(f, "{:?}", field.name)?;
                        }
                    }
                    return Ok(());
                }
            }
            JsonParentContext::SchemaField { schema, index } => {
                if std::ptr::eq(self.inner.error, &crate::error::MISSING_REQUIRED_FIELDS) {
                    if let Some(field) = schema.fields.get(*index) {
                        write!(f, ": {:?}", field.name)?;
                        return Ok(());
                    }
                }
            }
            _ => (),
        }
        write!(f, " near `{}`", self.inner.near_by_input().escape_ascii())
    }
}

/// Configuration options for the JSON parser.
#[derive(Clone, Copy)]
#[repr(align(8))]
pub struct JsonParserConfig {
    /// Maximum depth of nested structures (objects and arrays) allowed during parsing.
    /// Each non-empty object or array counts as one depth layer. Default is 128.
    pub recursion_limit: i32,

    /// When enabled, allows trailing commas in arrays and objects.
    /// A trailing comma can appear before the closing brace or bracket.
    pub allow_trailing_commas: bool,

    /// When enabled, allows C-style single-line comments in the JSON.
    /// Comments start with two forward slashes (//) and continue to the end of the line.
    pub allow_comments: bool,

    /// When enabled, allows unquoted strings for object keys that correspond to fields
    /// of rust types.
    /// Unquoted keys must be comprised of characters matching the following [A-Za-z0-9_]
    /// and cannot start with a number.
    pub allow_unquoted_field_keys: bool,

    /// When enabled, allows extra data to appear after the outermost JSON structure.
    /// This is primarily relevant when using the `from_json` function rather than
    /// interacting with the parser directly.
    pub allow_trailing_data: bool,
}

impl Default for JsonParserConfig {
    fn default() -> Self {
        Self {
            recursion_limit: 128,
            allow_trailing_commas: false,
            allow_comments: false,
            allow_unquoted_field_keys: false,
            allow_trailing_data: false,
        }
    }
}

/// Parses a value implementing `FromJson` from a JSON string.
/// # Example
///
/// ```rust
/// assert_eq!(jsony::from_json::<u32>("123")?, 123);
/// # Ok::<(), jsony::JsonError>(())
/// ```
/// # Errors
///
/// This function can fail if:
/// - The input string is not valid JSON.
/// - The JSON structure doesn't match the expected type `T`.
/// - The values in the JSON don't meet the constraints of type `T`.
///
/// # Notes
///
/// - This function uses strict JSON parsing by default, without any extensions.
/// - Unquoted strings, comments, and trailing commas will cause parsing to fail.
/// - There is a default recursion limit for parsing.
///
/// For more flexible parsing options, see `from_json_with_config`.
pub fn from_json<'a, T: FromJson<'a>>(json: &'a str) -> Result<T, JsonError> {
    from_json_with_config(
        json,
        const {
            JsonParserConfig {
                recursion_limit: 128,
                allow_trailing_commas: false,
                allow_comments: false,
                allow_unquoted_field_keys: false,
                allow_trailing_data: false,
            }
        },
    )
}

/// Parses a value implementing `FromJson` from a byte of slice of JSON.
///
/// See [from_json]
pub fn from_json_bytes<'a, T: FromJson<'a>>(json: &'a [u8]) -> Result<T, JsonError> {
    match std::str::from_utf8(json) {
        Ok(value) => from_json(value),
        Err(err) => Err(JsonError::new(&INVALID_UTF8, Some(err.to_string()))),
    }
}

static INVALID_UTF8: DecodeError = DecodeError {
    message: "Invalid UTF-8",
};

/// Parses a value implementing `FromJson` from a string with a custom parser configuration.
///
/// See [from_json] and [JsonParserConfig].
#[inline]
pub fn from_json_with_config<'a, T: FromJson<'a>>(
    json: &'a str,
    config: JsonParserConfig,
) -> Result<T, JsonError> {
    unsafe fn inner_from_json<'a>(
        value: NonNull<()>,
        func: unsafe fn(NonNull<()>, &mut Parser<'a>) -> Result<(), &'static DecodeError>,
        json: &'a str,
        config: JsonParserConfig,
    ) -> Result<bool, JsonError> {
        let mut parser = Parser::new(json, config);
        #[cfg(not(feature = "json_comments"))]
        if config.allow_comments {
            panic!(
                "jsony: 'json_comments' feature is not enabled but is required for `allow_comments`."
            )
        }
        // SAFETY: the caller supplied `value` as writable storage for the type
        // expected by `func`; `func` follows the `FromJson::emplace_from_json`
        // initialization contract.
        match unsafe { func(value, &mut parser) } {
            Ok(()) => Ok(config.allow_trailing_data || parser.at.eat_whitespace().is_none()),
            Err(err) => Err(JsonError::extract(err, &mut parser)),
        }
    }
    let mut value = std::mem::MaybeUninit::<T>::uninit();
    // SAFETY: `value` is valid uninitialized storage for `T`; the passed
    // emplace function initializes it if and only if `inner_from_json` returns
    // `Ok(_)`.
    match unsafe {
        inner_from_json(
            NonNull::new_unchecked(value.as_mut_ptr()).cast(),
            T::emplace_from_json,
            json,
            config,
        )
    } {
        // SAFETY: `inner_from_json` returned success, so `value` was initialized.
        Ok(true) => Ok(unsafe { value.assume_init() }),
        Ok(false) => {
            // SAFETY: `inner_from_json` returned success from the emplace
            // function, so `value` is initialized even though trailing data made
            // the full parse fail.
            unsafe {
                value.assume_init_drop();
            }
            Err(JsonError::trailing())
        }
        Err(err) => Err(err),
    }
}

/// Converts the given value into a JSON string representation.
///
/// This function takes a reference to any type `T` that implements the `ToJson` trait
/// and converts it into a JSON-formatted string.
///
/// # Examples
///
/// ```
/// use jsony::{Jsony, to_json};
///
/// #[derive(Jsony)]
/// #[jsony(ToJson)]
/// struct Person {
///     name: String,
///     age: u32,
/// }
///
/// let person = Person {
///     name: "Alice".to_string(),
///     age: 30,
/// };
///
/// let json_string = to_json(&person);
/// assert_eq!(json_string, r#"{"name":"Alice","age":30}"#);
/// ```
pub fn to_json<T: ToJson + ?Sized>(value: &T) -> String {
    let mut buf = TextWriter::new();
    value.encode_json__jsony(&mut buf);
    buf.into_string()
}

/// Converts the given value into a JSON string appending it to the provided output.
///
/// Can be more efficient then `to_json` when used it avoid allocations or
/// extra copies.
///
/// ## Examples
/// **Appending to a String:**
/// ```
/// let mut output = String::new();
/// assert_eq!(jsony::to_json_into(&false, &mut output), "false");
/// assert_eq!(jsony::to_json_into(&42u32, &mut output), "42");
/// assert_eq!(jsony::to_json_into(&None::<u32>, &mut output), "null");
/// assert_eq!(output, "false42null");
/// ```
/// **Avoiding heap allocation via a stack allocated buffer:**
/// ```
/// let mut temp = [std::mem::MaybeUninit::<u8>::uninit(); 32];
/// assert_eq!(jsony::to_json_into(&false, &mut temp[..]), "false");
/// assert_eq!(jsony::to_json_into(&42u32, &mut temp[..]), "42");
/// assert_eq!(jsony::to_json_into(&None::<u32>, &mut temp[..]), "null");
/// ```
/// Note: When the temp buffers capacity is exceeded a heap allocation will
/// be used hence the return type of `Cow<'a, [u8]>`.
///
/// **Writing to `std::io::Writer`:**
/// ```
/// let writer: &mut (dyn std::io::Write + Send) = &mut std::io::stdout();
/// assert_eq!(jsony::to_json_into(&false, writer)?, 5, "returns number of bytes written");
/// # Ok::<_, std::io::Error>(())
/// ```
pub fn to_json_into<'a, T: ToJson + ?Sized, W: IntoTextWriter<'a>>(
    value: &T,
    output: W,
) -> W::Output {
    let mut buffer = W::into_text_writer(output);
    value.encode_json__jsony(&mut buffer);
    W::finish_writing(buffer)
}

pub fn from_binary<'a, T: FromBinary<'a>>(slice: &'a [u8]) -> Result<T, FromBinaryError> {
    let mut decoder = Decoder::new(slice);
    let value = Ok(T::decode_binary(&mut decoder));
    if let Some(error) = decoder.consume_error() {
        Err(error)
    } else {
        value
    }
}

pub fn to_binary<T: ToBinary + ?Sized>(value: &T) -> Vec<u8> {
    let mut encoder = BytesWriter::new();
    value.encode_binary(&mut encoder);
    encoder.into_vec()
}

pub fn to_binary_into<'a, T: ToBinary + ?Sized, W: IntoByteWriter<'a>>(
    value: &T,
    output: W,
) -> W::Output {
    let mut buffer = W::into_byte_writer(output);
    value.encode_binary(&mut buffer);
    W::finish_writing(buffer)
}

/// Helper for `#[jsony(validate = ..)]` attribute
///
/// # Example
///
/// ```
/// use jsony::{Jsony, require};
/// #[derive(Jsony)]
/// struct Field {
///     // Closure requirement
///     #[jsony(validate = require!(|v| *v > 10, "value must be greater than 10"))]
///     value: u32,
///     // Pattern requirement
///     #[jsony(validate = require!(5..20, "value must be between 4 and 20"))]
///     other: u32,
///     // Pattern requirement with implicit method
///     #[jsony(validate = require!((5..20) | (30..50)))]
///     last: u32,
/// }
/// ```
#[macro_export]
macro_rules! require {
    (|$field:ident $(: $type: ty)?| $expr: expr, $message: literal) => {
        |$field $(: $type)?| {
            if $expr {
                Ok(())
            } else {
                Err(format!("{:?} was invalid: {}", $field, $message))
            }
        }
    };
    ($required_pattern: pat) => {
        |value| match *value {
            $required_pattern => Ok(()),
            _ => Err(format!(
                "Got `{:?}` which does not match the required pattern `{}`",
                value,
                stringify!($required_pattern)
            )),
        }
    };
    ($required_pattern: pat, $message: literal) => {
        |value| match *value {
            $required_pattern => Ok(()),
            _ => Err(format!("{:?} was invalid: {}", value, $message)),
        }
    };
}