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
//! Open extension API: render your own types as JSONX `name(value)`
//! constructors.
//!
//! JSONX is deliberately open. A document is a valid ES5 expression, so
//! `myType(value)` is just a function call — given a definition of `myType`,
//! any constructor can be added. This module lets you teach the jsonx
//! serializer and deserializer a new constructor for one of *your* types, while
//! every other serde format still sees a plain, transparent value.
//!
//! It is the same mechanism the built-in [`ip`](crate::ip) /
//! [`ipport`](crate::ipport) / [`datetime`](crate::datetime) types use: an
//! extended value travels through serde as a newtype struct whose name is a
//! sentinel-encoded constructor name (produced by the [`ctor!`](crate::ctor)
//! macro). Our serializer turns it into `name(value)`; other serializers ignore
//! the name and emit the inner value transparently.
//!
//! # The quick way: `#[derive(JsonxConstructor)]`
//!
//! If your type already implements [`Display`](std::fmt::Display) and
//! [`FromStr`](std::str::FromStr), the [derive](macro@crate::JsonxConstructor)
//! generates everything — the trait impl *and* the serde impls — from those.
//! The constructor name defaults to the type name lowercased; override it with
//! `#[jsonx(name = "...")]`. (Requires the default `derive` feature; see the
//! [derive macro](macro@crate::JsonxConstructor) for a runnable example.)
//!
//! # The manual way: implement [`JsonxConstructor`] by hand
//!
//! When a string `Display`/`FromStr` representation doesn't fit, implement
//! [`JsonxConstructor`] directly, then delegate serde to this module's
//! [`serialize`]/[`deserialize`] helpers:
//!
//! ```
//! use jsonx::JsonxConstructor;
//!
//! #[derive(Debug, PartialEq)]
//! struct Color(u32); // an RGB triple, e.g. 0xff8800
//!
//! impl JsonxConstructor for Color {
//! const TOKEN: &'static str = jsonx::ctor!("color");
//! fn to_jsonx_arg(&self) -> String {
//! format!("#{:06x}", self.0)
//! }
//! fn from_jsonx_arg(arg: &str) -> Result<Self, String> {
//! let hex = arg.strip_prefix('#').unwrap_or(arg);
//! u32::from_str_radix(hex, 16).map(Color).map_err(|e| e.to_string())
//! }
//! }
//!
//! impl serde::Serialize for Color {
//! fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
//! jsonx::constructor::serialize(self, s)
//! }
//! }
//! impl<'de> serde::Deserialize<'de> for Color {
//! fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
//! jsonx::constructor::deserialize(d)
//! }
//! }
//!
//! let text = jsonx::to_string(&Color(0xff8800)).unwrap();
//! assert_eq!(text, r##"color("#ff8800")"##);
//! assert_eq!(jsonx::from_str::<Color>(&text).unwrap(), Color(0xff8800));
//! ```
//!
//! Prefer not to write the serde impls? Apply this module through serde's
//! `with` attribute instead — it dispatches through [`JsonxConstructor`] too:
//!
//! ```
//! # use jsonx::JsonxConstructor;
//! # #[derive(Debug, PartialEq)]
//! # struct Color(u32);
//! # impl JsonxConstructor for Color {
//! # const TOKEN: &'static str = jsonx::ctor!("color");
//! # fn to_jsonx_arg(&self) -> String { format!("#{:06x}", self.0) }
//! # fn from_jsonx_arg(arg: &str) -> Result<Self, String> {
//! # u32::from_str_radix(arg.strip_prefix('#').unwrap_or(arg), 16).map(Color).map_err(|e| e.to_string())
//! # }
//! # }
//! #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
//! struct Paint {
//! #[serde(with = "jsonx::constructor")]
//! fill: Color,
//! }
//! ```
//!
//! # Foreign types
//!
//! Rust's orphan rule means you can only implement [`JsonxConstructor`] for a
//! type defined in your own crate. For a foreign type (e.g. `uuid::Uuid`), wrap
//! it in a newtype you own and implement the trait on the wrapper — exactly how
//! [`Ip`](crate::Ip) wraps [`std::net::IpAddr`].
use fmt;
use ;
use ;
/// Encodes a constructor `name` into the `&'static str` token the jsonx
/// serializer recognizes. Use it to set [`JsonxConstructor::TOKEN`].
///
/// ```
/// const TOKEN: &str = jsonx::ctor!("mytype");
/// assert!(TOKEN.ends_with("mytype"));
/// ```
/// A type that has a JSONX `name(value)` constructor form.
///
/// The value's textual argument is a string: `to_jsonx_arg` renders it and
/// `from_jsonx_arg` parses it back. In JSONX it serializes as
/// `name("argument")`; in every other serde format it stays a plain string.
///
/// See the [module docs](self) for a worked example.
/// Low-level: serialize `repr` as the body of a JSONX `name(...)` constructor,
/// where `token` is a [`ctor!`](crate::ctor)-encoded name.
///
/// Most callers should implement [`JsonxConstructor`] and use [`serialize`]
/// instead; reach for this only when the argument is not a `String`.
/// Low-level: read the string argument of a JSONX `name(...)` constructor,
/// where `token` is a [`ctor!`](crate::ctor)-encoded name. Also accepts a bare
/// string, so values round-trip through non-JSONX formats.
/// Serializes a [`JsonxConstructor`] value. Usable on its own or through
/// `#[serde(with = "jsonx::constructor")]`.
/// Deserializes a [`JsonxConstructor`] value. Usable on its own or through
/// `#[serde(with = "jsonx::constructor")]`.