Improve freadseek's efficiency after ungetc.
[gnulib.git] / lib / freadseek.c
1 /* Skipping input from a FILE stream.
2    Copyright (C) 2007-2008 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 /* Specification.  */
20 #include "freadseek.h"
21
22 #include <stdlib.h>
23 #include <unistd.h>
24
25 #include "freadahead.h"
26 #include "freadptr.h"
27
28 /* Increment the in-memory pointer.  INCREMENT must be at most the buffer size
29    returned by freadptr().
30    This is very cheap (no system calls).  */
31 static inline void
32 freadptrinc (FILE *fp, size_t increment)
33 {
34   /* Keep this code in sync with freadptr!  */
35 #if defined _IO_ferror_unlocked     /* GNU libc, BeOS */
36   fp->_IO_read_ptr += increment;
37 #elif defined __sferror             /* FreeBSD, NetBSD, OpenBSD, MacOS X, Cygwin */
38   fp->_p += increment;
39   fp->_r -= increment;
40 #elif defined _IOERR                /* AIX, HP-UX, IRIX, OSF/1, Solaris, mingw */
41 # if defined __sun && defined _LP64 /* Solaris/{SPARC,AMD64} 64-bit */
42 #  define fp_ ((struct { unsigned char *_ptr; \
43                          unsigned char *_base; \
44                          unsigned char *_end; \
45                          long _cnt; \
46                          int _file; \
47                          unsigned int _flag; \
48                        } *) fp)
49   fp_->_ptr += increment;
50   fp_->_cnt -= increment;
51 # else
52   fp->_ptr += increment;
53   fp->_cnt -= increment;
54 # endif
55 #elif defined __UCLIBC__            /* uClibc */
56 # ifdef __STDIO_BUFFERS
57   fp->__bufpos += increment;
58 # else
59   abort ();
60 # endif
61 #elif defined __QNX__               /* QNX */
62   fp->_Next += increment;
63 #else
64  #error "Please port gnulib freadseek.c to your platform! Look at the definition of getc, getc_unlocked on your system, then report this to bug-gnulib."
65 #endif
66 }
67
68 int
69 freadseek (FILE *fp, size_t offset)
70 {
71   size_t total_buffered;
72   int fd;
73
74   if (offset == 0)
75     return 0;
76
77   /* Seek over the already read and buffered input as quickly as possible,
78      without doing any system calls.  */
79   total_buffered = freadahead (fp);
80   /* This loop is usually executed at most twice: once for ungetc buffer (if
81      present) and once for the main buffer.  */
82   while (total_buffered > 0)
83     {
84       size_t buffered;
85
86       if (freadptr (fp, &buffered) != NULL && buffered > 0)
87         {
88           size_t increment = (buffered < offset ? buffered : offset);
89
90           freadptrinc (fp, increment);
91           offset -= increment;
92           if (offset == 0)
93             return 0;
94           total_buffered -= increment;
95           if (total_buffered == 0)
96             break;
97         }
98       /* Read one byte.  If we were reading from the ungetc buffer, this
99          switches the stream back to the main buffer.  */
100       if (fgetc (fp) == EOF)
101         goto eof;
102       offset--;
103       if (offset == 0)
104         return 0;
105       total_buffered--;
106     }
107
108   /* Test whether the stream is seekable or not.  */
109   fd = fileno (fp);
110   if (fd >= 0 && lseek (fd, 0, SEEK_CUR) >= 0)
111     {
112       /* FP refers to a regular file.  fseek is most efficient in this case.  */
113       return fseek (fp, offset, SEEK_CUR);
114     }
115   else
116     {
117       /* FP is a non-seekable stream, possibly not even referring to a file
118          descriptor.  Read OFFSET bytes explicitly and discard them.  */
119       char buf[4096];
120
121       do
122         {
123           size_t count = (sizeof (buf) < offset ? sizeof (buf) : offset);
124           if (fread (buf, 1, count, fp) < count)
125             goto eof;
126           offset -= count;
127         }
128       while (offset > 0);
129
130       return 0;
131    }
132
133  eof:
134   /* EOF, or error before or while reading.  */
135   if (ferror (fp))
136     return EOF;
137   else
138     /* Encountered EOF.  */
139     return 0;
140 }