Attached is a patch that makes a minor addition to the StringInfo API:
resetStringInfo(), which clears the current content of the StringInfo
but leaves it valid for future operations.

I needed this for an external project, but ISTM this would be worth
including in mainline: I'd imagine it's a fairly common operation, and
there's no easy way to do it at the moment. Clients can manually reset
the StringInfo's fields, but that is poor interface design, as well as
being error-prone: many people might just reset "len" and forget to
NUL-terminate the data buffer and reset the cursor. initStringInfo()
could be used, but it reallocates the StringInfo's data buffer, which is
often undesirable.

-Neil

Index: src/backend/lib/stringinfo.c
===================================================================
RCS file: /home/neilc/postgres/cvs_root/pgsql/src/backend/lib/stringinfo.c,v
retrieving revision 1.44
diff -c -p -r1.44 stringinfo.c
*** src/backend/lib/stringinfo.c	5 Jan 2007 22:19:29 -0000	1.44
--- src/backend/lib/stringinfo.c	3 Mar 2007 06:51:47 -0000
*************** initStringInfo(StringInfo str)
*** 49,56 ****
  
  	str->data = (char *) palloc(size);
  	str->maxlen = size;
! 	str->len = 0;
  	str->data[0] = '\0';
  	str->cursor = 0;
  }
  
--- 49,68 ----
  
  	str->data = (char *) palloc(size);
  	str->maxlen = size;
! 	resetStringInfo(str);
! }
! 
! /*
!  * resetStringInfo
!  *
!  * Reset the StringInfo: the data buffer remains valid, but its
!  * previous content, if any, is cleared.
!  */
! void
! resetStringInfo(StringInfo str)
! {
  	str->data[0] = '\0';
+ 	str->len = 0;
  	str->cursor = 0;
  }
  
Index: src/include/lib/stringinfo.h
===================================================================
RCS file: /home/neilc/postgres/cvs_root/pgsql/src/include/lib/stringinfo.h,v
retrieving revision 1.33
diff -c -p -r1.33 stringinfo.h
*** src/include/lib/stringinfo.h	5 Jan 2007 22:19:55 -0000	1.33
--- src/include/lib/stringinfo.h	3 Mar 2007 06:51:12 -0000
*************** extern StringInfo makeStringInfo(void);
*** 79,84 ****
--- 79,91 ----
  extern void initStringInfo(StringInfo str);
  
  /*------------------------
+  * resetStringInfo
+  * Clears the current content of the StringInfo, if any. The
+  * StringInfo remains valid.
+  */
+ extern void resetStringInfo(StringInfo str);
+ 
+ /*------------------------
   * appendStringInfo
   * Format text data under the control of fmt (an sprintf-style format string)
   * and append it to whatever is already in str.  More space is allocated
---------------------------(end of broadcast)---------------------------
TIP 5: don't forget to increase your free space map settings

Reply via email to