Skip to content

Commit 3fea7cf

Browse files
committed
basename: Fix basename function, print raw byte slice.
1 parent 2f53d59 commit 3fea7cf

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

src/uu/basename/src/basename.rs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use clap::builder::ValueParser;
99
use clap::{Arg, ArgAction, Command};
1010
use std::collections::HashMap;
1111
use std::ffi::OsString;
12+
use std::io::{Write, stdout};
1213
use std::path::PathBuf;
1314
use uucore::display::Quotable;
1415
use uucore::error::{UResult, UUsageError};
@@ -73,7 +74,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
7374
//
7475

7576
for path in name_args {
76-
print!("{}{line_ending}", basename(path, &suffix));
77+
stdout().write_all(&basename(path, &suffix)?)?;
78+
print!("{line_ending}");
7779
}
7880

7981
Ok(())
@@ -120,24 +122,30 @@ pub fn uu_app() -> Command {
120122
)
121123
}
122124

123-
fn basename(fullname: &OsString, suffix: &OsString) -> String {
124-
// TODO: Remove those 2 lines.
125-
let fullname = &fullname.to_string_lossy().to_string();
126-
let suffix = &suffix.to_string_lossy().to_string();
125+
// We return a Vec<u8>. Returning a seemingly more proper `OsString` would
126+
// require back and forth conversions as we need a &[u8] for printing anyway.
127+
fn basename(fullname: &OsString, suffix: &OsString) -> UResult<Vec<u8>> {
128+
let fullname_bytes = uucore::os_str_as_bytes(fullname)?;
127129

128130
// Handle special case where path ends with /.
129-
if fullname.ends_with("/.") {
130-
return ".".to_string();
131+
if fullname_bytes.ends_with(b"/.") {
132+
return Ok(b".".into());
131133
}
132134

135+
// Convert to path buffer and get last path component
133136
let pb = PathBuf::from(fullname);
134137

135-
pb.components().next_back().map_or_else(String::new, |c| {
136-
let name = c.as_os_str().to_str().unwrap();
138+
pb.components().next_back().map_or(Ok([].into()), |c| {
139+
let name = c.as_os_str();
140+
let name_bytes = uucore::os_str_as_bytes(name)?;
137141
if name == suffix {
138-
name.to_string()
142+
Ok(name_bytes.into())
139143
} else {
140-
name.strip_suffix(suffix).unwrap_or(name).to_string()
144+
let suffix_bytes = uucore::os_str_as_bytes(suffix)?;
145+
Ok(name_bytes
146+
.strip_suffix(suffix_bytes)
147+
.unwrap_or(name_bytes)
148+
.into())
141149
}
142150
})
143151
}

0 commit comments

Comments
 (0)