librojo/
path_serializer.rs

1//! Path serializer is used to serialize absolute paths in a cross-platform way,
2//! by replacing all directory separators with /.
3
4use std::path::Path;
5
6use serde::{ser::SerializeSeq, Serialize, Serializer};
7
8pub fn serialize_absolute<S, T>(path: T, serializer: S) -> Result<S::Ok, S::Error>
9where
10    S: Serializer,
11    T: AsRef<Path>,
12{
13    let as_str = path
14        .as_ref()
15        .as_os_str()
16        .to_str()
17        .expect("Invalid Unicode in file path, cannot serialize");
18    let replaced = as_str.replace('\\', "/");
19
20    serializer.serialize_str(&replaced)
21}
22
23#[derive(Serialize)]
24struct WithAbsolute<'a>(#[serde(serialize_with = "serialize_absolute")] &'a Path);
25
26pub fn serialize_vec_absolute<S, T>(paths: &[T], serializer: S) -> Result<S::Ok, S::Error>
27where
28    S: Serializer,
29    T: AsRef<Path>,
30{
31    let mut seq = serializer.serialize_seq(Some(paths.len()))?;
32
33    for path in paths {
34        seq.serialize_element(&WithAbsolute(path.as_ref()))?;
35    }
36
37    seq.end()
38}