Skip to content

Commit 42d06f9

Browse files
committed
printf: fix OsString handling
1 parent af577e7 commit 42d06f9

File tree

1 file changed

+5
-29
lines changed

1 file changed

+5
-29
lines changed

src/uu/printf/src/printf.rs

Lines changed: 5 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,9 @@
55
use clap::{Arg, ArgAction, Command};
66
use std::io::stdout;
77
use std::ops::ControlFlow;
8-
#[cfg(unix)]
9-
use std::os::unix::ffi::{OsStrExt, OsStringExt};
10-
#[cfg(windows)]
11-
use std::os::windows::ffi::OsStrExt;
128
use uucore::error::{UResult, UUsageError};
139
use uucore::format::{FormatArgument, FormatItem, parse_spec_and_escape};
14-
use uucore::{format_usage, help_about, help_section, help_usage, show_warning};
10+
use uucore::{format_usage, help_about, help_section, help_usage, os_str_as_bytes, show_warning};
1511

1612
const VERSION: &str = "version";
1713
const HELP: &str = "help";
@@ -30,33 +26,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
3026
let format = matches
3127
.get_one::<std::ffi::OsString>(options::FORMAT)
3228
.ok_or_else(|| UUsageError::new(1, "missing operand"))?;
33-
34-
#[cfg(unix)]
35-
let format = format.as_bytes();
36-
37-
#[cfg(windows)]
38-
let format_vec: Vec<u8> = format
39-
.encode_wide()
40-
.flat_map(|wchar| wchar.to_le_bytes())
41-
.collect();
42-
#[cfg(windows)]
43-
let format = format_vec.as_slice();
29+
let format = os_str_as_bytes(format)?;
4430

4531
let values: Vec<_> = match matches.get_many::<std::ffi::OsString>(options::ARGUMENT) {
32+
// FIXME: use os_str_as_bytes once FormatArgument supports Vec<u8>
4633
Some(s) => s
47-
.map(|os_str| {
48-
#[cfg(unix)]
49-
let raw_bytes: Vec<u8> = os_str.clone().into_vec();
50-
51-
#[cfg(windows)]
52-
let raw_bytes: Vec<u8> = os_str
53-
.encode_wide()
54-
.flat_map(|wchar| wchar.to_le_bytes())
55-
.collect();
56-
FormatArgument::Unparsed(
57-
String::from_utf8(raw_bytes.clone())
58-
.unwrap_or_else(|_| raw_bytes.iter().map(|&b| b as char).collect()),
59-
)
34+
.map(|os_string| {
35+
FormatArgument::Unparsed(std::ffi::OsStr::to_string_lossy(os_string).to_string())
6036
})
6137
.collect(),
6238
None => vec![],

0 commit comments

Comments
 (0)