00001
00002
00003 #ifndef DUNE_COMMON_STRINGUTILITY_HH
00004 #define DUNE_COMMON_STRINGUTILITY_HH
00005
00010 #include <cstddef>
00011 #include <cstring>
00012 #include <algorithm>
00013 #include <cassert>
00014 #include <cstdio>
00015 #include <memory>
00016 #include <string>
00017 #include <new>
00018
00019 #include <dune/common/exceptions.hh>
00020 #include <dune/common/std/memory.hh>
00021
00022
00023 namespace Dune {
00024
00035 template<typename C>
00036 bool hasPrefix(const C& c, const char* prefix) {
00037 std::size_t len = std::strlen(prefix);
00038 return c.size() >= len &&
00039 std::equal(prefix, prefix+len, c.begin());
00040 }
00041
00051 template<typename C>
00052 bool hasSuffix(const C& c, const char* suffix) {
00053 std::size_t len = std::strlen(suffix);
00054 if(c.size() < len) return false;
00055 typename C::const_iterator it = c.begin();
00056 std::advance(it, c.size() - len);
00057 return std::equal(suffix, suffix+len, it);
00058 }
00059
00071 template<class... T>
00072 static std::string formatString(const std::string& s, const T&... args)
00073 {
00074 static const int bufferSize=1000;
00075 char buffer[bufferSize];
00076
00077
00078 int r = std::snprintf(buffer, bufferSize, s.c_str(), args...);
00079
00080
00081 if (r<0)
00082 DUNE_THROW(Dune::Exception,"Could not convert format string using given arguments.");
00083
00084
00085 if (r<bufferSize)
00086 return std::string(buffer);
00087
00088
00089
00090 int dynamicBufferSize = r+1;
00091
00092 std::unique_ptr<char[]> dynamicBuffer;
00093 try {
00094 dynamicBuffer = Dune::Std::make_unique<char[]>(dynamicBufferSize);
00095 }
00096 catch (const std::bad_alloc&) {
00097 DUNE_THROW(Dune::Exception,"Could allocate large enough dynamic buffer in formatString.");
00098 }
00099
00100
00101 r = std::snprintf(dynamicBuffer.get(), dynamicBufferSize, s.c_str(), args...);
00102 if (r<0)
00103 DUNE_THROW(Dune::Exception,"Could not convert format string using given arguments.");
00104
00105
00106 assert(r<dynamicBufferSize);
00107
00108 return std::string(dynamicBuffer.get());
00109 }
00112 }
00113
00114 #endif // DUNE_COMMON_STRINGUTILITY_HH