shgetc sets up to be able to perform an "unget" operation without the
caller having to remember and pass back the character value, and for
this purpose used a conditional store idiom:
if (f->rpos[-1] != c) f->rpos[-1] = c
to make it safe to use with non-writable buffers (setup by the
sh_fromstring macro or __string_read with sscanf).
however, validity of this depends on the buffer space at rpos[-1]
being initialized, which is not the case under some conditions
(including at least unbuffered files and fmemopen ones).
whenever data was read "through the buffer", the desired character
value is already in place and does not need to be written. thus,
rather than testing for the absence of the value, we can test for
rpos<=buf, indicating that the last character read could not have come
from the buffer, and thereby that we have a "real" buffer (possibly of
zero length) with writable pushback (UNGET bytes) below it.
38 lines
921 B
C
38 lines
921 B
C
#include "shgetc.h"
|
|
|
|
/* The shcnt field stores the number of bytes read so far, offset by
|
|
* the value of buf-rpos at the last function call (__shlim or __shgetc),
|
|
* so that between calls the inline shcnt macro can add rpos-buf to get
|
|
* the actual count. */
|
|
|
|
void __shlim(FILE *f, off_t lim)
|
|
{
|
|
f->shlim = lim;
|
|
f->shcnt = f->buf - f->rpos;
|
|
/* If lim is nonzero, rend must be a valid pointer. */
|
|
if (lim && f->rend - f->rpos > lim)
|
|
f->shend = f->rpos + lim;
|
|
else
|
|
f->shend = f->rend;
|
|
}
|
|
|
|
int __shgetc(FILE *f)
|
|
{
|
|
int c;
|
|
off_t cnt = shcnt(f);
|
|
if (f->shlim && cnt >= f->shlim || (c=__uflow(f)) < 0) {
|
|
f->shcnt = f->buf - f->rpos + cnt;
|
|
f->shend = f->rpos;
|
|
f->shlim = -1;
|
|
return EOF;
|
|
}
|
|
cnt++;
|
|
if (f->shlim && f->rend - f->rpos > f->shlim - cnt)
|
|
f->shend = f->rpos + (f->shlim - cnt);
|
|
else
|
|
f->shend = f->rend;
|
|
f->shcnt = f->buf - f->rpos + cnt;
|
|
if (f->rpos <= f->buf) f->rpos[-1] = c;
|
|
return c;
|
|
}
|