1use core::fmt;
19use std::sync::OnceLock;
20
21use crate::parse;
22
23#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
25#[non_exhaustive]
26pub enum Kind {
27 Linux,
29 Windows,
31 MacOs,
33 Android,
35 Ios,
37 FreeBsd,
39 OpenBsd,
41 NetBsd,
43 Other,
45}
46
47impl Kind {
48 #[must_use]
54 pub const fn name(self) -> &'static str {
55 match self {
56 Self::Linux => "linux",
57 Self::Windows => "windows",
58 Self::MacOs => "macos",
59 Self::Android => "android",
60 Self::Ios => "ios",
61 Self::FreeBsd => "freebsd",
62 Self::OpenBsd => "openbsd",
63 Self::NetBsd => "netbsd",
64 Self::Other => "other",
65 }
66 }
67}
68
69#[must_use]
77pub const fn kind() -> Kind {
78 if cfg!(target_os = "android") {
79 Kind::Android
80 } else if cfg!(target_os = "linux") {
81 Kind::Linux
82 } else if cfg!(target_os = "windows") {
83 Kind::Windows
84 } else if cfg!(target_os = "macos") {
85 Kind::MacOs
86 } else if cfg!(target_os = "ios") {
87 Kind::Ios
88 } else if cfg!(target_os = "freebsd") {
89 Kind::FreeBsd
90 } else if cfg!(target_os = "openbsd") {
91 Kind::OpenBsd
92 } else if cfg!(target_os = "netbsd") {
93 Kind::NetBsd
94 } else {
95 Kind::Other
96 }
97}
98
99#[must_use]
101pub const fn is_windows() -> bool {
102 cfg!(target_os = "windows")
103}
104
105#[must_use]
107pub const fn is_linux() -> bool {
108 cfg!(target_os = "linux")
109}
110
111#[must_use]
113pub const fn is_macos() -> bool {
114 cfg!(target_os = "macos")
115}
116
117#[must_use]
119pub const fn is_mac() -> bool {
120 is_macos()
121}
122
123#[must_use]
125pub const fn is_android() -> bool {
126 cfg!(target_os = "android")
127}
128
129#[must_use]
131pub const fn is_ios() -> bool {
132 cfg!(target_os = "ios")
133}
134
135#[must_use]
137pub const fn is_unix() -> bool {
138 cfg!(unix)
139}
140
141#[must_use]
143pub const fn is_bsd() -> bool {
144 cfg!(any(
145 target_os = "freebsd",
146 target_os = "openbsd",
147 target_os = "netbsd",
148 target_os = "dragonfly"
149 ))
150}
151
152#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
162#[non_exhaustive]
163pub struct Version {
164 pub major: u32,
166 pub minor: u32,
168 pub patch: u32,
170 pub build: Option<u32>,
172 pub text: &'static str,
174}
175
176impl fmt::Display for Version {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.pad(self.text)
179 }
180}
181
182#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
184#[non_exhaustive]
185pub enum Source {
186 OsRelease,
188 UsrLibOsRelease,
190 LegacyRelease,
192 Sysctl,
194 Registry,
196 SystemProperty,
198 Fallback,
200}
201
202#[derive(Clone, Copy, Debug)]
210#[non_exhaustive]
211pub struct OsRelease {
212 pub id: &'static str,
214 pub id_like: &'static [&'static str],
216 pub name: &'static str,
218 pub pretty_name: &'static str,
220 pub version: Option<&'static str>,
222 pub version_id: Option<&'static str>,
224 pub codename: Option<&'static str>,
226 pub variant_id: Option<&'static str>,
228 pub build_id: Option<&'static str>,
230 pub source: Source,
232}
233
234#[derive(Clone, Copy, Debug)]
236#[non_exhaustive]
237pub struct OsInfo {
238 pub kind: Kind,
240 pub name: &'static str,
242 pub version: Option<&'static Version>,
244 pub kernel: &'static str,
246 pub distro: &'static str,
248 pub distro_id: &'static str,
250 pub os_release: Option<&'static OsRelease>,
252 pub edition: Option<&'static str>,
254 pub codename: Option<&'static str>,
256 pub is_64bit: bool,
258 pub name_source: Source,
260}
261
262#[must_use]
266pub fn name() -> &'static str {
267 info().name
268}
269
270#[must_use]
273pub fn version() -> Option<&'static Version> {
274 info().version
275}
276
277#[must_use]
279pub fn kernel() -> &'static str {
280 info().kernel
281}
282
283#[must_use]
294pub fn distro() -> &'static str {
295 info().distro
296}
297
298#[must_use]
301pub fn distro_id() -> &'static str {
302 info().distro_id
303}
304
305#[must_use]
315pub fn is_like(id: &str) -> bool {
316 let info = info();
317 info.distro_id == id
318 || info
319 .os_release
320 .is_some_and(|r| r.id == id || r.id_like.contains(&id))
321}
322
323#[must_use]
326pub fn os_release() -> Option<&'static OsRelease> {
327 info().os_release
328}
329
330#[must_use]
333pub fn edition() -> Option<&'static str> {
334 info().edition
335}
336
337#[must_use]
339pub fn codename() -> Option<&'static str> {
340 info().codename
341}
342
343#[must_use]
346pub fn is_server_edition() -> Option<bool> {
347 static SERVER: OnceLock<Option<bool>> = OnceLock::new();
348 *SERVER.get_or_init(crate::sys::is_server_edition)
349}
350
351#[must_use]
353pub fn is_64bit() -> bool {
354 info().is_64bit
355}
356
357#[must_use]
359pub fn info() -> &'static OsInfo {
360 static INFO: OnceLock<OsInfo> = OnceLock::new();
361 INFO.get_or_init(|| from_facts(crate::sys::os()))
362}
363
364#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
366#[non_exhaustive]
367pub enum FormFactor {
368 Desktop,
370 Laptop,
372 Convertible,
374 Tablet,
376 Phone,
378 Handheld,
380 Server,
382 Embedded,
384 Wearable,
386 Tv,
388 Unknown,
391}
392
393impl FormFactor {
394 #[must_use]
400 pub const fn name(self) -> &'static str {
401 match self {
402 Self::Desktop => "desktop",
403 Self::Laptop => "laptop",
404 Self::Convertible => "convertible",
405 Self::Tablet => "tablet",
406 Self::Phone => "phone",
407 Self::Handheld => "handheld",
408 Self::Server => "server",
409 Self::Embedded => "embedded",
410 Self::Wearable => "wearable",
411 Self::Tv => "tv",
412 Self::Unknown => "unknown",
413 }
414 }
415}
416
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
419#[non_exhaustive]
420pub struct Detection<T> {
421 pub value: T,
423 pub source: &'static str,
425 pub confidence: Confidence,
427}
428
429impl<T> Detection<T> {
430 pub(crate) const fn new(value: T, source: &'static str, confidence: Confidence) -> Self {
431 Self {
432 value,
433 source,
434 confidence,
435 }
436 }
437}
438
439#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
441#[non_exhaustive]
442pub enum Confidence {
443 None,
445 Low,
447 Medium,
449 High,
451}
452
453#[must_use]
463pub fn form_factor() -> FormFactor {
464 detect_form_factor().value
465}
466
467#[must_use]
469pub fn detect_form_factor() -> &'static Detection<FormFactor> {
470 static FACT: OnceLock<Detection<FormFactor>> = OnceLock::new();
471 FACT.get_or_init(crate::sys::form_factor)
472}
473
474#[must_use]
476pub fn is_desktop() -> bool {
477 form_factor() == FormFactor::Desktop
478}
479
480#[must_use]
482pub fn is_laptop() -> bool {
483 matches!(form_factor(), FormFactor::Laptop | FormFactor::Convertible)
484}
485
486#[must_use]
488pub fn is_mobile() -> bool {
489 matches!(
490 form_factor(),
491 FormFactor::Phone | FormFactor::Tablet | FormFactor::Handheld | FormFactor::Wearable
492 )
493}
494
495#[must_use]
497pub fn is_phone() -> bool {
498 form_factor() == FormFactor::Phone
499}
500
501#[must_use]
503pub fn is_tablet() -> bool {
504 form_factor() == FormFactor::Tablet
505}
506
507#[must_use]
509pub fn is_server() -> bool {
510 form_factor() == FormFactor::Server
511}
512
513#[cfg_attr(any(target_vendor = "apple", target_os = "android"), allow(dead_code))]
517pub(crate) const fn form_from_chassis(chassis: u8) -> Option<FormFactor> {
518 Some(match chassis {
519 0x03 | 0x04 | 0x06 | 0x07 | 0x0D | 0x23 | 0x24 => FormFactor::Desktop,
520 0x08 | 0x09 | 0x0A | 0x0E => FormFactor::Laptop,
521 0x0B => FormFactor::Handheld,
522 0x11 | 0x17 | 0x19 | 0x1C | 0x1D => FormFactor::Server,
523 0x1E => FormFactor::Tablet,
524 0x1F | 0x20 => FormFactor::Convertible,
525 0x21 | 0x22 => FormFactor::Embedded,
526 _ => return None,
527 })
528}
529
530#[cfg_attr(
532 any(target_vendor = "apple", target_os = "android", target_os = "freebsd"),
533 allow(dead_code)
534)]
535pub(crate) const fn form_from_pm_profile(profile: u8) -> Option<FormFactor> {
536 Some(match profile {
537 1 | 3 | 6 => FormFactor::Desktop,
538 2 => FormFactor::Laptop,
539 4 | 5 | 7 => FormFactor::Server,
540 8 => FormFactor::Tablet,
541 _ => return None,
542 })
543}
544
545pub(crate) fn keep(s: String) -> &'static str {
548 Box::leak(s.into_boxed_str())
549}
550
551fn keep_opt(s: Option<String>) -> Option<&'static str> {
552 s.map(keep)
553}
554
555pub(crate) fn from_facts(f: crate::sys::OsFacts) -> OsInfo {
556 let version = f.version.as_deref().and_then(|text| {
557 let (major, minor, patch, build) = parse::version::parse(text)?;
558 Some(&*Box::leak(Box::new(Version {
559 major,
560 minor,
561 patch,
562 build,
563 text: keep(text.to_owned()),
564 })))
565 });
566 let os_release = f.release.map(|r| {
567 let id_like: Vec<&'static str> = r.id_like.into_iter().map(keep).collect();
568 let name = r.name.unwrap_or_else(|| "Linux".to_owned());
569 &*Box::leak(Box::new(OsRelease {
570 id: keep(r.id.unwrap_or_else(|| "linux".to_owned())),
571 id_like: Box::leak(id_like.into_boxed_slice()),
572 pretty_name: keep(r.pretty_name.unwrap_or_else(|| name.clone())),
573 name: keep(name),
574 version: keep_opt(r.version),
575 version_id: keep_opt(r.version_id),
576 codename: keep_opt(r.codename),
577 variant_id: keep_opt(r.variant_id),
578 build_id: keep_opt(r.build_id),
579 source: r.source,
580 }))
581 });
582 OsInfo {
583 kind: kind(),
584 name: keep(f.name),
585 version,
586 kernel: keep(f.kernel),
587 distro: keep(f.distro),
588 distro_id: keep(f.distro_id),
589 os_release,
590 edition: keep_opt(f.edition),
591 codename: keep_opt(f.codename),
592 is_64bit: crate::cpu::is_64bit(),
593 name_source: f.name_source,
594 }
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600
601 #[test]
602 fn test_os_constants_are_consistent() {
603 assert_eq!(is_mac(), is_macos());
604 assert!(!(is_linux() && is_android()));
605 assert_eq!(kind() == Kind::Windows, is_windows());
606 assert_eq!(kind() == Kind::Linux, is_linux());
607 if is_linux() || is_macos() || is_android() || is_ios() {
608 assert!(is_unix());
609 }
610 }
611
612 #[test]
613 fn test_os_live_answers_are_never_empty() {
614 assert!(!name().is_empty());
615 assert!(!distro().is_empty());
616 assert!(!distro_id().is_empty());
617 assert!(is_like(distro_id()));
618 assert!(!is_like("not-a-distribution"));
619 if is_windows() {
620 assert_eq!((distro(), distro_id()), ("Windows", "windows"));
621 }
622 if is_macos() {
623 assert_eq!((distro(), distro_id()), ("macOS", "macos"));
624 }
625 }
626
627 #[test]
628 fn test_os_info_is_cached() {
629 assert!(std::ptr::eq(info(), info()));
630 assert!(std::ptr::eq(name(), info().name));
631 }
632
633 #[test]
634 fn test_os_from_facts_fills_defaults() {
635 let info = from_facts(crate::sys::OsFacts {
636 name: "X 1".into(),
637 version: Some("8.10-beta".into()),
638 kernel: "k".into(),
639 distro: "X".into(),
640 distro_id: "x".into(),
641 edition: Some("server".into()),
642 codename: None,
643 release: Some(crate::sys::ReleaseFacts {
644 id: None,
645 id_like: vec!["rhel".into(), "fedora".into()],
646 name: None,
647 pretty_name: None,
648 version: None,
649 version_id: None,
650 codename: None,
651 variant_id: None,
652 build_id: None,
653 source: Source::OsRelease,
654 }),
655 name_source: Source::OsRelease,
656 });
657 let v = info.version.unwrap();
658 assert_eq!(
659 (v.major, v.minor, v.patch, v.build, v.text),
660 (8, 10, 0, None, "8.10-beta")
661 );
662 assert_eq!(v.to_string(), "8.10-beta");
663 let r = info.os_release.unwrap();
664 assert_eq!((r.id, r.name, r.pretty_name), ("linux", "Linux", "Linux"));
665 assert_eq!(r.id_like, &["rhel", "fedora"]);
666 }
667
668 #[test]
669 fn test_os_concurrent_first_use_sees_one_value() {
670 let ptrs: Vec<usize> = std::thread::scope(|s| {
672 let handles: Vec<_> = (0..64)
673 .map(|_| s.spawn(|| core::ptr::from_ref(info()) as usize))
674 .collect();
675 handles.into_iter().map(|h| h.join().unwrap_or(0)).collect()
676 });
677 assert!(ptrs.windows(2).all(|w| w[0] == w[1]));
678 }
679}