Files
s390-tools/rust/utils/src/hostname.rs
Marc Hartmayer 6689e25865 rust: Fix all cargo clippy findings
- Remove useless type conversion in uvdevice.rs
- Replace useless comparison in hostname.rs
- Replace unnecessary unwrap patterns in pvapconfig
- Use sort_by_key instead of sort_by in pvimg example

Command line used to get the findings:

  $ clippy --all-features -- --cap-lints=warn
  warning: useless conversion to the same type: `u64`
    --> pv_core/src/uvdevice.rs:56:28
     |
  56 |         rc = ioctl(raw_fd, cmd.try_into().unwrap(), cb.as_ptr_mut());
     |                            ^^^^^^^^^^^^^^
     |
     = help: consider removing `.try_into()`
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_conversion
     = note: `#[warn(clippy::useless_conversion)]` on by default

  warning: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false
    --> utils/src/hostname.rs:60:13
     |
  60 |     assert!(isize::try_from(buf_len).unwrap() <= isize::MAX);
     |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |
     = help: because `isize::MAX` is the maximum value for this type, this comparison is always true
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#absurd_extreme_comparisons
     = note: `#[warn(clippy::absurd_extreme_comparisons)]` on by default

  warning: `utils` (lib) generated 1 warning
      Checking pvebc v0.12.0 (/home/mhartmay/git/s390-tools/rust/pvebc)
  warning: consider using `sort_unstable_by_key`
     --> pvapconfig/src/ap.rs:177:9
      |
  177 |         self.0.sort_unstable_by(|a, b| b.gen.cmp(&a.gen));
      |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      |
      = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by
      = note: `#[warn(clippy::unnecessary_sort_by)]` on by default
  help: try
      |
  177 -         self.0.sort_unstable_by(|a, b| b.gen.cmp(&a.gen));
  177 +         self.0.sort_unstable_by_key(|b| std::cmp::Reverse(b.gen));

  warning: called `unwrap_err` on `r` after checking its variant with `is_err`
    --> pvapconfig/src/main.rs:55:29
     |
  54 |         if $r.is_err() {
     |         -------------- help: try: `if let Err(<item>) = r`
  55 |             eprintln!("{}", $r.unwrap_err());
     |                             ^^^^^^^^^^^^^^^
  ...
  87 |     on_error_print_and_exit!(r);
     |     --------------------------- in this macro invocation
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_unwrap
     = note: this warning originates in the macro `on_error_print_and_exit` (in Nightly builds, run with -Z macro-backtrace for more info)

  warning: this `repeat().take()` can be written more concisely
    --> pvimg/src/se_img_comps/bootloader/ipl.rs:95:21
     |
  95 |           let comps = iter::repeat(ipl_pb0_pv_comp::default())
     |  _____________________^
  96 | |             .take(num_comp)
     | |___________________________^ help: consider using `repeat_n()` instead: `std::iter::repeat_n(ipl_pb0_pv_comp::default(), num_comp)`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_repeat_n
     = note: `#[warn(clippy::manual_repeat_n)]` on by default

  warning: this `repeat().take()` can be written more concisely
     --> pvimg/src/se_img_comps/bootloader/ipl.rs:113:21
      |
  113 |         let comps = iter::repeat(comp).take(num_comp).collect();
      |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `repeat_n()` instead: `std::iter::repeat_n(comp, num_comp)`
      |
      = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_repeat_n

Reviewed-by: Timo Keller <tkeller@linux.ibm.com>
Reviewed-by: Steffen Eiden <seiden@linux.ibm.com>
Reviewed-by: Harald Freudenberger <freude@linux.ibm.com>
Signed-off-by: Marc Hartmayer <marc@linux.ibm.com>
Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
2026-06-25 14:14:43 +02:00

70 lines
2.1 KiB
Rust

// SPDX-License-Identifier: MIT
//
// Copyright IBM Corp. 2026
use std::ffi::CStr;
use std::io;
/// Returns the maximum hostname length supported by the system.
///
/// # Returns
///
/// The maximum hostname length in bytes, excluding the NUL terminator.
fn max_hostname_len() -> usize {
const _POSIX_HOST_NAME_MAX: usize = 255;
// SAFETY: sysconf is safe to call with _SC_HOST_NAME_MAX and only reads system configuration
// without side effects.
let n = unsafe { libc::sysconf(libc::_SC_HOST_NAME_MAX) };
if n < 0 {
_POSIX_HOST_NAME_MAX
} else {
n.try_into().unwrap()
}
}
/// Retrieves the system hostname using libc gethostname.
///
/// # Returns
///
/// Returns `Ok(String)` containing the hostname on success, or an `Err(io::Error)` otherwise.
///
/// # Examples
///
/// ```rust,no_run
/// use utils::gethostname;
///
/// let hostname = gethostname().expect("Failed to get hostname");
/// println!("Hostname: {}", hostname);
/// ```
pub fn gethostname() -> io::Result<String> {
// Add space for NUL terminator
let buf_len = max_hostname_len().checked_add(1).unwrap();
let mut buf = vec![0u8; buf_len];
// SAFETY: `buf` is a byte array large enough for storing the result of
// `gethostname` as the max length was just checked before.
let result = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
if result != 0 {
// libc::gethostname returns -1 on error and sets errno
return Err(io::Error::last_os_error());
}
// If it is not NUL-terminated, then add the NUL-termination at the end
if !buf.contains(&0) {
if let Some(last) = buf.last_mut() {
*last = 0;
}
}
assert!(buf_len <= isize::MAX as usize);
// SAFETY: We made sure that `buf` is:
// 1. NUL-terminated
// 2. A single allocation (vec![...] was used for the allocation)
// 3. `buf_len` is <= isize::MAX (verified by assertion above)
// Therefore, it's safe to construct a CStr from the buffer pointer.
let cstr = unsafe { CStr::from_ptr(buf.as_ptr() as *const libc::c_char) };
Ok(cstr.to_string_lossy().into_owned())
}