rosu_map/util/
str_ext.rs

1use crate::util::{ParseNumber, ParseNumberError};
2
3/// Extension methods for `str` which are commonly used in and around this library.
4pub trait StrExt {
5    /// Trim trailing comments and whitespace.
6    fn trim_comment(&self) -> &str;
7
8    /// Parse `&str` to a number without exceeding [`MAX_PARSE_VALUE`].
9    ///
10    /// [`MAX_PARSE_VALUE`]: crate::util::MAX_PARSE_VALUE
11    fn parse_num<N: ParseNumber>(&self) -> Result<N, ParseNumberError>;
12
13    /// Parse `&str` to a number without exceeding the given limit.
14    fn parse_with_limits<N: ParseNumber>(&self, limit: N) -> Result<N, ParseNumberError>;
15
16    /// Replace windows path separators with unix ones.
17    fn to_standardized_path(&self) -> String;
18
19    /// Fix path and quotation segments to normalize filenames.
20    fn clean_filename(&self) -> String;
21}
22
23impl StrExt for str {
24    fn trim_comment(&self) -> &str {
25        self.find("//").map_or(self, |i| &self[..i]).trim_end()
26    }
27
28    fn parse_num<N: ParseNumber>(&self) -> Result<N, ParseNumberError> {
29        N::parse(self)
30    }
31
32    fn parse_with_limits<N: ParseNumber>(&self, limit: N) -> Result<N, ParseNumberError> {
33        N::parse_with_limits(self, limit)
34    }
35
36    fn to_standardized_path(&self) -> String {
37        self.replace('\\', "/")
38    }
39
40    fn clean_filename(&self) -> String {
41        self.trim_matches('"')
42            .replace("\\\\", "\\")
43            .to_standardized_path()
44    }
45}