medfall

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit f5c6767f4dabffe9fd2427bd4a5a315049213964
parent 7e30adcbc9f27d53dc5bb4f05c2944aaa36356c5
Author: Michael Savage <mikejsavage@gmail.com>
Date:   Fri Sep  2 15:55:05 -0700

Add str.h

Diffstat:
str.h | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 85 insertions(+), 0 deletions(-)
diff --git a/str.h b/str.h @@ -0,0 +1,85 @@ +#ifndef _STR_H_ +#define _STR_H_ + +#include <stdio.h> +#include <stdarg.h> +#include <bsd/string.h> + +#include "intrinsics.h" + +template< size_t N > +class str { +public: + str() { + clear(); + } + + void clear() { + buf[ 0 ] = '\0'; + length = 0; + } + + void operator+=( const char * rhs ) { + size_t copied = strlcpy( buf + length, rhs, N - length ); + length += min( copied, N - length - 1 ); + } + + void operator+=( int n ) { + appendf( "%d", n ); + } + + void operator+=( long n ) { + appendf( "%ld", n ); + } + + void operator+=( long long n ) { + appendf( "%lld", n ); + } + + void operator+=( unsigned int n ) { + appendf( "%u", n ); + } + + void operator+=( unsigned long n ) { + appendf( "%lu", n ); + } + + void operator+=( unsigned long long n ) { + appendf( "%llu", n ); + } + + void operator+=( double x ) { + appendf( "%f", x ); + } + + // TODO: implement our own vsnprintf with support for vectors etc + void sprintf( const char * fmt, ... ) { + va_list argp; + va_start( argp, fmt ); + size_t copied = vsnprintf( buf, N, fmt, argp ); + length = min( copied, N - 1 ); + va_end( argp ); + } + + void appendf( const char * fmt, ... ) { + va_list argp; + va_start( argp, fmt ); + size_t copied = vsnprintf( buf + length, N - length, fmt, argp ); + length += min( copied, N - length - 1 ); + va_end( argp ); + } + + const char * c_str() { + return buf; + } + + size_t len() { + return length; + } + +private: + char buf[ N ]; + size_t length; +}; + +#endif // _STR_H_