summaryrefslogtreecommitdiff
path: root/src/common
diff options
context:
space:
mode:
authorTom Lane2020-09-22 19:55:13 +0000
committerTom Lane2020-09-22 19:55:13 +0000
commit931487018c409a3102452f965ccaa48367244a41 (patch)
treee959b76c7754b2b7af7bfa593e1825fa0328f88d /src/common
parentc4133ec169dfe47803656325dbfb8397f85a70ea (diff)
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
Diffstat (limited to 'src/common')
-rw-r--r--src/common/pg_get_line.c29
1 files changed, 28 insertions, 1 deletions
diff --git a/src/common/pg_get_line.c b/src/common/pg_get_line.c
index 2fb8e19893..9eb1a33bbb 100644
--- a/src/common/pg_get_line.c
+++ b/src/common/pg_get_line.c
@@ -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)
@@ -68,10 +69,36 @@ pg_get_line(FILE *stream)
}
/*
+ * 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