1
0
mirror of https://github.com/postgres/postgres.git synced 2025-07-28 23:42:10 +03:00

Rethink API for pg_get_line.c, one more time.

Further experience says that the appending behavior offered by
pg_get_line_append is useful to only a very small minority of callers.
For most, the requirement to reset the buffer after each line is just
an error-prone nuisance.  Hence, invent another alternative call
pg_get_line_buf, which takes care of that detail.

Noted while reviewing a patch from Daniel Gustafsson.

Discussion: https://postgr.es/m/48A4FA71-524E-41B9-953A-FD04EF36E2E7@yesql.se
This commit is contained in:
Tom Lane
2020-09-22 15:55:13 -04:00
parent c4133ec169
commit 931487018c
5 changed files with 32 additions and 8 deletions

View File

@ -45,7 +45,8 @@
* Also note that the palloc'd buffer is usually a lot longer than
* strictly necessary, so it may be inadvisable to use this function
* to collect lots of long-lived data. A less memory-hungry option
* is to use pg_get_line_append() in a loop, then pstrdup() each line.
* is to use pg_get_line_buf() or pg_get_line_append() in a loop,
* then pstrdup() each line.
*/
char *
pg_get_line(FILE *stream)
@ -67,11 +68,37 @@ pg_get_line(FILE *stream)
return buf.data;
}
/*
* pg_get_line_buf()
*
* This has similar behavior to pg_get_line(), and thence to fgets(),
* except that the collected data is returned in a caller-supplied
* StringInfo buffer. This is a convenient API for code that just
* wants to read and process one line at a time, without any artificial
* limit on line length.
*
* Returns true if a line was successfully collected (including the
* case of a non-newline-terminated line at EOF). Returns false if
* there was an I/O error or no data was available before EOF.
* (Check ferror(stream) to distinguish these cases.)
*
* In the false-result case, buf is reset to empty.
*/
bool
pg_get_line_buf(FILE *stream, StringInfo buf)
{
/* We just need to drop any data from the previous call */
resetStringInfo(buf);
return pg_get_line_append(stream, buf);
}
/*
* pg_get_line_append()
*
* This has similar behavior to pg_get_line(), and thence to fgets(),
* except that the collected data is appended to whatever is in *buf.
* This is useful in preference to pg_get_line_buf() if the caller wants
* to merge some lines together, e.g. to implement backslash continuation.
*
* Returns true if a line was successfully collected (including the
* case of a non-newline-terminated line at EOF). Returns false if