Skip to content

Commit 456fac3

Browse files
committed
Make yes command behaviour match gnu
1 parent 1426c50 commit 456fac3

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

src/bin/yes.rs

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::{
22
borrow::Cow,
3-
ffi::OsString,
43
io::{BufWriter, Write, stdout},
54
os::unix::ffi::OsStringExt,
65
};
@@ -20,9 +19,9 @@ fn main() -> Result {
2019
// No point in locking stdout since we only use it once in this program
2120
let mut stdout = stdout();
2221

23-
let mut first_value: Option<Vec<u8>> = None;
22+
let mut buffer: Option<Vec<u8>> = None;
2423

25-
if let Some(arg) = arg_parser.forward()? {
24+
while let Some(arg) = arg_parser.forward()? {
2625
match arg {
2726
Long("version") => {
2827
stdout.write_all(VERSION)?;
@@ -36,29 +35,22 @@ fn main() -> Result {
3635

3736
return Ok(());
3837
}
38+
Value(value) => {
39+
extend_buffer(&mut buffer, value.as_bytes().to_vec());
40+
}
3941
Long(_) | Short(_) => return Err(Exit::ArgError(arg.into_error(None))),
40-
Value(value) => first_value = Some(value.as_bytes().to_vec()),
4142
}
4243
}
4344

44-
let mut args = arg_parser.into_inner();
45-
46-
if first_value.is_none() {
47-
first_value = args.next().map(OsString::into_vec);
48-
}
49-
50-
// We prepare the output so it doesn't need to go through the formatting each time
51-
let output: Cow<'_, [u8]> = if let Some(mut first) = first_value {
52-
for arg in args {
53-
first.push(b' '); // Manually put the space
54-
first.append(&mut arg.into_vec()); // Append will move the data efficiently from the other vector
55-
}
56-
57-
first.push(b'\n');
45+
arg_parser
46+
.into_inner()
47+
.for_each(|arg| extend_buffer(&mut buffer, arg.into_vec()));
5848

59-
Cow::Owned(first)
49+
let output: Cow<'_, [u8]> = if let Some(mut buffer) = buffer {
50+
buffer.push(b'\n');
51+
Cow::Owned(buffer)
6052
} else {
61-
Cow::Borrowed(b"y\n") // If there are no args we can just hardcode it and avoid allocation
53+
Cow::Borrowed(b"y\n")
6254
};
6355

6456
// Write everything to stdout, BufWriter will handle the buffering
@@ -68,3 +60,13 @@ fn main() -> Result {
6860
stdout.write_all(&output)?;
6961
}
7062
}
63+
64+
#[inline]
65+
fn extend_buffer(buffer: &mut Option<Vec<u8>>, mut arg: Vec<u8>) {
66+
if let Some(buffer) = buffer {
67+
buffer.push(b' '); // Manually put the space
68+
buffer.append(&mut arg);
69+
} else {
70+
*buffer = Some(arg)
71+
}
72+
}

0 commit comments

Comments
 (0)