Skip to main content

workyard_state/
path.rs

1//! Private lossless path encoding. Plain Unicode paths stay readable.
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5/// Lossless on-disk representation of a native path.
6#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
7#[serde(untagged)]
8pub enum StoredPath {
9	/// A path representable as Unicode text.
10	Text(String),
11	/// Unix path bytes.
12	Unix {
13		/// Original Unix filename bytes.
14		unix: Vec<u8>,
15	},
16	/// Windows wide path units.
17	Windows {
18		/// Original Windows UTF-16 code units.
19		windows: Vec<u16>,
20	},
21}
22
23impl From<&std::path::Path> for StoredPath {
24	fn from(path: &std::path::Path) -> Self {
25		if let Some(text) = path.to_str() {
26			return Self::Text(text.into());
27		}
28		#[cfg(unix)]
29		{
30			use std::os::unix::ffi::OsStrExt;
31			Self::Unix {
32				unix: path.as_os_str().as_bytes().to_vec(),
33			}
34		}
35		#[cfg(windows)]
36		{
37			use std::os::windows::ffi::OsStrExt;
38			Self::Windows {
39				windows: path.as_os_str().encode_wide().collect(),
40			}
41		}
42	}
43}
44
45impl StoredPath {
46	pub(crate) fn registration(&self) -> Result<PathBuf, workyard_core::Problem> {
47		let path = self.decode()?;
48		if !path.is_absolute() || path.as_os_str().as_encoded_bytes().contains(&0) {
49			return Err(crate::damage::damaged(
50				"Invalid absolute project registration in task evidence.",
51			));
52		}
53		Ok(path)
54	}
55
56	/// Convert persisted data into the domain representation.
57	pub fn decode(&self) -> Result<PathBuf, workyard_core::Problem> {
58		match self {
59			Self::Text(text) => Ok(text.into()),
60			#[cfg(unix)]
61			Self::Unix { unix } => {
62				use std::os::unix::ffi::OsStringExt;
63				Ok(std::ffi::OsString::from_vec(unix.clone()).into())
64			}
65			#[cfg(windows)]
66			Self::Windows { windows } => {
67				use std::os::windows::ffi::OsStringExt;
68				Ok(std::ffi::OsString::from_wide(windows).into())
69			}
70			_ => Err(workyard_core::Problem::new(
71				workyard_core::ProblemCode::IncompatibleState,
72				"State contains paths from another OS.",
73			)),
74		}
75	}
76}