use core::fmt;
use std::sync::OnceLock;
use crate::parse;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Kind {
Linux,
Windows,
MacOs,
Android,
Ios,
FreeBsd,
OpenBsd,
NetBsd,
Other,
}
impl Kind {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Linux => "linux",
Self::Windows => "windows",
Self::MacOs => "macos",
Self::Android => "android",
Self::Ios => "ios",
Self::FreeBsd => "freebsd",
Self::OpenBsd => "openbsd",
Self::NetBsd => "netbsd",
Self::Other => "other",
}
}
}
#[must_use]
pub const fn kind() -> Kind {
if cfg!(target_os = "android") {
Kind::Android
} else if cfg!(target_os = "linux") {
Kind::Linux
} else if cfg!(target_os = "windows") {
Kind::Windows
} else if cfg!(target_os = "macos") {
Kind::MacOs
} else if cfg!(target_os = "ios") {
Kind::Ios
} else if cfg!(target_os = "freebsd") {
Kind::FreeBsd
} else if cfg!(target_os = "openbsd") {
Kind::OpenBsd
} else if cfg!(target_os = "netbsd") {
Kind::NetBsd
} else {
Kind::Other
}
}
#[must_use]
pub const fn is_windows() -> bool {
cfg!(target_os = "windows")
}
#[must_use]
pub const fn is_linux() -> bool {
cfg!(target_os = "linux")
}
#[must_use]
pub const fn is_macos() -> bool {
cfg!(target_os = "macos")
}
#[must_use]
pub const fn is_mac() -> bool {
is_macos()
}
#[must_use]
pub const fn is_android() -> bool {
cfg!(target_os = "android")
}
#[must_use]
pub const fn is_ios() -> bool {
cfg!(target_os = "ios")
}
#[must_use]
pub const fn is_unix() -> bool {
cfg!(unix)
}
#[must_use]
pub const fn is_bsd() -> bool {
cfg!(any(
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
))
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[non_exhaustive]
pub struct Version {
pub major: u32,
pub minor: u32,
pub patch: u32,
pub build: Option<u32>,
pub text: &'static str,
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.text)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Source {
OsRelease,
UsrLibOsRelease,
LegacyRelease,
Sysctl,
Registry,
SystemProperty,
Fallback,
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct OsRelease {
pub id: &'static str,
pub id_like: &'static [&'static str],
pub name: &'static str,
pub pretty_name: &'static str,
pub version: Option<&'static str>,
pub version_id: Option<&'static str>,
pub codename: Option<&'static str>,
pub variant_id: Option<&'static str>,
pub build_id: Option<&'static str>,
pub source: Source,
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct OsInfo {
pub kind: Kind,
pub name: &'static str,
pub version: Option<&'static Version>,
pub kernel: &'static str,
pub distro: &'static str,
pub distro_id: &'static str,
pub os_release: Option<&'static OsRelease>,
pub edition: Option<&'static str>,
pub codename: Option<&'static str>,
pub is_64bit: bool,
pub name_source: Source,
}
#[must_use]
pub fn name() -> &'static str {
info().name
}
#[must_use]
pub fn version() -> Option<&'static Version> {
info().version
}
#[must_use]
pub fn kernel() -> &'static str {
info().kernel
}
#[must_use]
pub fn distro() -> &'static str {
info().distro
}
#[must_use]
pub fn distro_id() -> &'static str {
info().distro_id
}
#[must_use]
pub fn is_like(id: &str) -> bool {
let info = info();
info.distro_id == id
|| info
.os_release
.is_some_and(|r| r.id == id || r.id_like.contains(&id))
}
#[must_use]
pub fn os_release() -> Option<&'static OsRelease> {
info().os_release
}
#[must_use]
pub fn edition() -> Option<&'static str> {
info().edition
}
#[must_use]
pub fn codename() -> Option<&'static str> {
info().codename
}
#[must_use]
pub fn is_server_edition() -> Option<bool> {
static SERVER: OnceLock<Option<bool>> = OnceLock::new();
*SERVER.get_or_init(crate::sys::is_server_edition)
}
#[must_use]
pub fn is_64bit() -> bool {
info().is_64bit
}
#[must_use]
pub fn info() -> &'static OsInfo {
static INFO: OnceLock<OsInfo> = OnceLock::new();
INFO.get_or_init(|| from_facts(crate::sys::os()))
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum FormFactor {
Desktop,
Laptop,
Convertible,
Tablet,
Phone,
Handheld,
Server,
Embedded,
Wearable,
Tv,
Unknown,
}
impl FormFactor {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Desktop => "desktop",
Self::Laptop => "laptop",
Self::Convertible => "convertible",
Self::Tablet => "tablet",
Self::Phone => "phone",
Self::Handheld => "handheld",
Self::Server => "server",
Self::Embedded => "embedded",
Self::Wearable => "wearable",
Self::Tv => "tv",
Self::Unknown => "unknown",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Detection<T> {
pub value: T,
pub source: &'static str,
pub confidence: Confidence,
}
impl<T> Detection<T> {
pub(crate) const fn new(value: T, source: &'static str, confidence: Confidence) -> Self {
Self {
value,
source,
confidence,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[non_exhaustive]
pub enum Confidence {
None,
Low,
Medium,
High,
}
#[must_use]
pub fn form_factor() -> FormFactor {
detect_form_factor().value
}
#[must_use]
pub fn detect_form_factor() -> &'static Detection<FormFactor> {
static FACT: OnceLock<Detection<FormFactor>> = OnceLock::new();
FACT.get_or_init(crate::sys::form_factor)
}
#[must_use]
pub fn is_desktop() -> bool {
form_factor() == FormFactor::Desktop
}
#[must_use]
pub fn is_laptop() -> bool {
matches!(form_factor(), FormFactor::Laptop | FormFactor::Convertible)
}
#[must_use]
pub fn is_mobile() -> bool {
matches!(
form_factor(),
FormFactor::Phone | FormFactor::Tablet | FormFactor::Handheld | FormFactor::Wearable
)
}
#[must_use]
pub fn is_phone() -> bool {
form_factor() == FormFactor::Phone
}
#[must_use]
pub fn is_tablet() -> bool {
form_factor() == FormFactor::Tablet
}
#[must_use]
pub fn is_server() -> bool {
form_factor() == FormFactor::Server
}
#[cfg_attr(any(target_vendor = "apple", target_os = "android"), allow(dead_code))]
pub(crate) const fn form_from_chassis(chassis: u8) -> Option<FormFactor> {
Some(match chassis {
0x03 | 0x04 | 0x06 | 0x07 | 0x0D | 0x23 | 0x24 => FormFactor::Desktop,
0x08 | 0x09 | 0x0A | 0x0E => FormFactor::Laptop,
0x0B => FormFactor::Handheld,
0x11 | 0x17 | 0x19 | 0x1C | 0x1D => FormFactor::Server,
0x1E => FormFactor::Tablet,
0x1F | 0x20 => FormFactor::Convertible,
0x21 | 0x22 => FormFactor::Embedded,
_ => return None,
})
}
#[cfg_attr(any(target_vendor = "apple", target_os = "android"), allow(dead_code))]
pub(crate) const fn form_from_pm_profile(profile: u8) -> Option<FormFactor> {
Some(match profile {
1 | 3 | 6 => FormFactor::Desktop,
2 => FormFactor::Laptop,
4 | 5 | 7 => FormFactor::Server,
8 => FormFactor::Tablet,
_ => return None,
})
}
pub(crate) fn keep(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn keep_opt(s: Option<String>) -> Option<&'static str> {
s.map(keep)
}
pub(crate) fn from_facts(f: crate::sys::OsFacts) -> OsInfo {
let version = f.version.as_deref().and_then(|text| {
let (major, minor, patch, build) = parse::version::parse(text)?;
Some(&*Box::leak(Box::new(Version {
major,
minor,
patch,
build,
text: keep(text.to_owned()),
})))
});
let os_release = f.release.map(|r| {
let id_like: Vec<&'static str> = r.id_like.into_iter().map(keep).collect();
let name = r.name.unwrap_or_else(|| "Linux".to_owned());
&*Box::leak(Box::new(OsRelease {
id: keep(r.id.unwrap_or_else(|| "linux".to_owned())),
id_like: Box::leak(id_like.into_boxed_slice()),
pretty_name: keep(r.pretty_name.unwrap_or_else(|| name.clone())),
name: keep(name),
version: keep_opt(r.version),
version_id: keep_opt(r.version_id),
codename: keep_opt(r.codename),
variant_id: keep_opt(r.variant_id),
build_id: keep_opt(r.build_id),
source: r.source,
}))
});
OsInfo {
kind: kind(),
name: keep(f.name),
version,
kernel: keep(f.kernel),
distro: keep(f.distro),
distro_id: keep(f.distro_id),
os_release,
edition: keep_opt(f.edition),
codename: keep_opt(f.codename),
is_64bit: crate::cpu::is_64bit(),
name_source: f.name_source,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_os_constants_are_consistent() {
assert_eq!(is_mac(), is_macos());
assert!(!(is_linux() && is_android()));
assert_eq!(kind() == Kind::Windows, is_windows());
assert_eq!(kind() == Kind::Linux, is_linux());
if is_linux() || is_macos() || is_android() || is_ios() {
assert!(is_unix());
}
}
#[test]
fn test_os_live_answers_are_never_empty() {
assert!(!name().is_empty());
assert!(!distro().is_empty());
assert!(!distro_id().is_empty());
assert!(is_like(distro_id()));
assert!(!is_like("not-a-distribution"));
if is_windows() {
assert_eq!((distro(), distro_id()), ("Windows", "windows"));
}
if is_macos() {
assert_eq!((distro(), distro_id()), ("macOS", "macos"));
}
}
#[test]
fn test_os_info_is_cached() {
assert!(std::ptr::eq(info(), info()));
assert!(std::ptr::eq(name(), info().name));
}
#[test]
fn test_os_from_facts_fills_defaults() {
let info = from_facts(crate::sys::OsFacts {
name: "X 1".into(),
version: Some("8.10-beta".into()),
kernel: "k".into(),
distro: "X".into(),
distro_id: "x".into(),
edition: Some("server".into()),
codename: None,
release: Some(crate::sys::ReleaseFacts {
id: None,
id_like: vec!["rhel".into(), "fedora".into()],
name: None,
pretty_name: None,
version: None,
version_id: None,
codename: None,
variant_id: None,
build_id: None,
source: Source::OsRelease,
}),
name_source: Source::OsRelease,
});
let v = info.version.unwrap();
assert_eq!(
(v.major, v.minor, v.patch, v.build, v.text),
(8, 10, 0, None, "8.10-beta")
);
assert_eq!(v.to_string(), "8.10-beta");
let r = info.os_release.unwrap();
assert_eq!((r.id, r.name, r.pretty_name), ("linux", "Linux", "Linux"));
assert_eq!(r.id_like, &["rhel", "fedora"]);
}
#[test]
fn test_os_concurrent_first_use_sees_one_value() {
let ptrs: Vec<usize> = std::thread::scope(|s| {
let handles: Vec<_> = (0..64)
.map(|_| s.spawn(|| core::ptr::from_ref(info()) as usize))
.collect();
handles.into_iter().map(|h| h.join().unwrap_or(0)).collect()
});
assert!(ptrs.windows(2).all(|w| w[0] == w[1]));
}
}