libobs_wrapper\utils/path.rs
1use std::{env, path::{Path, PathBuf}};
2
3use super::ObsString;
4
5
6
7/// Builds into an `ObsString` that represents a path used
8/// by libobs.
9///
10/// Note that only this path only supports UTF-8 for the
11/// entire absolute path because libobs only supports
12/// UTF-8.
13#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
14pub struct ObsPath {
15 path: PathBuf,
16}
17
18impl ObsPath {
19 /// Creates a new `ObsPath` strictly using the path
20 /// `path_str` without any modifications.
21 ///
22 /// If you want to create a relative path, use
23 /// `ObsPath::from_relative`.
24 pub fn new(path_str: &str) -> Self {
25 Self {
26 path: Path::new(path_str).into(),
27 }
28 }
29
30 /// Creates a new `ObsPath` with `path_str`
31 /// appended to the path of the directory which the
32 /// executable file is in.
33 ///
34 /// If you want to create an absolute path, use
35 /// `ObsPath::new`.
36 pub fn from_relative(path_str: &str) -> Self {
37 let mut relative_path = env::current_exe().unwrap();
38
39 relative_path.pop();
40
41 let obs_path = Self {
42 path: relative_path,
43 };
44
45 let path_str = path_str.trim_matches('/');
46
47 obs_path.push(path_str)
48 }
49
50 /// Modifies the path to point to the path
51 /// `path_str` appended to the current path which
52 /// `ObsPath` is pointing to.
53 pub fn push(mut self, value: &str) -> Self {
54 let split = value.split(['/', '\\'].as_ref());
55
56 for item in split {
57 if item.len() > 0 {
58 self.path.push(item);
59 }
60 }
61
62 self
63 }
64
65 /// Modifies the path to point to its current
66 /// parent. This is analogous to `Obs::push(".")`.
67 pub fn pop(mut self) -> Self {
68 self.path.pop();
69 self
70 }
71
72 /// Consumes the `ObsPath` to create a new
73 /// immutable ObsString that encodes a UTF-8
74 /// C-type string which describes the path that
75 /// the `ObsPath` is pointing to.
76 ///
77 /// Note that this function is lossy in that
78 /// any non-Unicode data is completely removed
79 /// from the string. This is because libobs
80 /// does not support non-Unicode characters in
81 /// its path.
82 pub fn build(self) -> ObsString {
83 let mut bytes = self.path.display().to_string().replace("\\", "/");
84
85 if self.path.is_dir() {
86 bytes = bytes + "/";
87 }
88 let obs_string = ObsString::from(bytes.as_str());
89
90 drop(self);
91 obs_string
92 }
93}
94
95impl Into<ObsString> for ObsPath {
96 fn into(self) -> ObsString {
97 self.build()
98 }
99}