Use CStr instead of strlen to improve readability

This commit is contained in:
Yuyi Wang
2025-05-19 16:44:14 +08:00
parent 223b98f2ff
commit 7a79366f91
2 changed files with 6 additions and 10 deletions

View File

@@ -1184,15 +1184,12 @@ pub fn truncate_at_nul(input: &wstr) -> &wstr {
}
pub fn cstr2wcstring(input: &[u8]) -> WString {
let strlen = input.iter().position(|c| *c == b'\0').unwrap();
str2wcstring(&input[0..strlen])
let input = CStr::from_bytes_until_nul(input).unwrap().to_bytes();
str2wcstring(input)
}
pub(crate) fn charptr2wcstring(input: *const libc::c_char) -> WString {
let input: &[u8] = unsafe {
let strlen = libc::strlen(input);
slice::from_raw_parts(input.cast(), strlen)
};
let input: &[u8] = unsafe { CStr::from_ptr(input).to_bytes() };
str2wcstring(input)
}

View File

@@ -21,7 +21,7 @@
use crate::wcstringutil::{join_strings, wcs2string_callback};
use errno::errno;
pub use gettext::{wgettext, wgettext_fmt, wgettext_maybe_fmt, wgettext_str};
use std::ffi::OsStr;
use std::ffi::{CStr, OsStr};
use std::fs::{self, canonicalize};
use std::io::{self, Write};
use std::os::unix::prelude::*;
@@ -89,9 +89,8 @@ pub fn perror(s: &str) {
let _ = write!(stderr, "{s}: ");
}
let slice = unsafe {
let msg = libc::strerror(e) as *const u8;
let len = libc::strlen(msg as *const _);
std::slice::from_raw_parts(msg, len)
let msg = libc::strerror(e);
CStr::from_ptr(msg).to_bytes()
};
let _ = stderr.write_all(slice);
let _ = stderr.write_all(b"\n");