### Getting Started with Whoami Source: https://docs.rs/whoami/2.1.1/index.html This snippet demonstrates how to use various functions from the whoami crate to get user and environment information. It covers functions returning strings, enums, and LanguagePreferences. ```APIDOC ## Getting Started with Whoami ### Description This example shows how to use most of the public functions provided by the `whoami` crate to retrieve user and environment details. It includes examples for language preferences, user names, device information, platform, distribution, desktop environment, and CPU architecture. ### Usage ```rust println!("User's Language whoami::lang_prefs(): {}", whoami::lang_prefs().unwrap_or_default()); println!("User's Name whoami::realname(): {}", whoami::realname().unwrap_or_else(|_| "".to_string())); println!("User's Username whoami::username(): {}", whoami::username().unwrap_or_else(|_| "".to_string())); println!("User's Username whoami::account(): {}", whoami::account().unwrap_or_else(|_| "".to_string())); println!("Device's Pretty Name whoami::devicename(): {}", whoami::devicename().unwrap_or_else(|_| "".to_string())); println!("Device's Hostname whoami::hostname(): {}", whoami::hostname().unwrap_or_else(|_| "".to_string())); println!("Device's Platform whoami::platform(): {}", whoami::platform()); println!("Device's OS Distro whoami::distro(): {}", whoami::distro().unwrap_or_else(|_| "".to_string())); println!("Device's Desktop Env. whoami::desktop_env(): {}", whoami::desktop_env().map(|e| e.to_string()).unwrap_or_else(|| "".to_string())); println!("Device's CPU Arch whoami::cpu_arch(): {}", whoami::cpu_arch()); ``` ### Functions Used - `lang_prefs()`: Returns user's preferred language(s). - `realname()`: Returns the user's full name. - `username()`: Returns the user's username. - `account()`: Returns the user's account name. - `devicename()`: Returns the device's pretty name. - `hostname()`: Returns the device's hostname. - `platform()`: Returns the device's platform. - `distro()`: Returns the operating system distribution and version. - `desktop_env()`: Returns the desktop environment, if any. - `cpu_arch()`: Returns the CPU architecture. ``` -------------------------------- ### Get Desktop Environment - Rust Source: https://docs.rs/whoami/2.1.1/whoami/fn.desktop_env.html Retrieves the current desktop environment. Returns None if not available, such as in a TTY or over SSH. Examples include "gnome" or "windows". ```rust pub fn desktop_env() -> Option ``` -------------------------------- ### Get Operating System Distribution Source: https://docs.rs/whoami/2.1.1/whoami/fn.distro.html Retrieves the name of the operating system distribution and its version, if available. Examples include 'Windows 10' or 'Fedora 26 (Workstation Edition)'. ```APIDOC ## Function distro ### Description Get the name of the operating system distribution and (possibly) version. Example: ‘Windows 10’ or ‘Fedora 26 (Workstation Edition)’ ### Signature ```rust pub fn distro() -> Result ``` ### Returns A `Result` containing a `String` with the distribution name and version on success, or an error on failure. ``` -------------------------------- ### GET /cpu_arch Source: https://docs.rs/whoami/2.1.1/whoami/fn.cpu_arch.html Retrieves the CPU architecture of the current system. ```APIDOC ## cpu_arch ### Description Get the CPU Architecture of the current system. ### Method Function Call ### Endpoint whoami::cpu_arch() ### Response - **CpuArchitecture** (enum) - Returns the CPU architecture of the host system. ``` -------------------------------- ### Retrieve System and User Information in Rust Source: https://docs.rs/whoami/2.1.1/index.html Demonstrates usage of various whoami functions to print user and device details to the console. Functions returning OsString are excluded from this example. ```rust println!( "User's Language whoami::lang_prefs(): {}", whoami::lang_prefs().unwrap_or_default(), ); println!( "User's Name whoami::realname(): {}", whoami::realname().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::username(): {}", whoami::username().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::account(): {}", whoami::account().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Pretty Name whoami::devicename(): {}", whoami::devicename().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Hostname whoami::hostname(): {}", whoami::hostname().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Platform whoami::platform(): {}", whoami::platform(), ); println!( "Device's OS Distro whoami::distro(): {}", whoami::distro().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Desktop Env. whoami::desktop_env(): {}", whoami::desktop_env() .map(|e| e.to_string()) .unwrap_or_else(|| "".to_string()), ); println!( "Device's CPU Arch whoami::cpu_arch(): {}", whoami::cpu_arch(), ); ``` -------------------------------- ### Get Platform Information Source: https://docs.rs/whoami/2.1.1/whoami/fn.platform.html Retrieves information about the current operating system platform. ```APIDOC ## GET /platform ### Description Get the platform. ### Method GET ### Endpoint /platform ### Parameters None ### Request Body None ### Response #### Success Response (200) - **platform** (Platform) - The operating system platform. #### Response Example ```json { "platform": "linux" } ``` ``` -------------------------------- ### Get User and Environment Info with whoami Source: https://docs.rs/whoami/2.1.1/whoami/index.html Demonstrates how to use various functions from the whoami crate to retrieve user and system details. Handles potential errors using unwrap_or_else or map. ```rust println!( "User's Language whoami::lang_prefs(): fonbet{}", whoami::lang_prefs().unwrap_or_default(), ); println!( "User's Name whoami::realname(): fonbet{}", whoami::realname().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::username(): fonbet{}", whoami::username().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::account(): fonbet{}", whoami::account().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Pretty Name whoami::devicename(): fonbet{}", whoami::devicename().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Hostname whoami::hostname(): fonbet{}", whoami::hostname().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Platform whoami::platform(): fonbet{}", whoami::platform(), ); println!( "Device's OS Distro whoami::distro(): fonbet{}", whoami::distro().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Desktop Env. whoami::desktop_env(): fonbet{}", whoami::desktop_env() .map(|e| e.to_string()) .unwrap_or_else(|| "".to_string()), ); println!( "Device's CPU Arch whoami::cpu_arch(): fonbet{}", whoami::cpu_arch(), ); ``` -------------------------------- ### Get User and Environment Information in Rust Source: https://docs.rs/whoami/2.1.1/src/whoami/lib.rs.html Demonstrates how to use various functions from the whoami crate to retrieve user and system details. Includes error handling for functions that might fail. Ensure the 'std' feature is enabled if you need access to standard library types like String. ```rust println!( "User's Language whoami::lang_prefs(): fonbet{}", whoami::lang_prefs().unwrap_or_default(), ); println!( "User's Name whoami::realname(): fonbet{}", whoami::realname().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::username(): fonbet{}", whoami::username().unwrap_or_else(|_| "".to_string()), ); println!( "User's Username whoami::account(): fonbet{}", whoami::account().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Pretty Name whoami::devicename(): fonbet{}", whoami::devicename().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Hostname whoami::hostname(): fonbet{}", whoami::hostname().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Platform whoami::platform(): fonbet{}", whoami::platform(), ); println!( "Device's OS Distro whoami::distro(): fonbet{}", whoami::distro().unwrap_or_else(|_| "".to_string()), ); println!( "Device's Desktop Env. whoami::desktop_env(): fonbet{}", whoami::desktop_env() .map(|e| e.to_string()) .unwrap_or_else(|| "".to_string()), ); println!( "Device's CPU Arch whoami::cpu_arch(): fonbet{}", whoami::cpu_arch(), ); ``` -------------------------------- ### Get Device Name (Pretty Name) Source: https://docs.rs/whoami/2.1.1/whoami/fn.devicename_os.html Retrieves the device's pretty name, often used for Bluetooth pairing. Returns a Result containing an OsString. ```rust pub fn devicename_os() -> Result ``` -------------------------------- ### GET lang_prefs Source: https://docs.rs/whoami/2.1.1/whoami/fn.lang_prefs.html Retrieves the user's preferred language(s) as a LanguagePreferences instance. ```APIDOC ## GET lang_prefs ### Description Get the user's preferred language(s). ### Method GET ### Response #### Success Response (200) - **LanguagePreferences** (object) - An instance containing the user's preferred language settings. ``` -------------------------------- ### Get Device Name (Linux/BSD) Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Parses `/etc/machine-info` to find the `PRETTY_HOSTNAME` on Linux and BSD systems. It iterates through lines and splits them by '=' to find the relevant key-value pair. ```rust let machine_info = fs::read("/etc/machine-info").map_err(Error::from_io)?; for i in machine_info.split(|b| *b == b'\n') { let mut j = i.split(|b| *b == b'='); if j.next() == Some(b"PRETTY_HOSTNAME") { ``` -------------------------------- ### Get Platform Information in Rust Source: https://docs.rs/whoami/2.1.1/src/whoami/api.rs.html Retrieves the current platform information. This function is intended for direct use and is marked with `#[inline(always)]` for potential performance benefits. ```rust /// Get the platform. #[must_use] #[inline(always)] pub fn platform() -> Platform { Target::platform(Os) } ``` -------------------------------- ### hostname() - Get Hostname Source: https://docs.rs/whoami/2.1.1/whoami/fn.hostname.html Retrieves the host device's hostname. The function returns a `Result` which contains the hostname on success. ```APIDOC ## hostname() ### Description Get the host device’s hostname. Usually hostnames are case-insensitive, but it’s not a hard requirement. ### Method N/A (Function call) ### Endpoint N/A (Function call) ### Parameters None ### Request Example N/A (Function call) ### Response #### Success Response - **String** - The hostname of the device. #### Response Example ```json { "hostname": "my-computer-name" } ``` ### Platform-Specific Character Limitations #### Unix/Linux/BSD - **Maximum length**: 255 bytes (excluding null terminator) - **Encoding**: Must be valid UTF-8 - **Characters**: Typically follows RFC 952/1123 DNS hostname rules: Alphanumeric characters (a-z, A-Z, 0-9), Hyphens (-), but not at start or end. POSIX allows any character except null and newline, but network hostnames should follow DNS rules for interoperability. #### Windows - **Maximum length**: 63 characters for DNS hostname (per label) - **Encoding**: UTF-16 (converted to UTF-8 String) - **Characters**: Follows DNS hostname rules (RFC 1123): Alphanumeric characters (a-z, A-Z, 0-9), Hyphens (-), but not at start or end. #### Redox - Reads from `/etc/hostname` file. First line of file is used as hostname. No inherent character limitations beyond file system. #### Web (WASM) - Returns the document’s domain name. Follows DNS hostname rules as enforced by browsers. Must be valid UTF-8. #### Other Platforms - WASI: Returns system hostname or defaults to “localhost”. - Default: Returns “localhost” for unsupported platforms. ### Notes For maximum compatibility across all platforms and network protocols, hostnames should: - Be 63 characters or less - Contain only ASCII alphanumeric characters and hyphens - Not start or end with a hyphen - Be case-insensitive (though case may be preserved) ``` -------------------------------- ### Get User Account Name Source: https://docs.rs/whoami/2.1.1/whoami/fn.account_os.html Retrieves the user's account name, which may include a server hostname. For just the username, use `username()`. ```Rust pub fn account_os() -> Result ``` -------------------------------- ### Get Device Name (macOS) Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Retrieves the computer's name on macOS using `SCDynamicStore::computer_name`. It handles potential null pointers and empty names, converting the result to a UTF-8 string. ```rust use std::ptr::null_mut(); use objc2_system_configuration::SCDynamicStore; let Some(name) = (unsafe { SCDynamicStore::computer_name(None, null_mut()) }) else { return Err(Error::missing_record()); }; // this should be able to convert whichever encoding is being used // to UTF-8, so we shouldn't have to worry about invalid codepoints. let name = name.to_string(); if name.is_empty() { return Err(Error::empty_record()); } Ok(name.into()) ``` -------------------------------- ### Get Username (username_os) Source: https://docs.rs/whoami/2.1.1/whoami/fn.username_os.html Retrieves the current user's username. On Unix-like systems, this username does not contain spaces, differentiating it from the real name. ```APIDOC ## username_os ### Description Get the user’s username. On unix-systems this differs from `realname_os()` most notably in that spaces are not allowed in the username. ### Method GET ### Endpoint /username_os ### Response #### Success Response (200) - **username** (OsString) - The username of the current user. #### Response Example ```json { "username": "user123" } ``` ``` -------------------------------- ### Get Device Name Source: https://docs.rs/whoami/2.1.1/whoami/fn.devicename.html Retrieves the device name, also known as the 'Pretty Name', which is often used for Bluetooth pairing. ```APIDOC ## Function devicename ### Description Get the device name (also known as “Pretty Name”). Often used to identify device for bluetooth pairing. ### Signature ```rust pub fn devicename() -> Result ``` ### Returns A `Result` containing the device name as a `String` on success, or an error if the name cannot be retrieved. ``` -------------------------------- ### Get User's Preferred Languages in Rust Source: https://docs.rs/whoami/2.1.1/src/whoami/api.rs.html Fetches the user's preferred language settings. The result is an instance of `LanguagePreferences`, with fallbacks automatically added. This function is inlined for performance. ```rust /// Get the user's preferred language(s). /// /// Returned as an instance of [`LanguagePreferences`] #[inline(always)] pub fn lang_prefs() -> Result { Target::lang_prefs(Os).map(LanguagePreferences::add_stripped_fallbacks) } ``` -------------------------------- ### Get Device Name (Illumos) Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Reads the device name from `/etc/nodename` on Illumos. It removes any trailing newline characters and handles empty file content. ```rust let mut nodename = fs::read("/etc/nodename").map_err(Error::from_io)?; // Remove all at and after the first newline (before end of file) if let Some(slice) = nodename.split(|x| *x == b'\n').next() { nodename.drain(slice.len()..); } if nodename.is_empty() { return Err(Error::empty_record()); } Ok(OsString::from_vec(nodename)) ``` -------------------------------- ### Check if DesktopEnvironment is KDE-based Source: https://docs.rs/whoami/2.1.1/whoami/enum.DesktopEnvironment.html Use this function to determine if the current desktop environment is based on the KDE framework. No specific setup is required beyond having an instance of DesktopEnvironment. ```rust pub const fn is_kde(&self) -> bool ``` -------------------------------- ### Get CPU Architecture Width Source: https://docs.rs/whoami/2.1.1/src/whoami/arch.rs.html Provides a method to determine the bit width (`Width::Bits32` or `Width::Bits64`) of a given `CpuArchitecture`. Returns an `Error` for unknown architectures. ```rust impl CpuArchitecture { /// Get the width of this architecture. pub fn width(&self) -> Result { match self { Self::ArmV5 | Self::ArmV6 | Self::ArmV7 | Self::I386 | Self::I586 | Self::I686 | Self::Mips | Self::MipsEl | Self::PowerPc | Self::Riscv32 | Self::Sparc | Self::Wasm32 => Ok(Width::Bits32), Self::Arm64 | Self::Mips64 | Self::Mips64El | Self::PowerPc64 | Self::PowerPc64Le | Self::Riscv64 | Self::S390x | Self::Sparc64 | Self::Wasm64 | Self::X64 => Ok(Width::Bits64), Self::Unknown(unknown_arch) => { Err(Error::with_invalid_data(alloc::format!( "Tried getting width of unknown arch ({unknown_arch})" ))) } } } } ``` -------------------------------- ### Get User Information (Unix) Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Retrieves user information (username or real name) using the `getpwuid_r` C function. This function requires a buffer for the passwd struct and handles potential errors. ```rust unsafe fn strlen(mut cs: *const u8) -> usize where T: Terminators, { let mut len = 0; while !T::CHARS.contains(&*cs) { len += 1; cs = cs.offset(1); } len } fn os_from_cstring(string: *const u8) -> Result where T: Terminators, { if string.is_null() { return Err(Error::null_record()); } // Get a byte slice of the c string. let slice = unsafe { let length = strlen::(string); if length == 0 { return Err(Error::empty_record()); } slice::from_raw_parts(string, length) }; // Turn byte slice into Rust String. Ok(OsString::from_vec(slice.to_vec())) } // This function must allocate, because a slice or `Cow` would still // reference `passwd` which is dropped when this function returns. #[inline(always)] fn getpwuid(name: Name) -> Result { const BUF_SIZE: usize = 16_384; // size from the man page let mut buffer = mem::MaybeUninit::<[u8; BUF_SIZE]>::uninit(); let mut passwd = mem::MaybeUninit::::uninit(); // Get passwd `struct`. let passwd = unsafe { let mut _passwd = mem::MaybeUninit::<*mut libc::passwd>::uninit(); let ret = libc::getpwuid_r( libc::geteuid(), passwd.as_mut_ptr(), buffer.as_mut_ptr().cast(), BUF_SIZE, _passwd.as_mut_ptr(), ); if ret != 0 { return Err(Error::from_io(io::Error::last_os_error())); } let _passwd = _passwd.assume_init(); if _passwd.is_null() { return Err(Error::null_record()); } passwd.assume_init() }; // Extract names. if let Name::Real = name { os_from_cstring::(passwd.pw_gecos.cast()) } else { os_from_cstring::(passwd.pw_name.cast()) } } ``` -------------------------------- ### Display Implementation for DesktopEnvironment Source: https://docs.rs/whoami/2.1.1/src/whoami/desktop_env.rs.html Provides a human-readable string representation for each `DesktopEnvironment` variant. This allows for easy printing and logging of the detected desktop environment. ```APIDOC ## Display for DesktopEnvironment ### Description Implements the `Display` trait for the `DesktopEnvironment` enum, providing a human-readable string representation for each variant. This allows for easy printing and logging of the detected desktop environment. ### Method `fmt(&self, f: &mut Formatter<'_>) -> fmt::Result` ### Example Output - `DesktopEnvironment::Gnome` -> "Gnome" - `DesktopEnvironment::WebBrowser(String::from("Chrome"))` -> "WebBrowser (Chrome)" - `DesktopEnvironment::Unknown(String::from("CustomDE"))` -> "Unknown: CustomDE" ### Example Usage ```rust use whoami::DesktopEnvironment; let de = DesktopEnvironment::Windows; println!("Detected: {}", de); // Output: Detected: Windows let browser_de = DesktopEnvironment::WebBrowser(String::from("Firefox")); println!("Detected: {}", browser_de); // Output: Detected: WebBrowser (Firefox) ``` ``` -------------------------------- ### Desktop Environment API Source: https://docs.rs/whoami/2.1.1/whoami/fn.desktop_env.html Retrieves the current desktop environment. Returns None if not available. ```APIDOC ## desktop_env ### Description Get the desktop environment (if any). Example: “gnome” or “windows” Returns `None` if a desktop environment is not available (for example in a TTY or over SSH) ### Signature ```rust pub fn desktop_env() -> Option ``` ### Returns - `Option`: The name of the desktop environment, or `None` if not available. ``` -------------------------------- ### Get User's Real Name Source: https://docs.rs/whoami/2.1.1/whoami/fn.realname.html Retrieves the user's full name. ```APIDOC ## realname ### Description Get the user’s real (full) name. ### Method GET ### Endpoint /realname ### Parameters #### Query Parameters - **None** ### Request Example ```json {} ``` ### Response #### Success Response (200) - **name** (string) - The user's full name. #### Response Example ```json { "name": "John Doe" } ``` ``` -------------------------------- ### Rust Crate Configuration and Imports Source: https://docs.rs/whoami/2.1.1/src/whoami/lib.rs.html This snippet shows the necessary crate-level attributes and external crate declarations for the whoami library. It includes feature flags and module imports, setting up the library's environment. ```rust #![no_std] #![warn( anonymous_parameters, missing_copy_implementations, missing_debug_implementations, missing_docs, nonstandard_style, rust_2018_idioms, single_use_lifetimes, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_extern_crates, unused_qualifications, variant_size_differences, unsafe_code )] #![deny( rustdoc::broken_intra_doc_links, rustdoc::private_intra_doc_links, rustdoc::missing_crate_level_docs, rustdoc::private_doc_tests, rustdoc::invalid_codeblock_attributes, rustdoc::invalid_html_tags, rustdoc::invalid_rust_codeblocks, rustdoc::bare_urls, rustdoc::unescaped_backticks, rustdoc::redundant_explicit_links )] #![doc( html_logo_url = "https://raw.githubusercontent.com/ardaku/whoami/v2/res/icon.svg", html_favicon_url = "https://raw.githubusercontent.com/ardaku/whoami/v2/res/icon.svg" )] extern crate alloc; #[cfg(feature = "std")] extern crate std; mod api; mod arch; mod conversions; mod desktop_env; mod error; mod langs; mod os; mod platform; mod result; use self::conversions::OsString; pub use self::{ api::{ account, account_os, cpu_arch, desktop_env, devicename, devicename_os, distro, hostname, lang_prefs, platform, realname, realname_os, username, username_os, }, arch::{CpuArchitecture, Width}, desktop_env::DesktopEnvironment, error::Error, langs::{Language, LanguagePreferences}, platform::Platform, result::Result, }; ``` -------------------------------- ### Generic CloneToUninit Implementation (Nightly) Source: https://docs.rs/whoami/2.1.1/whoami/enum.Platform.html An experimental, nightly-only API that allows cloning data into uninitialized memory. Use with caution and ensure proper memory management. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation details ... } ``` -------------------------------- ### Get Hostname Function Signature Source: https://docs.rs/whoami/2.1.1/whoami/fn.hostname.html This function retrieves the host device's hostname. Hostnames are typically case-insensitive, but this is not a strict requirement. ```rust pub fn hostname() -> Result ``` -------------------------------- ### Retrieve OS Distribution Information Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Parses system version files on Apple platforms or reads /etc/os-release on other systems to determine the distribution name. ```rust 290 if let Some(user_visible_version) = user_visible_version { 291 std::format!("{product_name} {user_visible_version}") 292 } else { 293 product_name.to_string() 294 } 295 } else { 296 user_visible_version 297 .map(|v| std::format!("Mac OS (Unknown) {v}")) 298 .ok_or_else(|| { 299 Error::with_invalid_data("Parsing failed") 300 })? 301 }) 302 } 303 304 if let Ok(data) = fs::read_to_string( 305 "/System/Library/CoreServices/ServerVersion.plist", 306 ) { 307 distro_xml(data) 308 } else if let Ok(data) = fs::read_to_string( 309 "/System/Library/CoreServices/SystemVersion.plist", 310 ) { 311 distro_xml(data) 312 } else { 313 Err(Error::missing_record()) 314 } 315 } 316 317 #[cfg(not(target_vendor = "apple"))] 318 { 319 let program = 320 fs::read("/etc/os-release").map_err(Error::from_io)?; 321 let distro = String::from_utf8_lossy(&program); 322 let err = || Error::with_invalid_data("Parsing failed"); 323 let mut fallback = None; 324 325 for i in distro.split('\n') { 326 let mut j = i.split('='); 327 328 match j.next().ok_or_else(err)? { 329 "PRETTY_NAME" => { 330 return Ok(j 331 .next() 332 .ok_or_else(err)? 333 .trim_matches('"') 334 .to_string()); 335 } 336 "NAME" => { 337 fallback = Some( 338 j.next() 339 .ok_or_else(err)? 340 .trim_matches('"') 341 .to_string(), 342 ) 343 } 344 _ => {} 345 } 346 } 347 348 fallback.ok_or_else(err) 349 } 350 } ``` -------------------------------- ### Generic ToString Implementation Source: https://docs.rs/whoami/2.1.1/whoami/enum.Platform.html Enables converting any type that implements `Display` into a `String`. This is a common way to get a string representation of a value. ```rust fn to_string(&self) -> String { // ... implementation details ... } ``` -------------------------------- ### Implement Unix Language Preferences Source: https://docs.rs/whoami/2.1.1/src/whoami/os.rs.html Retrieves language preferences from environment variables following GNU gettext conventions for Unix-like systems. ```rust // This is only used on some platforms #[cfg(feature = "std")] #[allow(dead_code)] fn unix_lang() -> Result { use std::{ env::{self, VarError}, str::FromStr, vec::Vec, }; use crate::{Error, Language}; let env_var = |var: &str| match env::var(var) { Ok(value) => Ok(if value.is_empty() { None } else { Some(value) }), Err(VarError::NotPresent) => Ok(None), Err(VarError::NotUnicode(_)) => { Err(Error::with_invalid_data("not unicode")) } }; // Uses priority defined in // let lc_all = env_var("LC_ALL")?; let lang = env_var("LANG")?; if lang.is_none() && lc_all.is_none() { return Err(Error::empty_record()); } // Standard locales that have a higher global precedence than their specific // counterparts, indicating that one should not perform any localization. // https://www.gnu.org/software/libc/manual/html_node/Standard-Locales.html if let Some(l) = &lang { if l == "C" || l == "POSIX" { return Ok(LanguagePreferences { fallbacks: Vec::new(), ..Default::default() }); } } // The LANGUAGE environment variable takes precedence if and only if // localization is enabled, i.e., LC_ALL / LANG is not "C" or "POSIX". // if let Some(language) = env_var("LANGUAGE")? { return Ok(LanguagePreferences { fallbacks: language ``` -------------------------------- ### OS String Conversion Logic Source: https://docs.rs/whoami/2.1.1/src/whoami/conversions.rs.html Handles conversion from OsString to String across different platforms and feature configurations. ```rust 1use alloc::string::String; 2 3use crate::Result; 4 5#[cfg(feature = "std")] 6pub(super) type OsString = std::ffi::OsString; 7#[cfg(not(feature = "std"))] 8pub(super) type OsString = String; 9 10#[cfg(not(feature = "std"))] 11pub(crate) fn string_from_os(string: String) -> Result { 12 Ok(string) 13} 14 15#[cfg(feature = "std")] 16pub(crate) fn string_from_os(string: OsString) -> Result { 17 use crate::Error; 18 19 #[cfg(any( 20 all(not(target_os = "windows"), not(target_arch = "wasm32")), 21 all(target_arch = "wasm32", target_os = "wasi"), 22 ))] 23 { 24 #[cfg(not(target_os = "wasi"))] 25 use std::os::unix::ffi::OsStringExt; 26 #[cfg(target_os = "wasi")] 27 use std::os::wasi::ffi::OsStringExt; 28 use std::string::ToString; 29 30 String::from_utf8(string.into_vec()) 31 .map_err(|e| Error::with_invalid_data(e.to_string())) 32 } 33 34 #[cfg(any( 35 target_os = "windows", 36 all(target_arch = "wasm32", not(target_os = "wasi")), 37 ))] 38 { 39 string 40 .into_string() 41 .map_err(|_| Error::with_invalid_data("Not valid unicode")) 42 } 43} ``` -------------------------------- ### Implementing PartialEq for Platform Source: https://docs.rs/whoami/2.1.1/whoami/enum.Platform.html Provides the equality comparison operators (`==` and `!=`) for the Platform enum. This allows direct comparison of platform values. ```rust fn eq(&self, other: &Platform) -> bool { // ... implementation details ... } fn ne(&self, other: &Rhs) -> bool { // ... implementation details ... } ``` -------------------------------- ### PartialEq implementation for DesktopEnvironment Source: https://docs.rs/whoami/2.1.1/whoami/enum.DesktopEnvironment.html This implementation enables equality comparisons between DesktopEnvironment values using the `==` operator. ```rust fn eq(&self, other: &DesktopEnvironment) -> bool ``` -------------------------------- ### Retrieve CPU Architecture Source: https://docs.rs/whoami/2.1.1/src/whoami/os/unix.rs.html Uses libc's uname to query system architecture information. ```rust 424 #[inline(always)] 425 fn arch(self) -> Result { 426 let mut buf: libc::utsname = unsafe { mem::zeroed() }; 427 428 if unsafe { libc::uname(&mut buf) } == -1 { ``` -------------------------------- ### Get User's Real Name Source: https://docs.rs/whoami/2.1.1/whoami/fn.realname.html Use this function to retrieve the user's full name. It returns a Result containing the name as a String. ```rust pub fn realname() -> Result ``` -------------------------------- ### Get Collation Language Preferences Source: https://docs.rs/whoami/2.1.1/src/whoami/langs.rs.html Returns an iterator over the collation language preferences in order of user preference. Collation languages are used for sorting and regular expressions. ```rust pub fn collation_langs(&self) -> impl Iterator + '_ { self.chain_fallbacks(&self.collation) } ``` -------------------------------- ### Check if DesktopEnvironment is GTK-based Source: https://docs.rs/whoami/2.1.1/whoami/enum.DesktopEnvironment.html Use this function to determine if the current desktop environment is based on the GTK toolkit. No specific setup is required beyond having an instance of DesktopEnvironment. ```rust pub const fn is_gtk(&self) -> bool ``` -------------------------------- ### Platform Information Source: https://docs.rs/whoami/2.1.1/src/whoami/api.rs.html Retrieves the current operating system's platform information. ```APIDOC ## GET /platform ### Description Get the platform of the operating system. ### Method GET ### Endpoint /platform ### Response #### Success Response (200) - **platform** (Platform) - The operating system platform. #### Response Example ```json { "platform": "desktop" } ``` ``` -------------------------------- ### PartialEq Implementations for Language Source: https://docs.rs/whoami/2.1.1/whoami/struct.Language.html Provides implementations for comparing `Language` structs with strings and other `Language` structs. This allows for flexible equality checks using various string formats and direct struct comparisons. ```APIDOC ### impl PartialEq<&str> for Language #### fn eq(&self, string: &&str) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for &str #### fn eq(&self, lang: &Language) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for String #### fn eq(&self, lang: &Language) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for str #### fn eq(&self, string: &str) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for Language #### fn eq(&self, string: &String) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for Language #### fn eq(&self, string: &str) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ### impl PartialEq for Language #### fn eq(&self, other: &Language) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ``` -------------------------------- ### Retrieve device name Source: https://docs.rs/whoami/2.1.1/whoami/fn.devicename.html Returns the device's pretty name as a Result containing a String. ```rust pub fn devicename() -> Result ``` -------------------------------- ### whoami Library Functions Source: https://docs.rs/whoami/2.1.1/whoami/index.html A collection of functions to retrieve user and system environment information. ```APIDOC ## Library Functions ### Description These functions provide access to system and user information. Most return a String or an enum representing the requested data. ### Functions - **whoami::username()** - Returns the user's username as a String. - **whoami::realname()** - Returns the user's full name as a String. - **whoami::hostname()** - Returns the device's hostname as a String. - **whoami::devicename()** - Returns the device's pretty name as a String. - **whoami::platform()** - Returns the underlying platform as a Platform enum. - **whoami::cpu_arch()** - Returns the CPU architecture as a CpuArchitecture enum. - **whoami::desktop_env()** - Returns the desktop environment as a DesktopEnvironment enum. - **whoami::lang_prefs()** - Returns the user's language preferences as a LanguagePreferences object. - **whoami::distro()** - Returns the OS distribution name as a String. ### Usage Example ```rust println!("User: {}", whoami::username().unwrap_or_default()); println!("Platform: {}", whoami::platform()); ``` ``` -------------------------------- ### Retrieve System Information via whoami API Source: https://docs.rs/whoami/2.1.1/src/whoami/api.rs.html A collection of functions for accessing system-level identity and environment information. Most functions provide both a standard String return and an OsString variant for platform-specific handling. ```rust 1use alloc::string::String; use crate::{ conversions, os::{Os, Target}, CpuArchitecture, DesktopEnvironment, LanguagePreferences, OsString, Platform, Result, }; macro_rules! report_message { () => { "Please report this issue at https://github.com/ardaku/whoami/issues" }; } /// Get the CPU Architecture. #[must_use] #[inline(always)] pub fn cpu_arch() -> CpuArchitecture { Target::arch(Os).expect(concat!("arch() failed. ", report_message!())) } /// Get the user's account name; usually just the username, but may include an /// account server hostname. /// /// If you don't want the account server hostname, use [`username()`]. /// /// Example: `username@example.com` #[inline(always)] pub fn account() -> Result { account_os().and_then(conversions::string_from_os) } /// Get the user's account name; usually just the username, but may /// include an account server hostname. /// /// If you don't want the account server hostname, use [`username()`]. /// /// Example: `username@example.com` #[inline(always)] pub fn account_os() -> Result { Target::account(Os) } /// Get the user's username. /// /// On unix-systems this differs from [`realname()`] most notably in that spaces /// are not allowed in the username. #[inline(always)] pub fn username() -> Result { username_os().and_then(conversions::string_from_os) } /// Get the user's username. /// /// On unix-systems this differs from [`realname_os()`] most notably in that /// spaces are not allowed in the username. #[inline(always)] pub fn username_os() -> Result { Target::username(Os) } /// Get the user's real (full) name. #[inline(always)] pub fn realname() -> Result { realname_os().and_then(conversions::string_from_os) } /// Get the user's real (full) name. #[inline(always)] pub fn realname_os() -> Result { Target::realname(Os) } /// Get the host device's hostname. /// /// Usually hostnames are case-insensitive, but it's not a hard requirement. /// /// # Platform-Specific Character Limitations /// /// ## Unix/Linux/BSD /// - **Maximum length**: 255 bytes (excluding null terminator) /// - **Encoding**: Must be valid UTF-8 /// - **Characters**: Typically follows RFC 952/1123 DNS hostname rules: /// - Alphanumeric characters (a-z, A-Z, 0-9) /// - Hyphens (-), but not at start or end /// - Note: POSIX allows any character except null and newline, but network /// hostnames should follow DNS rules for interoperability /// /// ## Windows /// - **Maximum length**: 63 characters for DNS hostname (per label) /// - **Encoding**: UTF-16 (converted to UTF-8 String) /// - **Characters**: Follows DNS hostname rules (RFC 1123): /// - Alphanumeric characters (a-z, A-Z, 0-9) /// - Hyphens (-), but not at start or end /// /// ## Redox /// - Reads from `/etc/hostname` file /// - First line of file is used as hostname /// - No inherent character limitations beyond file system /// /// ## Web (WASM) /// - Returns the document's domain name /// - Follows DNS hostname rules as enforced by browsers /// - Must be valid UTF-8 /// /// ## Other Platforms /// - WASI: Returns system hostname or defaults to "localhost" /// - Default: Returns "localhost" for unsupported platforms /// /// # Notes /// For maximum compatibility across all platforms and network protocols, /// hostnames should: /// - Be 63 characters or less /// - Contain only ASCII alphanumeric characters and hyphens /// - Not start or end with a hyphen /// - Be case-insensitive (though case may be preserved) #[inline(always)] pub fn hostname() -> Result { Target::hostname(Os) } /// Get the device name (also known as "Pretty Name"). /// /// Often used to identify device for bluetooth pairing. #[inline(always)] pub fn devicename() -> Result { devicename_os().and_then(conversions::string_from_os) } /// Get the device name (also known as "Pretty Name"). /// /// Often used to identify device for bluetooth pairing. #[inline(always)] pub fn devicename_os() -> Result { Target::devicename(Os) } /// Get the name of the operating system distribution and (possibly) version. /// /// Example: "Windows 10" or "Fedora 26 (Workstation Edition)" #[inline(always)] pub fn distro() -> Result { Target::distro(Os) } /// Get the desktop environment (if any). /// /// Example: "gnome" or "windows" /// /// Returns `None` if a desktop environment is not available (for example in a /// TTY or over SSH) #[must_use] #[inline(always)] pub fn desktop_env() -> Option { ``` -------------------------------- ### Whoami Functions API Source: https://docs.rs/whoami/2.1.1/index.html This section details the available functions in the whoami crate for retrieving user and system information. ```APIDOC ## Whoami Functions API ### Description This API documentation outlines the various functions provided by the `whoami` crate to query information about the current user and their operating environment. Each function is designed to return specific details, often as strings or specific enum types. ### Functions #### `account()` - **Description**: Get the user’s account name; usually just the username, but may include an account server hostname. - **Returns**: `Result` #### `account_os()` - **Description**: Get the user’s account name; usually just the username, but may include an account server hostname. (OS specific implementation) - **Returns**: `Result` #### `cpu_arch()` - **Description**: Get the CPU Architecture. - **Returns**: `CpuArchitecture` #### `desktop_env()` - **Description**: Get the desktop environment (if any). - **Returns**: `Option` #### `devicename()` - **Description**: Get the device name (also known as “Pretty Name”). - **Returns**: `Result` #### `devicename_os()` - **Description**: Get the device name (also known as “Pretty Name”). (OS specific implementation) - **Returns**: `Result` #### `distro()` - **Description**: Get the name of the operating system distribution and (possibly) version. - **Returns**: `Result` #### `hostname()` - **Description**: Get the host device’s hostname. - **Returns**: `Result` #### `lang_prefs()` - **Description**: Get the user’s preferred language(s). - **Returns**: `Result` #### `platform()` - **Description**: Get the platform. - **Returns**: `Platform` #### `realname()` - **Description**: Get the user’s real (full) name. - **Returns**: `Result` #### `realname_os()` - **Description**: Get the user’s real (full) name. (OS specific implementation) - **Returns**: `Result` #### `username()` - **Description**: Get the user’s username. - **Returns**: `Result` #### `username_os()` - **Description**: Get the user’s username. (OS specific implementation) - **Returns**: `Result` ``` -------------------------------- ### Account OS Function Source: https://docs.rs/whoami/2.1.1/whoami/fn.account_os.html Retrieves the user's account name, which may include the account server hostname. For just the username, use the `username()` function. ```APIDOC ## account_os ### Description Get the user’s account name; usually just the username, but may include an account server hostname. If you don’t want the account server hostname, use `username()`. ### Method GET (Conceptual - this is a function call, not a direct HTTP endpoint) ### Endpoint N/A (Rust function) ### Parameters None ### Request Example ```rust use whoami::account_os; fn main() { match account_os() { Ok(account) => println!("Account: {}", account.to_string_lossy()), Err(e) => eprintln!("Error getting account: {}", e), } } ``` ### Response #### Success Response (Result) - **account_os** (OsString) - The user's account name, potentially including the hostname. #### Response Example ```json { "account_os": "username@example.com" } ``` ``` -------------------------------- ### Implement TryInto for TryFrom types Source: https://docs.rs/whoami/2.1.1/whoami/enum.DesktopEnvironment.html Provides a blanket implementation of TryInto for any type that implements TryFrom. ```rust impl TryInto for T where U: TryFrom, ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ```