2
* fast fgets() replacement for log parsing
4
* Copyright 2000-2009 Willy Tarreau <w@1wt.eu>
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version
9
* 2 of the License, or (at your option) any later version.
11
* This function manages its own buffer and returns a pointer to that buffer
12
* in order to avoid expensive memory copies. It also checks for line breaks
13
* 32 bits at a time. It could be improved a lot using mmap() but we would
14
* not be allowed to replace trailing \n with zeroes and we would be limited
15
* to small log files on 32-bit machines.
24
// return 1 if the integer contains at least one zero byte
25
static inline unsigned int has_zero(unsigned int x)
27
if (!(x & 0xFF000000U) ||
36
#define FGETS2_BUFSIZE (256*1024)
37
const char *fgets2(FILE *stream)
39
static char buffer[FGETS2_BUFSIZE + 5];
40
static char *end = buffer;
41
static char *line = buffer;
49
/* this is a speed-up, we read 32 bits at once and check for an
50
* LF character there. We stop if found then continue one at a
53
while (next < end && (((unsigned long)next) & 3) && *next != '\n')
56
/* now next is multiple of 4 or equal to end */
57
while (next <= (end-32)) {
58
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
61
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
64
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
67
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
70
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
73
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
76
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
79
if (has_zero(*(unsigned int *)next ^ 0x0A0A0A0A))
84
/* we finish if needed. Note that next might be slightly higher
85
* than end here because we might have gone past it above.
89
const char *start = line;
98
/* we found an incomplete line. First, let's move the
99
* remaining part of the buffer to the beginning, then
100
* try to complete the buffer with a new read.
104
memmove(buffer, line, end - line);
105
end = buffer + (end - line);
109
if (end == buffer + FGETS2_BUFSIZE)
113
ret = read(fileno(stream), end, buffer + FGETS2_BUFSIZE - end);
124
/* search for '\n' again */
131
unsigned int lines = 0;
133
while ((p=fgets2(stdin)))
135
printf("lines=%d\n", lines);