Skip to main content

iri_s/iri/
visitor.rs

1use crate::error::IriSError;
2use crate::iri::IriS;
3use serde::de::{Error, Visitor};
4use serde::{Deserialize, Deserializer};
5use std::fmt::Formatter;
6use std::str::FromStr;
7
8struct IriVisitor;
9
10impl Visitor<'_> for IriVisitor {
11    type Value = IriS;
12
13    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
14        formatter.write_str("an IRI")
15    }
16
17    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
18    where
19        E: Error,
20    {
21        match IriS::from_str(v) {
22            Ok(iri) => Ok(iri),
23            Err(IriSError::IriParseError { str, error: err }) => Err(E::custom(format!(
24                "Error parsing \"{v}\" as IRI. String \"{str}\", Error: {err}"
25            ))),
26            Err(other) => Err(E::custom(format!("Can not parse value \"{v}\" to IRI. Error: {other}"))),
27        }
28    }
29}
30
31impl<'de> Deserialize<'de> for IriS {
32    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
33    where
34        D: Deserializer<'de>,
35    {
36        deserializer.deserialize_str(IriVisitor)
37    }
38}