tauri_plugin_android_fs/models/
file_uri.rs1use serde::{Deserialize, Serialize};
2
3
4#[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize, Serialize)]
27#[serde(rename_all = "camelCase")]
28pub struct FileUri {
29 pub uri: String,
31
32 pub document_top_tree_uri: Option<String>,
34}
35
36impl FileUri {
37
38 #[deprecated = "Confusing name. Use FileUri::to_json_string instead"]
40 pub fn to_string(&self) -> crate::Result<String> {
41 serde_json::to_string(self).map_err(Into::into)
42 }
43
44 #[deprecated = "Confusing name. Use FileUri::from_json_str instead"]
46 pub fn from_str(s: &str) -> crate::Result<Self> {
47 serde_json::from_str(s).map_err(Into::into)
48 }
49
50 pub fn to_json_string(&self) -> crate::Result<String> {
51 serde_json::to_string(self).map_err(Into::into)
52 }
53
54 pub fn from_json_str(json: impl AsRef<str>) -> crate::Result<Self> {
55 serde_json::from_str(json.as_ref()).map_err(Into::into)
56 }
57
58 pub fn to_bytes(&self) -> crate::Result<Vec<u8>> {
59 serde_json::to_vec(self).map_err(Into::into)
60 }
61
62 pub fn from_bytes(bytes: impl AsRef<[u8]>) -> crate::Result<Self> {
63 serde_json::from_slice(bytes.as_ref()).map_err(Into::into)
64 }
65
66 pub fn from_path(path: impl AsRef<std::path::Path>) -> Self {
67 Self { uri: format!("file://{}", path.as_ref().to_string_lossy()), document_top_tree_uri: None }
68 }
69
70 #[allow(unused)]
71 pub(crate) fn as_path(&self) -> Option<&std::path::Path> {
72 if self.uri.starts_with("file://") {
73 return Some(std::path::Path::new(self.uri.trim_start_matches("file://")))
74 }
75 None
76 }
77}
78
79impl From<&std::path::Path> for FileUri {
80
81 fn from(path: &std::path::Path) -> Self {
82 Self::from_path(path)
83 }
84}
85
86impl From<&std::path::PathBuf> for FileUri {
87
88 fn from(path: &std::path::PathBuf) -> Self {
89 Self::from_path(path)
90 }
91}
92
93impl From<std::path::PathBuf> for FileUri {
94
95 fn from(path: std::path::PathBuf) -> Self {
96 Self::from_path(path)
97 }
98}
99
100#[cfg(feature = "tauri-plugin-fs")]
101impl From<tauri_plugin_fs::FilePath> for FileUri {
102
103 fn from(value: tauri_plugin_fs::FilePath) -> Self {
104 match value {
105 tauri_plugin_fs::FilePath::Url(url) => Self { uri: url.to_string(), document_top_tree_uri: None },
106 tauri_plugin_fs::FilePath::Path(path_buf) => path_buf.into(),
107 }
108 }
109}
110
111#[cfg(feature = "tauri-plugin-fs")]
112impl From<FileUri> for tauri_plugin_fs::FilePath {
113
114 fn from(value: FileUri) -> Self {
115 type NeverErr<T> = std::result::Result::<T, std::convert::Infallible>;
116 NeverErr::unwrap(value.uri.parse())
117 }
118}