str.h (1565B)
1 #pragma once 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #include "intrinsics.h" 8 #include "strlcpy.h" 9 #include "ggformat.h" 10 11 template< size_t N > 12 class str { 13 public: 14 STATIC_ASSERT( N > 0 ); 15 16 str() { 17 clear(); 18 } 19 20 template< typename... Rest > 21 str( const char * fmt, const Rest & ... rest ) { 22 sprintf( fmt, rest... ); 23 } 24 25 void clear() { 26 buf[ 0 ] = '\0'; 27 length = 0; 28 } 29 30 template< typename T > 31 void operator+=( const T & x ) { 32 appendf( "{}", x ); 33 } 34 35 template< typename... Rest > 36 void sprintf( const char * fmt, const Rest & ... rest ) { 37 size_t copied = ggformat( buf, N, fmt, rest... ); 38 length = min( copied, N - 1 ); 39 } 40 41 template< typename... Rest > 42 void appendf( const char * fmt, const Rest & ... rest ) { 43 size_t copied = ggformat( buf + length, N - length, fmt, rest... ); 44 length += min( copied, N - length - 1 ); 45 } 46 47 void truncate( size_t n ) { 48 if( n >= length ) { 49 return; 50 } 51 buf[ n ] = '\0'; 52 length = n; 53 } 54 55 char & operator[]( size_t i ) { 56 ASSERT( i < N ); 57 return buf[ i ]; 58 } 59 60 const char & operator[]( size_t i ) const { 61 ASSERT( i < N ); 62 return buf[ i ]; 63 } 64 65 const char * c_str() const { 66 return buf; 67 } 68 69 size_t len() const { 70 return length; 71 } 72 73 bool operator==( const char * rhs ) const { 74 return strcmp( buf, rhs ) == 0; 75 } 76 77 bool operator!=( const char * rhs ) const { 78 return !( *this == rhs ); 79 } 80 81 private: 82 char buf[ N ]; 83 size_t length; 84 }; 85 86 template< size_t N > 87 void format( FormatBuffer * fb, const str< N > & buf, const FormatOpts & opts ) { 88 format( fb, buf.c_str(), opts ); 89 }