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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#![doc=include_str!("../../doc/serdes/array.md")]

use core::{
	any,
	fmt::{
		self,
		Formatter,
	},
};

use serde::{
	de::{
		Deserialize,
		Deserializer,
		Error,
		MapAccess,
		SeqAccess,
		Unexpected,
		Visitor,
	},
	ser::{
		Serialize,
		SerializeStruct,
		Serializer,
	},
};

use super::{
	utils::{
		Array,
		TypeName,
	},
	Field,
	FIELDS,
};
use crate::{
	array::BitArray,
	index::BitIdx,
	mem::bits_of,
	order::BitOrder,
	store::BitStore,
};

impl<T, O> Serialize for BitArray<T, O>
where
	T: BitStore,
	O: BitOrder,
	T::Mem: Serialize,
{
	#[inline]
	fn serialize<S>(&self, serializer: S) -> super::Result<S>
	where S: Serializer {
		let mut state = serializer.serialize_struct("BitArr", FIELDS.len())?;

		state.serialize_field("order", &any::type_name::<O>())?;
		state.serialize_field("head", &BitIdx::<T::Mem>::MIN)?;
		state.serialize_field("bits", &(self.len() as u64))?;
		state.serialize_field(
			"data",
			Array::from_ref(core::array::from_ref(&self.data)),
		)?;

		state.end()
	}
}

impl<T, O, const N: usize> Serialize for BitArray<[T; N], O>
where
	T: BitStore,
	O: BitOrder,
	T::Mem: Serialize,
{
	#[inline]
	fn serialize<S>(&self, serializer: S) -> super::Result<S>
	where S: Serializer {
		let mut state = serializer.serialize_struct("BitArr", FIELDS.len())?;

		state.serialize_field("order", &any::type_name::<O>())?;
		state.serialize_field("head", &BitIdx::<T::Mem>::MIN)?;
		state.serialize_field("bits", &(self.len() as u64))?;
		state.serialize_field("data", Array::from_ref(&self.data))?;

		state.end()
	}
}

impl<'de, T, O> Deserialize<'de> for BitArray<T, O>
where
	T: BitStore,
	O: BitOrder,
	T::Mem: Deserialize<'de>,
{
	#[inline]
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where D: Deserializer<'de> {
		deserializer
			.deserialize_struct("BitArr", FIELDS, BitArrVisitor::<T, O, 1>::THIS)
			.map(|BitArray { data: [elem], .. }| BitArray::new(elem))
	}
}

impl<'de, T, O, const N: usize> Deserialize<'de> for BitArray<[T; N], O>
where
	T: BitStore,
	O: BitOrder,
	T::Mem: Deserialize<'de>,
{
	#[inline]
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where D: Deserializer<'de> {
		deserializer.deserialize_struct(
			"BitArr",
			FIELDS,
			BitArrVisitor::<T, O, N>::THIS,
		)
	}
}

/// Assists in deserialization of a static `BitArr`.
struct BitArrVisitor<T, O, const N: usize>
where
	T: BitStore,
	O: BitOrder,
{
	/// The deserialized bit-ordering string.
	order: Option<TypeName<O>>,
	/// The deserialized head-bit index. This must be zero; it is used for
	/// consistency with `BitSeq` and to carry `T::Mem` information.
	head:  Option<BitIdx<T::Mem>>,
	/// The deserialized bit-count. It must be `bits_of::<[T::Mem; N]>()`.
	bits:  Option<u64>,
	/// The deserialized data buffer.
	data:  Option<Array<T, N>>,
}

impl<'de, T, O, const N: usize> BitArrVisitor<T, O, N>
where
	T: BitStore,
	O: BitOrder,
	Array<T, N>: Deserialize<'de>,
{
	/// A new visitor in its ready condition.
	const THIS: Self = Self {
		order: None,
		head:  None,
		bits:  None,
		data:  None,
	};

	/// Attempts to assemble deserialized components into an output value.
	#[inline]
	fn assemble<E>(mut self) -> Result<BitArray<[T; N], O>, E>
	where E: Error {
		self.order.take().ok_or_else(|| E::missing_field("order"))?;
		let head = self.head.take().ok_or_else(|| E::missing_field("head"))?;
		let bits = self.bits.take().ok_or_else(|| E::missing_field("bits"))?;
		let data = self.data.take().ok_or_else(|| E::missing_field("data"))?;

		if head != BitIdx::MIN {
			return Err(E::invalid_value(
				Unexpected::Unsigned(head.into_inner() as u64),
				&"`BitArray` must have a head-bit of `0`",
			));
		}
		let bits = bits as usize;
		if bits != bits_of::<[T; N]>() {
			return Err(E::invalid_length(bits, &self));
		}

		Ok(BitArray::new(data.inner))
	}
}

impl<'de, T, O, const N: usize> Visitor<'de> for BitArrVisitor<T, O, N>
where
	T: BitStore,
	O: BitOrder,
	Array<T, N>: Deserialize<'de>,
{
	type Value = BitArray<[T; N], O>;

	#[inline]
	fn expecting(&self, fmt: &mut Formatter) -> fmt::Result {
		write!(
			fmt,
			"a `BitArray<[u{}; {}], {}>`",
			bits_of::<T::Mem>(),
			N,
			any::type_name::<O>(),
		)
	}

	#[inline]
	fn visit_seq<V>(mut self, mut seq: V) -> Result<Self::Value, V::Error>
	where V: SeqAccess<'de> {
		self.order = Some(
			seq.next_element()?
				.ok_or_else(|| <V::Error>::invalid_length(0, &self))?,
		);
		self.head = Some(
			seq.next_element()?
				.ok_or_else(|| <V::Error>::invalid_length(1, &self))?,
		);
		self.bits = Some(
			seq.next_element()?
				.ok_or_else(|| <V::Error>::invalid_length(2, &self))?,
		);
		self.data = Some(
			seq.next_element()?
				.ok_or_else(|| <V::Error>::invalid_length(3, &self))?,
		);

		self.assemble()
	}

	#[inline]
	fn visit_map<V>(mut self, mut map: V) -> Result<Self::Value, V::Error>
	where V: MapAccess<'de> {
		while let Some(key) = map.next_key()? {
			match key {
				Field::Order => {
					if self.order.replace(map.next_value()?).is_some() {
						return Err(<V::Error>::duplicate_field("order"));
					}
				},
				Field::Head => {
					if self.head.replace(map.next_value()?).is_some() {
						return Err(<V::Error>::duplicate_field("head"));
					}
				},
				Field::Bits => {
					if self.bits.replace(map.next_value()?).is_some() {
						return Err(<V::Error>::duplicate_field("bits"));
					}
				},
				Field::Data => {
					if self.data.replace(map.next_value()?).is_some() {
						return Err(<V::Error>::duplicate_field("data"));
					}
				},
			}
		}

		self.assemble()
	}
}

#[cfg(test)]
mod tests {
	#[cfg(all(feature = "alloc", not(feature = "std")))]
	use alloc::format;
	use core::any;

	use serde_test::{
		assert_de_tokens,
		assert_de_tokens_error,
		assert_ser_tokens,
		Token,
	};

	use crate::prelude::*;

	#[test]
	#[cfg(feature = "std")]
	fn roundtrip() -> Result<(), Box<dyn std::error::Error>> {
		type BA = BitArr!(for 16, in u8, Msb0);
		let array = [0x3Cu8, 0xA5].into_bitarray::<Msb0>();

		let bytes = bincode::serialize(&array)?;
		let array2 = bincode::deserialize::<BA>(&bytes)?;
		assert_eq!(array, array2);

		let json = serde_json::to_string(&array)?;
		let array3 = serde_json::from_str::<BA>(&json)?;
		assert_eq!(array, array3);

		let json_value = serde_json::to_value(&array)?;
		let array4 = serde_json::from_value::<BA>(json_value)?;
		assert_eq!(array, array4);

		type BA2 = BitArray<u16, Msb0>;
		let array = BA2::new(44203);

		let bytes = bincode::serialize(&array)?;
		let array2 = bincode::deserialize::<BA2>(&bytes)?;
		assert_eq!(array, array2);

		let json = serde_json::to_string(&array)?;
		let array3 = serde_json::from_str::<BA2>(&json)?;
		assert_eq!(array, array3);

		let json_value = serde_json::to_value(&array)?;
		let array4 = serde_json::from_value::<BA2>(json_value)?;
		assert_eq!(array, array4);

		Ok(())
	}

	#[test]
	fn tokens() {
		let array = [0x3Cu8, 0xA5].into_bitarray::<Msb0>();
		let tokens = &mut [
			Token::Struct {
				name: "BitArr",
				len:  4,
			},
			Token::Str("order"),
			Token::Str(any::type_name::<Msb0>()),
			Token::Str("head"),
			Token::Struct {
				name: "BitIdx",
				len:  2,
			},
			Token::Str("width"),
			Token::U8(8),
			Token::Str("index"),
			Token::U8(0),
			Token::StructEnd,
			Token::Str("bits"),
			Token::U64(16),
			Token::Str("data"),
			Token::Tuple { len: 2 },
			Token::U8(0x3C),
			Token::U8(0xA5),
			Token::TupleEnd,
			Token::StructEnd,
		];

		assert_ser_tokens(&array, tokens);

		tokens[1 .. 4].copy_from_slice(&[
			Token::BorrowedStr("order"),
			Token::BorrowedStr(any::type_name::<Msb0>()),
			Token::BorrowedStr("head"),
		]);
		tokens[5] = Token::BorrowedStr("width");
		tokens[7] = Token::BorrowedStr("index");
		tokens[10] = Token::BorrowedStr("bits");
		tokens[12] = Token::BorrowedStr("data");
		assert_de_tokens(&array, tokens);
	}

	#[test]
	#[cfg(feature = "alloc")]
	fn errors() {
		type BA = BitArr!(for 8, in u8, Msb0);
		let mut tokens = vec![
			Token::Seq { len: Some(4) },
			Token::BorrowedStr(any::type_name::<Msb0>()),
		];

		assert_de_tokens_error::<BitArr!(for 8, in u8, Lsb0)>(
			&tokens,
			&format!(
				"invalid value: string \"{}\", expected the string \"{}\"",
				any::type_name::<Msb0>(),
				any::type_name::<Lsb0>(),
			),
		);

		tokens.extend([
			Token::Seq { len: Some(2) },
			Token::U8(8),
			Token::U8(0),
			Token::SeqEnd,
			Token::U64(8),
			Token::Tuple { len: 1 },
			Token::U8(0),
			Token::TupleEnd,
			Token::SeqEnd,
		]);

		tokens[6] = Token::U64(7);
		assert_de_tokens_error::<BA>(
			&tokens,
			"invalid length 7, expected a `BitArray<[u8; 1], \
			 bitvec::order::Msb0>`",
		);

		tokens[4] = Token::U8(1);
		assert_de_tokens_error::<BA>(
			&tokens,
			"invalid value: integer `1`, expected `BitArray` must have a \
			 head-bit of `0`",
		);

		assert_de_tokens_error::<BA>(
			&[
				Token::Struct {
					name: "BitArr",
					len:  2,
				},
				Token::BorrowedStr("placeholder"),
			],
			&format!(
				"unknown field `placeholder`, expected one of `{}`",
				super::FIELDS.join("`, `"),
			),
		);
		assert_de_tokens_error::<BA>(
			&[
				Token::Struct {
					name: "BitArr",
					len:  2,
				},
				Token::BorrowedStr("order"),
				Token::BorrowedStr(any::type_name::<Msb0>()),
				Token::BorrowedStr("order"),
				Token::BorrowedStr(any::type_name::<Msb0>()),
				Token::StructEnd,
			],
			"duplicate field `order`",
		);
		assert_de_tokens_error::<BA>(
			&[
				Token::Struct {
					name: "BitArr",
					len:  2,
				},
				Token::BorrowedStr("head"),
				Token::Seq { len: Some(2) },
				Token::U8(8),
				Token::U8(0),
				Token::SeqEnd,
				Token::BorrowedStr("head"),
				Token::Seq { len: Some(2) },
				Token::U8(8),
				Token::U8(0),
				Token::SeqEnd,
				Token::StructEnd,
			],
			"duplicate field `head`",
		);
		assert_de_tokens_error::<BA>(
			&[
				Token::Struct {
					name: "BitArr",
					len:  2,
				},
				Token::BorrowedStr("bits"),
				Token::U64(8),
				Token::BorrowedStr("bits"),
				Token::U64(8),
				Token::StructEnd,
			],
			"duplicate field `bits`",
		);
		assert_de_tokens_error::<BA>(
			&[
				Token::Struct {
					name: "BitArr",
					len:  2,
				},
				Token::BorrowedStr("data"),
				Token::Tuple { len: 1 },
				Token::U8(0),
				Token::TupleEnd,
				Token::BorrowedStr("data"),
				Token::Tuple { len: 1 },
				Token::U8(1),
				Token::TupleEnd,
				Token::StructEnd,
			],
			"duplicate field `data`",
		);
	}
}