Skip to content
Snippets Groups Projects
Commit b8580747 authored by graeser's avatar graeser Committed by graeser
Browse files

Add format string method

Interpret printf-like format strings using std::string instead
of raw char buffers. By using std::snprintf we avoid buffer
overflows and a boost::format dependency at the price of
depending on a c++11 feature.

Perhaps we'd like to have this in dune-common

[[Imported from SVN: r13087]]
parent b17fea26
No related branches found
No related tags found
No related merge requests found
...@@ -30,6 +30,7 @@ install(FILES ...@@ -30,6 +30,7 @@ install(FILES
dunepython.hh dunepython.hh
facehierarchy.hh facehierarchy.hh
facelocalfiniteelement.hh facelocalfiniteelement.hh
formatstring.hh
globalintersectioniterator.hh globalintersectioniterator.hh
improvegrid.hh improvegrid.hh
interval.hh interval.hh
......
...@@ -23,6 +23,8 @@ fufem_HEADERS = any.hh \ ...@@ -23,6 +23,8 @@ fufem_HEADERS = any.hh \
dunedataio.hh \ dunedataio.hh \
dunepython.hh \ dunepython.hh \
facehierarchy.hh \ facehierarchy.hh \
facelocalfiniteelement.hh \
formatstring.hh \
globalintersectioniterator.hh \ globalintersectioniterator.hh \
improvegrid.hh \ improvegrid.hh \
indexedsliceiterator.hh \ indexedsliceiterator.hh \
......
#ifndef DUNE_FUFEM_FORMATSTRING_HH
#define DUNE_FUFEM_FORMATSTRING_HH
#include <cstdio>
#include <dune/common/exceptions.hh>
namespace Dune {
namespace Fufem {
/**
* \brief Return formated output for printf like string
*
* \param s Format string using printf syntax
* \param args Arguments for format string
* \returns Result of conversion as string
*/
template<class... T>
std::string formatString(const std::string& s, const T&... args)
{
static const int bufferSize=1000;
char buffer[bufferSize];
r = std::snprintf(buffer, s.c_str(), bufferSize, args...);
// negative return values correspond to errors
if (r<0)
DUNE_THROW(Dune::Exception,"Could not convert format string using given arguments.");
// if buffer was large enough return result as string
if (r<bufferSize)
return std::string(buffer);
// if buffer was to small allocate a larger buffer using
// the returned size hint +1 for the terminating 0-byte.
int dynamicBufferSize = r+1;
char* dynamicBuffer = new char[dynamicBufferSize];
// convert and check for errors again
r = std::snprintf(dynamicBuffer, s.c_str(), dynamicBufferSize, args...);
if (r<0)
DUNE_THROW(Dune::Exception,"Could not convert format string using given arguments.");
// the new buffer should always be large enough
assert(r<dynamicBufferSize);
// convert result to string, release buffer, return result
std::string result(dynamicBuffer);
delete[] dynamicBuffer;
return result;
}
}
}
#endif // DUNE_FUFEM_FORMATSTRING_HH
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment