Skip to main content

objdiff_core/config/
path.rs

1// For argp::FromArgs
2#[cfg(feature = "std")]
3pub fn platform_path(value: &str) -> Result<typed_path::Utf8PlatformPathBuf, String> {
4    Ok(typed_path::Utf8PlatformPathBuf::from(value))
5}
6
7/// Checks if the path is valid UTF-8 and returns it as a [`Utf8PlatformPath`].
8#[cfg(feature = "std")]
9pub fn check_path(
10    path: &std::path::Path,
11) -> Result<&typed_path::Utf8PlatformPath, core::str::Utf8Error> {
12    typed_path::Utf8PlatformPath::from_bytes_path(typed_path::PlatformPath::new(
13        path.as_os_str().as_encoded_bytes(),
14    ))
15}
16
17/// Checks if the path is valid UTF-8 and returns it as a [`Utf8NativePathBuf`].
18#[cfg(feature = "std")]
19pub fn check_path_buf(
20    path: std::path::PathBuf,
21) -> Result<typed_path::Utf8PlatformPathBuf, alloc::string::FromUtf8Error> {
22    typed_path::Utf8PlatformPathBuf::from_bytes_path_buf(typed_path::PlatformPathBuf::from(
23        path.into_os_string().into_encoded_bytes(),
24    ))
25}
26
27#[cfg(feature = "serde")]
28pub mod unix_path_serde_option {
29    use serde::{Deserialize, Deserializer, Serializer};
30    use typed_path::Utf8UnixPathBuf;
31
32    pub fn serialize<S>(path: &Option<Utf8UnixPathBuf>, s: S) -> Result<S::Ok, S::Error>
33    where S: Serializer {
34        if let Some(path) = path { s.serialize_some(path.as_str()) } else { s.serialize_none() }
35    }
36
37    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Utf8UnixPathBuf>, D::Error>
38    where D: Deserializer<'de> {
39        Ok(Option::<String>::deserialize(deserializer)?.map(Utf8UnixPathBuf::from))
40    }
41}
42
43#[cfg(all(feature = "serde", feature = "std"))]
44pub mod platform_path_serde_option {
45    use serde::{Deserialize, Deserializer, Serializer};
46    use typed_path::Utf8PlatformPathBuf;
47
48    pub fn serialize<S>(path: &Option<Utf8PlatformPathBuf>, s: S) -> Result<S::Ok, S::Error>
49    where S: Serializer {
50        if let Some(path) = path { s.serialize_some(path.as_str()) } else { s.serialize_none() }
51    }
52
53    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Utf8PlatformPathBuf>, D::Error>
54    where D: Deserializer<'de> {
55        Ok(Option::<String>::deserialize(deserializer)?.map(Utf8PlatformPathBuf::from))
56    }
57}