Skip to main content

ftracker_identifiers/cnpj/
serde.rs

1//! `Serialize`/`Deserialize` for [`Cnpj`], gated behind the `serde` feature.
2//!
3//! `Cnpj` (de)serializes as its unformatted 14-character string (e.g. `"12ABC34501DE35"`), not the
4//! punctuated display form, so that it round-trips as a plain identifier in JSON/config files.
5//! Deserializing always re-runs full validation; an untrusted payload can never produce an invalid `Cnpj`.
6
7use ::serde::de::{self, Visitor};
8use ::serde::{Deserialize, Deserializer, Serialize, Serializer};
9use core::fmt;
10
11use super::Cnpj;
12
13impl Serialize for Cnpj {
14    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
15    where
16        S: Serializer,
17    {
18        serializer.serialize_str(self.as_str())
19    }
20}
21
22struct CnpjVisitor;
23
24impl<'de> Visitor<'de> for CnpjVisitor {
25    type Value = Cnpj;
26
27    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str("a 14-character CNPJ, optionally punctuated as AA.AAA.AAA/AAAA-DD")
29    }
30
31    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
32    where
33        E: de::Error,
34    {
35        Cnpj::parse(v).map_err(de::Error::custom)
36    }
37}
38
39impl<'de> Deserialize<'de> for Cnpj {
40    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
41    where
42        D: Deserializer<'de>,
43    {
44        deserializer.deserialize_str(CnpjVisitor)
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::super::Cnpj;
51
52    #[test]
53    fn round_trips_through_json() {
54        let cnpj = Cnpj::parse("00.000.000/0001-91").unwrap();
55        let json = serde_json::to_string(&cnpj).unwrap();
56        assert_eq!(json, "\"00000000000191\"");
57        let back: Cnpj = serde_json::from_str(&json).unwrap();
58        assert_eq!(cnpj, back);
59    }
60
61    #[test]
62    fn rejects_invalid_json_string() {
63        let err = serde_json::from_str::<Cnpj>("\"not-a-cnpj\"").unwrap_err();
64        assert!(err.to_string().contains("CNPJ"));
65    }
66}