scale_bits/bits/
serde.rs

1// Copyright (C) 2024 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the scale-value crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::Bits;
17use serde::{
18	de::{self, Deserializer, Visitor},
19	ser::SerializeSeq,
20	Deserialize, Serialize, Serializer,
21};
22
23impl Serialize for Bits {
24	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
25	where
26		S: Serializer,
27	{
28		let mut seq = serializer.serialize_seq(Some(self.len()))?;
29		for b in self.iter() {
30			seq.serialize_element(&b)?;
31		}
32		seq.end()
33	}
34}
35
36impl<'de> Deserialize<'de> for Bits {
37	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
38	where
39		D: Deserializer<'de>,
40	{
41		struct BitsVisitor;
42
43		impl<'de> Visitor<'de> for BitsVisitor {
44			type Value = Bits;
45
46			fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
47				formatter.write_str("a sequence of booleans")
48			}
49
50			fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
51			where
52				A: de::SeqAccess<'de>,
53			{
54				let prealloc_len = seq.size_hint().unwrap_or(0);
55				let mut bits = Bits::with_capacity(prealloc_len);
56				while let Some(b) = seq.next_element()? {
57					bits.push(b);
58				}
59				Ok(bits)
60			}
61		}
62
63		deserializer.deserialize_seq(BitsVisitor)
64	}
65}
66
67#[cfg(test)]
68mod test {
69	use crate::bits::Bits;
70	use alloc::vec;
71
72	#[test]
73	fn ser_deser_bits() {
74		let checks =
75			vec![(bits![], "[]"), (bits![true], "[true]"), (bits![false, true], "[false,true]")];
76
77		for (bits, json) in checks {
78			// test serializing.
79			assert_eq!(serde_json::to_string(&bits).unwrap(), json);
80			// test deserializing:
81			assert_eq!(serde_json::from_str::<Bits>(json).unwrap(), bits);
82		}
83	}
84}