Debian Codegraph @

debian/rust-vendor/tinystr/src/serde.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::TinyAsciiStr;
6 use core::fmt;
7 use core::marker::PhantomData;
8 use core::ops::Deref;
9 use serde_core::de::{Error, SeqAccess, Visitor};
10 use serde_core::ser::SerializeTuple;
11 use serde_core::{Deserialize, Deserializer, Serialize, Serializer};
12
13 impl<const N: usize> Serialize for TinyAsciiStr<N> {
14 #[inline]
15 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
16 where
17 S: Serializer,
18 {
19 if serializer.is_human_readable() {
20 self.deref().serialize(serializer)
21 } else {
22 let mut seq = serializer.serialize_tuple(N)?;
23 for byte in self.all_bytes() {
24 seq.serialize_element(byte)?;
25 }
26 seq.end()
27 }
28 }
29 }
30
31 struct TinyAsciiStrVisitor<const N: usize> {
32 marker: PhantomData<TinyAsciiStr<N>>,
33 }
34
35 impl<const N: usize> TinyAsciiStrVisitor<N> {
36 fn new() -> Self {
37 TinyAsciiStrVisitor {
38 marker: PhantomData,
39 }
40 }
41 }
42
43 impl<'de, const N: usize> Visitor<'de> for TinyAsciiStrVisitor<N> {
44 type Value = TinyAsciiStr<N>;
45
46 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
47 write!(formatter, "a TinyAsciiStr<{N}>")
48 }
49
50 #[inline]
51 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
52 where
53 A: SeqAccess<'de>,
54 {
55 let mut bytes = [0u8; N];
56 let mut zeroes = false;
57 for out in &mut bytes.iter_mut().take(N) {
58 let byte = seq
59 .next_element()?
60 .ok_or_else(|| Error::invalid_length(N, &self))?;
61 if byte == 0 {
62 zeroes = true;
63 } else if zeroes {
64 return Err(Error::custom("TinyAsciiStr cannot contain null bytes"));
65 }
66
67 if byte >= 0x80 {
68 return Err(Error::custom("TinyAsciiStr cannot contain non-ascii bytes"));
69 }
70 *out = byte;
71 }
72
73 Ok(unsafe { TinyAsciiStr::from_utf8_unchecked(bytes) })
74 }
75 }
76
77 impl<'de, const N: usize> Deserialize<'de> for TinyAsciiStr<N> {
78 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79 where
80 D: Deserializer<'de>,
81 {
82 if deserializer.is_human_readable() {
83 struct HumanVisitor<const N: usize>;
84 impl<'de, const M: usize> Visitor<'de> for HumanVisitor<M> {
85 type Value = TinyAsciiStr<M>;
86
87 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
88 write!(formatter, "a TinyAsciiStr<{M}>")
89 }
90
91 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
92 where
93 E: Error,
94 {
95 TinyAsciiStr::try_from_str(v).map_err(|_| Error::custom("invalid str"))
96 }
97 }
98 deserializer.deserialize_str(HumanVisitor::<N>)
99 } else {
100 deserializer.deserialize_tuple(N, TinyAsciiStrVisitor::<N>::new())
101 }
102 }
103 }