dynstr.h (1387B)
1 #pragma once 2 3 #include <string.h> 4 5 #include "array.h" 6 #include "ggformat.h" 7 8 class DynamicString { 9 public: 10 DynamicString() { } 11 12 template< typename... Rest > 13 DynamicString( const char * fmt, const Rest & ... rest ) { 14 sprintf( fmt, rest... ); 15 } 16 17 template< typename T > 18 void operator+=( const T & x ) { 19 appendf( "{}", x ); 20 } 21 22 void append( const char * str ) { 23 append( str, strlen( str ) ); 24 } 25 26 void append( const void * data, size_t n ) { 27 size_t old_len = length(); 28 buf.extend( old_len == 0 ? n + 1 : n ); 29 memmove( &buf[ old_len ], data, n ); 30 } 31 32 template< typename... Rest > 33 void sprintf( const char * fmt, const Rest & ... rest ) { 34 size_t len = ggformat( NULL, 0, fmt, rest... ); 35 buf.resize( len + 1 ); 36 ggformat( &buf[ 0 ], len + 1, fmt, rest... ); 37 } 38 39 template< typename... Rest > 40 void appendf( const char * fmt, const Rest & ... rest ) { 41 size_t len = ggformat( NULL, 0, fmt, rest... ); 42 size_t old_len = length(); 43 buf.resize( old_len + len + 1 ); 44 ggformat( &buf[ old_len ], len + 1, fmt, rest... ); 45 } 46 47 const char * c_str() const { 48 if( buf.size() == 0 ) { 49 return ""; 50 } 51 52 return buf.ptr(); 53 } 54 55 size_t length() const { 56 return buf.size() == 0 ? 0 : buf.size() - 1; 57 } 58 59 private: 60 DynamicArray< char > buf; 61 }; 62 63 inline void format( FormatBuffer * fb, const DynamicString & str, const FormatOpts & opts ) { 64 format( fb, str.c_str(), opts ); 65 }