From: scottmk Date: Mon, 5 Jan 2009 14:27:39 +0000 (+0000) Subject: Add a new function buffer_add_n(), and the corresponding X-Git-Url: https://old-git.evergreen-ils.org/?a=commitdiff_plain;h=01df3f9bd9a1b0ebc046871d732c5c8b4a786f73;p=opensrf%2Fbjwebb.git Add a new function buffer_add_n(), and the corresponding function-like macro OSRF_BUFFER_ADD_N. These facilities append a specified number of characters from an input string to a growing_buffer. They are intended for situations where the length of the input string is already known, or where the input string is not nul-terminated in the right place. git-svn-id: svn://svn.open-ils.org/OpenSRF/trunk@1568 9efc2488-bf62-4759-914b-345cdb29e865 --- diff --git a/include/opensrf/utils.h b/include/opensrf/utils.h index 91f4c2d..dd2be90 100644 --- a/include/opensrf/utils.h +++ b/include/opensrf/utils.h @@ -66,6 +66,21 @@ GNU General Public License for more details. }\ } while(0) +#define OSRF_BUFFER_ADD_N(gb, data, n) \ + do {\ + growing_buffer* gb__ = gb; \ + const char* data__ = data; \ + size_t n__ = n; \ + if(gb__ && data__) {\ + int tl__ = n__ + gb__->n_used;\ + if( tl__ < gb__->size ) {\ + memcpy( gb__->buf + gb__->n_used, data__, n__ ); \ + gb__->buf[tl__] = '\0'; \ + gb__->n_used = tl__; \ +} else { buffer_add_n(gb__, data__, n__); }\ +}\ +} while(0) + #define OSRF_BUFFER_ADD_CHAR(gb, c)\ do {\ if(gb) {\ @@ -193,6 +208,7 @@ growing_buffer* buffer_init( int initial_num_bytes); //int buffer_addchar(growing_buffer* gb, char c); int buffer_add(growing_buffer* gb, const char* c); +int buffer_add_n(growing_buffer* gb, const char* data, size_t n); int buffer_fadd(growing_buffer* gb, const char* format, ... ); int buffer_reset( growing_buffer* gb); char* buffer_data( const growing_buffer* gb); diff --git a/src/libopensrf/utils.c b/src/libopensrf/utils.c index 106463a..28d963a 100644 --- a/src/libopensrf/utils.c +++ b/src/libopensrf/utils.c @@ -247,6 +247,28 @@ int buffer_add(growing_buffer* gb, const char* data) { return total_len; } +/** Append a specified number of characters to a growing_buffer. + If the characters so appended include an embedded nul, the results + are likely to be unhappy. +*/ +int buffer_add_n(growing_buffer* gb, const char* data, size_t n) { + if(!(gb && data)) return 0; + + if(n == 0) return 0; + + int total_len = n + gb->n_used; + + if( total_len >= gb->size ) { + if( buffer_expand( gb, total_len ) ) + return -1; + } + + memcpy( gb->buf + gb->n_used, data, n ); + gb->buf[total_len] = '\0'; + gb->n_used = total_len; + return total_len; +} + int buffer_reset( growing_buffer *gb){ if( gb == NULL ) { return -1; }