Simpact Cyan
Population based event driven simulation using mNRM
util.h
1 #ifndef UTIL_H
2 
3 #define UTIL_H
4 
5 #define __STDC_FORMAT_MACROS // Need this for PRId64
6 #include <inttypes.h>
7 #include <stdarg.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <string>
11 #include <vector>
12 
13 //long double GetSystemTime();
14 bool ReadInputLine(FILE *fi, std::string &line);
15 void SplitLine(const std::string &line, std::vector<std::string> &args, const std::string &separatorChars = " \t",
16  const std::string &quoteChars = "\"'", const std::string &commentStartChars = "#",
17  bool ignoreZeroLengthFields = true);
18 
19 std::string createFullPath(const std::string &dir, const std::string &file);
20 
21 void abortWithMessage(const std::string &msg);
22 
23 bool parseAsInt(const std::string &str, int &number);
24 bool parseAsInt(const std::string &str, int64_t &number);
25 bool parseAsDouble(const std::string &str, double &number);
26 bool parseAsDoubleVector(const std::string &str, std::vector<double> &numbers, std::string &badField);
27 std::string doubleToString(double x);
28 std::string intToString(int x);
29 std::string intToString(int64_t x);
30 std::string stringToString(const std::string &str);
31 
32 std::string trim(const std::string &str, const std::string &trimChars = " \t\r\n");
33 std::string replace(const std::string &input, const std::string &target, const std::string &replacement);
34 
35 std::string strprintf_cstr(const char *format, ...);
36 
37 #define strprintf(format, ...) strprintf_cstr(stringToString(format).c_str(), __VA_ARGS__ )
38 
39 //
40 // inline implementations
41 //
42 
43 //inline std::string strprintf(const std::string &format, ...)
44 inline std::string strprintf_cstr(const char *format, ...)
45 {
46  const int MAXBUFLEN = 8192;
47  char buf[MAXBUFLEN+1];
48  va_list ap;
49 
50  va_start(ap, format);
51 #ifndef WIN32
52  vsnprintf(buf, MAXBUFLEN, format, ap);
53 #else
54  vsnprintf_s(buf, MAXBUFLEN, _TRUNCATE, format, ap);
55 #endif // WIN32
56  va_end(ap);
57 
58  buf[MAXBUFLEN] = 0;
59  return std::string(buf);
60 }
61 
62 inline std::string doubleToString(double x)
63 {
64  std::string s = strprintf("%.15g", x);
65  if (s == "1.#INF")
66  return "inf";
67  if (s == "-1.#INF")
68  return "-inf";
69  return s;
70 }
71 
72 inline std::string intToString(int x)
73 {
74  return strprintf("%d", x);
75 }
76 
77 inline std::string intToString(int64_t x)
78 {
79  return strprintf("%" PRId64, x);
80 }
81 
82 inline std::string stringToString(const std::string &str)
83 {
84  return str;
85 }
86 
87 #endif // UTIL_H
88