Skip to main content

robius_common/
lib.rs

1use std::path::{Path, PathBuf};
2
3/// The platform-specific location of a file-like item (a file or a content URI).
4///
5/// Most platforms expose selected or shareable files as normal fs paths,
6/// but Android exposes them as platform URIs (like `content://...`),
7/// so this type abstracts that away.
8#[derive(Clone, Debug, PartialEq, Eq, Hash)]
9pub enum FileLocation {
10    /// A normal filesystem path.
11    Path(PathBuf),
12    /// A platform URI, such as an Android `content://` URI.
13    Uri(String),
14}
15
16impl FileLocation {
17    /// Creates a file location from a filesystem path.
18    pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
19        Self::Path(path.as_ref().to_owned())
20    }
21
22    /// Creates a file location from a platform URI.
23    pub fn from_uri(uri: impl Into<String>) -> Self {
24        Self::Uri(uri.into())
25    }
26
27    /// Returns this location as a filesystem path, if it is one.
28    pub fn path(&self) -> Option<&Path> {
29        match self {
30            Self::Path(path) => Some(path),
31            Self::Uri(_) => None,
32        }
33    }
34
35    /// Returns this location as a platform URI, if it is one.
36    pub fn uri(&self) -> Option<&str> {
37        match self {
38            Self::Path(_) => None,
39            Self::Uri(uri) => Some(uri),
40        }
41    }
42
43    /// Consumes this location and returns its filesystem path, if it is one.
44    pub fn into_path(self) -> Option<PathBuf> {
45        match self {
46            Self::Path(path) => Some(path),
47            Self::Uri(_) => None,
48        }
49    }
50
51    /// Consumes this location and returns its platform URI, if it is one.
52    pub fn into_uri(self) -> Option<String> {
53        match self {
54            Self::Path(_) => None,
55            Self::Uri(uri) => Some(uri),
56        }
57    }
58}