Add idStr::(V)Format(), make idList compatible with C++ foreach

idStr::(V)Format() is a static (v)printf-like function that returns
and idStr. Can be used like a better va(), or for
idStr mystr = idStr::Format( "number of items: %d", myarr.Num() );
This commit is contained in:
Daniel Gibson 2024-05-11 14:20:38 +02:00
parent 0418f62489
commit 7023475c9d
3 changed files with 64 additions and 0 deletions

View file

@ -1785,6 +1785,48 @@ idStr idStr::FormatNumber( int number ) {
return string;
}
idStr idStr::Format( const char* format, ... )
{
va_list argptr;
va_start( argptr, format );
idStr ret = VFormat( format, argptr );
va_end( argptr );
return ret;
}
idStr idStr::VFormat( const char* format, va_list argptr )
{
idStr ret;
int len;
va_list argptrcopy;
char buffer[16000];
// make a copy of argptr in case we need to call D3_vsnprintf() again after truncation
#ifdef va_copy // IIRC older VS versions didn't have this?
va_copy( argptrcopy, argptr );
#else
argptrcopy = argptr;
#endif
len = D3_vsnprintfC99( buffer, sizeof(buffer), format, argptr );
ret.EnsureAlloced( len + 1 );
if ( len < sizeof(buffer) ) {
strcpy( ret.data, buffer );
ret.len = len;
} else {
// string was truncated, because buffer wasn't big enough.
// ret.EnsureAlloced( len + 1 ) already made sure that ret
// has a big enough buffer, so print into that directly
D3_vsnprintfC99( ret.data, len+1, format, argptrcopy );
ret.len = len;
}
va_end( argptrcopy );
return ret;
}
// behaves like C99's vsnprintf() by returning the amount of bytes that
// *would* have been written into a big enough buffer, even if that's > size
// unlike idStr::vsnPrintf() which returns -1 in that case

View file

@ -325,6 +325,9 @@ public:
int DynamicMemoryUsed() const;
static idStr FormatNumber( int number );
static idStr Format( const char* format, ... ) id_attribute((format(printf,1,2)));
static idStr VFormat( const char* format, va_list argptr );
protected:
int len;
char * data;

View file

@ -132,6 +132,25 @@ public:
void Swap( idList<type> &other ); // swap the contents of the lists
void DeleteContents( bool clear ); // delete the contents of the list
#if __cplusplus >= 201103L
// begin and end allow using C++11 for(ElemType& e : myIdlist) { ... }
type* begin() {
return list;
}
const type* begin() const {
return list;
}
type* end() {
return list + num;
}
const type* end() const {
return list + num;
}
#endif
private:
int num;
int size;