dune-common  2.2.0
misc.hh
Go to the documentation of this file.
1 // -*- tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 // vi: set ts=8 sw=2 et sts=2:
3 #ifndef MISC_HH
4 #define MISC_HH
5 
10 #include <algorithm>
11 #include <cstddef>
12 #include <cstring>
13 #include <cstdio>
14 #include <iostream>
15 #include <iomanip>
16 #include <iterator>
17 #include <sstream>
18 #include <complex>
19 
21 #include "exceptions.hh"
23 
24 namespace Dune {
25 
26 
32 
33 // conjugate complex does nothing for non-complex types
34 template<class K>
35 inline K conjugateComplex (const K& x)
36 {
37  return x;
38 }
39 
40 #ifndef DOXYGEN
41 // specialization for complex
42 template<class K>
43 inline std::complex<K> conjugateComplex (const std::complex<K>& c)
44 {
45  return std::complex<K>(c.real(),-c.imag());
46 }
47 #endif
48 
50 template <class T>
51 int sign(const T& val)
52 {
53  return (val < 0 ? -1 : 1);
54 }
55 
62 template<class T>
63 T SQR (T t)
64 {
65  return t*t;
66 }
67 
69 template <int m, int p>
70 struct Power_m_p
71 {
72  // power stores m^p
73  enum { power = (m * Power_m_p<m,p-1>::power ) };
74 };
75 
77 template <int m>
78 struct Power_m_p< m , 0>
79 {
80  // m^0 = 1
81  enum { power = 1 };
82 };
83 
85 template <int m>
86 struct Factorial
87 {
89  enum { factorial = m * Factorial<m-1>::factorial };
90 };
91 
93 template <>
94 struct Factorial<0>
95 {
96  // 0! = 1
97  enum { factorial = 1 };
98 };
99 
100 //********************************************************************
101 //
102 // generate filenames with timestep number in it
103 //
104 //********************************************************************
105 
107 inline std::string genFilename(const std::string& path,
108  const std::string& fn,
109  int ntime,
110  int precision = 6)
111 {
112  std::ostringstream name;
113 
114  if(path.size() > 0)
115  {
116  name << path;
117  name << "/";
118  }
119  name << fn << std::setw(precision) << std::setfill('0') << ntime;
120 
121  // Return the string corresponding to the stringstream
122  return name.str();
123 }
124 
125 
126 //********************************************************************
127 //
128 // check whether a given container has a prefix/suffix
129 //
130 //********************************************************************
131 
133 
136 template<typename C>
137 bool hasPrefix(const C& c, const char* prefix) {
138  std::size_t len = std::strlen(prefix);
139  return c.size() >= len &&
140  std::equal(prefix, prefix+len, c.begin());
141 }
142 
144 
152 template<typename C>
153 bool hasSuffix(const C& c, const char* suffix) {
154  std::size_t len = std::strlen(suffix);
155  if(c.size() < len) return false;
156  typename C::const_iterator it = c.begin();
157  std::advance(it, c.size() - len);
158  return std::equal(suffix, suffix+len, it);
159 }
162 }
163 
164 
165 #endif