serde_ast/lib.rs
1#![deny(
2 rust_2018_compatibility,
3 rust_2021_compatibility,
4 rust_2024_compatibility,
5 future_incompatible,
6 nonstandard_style,
7 let_underscore,
8 keyword_idents,
9 unused_variables
10)]
11#![warn(unused, missing_docs)]
12
13//! Implements an [Ast] representation of [serde] serialization.
14//!
15//! This allows to see the serialization calls made, inspect them, traverse, edit, or serialize with a [serde::Serializer].
16//!
17//! ```
18//! # use serde::{Deserialize, Serialize};
19//! # use serde_ast::to_ast;
20//! #[derive(Serialize, Deserialize)]
21//! struct Example {
22//! hello: String,
23//! }
24//! let example = Example { hello: "World".to_string() };
25//! let ast = to_ast(&example).expect("serialize to_ast");
26//! println!("{}", ast);
27//! ```
28//! ```text
29//! Struct {
30//! name: "Example",
31//! len: 1,
32//! ops: [
33//! Field {
34//! key: "hello",
35//! value: Str(
36//! "World",
37//! ),
38//! },
39//! ],
40//! }
41//! ```
42//!
43//! Serializing the [Ast] is equivalent to directly serializing the original value.
44//!
45//! ```
46//! # use serde::{Deserialize, Serialize};
47//! # use serde_ast::to_ast;
48//! # #[derive(Serialize, Deserialize)]
49//! # struct Example {
50//! # hello: String,
51//! # }
52//! # let example = Example { hello: "World".to_string() };
53//! # let ast = to_ast(&example).expect("serialize to_ast");
54//! // serialize the ast
55//! let output = serde_json::to_string(&ast).expect("serde_json::to_string");
56//! // serialize the value directly
57//! let direct = serde_json::to_string(&example).expect("serde_json::to_string");
58//! // the result is the same
59//! assert_eq!(output, direct);
60//! ```
61
62pub mod ast;
63pub mod ser;
64
65use serde::Serialize;
66
67pub use ast::Ast;
68pub use ser::Serializer;
69
70/// Serialize a value into [Ast].
71///
72/// Serializing the [Ast] is equivalent to directly serializing the value.
73pub fn to_ast<T>(value: &T) -> Result<Ast, ser::Error>
74where
75 T: Serialize + ?Sized,
76{
77 let serializer = Serializer::new();
78 value.serialize(serializer)
79}