Skip to main content

user_agent_parser/models/
os.rs

1use std::borrow::Cow;
2
3use super::version::join_version;
4
5/// The operating system a user agent runs on.
6#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
7pub struct OS<'a> {
8    /// The OS family, which falls back to `Some("Other")` when no pattern matches.
9    pub name:        Option<Cow<'a, str>>,
10    /// The major version, if the matching pattern captures one.
11    pub major:       Option<Cow<'a, str>>,
12    /// The minor version, if the matching pattern captures one.
13    pub minor:       Option<Cow<'a, str>>,
14    /// The patch version, if the matching pattern captures one.
15    pub patch:       Option<Cow<'a, str>>,
16    /// The patch minor version, if the matching pattern captures one.
17    pub patch_minor: Option<Cow<'a, str>>,
18}
19
20impl<'a> OS<'a> {
21    /// Joins the version parts into a full version string, stopping at the first part which is missing.
22    ///
23    /// ```
24    /// use std::borrow::Cow;
25    ///
26    /// use user_agent_parser::OS;
27    ///
28    /// let os = OS {
29    ///     name:        Some(Cow::from("Mac OS X")),
30    ///     major:       Some(Cow::from("10")),
31    ///     minor:       Some(Cow::from("15")),
32    ///     patch:       Some(Cow::from("7")),
33    ///     patch_minor: None,
34    /// };
35    ///
36    /// assert_eq!(Some(Cow::from("10.15.7")), os.version());
37    /// ```
38    #[inline]
39    pub fn version(&self) -> Option<Cow<'_, str>> {
40        join_version(&[
41            self.major.as_deref(),
42            self.minor.as_deref(),
43            self.patch.as_deref(),
44            self.patch_minor.as_deref(),
45        ])
46    }
47
48    /// Extracts the owned data.
49    #[inline]
50    pub fn into_owned(self) -> OS<'static> {
51        let name = self.name.map(|c| Cow::from(c.into_owned()));
52        let major = self.major.map(|c| Cow::from(c.into_owned()));
53        let minor = self.minor.map(|c| Cow::from(c.into_owned()));
54        let patch = self.patch.map(|c| Cow::from(c.into_owned()));
55        let patch_minor = self.patch_minor.map(|c| Cow::from(c.into_owned()));
56
57        OS {
58            name,
59            major,
60            minor,
61            patch,
62            patch_minor,
63        }
64    }
65}