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