| 1 | use crate::BitArray; |
| 2 | use core::fmt; |
| 3 | use serde::{ |
| 4 | de::{Error, Expected, SeqAccess, Visitor}, |
| 5 | Deserialize, Deserializer, Serialize, Serializer, |
| 6 | }; |
| 7 | |
| 8 | impl<const B: usize> Serialize for BitArray<B> { |
| 9 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 10 | where |
| 11 | S: Serializer, |
| 12 | { |
| 13 | serializer.serialize_bytes(&self.bytes) |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | impl<'de, const B: usize> Deserialize<'de> for BitArray<B> { |
| 18 | fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 19 | where |
| 20 | D: Deserializer<'de>, |
| 21 | { |
| 22 | deserializer.deserialize_bytes(BitArrayVisitor::<B>) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | struct BitArrayVisitor<const B: usize>; |
| 27 | |
| 28 | impl<'de, const B: usize> Visitor<'de> for BitArrayVisitor<B> { |
| 29 | type Value = BitArray<B>; |
| 30 | |
| 31 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 32 | write!(formatter, "[u8; {}]", B) |
| 33 | } |
| 34 | |
| 35 | fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> |
| 36 | where |
| 37 | A: SeqAccess<'de>, |
| 38 | { |
| 39 | let mut arr = [0u8; B]; |
| 40 | let mut ix = 0; |
| 41 | // Continuously fill the array with more values. |
| 42 | while let Some(value) = seq.next_element()? { |
| 43 | if ix == B { |
| 44 | return Err(Error::custom("bitarray: too many bytes in sequence")); |
| 45 | } |
| 46 | arr[ix] = value; |
| 47 | ix += 1; |
| 48 | } |
| 49 | |
| 50 | if ix != B { |
| 51 | Err(Error::invalid_length(ix, &BitArrayExpectedBytes::<B>)) |
| 52 | } else { |
| 53 | Ok(BitArray::new(arr)) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E> |
| 58 | where |
| 59 | E: Error, |
| 60 | { |
| 61 | if bytes.len() != B { |
| 62 | Err(Error::invalid_length( |
| 63 | bytes.len(), |
| 64 | &BitArrayExpectedBytes::<B>, |
| 65 | )) |
| 66 | } else { |
| 67 | let mut bitarray = BitArray::<B>::zeros(); |
| 68 | bitarray.bytes.copy_from_slice(bytes); |
| 69 | Ok(bitarray) |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | struct BitArrayExpectedBytes<const B: usize>; |
| 75 | |
| 76 | impl<const B: usize> Expected for BitArrayExpectedBytes<B> { |
| 77 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 78 | write!(formatter, "{} bytes", B) |
| 79 | } |
| 80 | } |