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
use core::fmt;
use awint_internals::*;
use serde::{
de,
de::{MapAccess, SeqAccess, Visitor},
ser::{SerializeStruct, SerializeTuple},
Deserialize, Deserializer, Serialize, Serializer,
};
use crate::InlAwi;
/// A `serde_support` impl
impl<const BW: usize, const LEN: usize> Serialize for InlAwi<BW, LEN> {
/// Serializes `self` in a platform independent way. In human readable form,
/// it serializes into a struct named "InlAwi" with two fields "bw" and
/// "bits". "bw" is the bitwidth in decimal, and "bits" are an unsigned
/// hexadecimal string equivalent to what would be generated from
/// `Awi::bits_to_string_radix(&self, false, 16, false, 0)`
/// from the `awint_ext` crate.
///
/// Note that there is clever use of buffers to avoid allocation on
/// `awint`'s side when serializing `InlAwi`s.
///
/// ```
/// // Example using the `ron` crate. Note that it
/// // omits the struct name which would be "InlAwi".
/// use awint::{inlawi, Bits, InlAwi};
/// use ron::to_string;
///
/// assert_eq!(
/// to_string(&inlawi!(0xfedcba9876543210u100)).unwrap(),
/// "(bw:100,bits:\"fedcba9876543210\")"
/// );
/// ```
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// TODO this buffer is ~5 times larger than needed. We have a
// `panicking_chars_upper_bound` that can be used in array lengths if the input
// is a constant, but annoyingly we currently can't use generic parameters for
// it.
let mut buf = [0u8; BW];
let mut pad = Self::zero();
// do the minimum amount of work necessary
let upper = chars_upper_bound(self.sig(), 16).unwrap();
self.to_bytes_radix(false, &mut buf[..upper], 16, false, pad.const_as_mut())
.unwrap();
// find the lower bound of signficant digits
let mut lower = 0;
for i in 0..upper {
if buf[i] != b'0' {
lower = i;
break
}
if (i + 1) == upper {
// all zeros, use one zero. `chars_upper_bound` always returns at least 1, so
// underflow is not possible.
lower = upper - 1;
break
}
}
let str_buf = core::str::from_utf8(&buf[lower..upper]).unwrap();
if serializer.is_human_readable() {
let mut s = serializer.serialize_struct("InlAwi", 2)?;
s.serialize_field("bw", &self.bw())?;
s.serialize_field("bits", str_buf)?;
s.end()
} else {
let mut s = serializer.serialize_tuple(2)?;
s.serialize_element(&self.bw())?;
s.serialize_element(str_buf)?;
s.end()
}
}
}
const FIELDS: &[&str] = &["bw", "bits"];
/// Helper for the deserialization impl
enum Field {
Bw,
Bits,
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`bw` or `bits`")
}
fn visit_str<E>(self, value: &str) -> Result<Field, E>
where
E: de::Error,
{
match value {
"bw" => Ok(Field::Bw),
"bits" => Ok(Field::Bits),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct InlAwiVisitor<const BW: usize, const LEN: usize>;
impl<'de, const BW: usize, const LEN: usize> Visitor<'de> for InlAwiVisitor<BW, LEN> {
type Value = InlAwi<BW, LEN>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(
"struct InlAwi consisting of a decimal bitwidth \"bw\" and a hexadecimal unsigned \
integer \"bits\"",
)
}
fn visit_map<V>(self, mut map: V) -> Result<InlAwi<BW, LEN>, V::Error>
where
V: MapAccess<'de>,
{
let mut w: Option<usize> = None;
let mut bits: Option<&str> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Bw => {
if w.is_some() {
return Err(de::Error::duplicate_field("bw"))
}
w = Some(map.next_value()?);
}
Field::Bits => {
if bits.is_some() {
return Err(de::Error::duplicate_field("bits"))
}
bits = Some(map.next_value()?);
}
}
}
let w = w.ok_or_else(|| de::Error::missing_field("bw"))?;
let bits = bits.ok_or_else(|| de::Error::missing_field("bits"))?;
if w == 0 {
// in case someone made `BW == 0` manually
return Err(de::Error::custom("`bw` field should be nonzero"))
}
if w != BW {
return Err(de::Error::custom(
"`bw` field does not equal `BW` of `InlAwi<BW, LEN>` type this deserialization is \
happening on",
))
}
let mut val = InlAwi::<BW, LEN>::zero();
let mut pad = InlAwi::<BW, LEN>::zero();
let result =
val.const_as_mut()
.power_of_two_bytes_(None, bits.as_bytes(), 16, pad.const_as_mut());
if let Err(e) = result {
return Err(de::Error::custom(e))
}
Ok(val)
}
fn visit_seq<V>(self, mut seq: V) -> Result<InlAwi<BW, LEN>, V::Error>
where
V: SeqAccess<'de>,
{
let w: usize = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let bits: &str = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
if w == 0 {
// in case someone made `BW == 0` manually
return Err(de::Error::custom("`bw` field should be nonzero"))
}
if w != BW {
return Err(de::Error::custom(
"`bw` field does not equal `BW` of `InlAwi<BW, LEN>` type this deserialization is \
happening on",
))
}
let mut val = InlAwi::<BW, LEN>::zero();
let mut pad = InlAwi::<BW, LEN>::zero();
let result =
val.const_as_mut()
.power_of_two_bytes_(None, bits.as_bytes(), 16, pad.const_as_mut());
if let Err(e) = result {
return Err(de::Error::custom(e))
}
Ok(val)
}
}
/// A `serde_support` impl
impl<'de, const BW: usize, const LEN: usize> Deserialize<'de> for InlAwi<BW, LEN> {
/// Deserializes `self` in a platform independent way.
///
/// ```
/// // Example using the `ron` crate. Note that it
/// // omits the struct name which would be "InlAwi".
/// use awint::{inlawi, inlawi_ty, Bits, InlAwi};
/// use ron::from_str;
///
/// // note: you will probably have to specify the type with `inlawi_ty`
/// let val: inlawi_ty!(100) = from_str("(bw:100,bits:\"fedcba9876543210\")").unwrap();
/// assert_eq!(val, inlawi!(0xfedcba9876543210u100));
/// ```
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_struct("InlAwi", FIELDS, InlAwiVisitor)
}
}