On Thu, 27 Jun 2019 09:10:28 +0200 Quentin Rameau <[email protected]> wrote:
Dear Quentin,
> I agree, yes is neither a benchmark tool nor a data generator, it just
> outputs 'y' for piping into other commands.
> Keep it simple.
I agree with you in general, but are we really "optimizing" yes(1) here
for the sake of performance? This looks to me like a case of premature
optimization.
We don't know if a script relies on the behaviour of yes(1) printing
all passed strings repeatedly. So, even though the tool is not
standardized by Posix the common "consensus" is that
- with no arguments, it shall print y and a newline repeatedly.
- with arguments, it shall print them, comma separated, followed by
newline, repeatedly.
The point about readability is a good one. I will even take the blame
for writing it as it is now. However, you could greatly improve
readability without sacrificing features/performance. The line
argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0;
is used in many places in sbase and is more or less an idiom. The
entire tool itself could then be written as follows. We can even
remove the checks consequently within the loop, which could be regarded
as a "performance" improvement.
int i;
argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0;
if (argc == 0) {
for (;;) {
fputs("y\n", stdout);
}
} else {
for (;;) {
for (i = 0; i < argc; i++) {
fputs(argv[i], stdout);
fputc(' ', stdout);
}
fputc('\n', stdout);
}
}
What do you think? Patch is attached.
With best regards
Laslo
--
Laslo Hunhold <[email protected]>
>From 0991e46b5a5953133454b573513a88bb7b7c1a19 Mon Sep 17 00:00:00 2001 From: Laslo Hunhold <[email protected]> Date: Fri, 28 Jun 2019 08:56:10 +0200 Subject: [PATCH] Improve yes(1) readability The code was terse, but at the cost of readability. Relax the loop a bit, separate the main check instead of doing it with ternary operators within the loop. Signed-off-by: Laslo Hunhold <[email protected]> --- yes.c | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/yes.c b/yes.c index dd97ea6..ebb9513 100644 --- a/yes.c +++ b/yes.c @@ -6,13 +6,22 @@ int main(int argc, char *argv[]) { - char **p; + int i; argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0; - for (p = argv; ; p = (*p && *(p + 1)) ? p + 1 : argv) { - fputs(*p ? *p : "y", stdout); - putchar((!*p || !*(p + 1)) ? '\n' : ' '); + if (argc == 0) { + for (;;) { + fputs("y\n", stdout); + } + } else { + for (;;) { + for (i = 0; i < argc; i++) { + fputs(argv[i], stdout); + fputc(' ', stdout); + } + fputc('\n', stdout); + } } return 1; /* not reached */ -- 2.22.0
pgpGXbrAQOApL.pgp
Description: PGP signature
