luminol_data/helpers/
optional_path_serde.rs

1// Copyright (C) 2024 Melody Madeline Lyons
2//
3// This file is part of Luminol.
4//
5// Luminol is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Luminol is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Luminol.  If not, see <http://www.gnu.org/licenses/>.
17use camino::Utf8PathBuf;
18
19pub fn serialize<S>(path: &Option<Utf8PathBuf>, serializer: S) -> Result<S::Ok, S::Error>
20where
21    S: serde::Serializer,
22{
23    match path {
24        Some(path) => serializer.serialize_str(path.as_str()),
25        None => serializer.serialize_str(""),
26    }
27}
28
29pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Utf8PathBuf>, D::Error>
30where
31    D: serde::Deserializer<'de>,
32{
33    struct Visitor;
34
35    impl serde::de::Visitor<'_> for Visitor {
36        type Value = Option<Utf8PathBuf>;
37
38        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39            formatter.write_str("a string")
40        }
41
42        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
43        where
44            E: serde::de::Error,
45        {
46            if v.is_empty() {
47                Ok(None)
48            } else {
49                Ok(Some(v.into()))
50            }
51        }
52
53        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
54        where
55            E: serde::de::Error,
56        {
57            if v.is_empty() {
58                Ok(None)
59            } else {
60                Ok(Some(v.into()))
61            }
62        }
63    }
64
65    deserializer.deserialize_string(Visitor)
66}