#include "sys_defs.h"
#include <stdio.h>
#include <string.h>
#include "msg.h"
#include "vstring.h"
#include "vstream.h"
#include "vstring_vstream.h"
#define VSTRING_GET_RESULT(vp) \
(VSTRING_LEN(vp) > 0 ? vstring_end(vp)[-1] : VSTREAM_EOF)
int vstring_get(VSTRING *vp, VSTREAM *fp)
{
int c;
VSTRING_RESET(vp);
while ((c = VSTREAM_GETC(fp)) != VSTREAM_EOF) {
VSTRING_ADDCH(vp, c);
if (c == '\n')
break;
}
VSTRING_TERMINATE(vp);
return (VSTRING_GET_RESULT(vp));
}
int vstring_get_nonl(VSTRING *vp, VSTREAM *fp)
{
int c;
VSTRING_RESET(vp);
while ((c = VSTREAM_GETC(fp)) != VSTREAM_EOF && c != '\n')
VSTRING_ADDCH(vp, c);
VSTRING_TERMINATE(vp);
return (c == '\n' ? c : VSTRING_GET_RESULT(vp));
}
int vstring_get_null(VSTRING *vp, VSTREAM *fp)
{
int c;
VSTRING_RESET(vp);
while ((c = VSTREAM_GETC(fp)) != VSTREAM_EOF && c != 0)
VSTRING_ADDCH(vp, c);
VSTRING_TERMINATE(vp);
return (c == 0 ? c : VSTRING_GET_RESULT(vp));
}
int vstring_get_bound(VSTRING *vp, VSTREAM *fp, int bound)
{
int c;
if (bound <= 0)
msg_panic("vstring_get_bound: invalid bound %d", bound);
VSTRING_RESET(vp);
while (bound-- > 0 && (c = VSTREAM_GETC(fp)) != VSTREAM_EOF) {
VSTRING_ADDCH(vp, c);
if (c == '\n')
break;
}
VSTRING_TERMINATE(vp);
return (VSTRING_GET_RESULT(vp));
}
int vstring_get_nonl_bound(VSTRING *vp, VSTREAM *fp, int bound)
{
int c;
if (bound <= 0)
msg_panic("vstring_get_nonl_bound: invalid bound %d", bound);
VSTRING_RESET(vp);
while (bound-- > 0 && (c = VSTREAM_GETC(fp)) != VSTREAM_EOF && c != '\n')
VSTRING_ADDCH(vp, c);
VSTRING_TERMINATE(vp);
return (c == '\n' ? c : VSTRING_GET_RESULT(vp));
}
int vstring_get_null_bound(VSTRING *vp, VSTREAM *fp, int bound)
{
int c;
if (bound <= 0)
msg_panic("vstring_get_nonl_bound: invalid bound %d", bound);
VSTRING_RESET(vp);
while (bound-- > 0 && (c = VSTREAM_GETC(fp)) != VSTREAM_EOF && c != 0)
VSTRING_ADDCH(vp, c);
VSTRING_TERMINATE(vp);
return (c == 0 ? c : VSTRING_GET_RESULT(vp));
}
#ifdef TEST
#include <fcntl.h>
#define TEXT_VSTREAM "vstring_vstream.c"
main(void)
{
VSTRING *vp = vstring_alloc(1);
VSTREAM *fp;
if ((fp = vstream_fopen(TEXT_VSTREAM, O_RDONLY, 0)) == 0)
msg_fatal("open %s: %m", TEXT_VSTREAM);
while (vstring_fgets(vp, fp))
vstream_fprintf(VSTREAM_OUT, "%s", vstring_str(vp));
vstream_fclose(fp);
vstream_fflush(VSTREAM_OUT);
vstring_free(vp);
}
#endif