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
//! # Serde Duper
//!
//! Duper is a format which aims to be a human-friendly extension of JSON, with
//! quality-of-life improvements, extra types, and semantic identifiers.
//!
//! ```duper
//! Product({
//! product_id: Uuid("1dd7b7aa-515e-405f-85a9-8ac812242609"),
//! name: "Wireless Bluetooth Headphones",
//! brand: "AudioTech",
//! price: Decimal("129.99"),
//! dimensions: (18.5, 15.2, 7.8), // In centimeters
//! weight: Kilograms(0.285),
//! in_stock: true,
//! specifications: {
//! battery_life: Duration("30h"),
//! noise_cancellation: true,
//! connectivity: ["Bluetooth 5.0", "3.5mm Jack"],
//! },
//! image_thumbnail: Png(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x64"),
//! tags: ["electronics", "audio", "wireless"],
//! release_date: Date("2023-11-15"),
//! /* Warranty is optional */
//! warranty_period: null,
//! customer_ratings: {
//! latest_review: r#"Absolutely ""astounding""!! 😎"#,
//! average: 4.5,
//! count: 127,
//! },
//! created_at: DateTime("2023-11-17T21:50:43+00:00"),
//! })
//! ```
//!
//! This crate allows you to convert between Duper's text representation and
//! Rust's native data types, thanks to the `serde` framework.
//!
//! Serde provides a powerful way of mapping Duper data to and from Rust data
//! structures largely automatically.
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use serde_duper::Result;
//!
//! #[derive(Serialize, Deserialize)]
//! struct Person {
//! name: String,
//! age: u8,
//! phones: Vec<String>,
//! }
//!
//! fn deserialize() -> Result<Person> {
//! // Some Duper input data as a &str. Maybe this comes from the user.
//! let data = r#"
//! Person({
//! name: "John Doe",
//! age: 43,
//! phones: [
//! ResidentialPhone("+44 1234567"),
//! CellPhone("+44 2345678"),
//! ],
//! })"#;
//!
//! // Parse the string of data into a Person object.
//! let p: Person = serde_duper::from_string(data)?;
//!
//! // Do things just like with any other Rust data structure.
//! println!("Please call {} at the number {}", p.name, p.phones[0]);
//!
//! Ok(p)
//! }
//!
//! fn serialize(p: Person) -> Result<()> {
//! // Serialize the person back into a Duper string.
//! let d = serde_duper::to_string(&p)?;
//!
//! // Print, write to a file, or send to an HTTP server.
//! println!("{}", d);
//!
//! Ok(())
//! }
//!
//! fn main() {
//! let p = deserialize().unwrap();
//! serialize(p).unwrap();
//! }
//! ```
//!
//! Any type that implements Serde's `Deserialize` trait can be deserialized
//! into a struct like this. This includes built-in Rust standard library type
//! like `Vec<T>` and `HashMap<K, V>`, as well as any structs or enums annotated
//! with `#[derive(Deserialize)]` in the Rust ecosystem.
//!
//! Conversely, any type that implements Serde's `Serialize` trait can be
//! serialized into a string like this. This includes built-in Rust standard
//! library types like `Vec<T>` and `HashMap<K, V>`, as well as any structs or
//! enums annotated with `#[derive(Serialize)]` in the Rust ecosystem.
//!
//! # Handling bytes
//!
//! This crate re-exports [`serde_bytes`] wrapper types via the [`bytes`]
//! module. Prefer using those over the following types if you'd like better
//! byte support:
//!
//! - [`serde_bytes::ByteBuf`] over [`Vec<u8>`]
//! - [`serde_bytes::ByteArray`] over `[u8; N]`
//! - [`serde_bytes::Bytes`] over `[u8]`
//!
//! # Support for identifiers
//!
//! By default, serialization will attempt to include identifiers for structs
//! and enums, while deserialization will ignore them. It's possible to
//! customize the emitted identifiers with the `#[serde(rename = "...")]`
//! attribute.
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use uuid::Uuid;
//!
//! #[derive(Serialize, Deserialize)]
//! #[serde(rename = "Status")]
//! enum UserStatus {
//! Disabled,
//! PendingApproval,
//! Enabled,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! id: Uuid,
//! status: UserStatus,
//! last_known_ips: Vec<String>,
//! }
//!
//! let u = User {
//! id: "314dfe6f-7a76-4c43-80b9-3b0ceb0960c0".parse().unwrap(),
//! status: UserStatus::Enabled,
//! last_known_ips: vec!["2a02:ec80:700:ed1a::1".to_string()],
//! };
//! let d = serde_duper::to_string(&u).unwrap();
//! println!("{}", d);
//! // This should print:
//! // User({
//! // id: "314dfe6f-7a76-4c43-80b9-3b0ceb0960c0",
//! // status: Status("Enabled"),
//! // last_known_ips: ["2a02:ec80:700:ed1a::1"],
//! // })
//! ```
//!
//! It's also possible to remove an identifier with `#[serde(rename = "")]`.
//!
//! In order to generate identifiers for fields, there are currently three
//! possibilities:
//!
//! ## 1. Wrapping your field in a newtype
//!
//! ```
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! #[serde(rename = "Status")]
//! enum UserStatus {
//! Disabled,
//! PendingApproval,
//! Enabled,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct Uuid(uuid::Uuid);
//!
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! id: Uuid,
//! status: UserStatus,
//! last_known_ips: Vec<String>,
//! }
//!
//! let u = User {
//! id: Uuid("314dfe6f-7a76-4c43-80b9-3b0ceb0960c0".parse().unwrap()),
//! status: UserStatus::Enabled,
//! last_known_ips: vec!["2a02:ec80:700:ed1a::1".to_string()],
//! };
//! let d = serde_duper::to_string(&u).unwrap();
//! println!("{}", d);
//! // This should print:
//! // User({
//! // id: Uuid("314dfe6f-7a76-4c43-80b9-3b0ceb0960c0"),
//! // status: Status("Enabled"),
//! // last_known_ips: ["2a02:ec80:700:ed1a::1"],
//! // })
//! ```
//!
//! This offers maximum customizability, but requires an extra layer of
//! indirection in your code.
//!
//! ## 2. Using a remote (de)serializer
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use serde_duper::types::DuperUuid;
//! use uuid::Uuid;
//!
//! #[derive(Serialize, Deserialize)]
//! #[serde(rename = "Status")]
//! enum UserStatus {
//! Disabled,
//! PendingApproval,
//! Enabled,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! #[serde(with = "DuperUuid")]
//! id: Uuid,
//! status: UserStatus,
//! last_known_ips: Vec<String>,
//! }
//!
//! let u = User {
//! id: "314dfe6f-7a76-4c43-80b9-3b0ceb0960c0".parse().unwrap(),
//! status: UserStatus::Enabled,
//! last_known_ips: vec!["2a02:ec80:700:ed1a::1".to_string()],
//! };
//! let d = serde_duper::to_string(&u).unwrap();
//! println!("{}", d);
//! // This should print:
//! // User({
//! // id: Uuid("314dfe6f-7a76-4c43-80b9-3b0ceb0960c0"),
//! // status: Status("Enabled"),
//! // last_known_ips: ["2a02:ec80:700:ed1a::1"],
//! // })
//! ```
//!
//! The [`types`] module provides a simple and quick plug-and-play
//! way of annotating types from [`std`] (as well as a few popular third-party
//! crates behind feature flags) with Duper identifiers. It works by providing
//! remote modules that will handle (de)serialization. This is less flexible,
//! but allows you to use the original types directly.
//!
//! Currently, modules are provided for `T` and `Option<T>`.
//!
//! ## 3. Using the proc-macro
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use serde_duper::duper;
//! use uuid::Uuid;
//!
//! #[derive(Serialize, Deserialize)]
//! #[serde(rename = "Status")]
//! enum UserStatus {
//! Disabled,
//! PendingApproval,
//! Enabled,
//! }
//!
//! duper! {
//! #[derive(Serialize, Deserialize)]
//! struct User {
//! #[duper(MyUuid)]
//! id: Uuid,
//! status: UserStatus,
//! #[duper(IpList)]
//! last_known_ips: Vec<String>,
//! }
//! }
//!
//! # fn main() {
//! let u = User {
//! id: "314dfe6f-7a76-4c43-80b9-3b0ceb0960c0".parse().unwrap(),
//! status: UserStatus::Enabled,
//! last_known_ips: vec!["2a02:ec80:700:ed1a::1".to_string()],
//! };
//! let d = serde_duper::to_string(&u).unwrap();
//! println!("{}", d);
//! // This should print:
//! // User({
//! // id: MyUuid("314dfe6f-7a76-4c43-80b9-3b0ceb0960c0"),
//! // status: Status("Enabled"),
//! // last_known_ips: IpList(["2a02:ec80:700:ed1a::1"]),
//! // })
//! # }
//! ```
//!
//! This will automatically generate the modules for any type that implements
//! [`serde_core::Serialize`] and/or [`serde_core::Deserialize`], not being
//! restricted only to those with a remote (de)serializer module.
//!
//! This requires the `macros` feature flag.
//!
pub use Deserializer;
pub use ;
pub use ;
pub use ;
pub use duper;
/// Interpret a [`DuperValue`] as an instance of type `T`.
///
/// # Example
///
/// ```
/// use std::borrow::Cow;
/// use serde::Deserialize;
/// use serde_duper::{
/// DuperBytes, DuperIdentifier, DuperInner, DuperKey, DuperObject,
/// DuperString, DuperValue,
/// };
///
/// #[derive(Deserialize, Debug)]
/// struct User {
/// fingerprint: Vec<u8>,
/// location: String,
/// }
///
/// // The type of `d` is `serde_duper::DuperValue`
/// let d = DuperValue {
/// identifier: Some(DuperIdentifier::try_from(Cow::Borrowed("User")).unwrap()),
/// inner: DuperInner::Object(DuperObject::try_from(vec![
/// (
/// DuperKey::from(Cow::Borrowed("fingerprint")),
/// DuperValue {
/// identifier: None,
/// inner: DuperInner::Bytes(DuperBytes::from(Cow::Borrowed(
/// &b"\xF9\xBA\x14\x3B\x95\xFF\x6D\x82"[..],
/// ))),
/// }
/// ),
/// (
/// DuperKey::from(Cow::Borrowed("location")),
/// DuperValue {
/// identifier: Some(
/// DuperIdentifier::try_from(Cow::Borrowed("City")).unwrap(),
/// ),
/// inner: DuperInner::String(DuperString::from(
/// Cow::Borrowed("Menlo Park, CA"),
/// )),
/// }
/// ),
/// ]).unwrap()),
/// };
///
/// let u: User = serde_duper::from_value(d).unwrap();
/// println!("{:#?}", u);
/// ```
///
/// # Errors
///
/// This conversion can fail if the structure of the input does not match the
/// structure expected by `T`, for example if `T` is a struct type but the input
/// contains something other than a Duper object. It can also fail if the
/// structure is correct but `T`'s implementation of [`Deserialize`] decides that
/// something is wrong with the data, for example required struct fields are
/// missing from the Duper object or some number is too big to fit in the
/// expected primitive type.
/// Deserialize an instance of type `T` from a str slice of Duper text.
///
/// # Example
///
/// ```
/// use serde::Deserialize;
///
/// #[derive(Deserialize, Debug)]
/// struct User {
/// fingerprint: Vec<u8>,
/// location: String,
/// }
///
///
/// // The type of `j` is `&str`
/// let j = r#"
/// User({
/// fingerprint: b"\xF9\xBA\x14\x3B\x95\xFF\x6D\x82",
/// location: City("Menlo Park, CA"),
/// })"#;
///
/// let u: User = serde_duper::from_string(j).unwrap();
/// println!("{:#?}", u);
/// ```
///
/// # Errors
///
/// This conversion can fail if the structure of the input does not match the
/// structure expected by `T`, for example if `T` is a struct type but the input
/// contains something other than a Duper object. It can also fail if the
/// structure is correct but `T`'s implementation of [`Deserialize`] decides that
/// something is wrong with the data, for example required struct fields are
/// missing from the Duper object or some number is too big to fit in the
/// expected primitive type.