Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added xvasprintf()

  • Loading branch information...
commit 743b0ef766bb7ca1170b1c18ab71b82f2d6a82f3 1 parent d74cc41
@sugyo sugyo authored
View
37 src/lib/wrapper.c
@@ -76,19 +76,42 @@ xstrdup( const char *s ) {
}
+static char *
+_xvasprintf( const char *format, va_list args, const char *error_message ) {
+ va_list args_copy;
+ va_copy( args_copy, args );
+ int n = vsnprintf( NULL, 0, format, args_copy );
+ va_end( args_copy );
+ if ( n <= 0 ) {
+ return NULL;
+ }
+ size_t size = ( size_t ) ( n + 1 );
+ char *str = _trema_malloc( size, error_message );
+ va_copy( args_copy, args );
+ n = vsnprintf( str, size, format, args_copy );
+ va_end( args_copy );
+ if ( n <= 0 || ( size_t ) n > size ) {
+ xfree( str );
+ return NULL;
+ }
+ return str;
+}
+
+
+char *
+xvasprintf( const char *format, va_list args ) {
+ return _xvasprintf( format, args, "Out of memory, xvasprintf failed" );
+}
+
+
char *
xasprintf( const char *format, ... ) {
const char error[] = "Out of memory, xasprintf failed";
va_list args;
va_start( args, format );
- char *str;
- if ( trema_vasprintf( &str, format, args ) < 0 ) {
- die( error );
- }
- char *result = _xstrdup( str, error );
- free( str );
+ char *str = _xvasprintf( format, args, error );
va_end( args );
- return result;
+ return str;
}
View
1  src/lib/wrapper.h
@@ -62,6 +62,7 @@ void *xcalloc( size_t nmemb, size_t size );
void xfree( void *ptr );
char *xstrdup( const char *s );
+char *xvasprintf( const char *format, va_list args );
char *xasprintf( const char *format, ... );
View
29 unittests/lib/wrapper_test.c
@@ -154,6 +154,32 @@ test_xstrdup_fail() {
}
+static char *
+test_xvasprintf_helper( const char *fmt, ... ) {
+ va_list ap;
+ va_start(ap, fmt);
+ char *str = xvasprintf( fmt, ap );
+ va_end(ap);
+ return str;
+}
+
+
+static void
+test_xvasprintf() {
+ char hello[] = "Hello";
+ char *printed_hello = test_xvasprintf_helper( "%s", hello );
+ assert_string_equal( hello, printed_hello );
+ xfree( printed_hello );
+}
+
+
+static void
+test_xvasprintf_fail() {
+ expect_string( mock_die, output, "Out of memory, xvasprintf failed" );
+ expect_assert_failure( test_xvasprintf_helper( "FAIL" ) );
+}
+
+
static void
test_xasprintf() {
char hello[] = "Hello";
@@ -186,6 +212,9 @@ main() {
unit_test_setup_teardown( test_xstrdup, setup, teardown ),
unit_test_setup_teardown( test_xstrdup_fail, setup_fail_allocators, teardown ),
+ unit_test_setup_teardown( test_xvasprintf, setup, teardown ),
+ unit_test_setup_teardown( test_xvasprintf_fail, setup_fail_allocators, teardown ),
+
unit_test_setup_teardown( test_xasprintf, setup, teardown ),
unit_test_setup_teardown( test_xasprintf_fail, setup_fail_allocators, teardown ),
};
Please sign in to comment.
Something went wrong with that request. Please try again.