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
// Copyright (c) 2024 Stephane Raux. Distributed under the 0BSD license.
use crate::;
use PhantomData;
use ;
/// Adapter for custom serialization when the serialization format is human-readable
///
/// If the serialization format is human-readable, `F` is used to serialize. Otherwise `G` is used.
///
/// # Example
/// ```
/// use bincode::Options as _;
/// use std::{fmt::{self, Display}, str::FromStr};
/// use serdapt as sa;
/// use serde::{Deserialize, Serialize};
/// use serde_json::json;
///
/// struct Color(u32);
///
/// impl Display for Color {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "#{:06x}", self.0)
/// }
/// }
///
/// impl FromStr for Color {
/// type Err = std::num::ParseIntError;
///
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// u32::from_str_radix(s.trim_start_matches('#'), 16).map(Color)
/// }
/// }
///
/// impl From<u32> for Color {
/// fn from(n: u32) -> Color {
/// Color(n)
/// }
/// }
///
/// impl From<Color> for u32 {
/// fn from(c: Color) -> u32 {
/// c.0
/// }
/// }
///
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// struct Palette {
/// #[serde(with = "sa::Seq::<sa::HumanOr<sa::Convert<Color, sa::Str>, sa::Id>>")]
/// colors: Vec<u32>,
/// }
///
/// let palette = Palette { colors: vec![0x000000, 0xffffff] };
/// let serialized = serde_json::to_value(&palette).unwrap();
/// assert_eq!(serialized, json!({ "colors": ["#000000", "#ffffff"] }));
/// let deserialized = serde_json::from_value::<Palette>(serialized).unwrap();
/// assert_eq!(deserialized, palette);
/// let bincode_config = bincode::options().with_fixint_encoding();
/// let serialized = bincode_config.serialize(&palette).unwrap();
/// assert_eq!(
/// serialized,
/// 2u64
/// .to_le_bytes()
/// .into_iter()
/// .chain(0u32.to_le_bytes())
/// .chain(0xffffffu32.to_le_bytes())
/// .collect::<Vec<_>>(),
/// );
/// let deserialized = bincode_config.deserialize::<Palette>(&serialized).unwrap();
/// assert_eq!(deserialized, palette);
/// ```
>);