1#include "shgetc.h"
2
3/* The shcnt field stores the number of bytes read so far, offset by
4 * the value of buf-rpos at the last function call (__shlim or __shgetc),
5 * so that between calls the inline shcnt macro can add rpos-buf to get
6 * the actual count. */
7
8void __shlim(FILE *f, off_t lim)
9{
10	f->shlim = lim;
11	f->shcnt = f->buf - f->rpos;
12	/* If lim is nonzero, rend must be a valid pointer. */
13	if (lim && f->rend - f->rpos > lim)
14		f->shend = f->rpos + lim;
15	else
16		f->shend = f->rend;
17}
18
19int __shgetc(FILE *f)
20{
21	int c;
22	off_t cnt = shcnt(f);
23	if (f->shlim && cnt >= f->shlim || (c=__uflow(f)) < 0) {
24		f->shcnt = f->buf - f->rpos + cnt;
25		f->shend = f->rpos;
26		f->shlim = -1;
27		return EOF;
28	}
29	cnt++;
30	if (f->shlim && f->rend - f->rpos > f->shlim - cnt)
31		f->shend = f->rpos + (f->shlim - cnt);
32	else
33		f->shend = f->rend;
34	f->shcnt = f->buf - f->rpos + cnt;
35	if (f->rpos[-1] != c) f->rpos[-1] = c;
36	return c;
37}
38