ch.c revision 1.2 1 /* $NetBSD: ch.c,v 1.2 1998/01/09 08:03:24 perry Exp $ */
2
3 /*
4 * Copyright (c) 1988 Mark Nudleman
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #ifndef lint
38 static char sccsid[] = "@(#)ch.c 8.1 (Berkeley) 6/6/93";
39 #endif /* not lint */
40
41 /*
42 * Low level character input from the input file.
43 * We use these special purpose routines which optimize moving
44 * both forward and backward from the current read pointer.
45 */
46
47 #include <sys/types.h>
48 #include <sys/file.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <less.h>
52
53 int file = -1; /* File descriptor of the input file */
54
55 /*
56 * Pool of buffers holding the most recently used blocks of the input file.
57 */
58 struct buf {
59 struct buf *next, *prev;
60 long block;
61 int datasize;
62 char data[BUFSIZ];
63 };
64 int nbufs;
65
66 /*
67 * The buffer pool is kept as a doubly-linked circular list, in order from
68 * most- to least-recently used. The circular list is anchored by buf_anchor.
69 */
70 #define END_OF_CHAIN ((struct buf *)&buf_anchor)
71 #define buf_head buf_anchor.next
72 #define buf_tail buf_anchor.prev
73
74 static struct {
75 struct buf *next, *prev;
76 } buf_anchor = { END_OF_CHAIN, END_OF_CHAIN };
77
78 extern int ispipe, cbufs, sigs;
79
80 /*
81 * Current position in file.
82 * Stored as a block number and an offset into the block.
83 */
84 static long ch_block;
85 static int ch_offset;
86
87 /* Length of file, needed if input is a pipe. */
88 static off_t ch_fsize;
89
90 /* Number of bytes read, if input is standard input (a pipe). */
91 static off_t last_piped_pos;
92
93 /*
94 * Get the character pointed to by the read pointer. ch_get() is a macro
95 * which is more efficient to call than fch_get (the function), in the usual
96 * case that the block desired is at the head of the chain.
97 */
98 #define ch_get() \
99 ((buf_head->block == ch_block && \
100 ch_offset < buf_head->datasize) ? \
101 buf_head->data[ch_offset] : fch_get())
102
103 static
104 fch_get()
105 {
106 extern int bs_mode;
107 register struct buf *bp;
108 register int n, ch;
109 register char *p, *t;
110 off_t pos, lseek();
111
112 /* look for a buffer holding the desired block. */
113 for (bp = buf_head; bp != END_OF_CHAIN; bp = bp->next)
114 if (bp->block == ch_block) {
115 if (ch_offset >= bp->datasize)
116 /*
117 * Need more data in this buffer.
118 */
119 goto read_more;
120 /*
121 * On a pipe, we don't sort the buffers LRU
122 * because this can cause gaps in the buffers.
123 * For example, suppose we've got 12 1K buffers,
124 * and a 15K input stream. If we read the first 12K
125 * sequentially, then jump to line 1, then jump to
126 * the end, the buffers have blocks 0,4,5,6,..,14.
127 * If we then jump to line 1 again and try to
128 * read sequentially, we're out of luck when we
129 * get to block 1 (we'd get the "pipe error" below).
130 * To avoid this, we only sort buffers on a pipe
131 * when we actually READ the data, not when we
132 * find it already buffered.
133 */
134 if (ispipe)
135 return(bp->data[ch_offset]);
136 goto found;
137 }
138 /*
139 * Block is not in a buffer. Take the least recently used buffer
140 * and read the desired block into it. If the LRU buffer has data
141 * in it, and input is a pipe, then try to allocate a new buffer first.
142 */
143 if (ispipe && buf_tail->block != (long)(-1))
144 (void)ch_addbuf(1);
145 bp = buf_tail;
146 bp->block = ch_block;
147 bp->datasize = 0;
148
149 read_more:
150 pos = (ch_block * BUFSIZ) + bp->datasize;
151 if (ispipe) {
152 /*
153 * The data requested should be immediately after
154 * the last data read from the pipe.
155 */
156 if (pos != last_piped_pos) {
157 error("pipe error");
158 quit();
159 }
160 } else
161 (void)lseek(file, pos, L_SET);
162
163 /*
164 * Read the block.
165 * If we read less than a full block, we just return the
166 * partial block and pick up the rest next time.
167 */
168 n = iread(file, &bp->data[bp->datasize], BUFSIZ - bp->datasize);
169 if (n == READ_INTR)
170 return (EOI);
171 if (n < 0) {
172 error("read error");
173 quit();
174 }
175 if (ispipe)
176 last_piped_pos += n;
177
178 p = &bp->data[bp->datasize];
179 bp->datasize += n;
180
181 /*
182 * Set an EOI marker in the buffered data itself. Then ensure the
183 * data is "clean": there are no extra EOI chars in the data and
184 * that the "meta" bit (the 0200 bit) is reset in each char;
185 * also translate \r\n sequences to \n if -u flag not set.
186 */
187 if (n == 0) {
188 ch_fsize = pos;
189 bp->data[bp->datasize++] = EOI;
190 }
191
192 if (bs_mode) {
193 for (p = &bp->data[bp->datasize]; --n >= 0;) {
194 *--p &= 0177;
195 if (*p == EOI)
196 *p = 0200;
197 }
198 }
199 else {
200 for (t = p; --n >= 0; ++p) {
201 ch = *p & 0177;
202 if (ch == '\r' && n && (p[1] & 0177) == '\n') {
203 ++p;
204 *t++ = '\n';
205 }
206 else
207 *t++ = (ch == EOI) ? 0200 : ch;
208 }
209 if (p != t) {
210 bp->datasize -= p - t;
211 if (ispipe)
212 last_piped_pos -= p - t;
213 }
214 }
215
216 found:
217 if (buf_head != bp) {
218 /*
219 * Move the buffer to the head of the buffer chain.
220 * This orders the buffer chain, most- to least-recently used.
221 */
222 bp->next->prev = bp->prev;
223 bp->prev->next = bp->next;
224
225 bp->next = buf_head;
226 bp->prev = END_OF_CHAIN;
227 buf_head->prev = bp;
228 buf_head = bp;
229 }
230
231 if (ch_offset >= bp->datasize)
232 /*
233 * After all that, we still don't have enough data.
234 * Go back and try again.
235 */
236 goto read_more;
237
238 return(bp->data[ch_offset]);
239 }
240
241 /*
242 * Determine if a specific block is currently in one of the buffers.
243 */
244 static
245 buffered(block)
246 long block;
247 {
248 register struct buf *bp;
249
250 for (bp = buf_head; bp != END_OF_CHAIN; bp = bp->next)
251 if (bp->block == block)
252 return(1);
253 return(0);
254 }
255
256 /*
257 * Seek to a specified position in the file.
258 * Return 0 if successful, non-zero if can't seek there.
259 */
260 ch_seek(pos)
261 register off_t pos;
262 {
263 long new_block;
264
265 new_block = pos / BUFSIZ;
266 if (!ispipe || pos == last_piped_pos || buffered(new_block)) {
267 /*
268 * Set read pointer.
269 */
270 ch_block = new_block;
271 ch_offset = pos % BUFSIZ;
272 return(0);
273 }
274 return(1);
275 }
276
277 /*
278 * Seek to the end of the file.
279 */
280 ch_end_seek()
281 {
282 off_t ch_length();
283
284 if (!ispipe)
285 return(ch_seek(ch_length()));
286
287 /*
288 * Do it the slow way: read till end of data.
289 */
290 while (ch_forw_get() != EOI)
291 if (sigs)
292 return(1);
293 return(0);
294 }
295
296 /*
297 * Seek to the beginning of the file, or as close to it as we can get.
298 * We may not be able to seek there if input is a pipe and the
299 * beginning of the pipe is no longer buffered.
300 */
301 ch_beg_seek()
302 {
303 register struct buf *bp, *firstbp;
304
305 /*
306 * Try a plain ch_seek first.
307 */
308 if (ch_seek((off_t)0) == 0)
309 return(0);
310
311 /*
312 * Can't get to position 0.
313 * Look thru the buffers for the one closest to position 0.
314 */
315 firstbp = bp = buf_head;
316 if (bp == END_OF_CHAIN)
317 return(1);
318 while ((bp = bp->next) != END_OF_CHAIN)
319 if (bp->block < firstbp->block)
320 firstbp = bp;
321 ch_block = firstbp->block;
322 ch_offset = 0;
323 return(0);
324 }
325
326 /*
327 * Return the length of the file, if known.
328 */
329 off_t
330 ch_length()
331 {
332 off_t lseek();
333
334 if (ispipe)
335 return(ch_fsize);
336 return((off_t)(lseek(file, (off_t)0, L_XTND)));
337 }
338
339 /*
340 * Return the current position in the file.
341 */
342 off_t
343 ch_tell()
344 {
345 return(ch_block * BUFSIZ + ch_offset);
346 }
347
348 /*
349 * Get the current char and post-increment the read pointer.
350 */
351 ch_forw_get()
352 {
353 register int c;
354
355 c = ch_get();
356 if (c != EOI && ++ch_offset >= BUFSIZ) {
357 ch_offset = 0;
358 ++ch_block;
359 }
360 return(c);
361 }
362
363 /*
364 * Pre-decrement the read pointer and get the new current char.
365 */
366 ch_back_get()
367 {
368 if (--ch_offset < 0) {
369 if (ch_block <= 0 || (ispipe && !buffered(ch_block-1))) {
370 ch_offset = 0;
371 return(EOI);
372 }
373 ch_offset = BUFSIZ - 1;
374 ch_block--;
375 }
376 return(ch_get());
377 }
378
379 /*
380 * Allocate buffers.
381 * Caller wants us to have a total of at least want_nbufs buffers.
382 * keep==1 means keep the data in the current buffers;
383 * otherwise discard the old data.
384 */
385 ch_init(want_nbufs, keep)
386 int want_nbufs;
387 int keep;
388 {
389 register struct buf *bp;
390 char message[80];
391
392 cbufs = nbufs;
393 if (nbufs < want_nbufs && ch_addbuf(want_nbufs - nbufs)) {
394 /*
395 * Cannot allocate enough buffers.
396 * If we don't have ANY, then quit.
397 * Otherwise, just report the error and return.
398 */
399 (void)sprintf(message, "cannot allocate %d buffers",
400 want_nbufs - nbufs);
401 error(message);
402 if (nbufs == 0)
403 quit();
404 return;
405 }
406
407 if (keep)
408 return;
409
410 /*
411 * We don't want to keep the old data,
412 * so initialize all the buffers now.
413 */
414 for (bp = buf_head; bp != END_OF_CHAIN; bp = bp->next)
415 bp->block = (long)(-1);
416 last_piped_pos = (off_t)0;
417 ch_fsize = NULL_POSITION;
418 (void)ch_seek((off_t)0);
419 }
420
421 /*
422 * Allocate some new buffers.
423 * The buffers are added to the tail of the buffer chain.
424 */
425 ch_addbuf(nnew)
426 int nnew;
427 {
428 register struct buf *bp;
429 register struct buf *newbufs;
430 char *calloc();
431
432 /*
433 * We don't have enough buffers.
434 * Allocate some new ones.
435 */
436 newbufs = (struct buf *)calloc((u_int)nnew, sizeof(struct buf));
437 if (newbufs == NULL)
438 return(1);
439
440 /*
441 * Initialize the new buffers and link them together.
442 * Link them all onto the tail of the buffer list.
443 */
444 nbufs += nnew;
445 cbufs = nbufs;
446 for (bp = &newbufs[0]; bp < &newbufs[nnew]; bp++) {
447 bp->next = bp + 1;
448 bp->prev = bp - 1;
449 bp->block = (long)(-1);
450 }
451 newbufs[nnew-1].next = END_OF_CHAIN;
452 newbufs[0].prev = buf_tail;
453 buf_tail->next = &newbufs[0];
454 buf_tail = &newbufs[nnew-1];
455 return(0);
456 }
457