madig / glyphsrw-rs

Toy tool to play with the structure of the https://glyphsapp.com/ file format.
MIT License
2 stars 0 forks source link

How to implement String to custom struct parsing? #1

Open madig opened 4 years ago

madig commented 4 years ago

E.g. this:

#[derive(Serialize, Deserialize, Debug)]
struct AlignmentZone {
    position: i32,
    size: i32,
}

impl FromStr for AlignmentZone {
    type Err = std::num::ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let alignment_zone: Vec<&str> = s
            .trim_matches(|p| p == '{' || p == '}')
            .split(',')
            .collect();
        let position: i32 = alignment_zone[0].parse()?;
        let size: i32 = alignment_zone[1].parse()?;
        Ok(AlignmentZone {
            position: position,
            size: size,
        })
    }
}

Can this be done without dealing with serde's visitor pattern?

RickyDaMa commented 1 year ago

Yes. Use #[serde(deserialize_with = "your_fn")] where your_fn deserialises to String, then uses the FromStr impl and changes the result to the correct type