Looks like I was overly cautious about decrementing an unsigned...
size_t n = bytes_read;
while (n)
{
if (all_lines)
n -= n ? 1 : 0; // ...here.
else
As it is under `while (n)' statement, n is always true here, and thus the
ternary operator, though makes no
harm, is needless, and the whole line can be replaced with just `n--;'. Sorry
for that.
The fixed version of the original patch is attached.
--
Алексей Шилин
--- coreutils-8.22.orig/src/head.c 2013-12-04 14:48:30.000000000 +0000
+++ coreutils-8.22/src/head.c 2014-01-03 20:12:07.572863652 +0000
@@ -636,8 +636,11 @@
return false;
}
+ /* n_lines == 0 case needs special treatment. */
+ const bool all_lines = !n_lines;
+
/* Count the incomplete line on files that don't end with a newline. */
- if (bytes_read && buffer[bytes_read - 1] != '\n')
+ if (n_lines && bytes_read && buffer[bytes_read - 1] != '\n')
--n_lines;
while (1)
@@ -647,11 +650,16 @@
size_t n = bytes_read;
while (n)
{
- char const *nl;
- nl = memrchr (buffer, '\n', n);
- if (nl == NULL)
- break;
- n = nl - buffer;
+ if (all_lines)
+ n--;
+ else
+ {
+ char const *nl;
+ nl = memrchr (buffer, '\n', n);
+ if (nl == NULL)
+ break;
+ n = nl - buffer;
+ }
if (n_lines-- == 0)
{
/* Found it. */