1
0
Fork 0
mirror of https://github.com/transmission/transmission synced 2024-12-25 17:17:31 +00:00

(trunk libT) avoid unnecessary malloc()s & free()s in tr_utf8clean()

This commit is contained in:
Charles Kerr 2009-04-16 21:00:48 +00:00
parent cdd779bb2a
commit 54e2e8ca2f

View file

@ -1352,35 +1352,44 @@ tr_lowerBound( const void * key,
char* char*
tr_utf8clean( const char * str, int max_len, tr_bool * err ) tr_utf8clean( const char * str, int max_len, tr_bool * err )
{ {
const char zero = '\0';
char * ret; char * ret;
struct evbuffer * buf = evbuffer_new( );
const char * end; const char * end;
if( err != NULL )
*err = FALSE;
if( max_len < 0 ) if( max_len < 0 )
max_len = (int) strlen( str ); max_len = (int) strlen( str );
while( !tr_utf8_validate ( str, max_len, &end ) ) if( err != NULL )
*err = FALSE;
if( tr_utf8_validate( str, max_len, &end ) )
{ {
const int good_len = end - str; ret = tr_strndup( str, max_len );
}
else
{
const char zero = '\0';
struct evbuffer * buf = evbuffer_new( );
evbuffer_add( buf, str, good_len ); while( !tr_utf8_validate ( str, max_len, &end ) )
max_len -= ( good_len + 1 ); {
str += ( good_len + 1 ); const int good_len = end - str;
evbuffer_add( buf, "?", 1 );
if( err != NULL ) evbuffer_add( buf, str, good_len );
*err = TRUE; max_len -= ( good_len + 1 );
str += ( good_len + 1 );
evbuffer_add( buf, "?", 1 );
if( err != NULL )
*err = TRUE;
}
evbuffer_add( buf, str, max_len );
evbuffer_add( buf, &zero, 1 );
ret = tr_memdup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
evbuffer_free( buf );
} }
evbuffer_add( buf, str, max_len );
evbuffer_add( buf, &zero, 1 );
ret = tr_memdup( EVBUFFER_DATA( buf ), EVBUFFER_LENGTH( buf ) );
assert( tr_utf8_validate( ret, -1, NULL ) ); assert( tr_utf8_validate( ret, -1, NULL ) );
evbuffer_free( buf );
return ret; return ret;
} }