Skip to main content

mux_media/types/
target.rs

1use crate::{ArcPathBuf, Msg, Result, StreamType};
2use std::{
3    borrow::Borrow,
4    ffi::OsStr,
5    fs,
6    hash::{Hash, Hasher},
7    path::Path,
8};
9
10/// A target of [`ConfigTarget`](crate::ConfigTarget).
11#[derive(Clone, Debug)]
12pub enum Target {
13    Global,
14    Stream(StreamType),
15    Path(ArcPathBuf),
16}
17
18impl Target {
19    /// Tries construct [`Target`] from an os string.
20    pub fn new<OS: AsRef<OsStr>>(os: OS) -> Result<Target> {
21        let os = os.as_ref();
22
23        if let Some(t) = os.to_str().and_then(|s| get_from_str(s)) {
24            return Ok(t);
25        }
26
27        let path = fs::canonicalize(os)
28            .map_err(|e| err!("Incorrect path target '{}': {}", Path::new(os).display(), e))?;
29
30        return Ok(Self::Path(path.into()));
31
32        fn get_from_str(s: &str) -> Option<Target> {
33            let s = s.trim().to_ascii_lowercase();
34            if matches!(s.as_str(), "g" | "global") {
35                Some(Target::Global)
36            } else if let Ok(ty) = s.parse::<StreamType>() {
37                Some(Target::Stream(ty))
38            } else {
39                None
40            }
41        }
42    }
43
44    pub(crate) fn to_str(&self) -> Option<&str> {
45        match self {
46            Self::Global => Some("global"),
47            Self::Stream(ty) => Some(ty.as_ref()),
48            Self::Path(p) => p.to_str(),
49        }
50    }
51
52    /// Returns a [`Path`] representation.
53    pub(crate) fn as_path(&self) -> &Path {
54        match self {
55            Self::Global => Path::new("global"),
56            Self::Stream(ty) => ty.as_path(),
57            Self::Path(apb) => apb.as_path(),
58        }
59    }
60
61    /// Prints the list of supported targets to stdout.
62    pub(crate) fn print_list_targets() {
63        println!("{}", Msg::ListTargets.as_str_localized());
64    }
65}
66
67impl AsRef<Path> for Target {
68    fn as_ref(&self) -> &Path {
69        self.as_path()
70    }
71}
72
73impl Borrow<Path> for Target {
74    fn borrow(&self) -> &Path {
75        self.as_path()
76    }
77}
78
79impl PartialEq for Target {
80    fn eq(&self, other: &Self) -> bool {
81        self.as_path() == other.as_path()
82    }
83}
84impl Eq for Target {}
85
86impl Hash for Target {
87    fn hash<H: Hasher>(&self, state: &mut H) {
88        self.as_path().hash(state)
89    }
90}