[Opensrf-commits] r1627 - in trunk: include/opensrf src/libopensrf

svn at svn.open-ils.org svn at svn.open-ils.org
Wed Jan 14 21:05:26 EST 2009


Author: scottmk
Date: 2009-01-14 21:05:24 -0500 (Wed, 14 Jan 2009)
New Revision: 1627

Modified:
   trunk/include/opensrf/string_array.h
   trunk/src/libopensrf/string_array.c
Log:
Add a new function osrfStringArrayTokenize.  It parses an input
string into tokens separated by a specified delimiter character,
much like strtok() or strtok_r(), and loads them into an
osrfStringArray.


Modified: trunk/include/opensrf/string_array.h
===================================================================
--- trunk/include/opensrf/string_array.h	2009-01-14 14:36:14 UTC (rev 1626)
+++ trunk/include/opensrf/string_array.h	2009-01-15 02:05:24 UTC (rev 1627)
@@ -34,6 +34,13 @@
 
 void osrfStringArrayRemove( osrfStringArray* arr, const char* str );
 
+/**
+  Parse a string into tokens separated by a specified delimiter,
+  as if by strtok() or strtok_r().  Load the tokens into an
+  osrfStringArray.
+  */
+osrfStringArray* osrfStringArrayTokenize( const char* src, char delim );
+
 #ifdef __cplusplus
 }
 #endif

Modified: trunk/src/libopensrf/string_array.c
===================================================================
--- trunk/src/libopensrf/string_array.c	2009-01-14 14:36:14 UTC (rev 1626)
+++ trunk/src/libopensrf/string_array.c	2009-01-15 02:05:24 UTC (rev 1627)
@@ -100,3 +100,53 @@
     osrfListSetDefaultFree(&arr->list);
 	arr->size--;
 }
+
+osrfStringArray* osrfStringArrayTokenize( const char* src, char delim )
+{
+	// Take the length so that we know how big a buffer we need,
+	// in the worst case.  Esitimate the number of tokens, assuming
+	// 5 characters per token, and add a few for a pad.
+
+	if( NULL == src || '\0' == *src )		// Got nothing?
+		return osrfNewStringArray( 1 );		// Retrun empty array
+
+	size_t src_len = strlen( src );
+	size_t est_count = src_len / 6 + 5;
+	int in_token = 0;     // boolean
+	char buf[ src_len + 1 ];
+	char* out = buf;
+	osrfStringArray* arr = osrfNewStringArray( est_count );
+
+	for( ;; ++src ) {
+		if( in_token ) {	// We're building a token
+			if( *src == delim ) {
+				*out = '\0';
+				osrfStringArrayAdd( arr, buf );
+				in_token = 0;
+			}
+			else if( '\0' == *src ) {
+				*out = '\0';
+				osrfStringArrayAdd( arr, buf );
+				break;
+			}
+			else {
+				*out++ = *src;
+			}
+		}
+		else {				// We're between tokens
+			if( *src == delim ) {
+				;			// skip it
+			}
+			else if( '\0' == *src ) {
+				break;
+			}
+			else {
+				out = buf;		// Start the next one
+				*out++ = *src;
+				in_token = 1;
+			}
+		}
+	}
+	
+	return arr;
+}



More information about the opensrf-commits mailing list