libpulse_binding/util.rs
1// Copyright 2017 Lyndon Brown
2//
3// This file is part of the PulseAudio Rust language binding.
4//
5// Licensed under the MIT license or the Apache license (version 2.0), at your option. You may not
6// copy, modify, or distribute this file except in compliance with said license. You can find copies
7// of these licenses either in the LICENSE-MIT and LICENSE-APACHE files, or alternatively at
8// <http://opensource.org/licenses/MIT> and <http://www.apache.org/licenses/LICENSE-2.0>
9// respectively.
10//
11// Portions of documentation are copied from the LGPL 2.1+ licensed PulseAudio C headers on a
12// fair-use basis, as discussed in the overall project readme (available in the git repository).
13
14//! Assorted utility functions.
15
16use std::ffi::CStr;
17
18macro_rules! fn_string_with_buffer {
19 ( $fn_call:ident, $l:ident ) => {{
20 let mut tmp = Vec::with_capacity($l);
21 unsafe {
22 // Need to check NULL return here because `get_binary_name` function is not
23 // supported on all architectures and so may return NULL, and might as well check
24 // NULL return for other uses anyway.
25 let ptr = capi::$fn_call(tmp.as_mut_ptr(), $l);
26 match ptr.is_null() {
27 true => None,
28 false => Some(CStr::from_ptr(tmp.as_mut_ptr()).to_string_lossy().into_owned()),
29 }
30 }
31 }};
32}
33
34/// Gets the current username.
35///
36/// Returns `None` on failure.
37pub fn get_user_name(l: usize) -> Option<String> {
38 fn_string_with_buffer!(pa_get_user_name, l)
39}
40
41/// Gets the current hostname.
42///
43/// Returns `None` on failure.
44pub fn get_host_name(l: usize) -> Option<String> {
45 fn_string_with_buffer!(pa_get_host_name, l)
46}
47
48/// Gets the fully qualified domain name.
49///
50/// Returns `None` on failure.
51pub fn get_fqdn(l: usize) -> Option<String> {
52 fn_string_with_buffer!(pa_get_fqdn, l)
53}
54
55/// Gets the home directory of the current user.
56///
57/// Returns `None` on failure.
58pub fn get_home_dir(l: usize) -> Option<String> {
59 fn_string_with_buffer!(pa_get_home_dir, l)
60}
61
62/// Gets the binary file name of the current process.
63///
64/// Returns `None` on failure.
65/// This is not supported on all architectures (in which case `NULL` is returned).
66pub fn get_binary_name(l: usize) -> Option<String> {
67 fn_string_with_buffer!(pa_get_binary_name, l)
68}
69
70/// Makes the calling thread realtime if we can.
71///
72/// On Linux, this uses RealTimeKit if available and POSIX APIs otherwise (the latter applies to
73/// other UNIX variants as well). This is also implemented for macOS and Windows.
74#[cfg(any(doc, feature = "pa_v13"))]
75#[cfg_attr(docsrs, doc(cfg(feature = "pa_v13")))]
76pub fn make_thread_realtime(rtprio: i32) -> Result<(), ()> {
77 match unsafe { capi::pa_thread_make_realtime(rtprio) } {
78 0 => Ok(()),
79 _ => Err(()),
80 }
81}