fork/slippc

git clone https://git.julia.blue/fork/slippc

Christian BartschUse auto returntype for put_time because the type is "unspecified" (std::_Put_time does not exist on mac clang)802ebe1

bench
19.6 KiB654 linesraw
1#ifndef UTIL_H_
2#define UTIL_H_
3
4#if defined(__GNUC__) || defined(__GNUG__)
5#define swap32 __builtin_bswap32
6#define swap16 __builtin_bswap16
7#elif defined(_MSC_VER)
8#define swap32 _byteswap_ulong
9#define swap16 _byteswap_ushort
10#include <intrin.h>
11#endif
12
13#include <string.h>
14#include <iomanip>
15#include <iostream>
16#include <sstream>
17#include <fstream>
18#include <codecvt>
19#include <algorithm> //std::find
20#include <sys/stat.h> //std::find
21#include <filesystem>
22
23#include "lzma.h"
24#include "picohash.h"
25#include "shiftjis.h"
26
27#define BYTE8(b1,b2,b3,b4,b5,b6,b7,b8) (*((uint64_t*)(uint8_t[]){b1,b2,b3,b4,b5,b6,b7,b8}))
28#define BYTE4(b1,b2,b3,b4)             (*((uint32_t*)(uint8_t[]){b1,b2,b3,b4}))
29#define BYTE2(b1,b2)                   (*((uint16_t*)(uint8_t[]){b1,b2}))
30
31const uint64_t SLP_HEADER  = BYTE8(0x7b,0x55,0x03,0x72,0x61,0x77,0x5b,0x24); // {U.raw[$
32const uint32_t LZMA_HEADER = BYTE4(0xfd,0x37,0x7a,0x58);
33
34const unsigned N_HEADER_BYTES      =  15; //Header is always 15 bytes
35const unsigned MIN_EV_PAYLOAD_SIZE =  14; //Payloads, game start, pre frame, post frame, game end always defined
36const unsigned MIN_GAME_START_SIZE = 353; //Minimum size for game start event (necessary for all replays)
37const unsigned MIN_REPLAY_LENGTH   = N_HEADER_BYTES + MIN_EV_PAYLOAD_SIZE + MIN_GAME_START_SIZE;
38
39// Version convenience macros
40#define MIN_VERSION(maj,min,rev) (_slippi_maj > (maj)) || (_slippi_maj == (maj) && ( (_slippi_min > (min)) || (_slippi_min == (min) && _slippi_rev >= (rev)) ))
41#define MAX_VERSION(maj,min,rev) (_slippi_maj < (maj)) || (_slippi_maj == (maj) && ( (_slippi_min < (min)) || (_slippi_min == (min) && _slippi_rev < (rev)) ))
42#define GET_VERSION() (std::to_string(int(_slippi_maj))+"."+std::to_string(int(_slippi_min))+"."+std::to_string(int(_slippi_rev)))
43#define ENCODE_VERSION_MIN(min) (_encode_ver == 0 || _encode_ver >= min)  //also allows unencoded files
44
45// Convenience pseudo-typedefs
46#define PATH std::filesystem::path
47
48// Variable checking whether error log has been initialized
49static bool errlog_init = false;
50
51//Debug output convenience macros
52#define DOUT1(s) if (_debug >= 1) { std::cerr << "  " << BLU << "DEBUG 1: " << BLN << s << std::endl; }
53#define DOUT2(s) if (_debug >= 2) { std::cerr << "  " << BLU << "DEBUG 2: " << BLN << s << std::endl; }
54#define DOUT3(s) if (_debug >= 3) { std::cerr << "  " << BLU << "DEBUG 3: " << BLN << s << std::endl; }
55#define INFO(e)                     std::cerr << "  " << GRN << "   INFO: " << BLN << e << std::endl;
56#define WARN(e)                     std::cerr << "  " << YLW << "WARNING: " << BLN << e << std::endl;
57#define FAIL(e)                     std::cerr << "  " << RED << "  ERROR: " << BLN << e << std::endl;
58#define YIKES(e)                    std::cerr << "  " << CRT << "  YIKES: " << BLN << e << std::endl;
59#define WARN_CORRUPT(e)             std::cerr << "  " << YLW << "WARNING: " << BLN << e << "; replay may be corrupt"   << std::endl;
60#define FAIL_CORRUPT(e)             std::cerr << "  " << RED << "  ERROR: " << BLN << e << "; cannot continue parsing" << std::endl;
61#define _LOG(e) \
62  std::cerr << "  " << MGN << "    LOG: " << BLN << e << std::endl;
63#define LOG(e,f) {\
64  std::cerr << "  " << MGN << "    LOG: " << BLN << e << std::endl; \
65  std::ofstream log(f, std::ios_base::app | std::ios_base::out); \
66  log << "  [" << timestamp() << "] " << e << std::endl; \
67  log.close(); };
68#define ERRLOG(path,e) \
69  PATH errorpath = (path / "_errors.txt"); \
70  if (!errlog_init) { \
71    errlog_init = true; \
72    _LOG("Logging errors to " << MGN << errorpath << BLN); \
73    LOG("Log opened",errorpath); \
74  } \
75  LOG(e,errorpath);
76
77// ANSI color codes don't work on Windows (I think?)
78#ifdef _WIN32
79    #define BLK ""
80    #define RED ""
81    #define GRN ""
82    #define YLW ""
83    #define BLU ""
84    #define MGN ""
85    #define CYN ""
86    #define WHT ""
87    #define CRT ""
88    #define BLN ""
89#else
90    #define BLK "\u001b[30m"
91    #define RED "\u001b[31m"
92    #define GRN "\u001b[32m"
93    #define YLW "\u001b[33m"
94    #define BLU "\u001b[34m"
95    #define MGN "\u001b[35m"
96    #define CYN "\u001b[36m"
97    #define WHT "\u001b[37m"
98    #define CRT "\u001b[41m"
99    #define BLN "\u001b[0m"
100#endif
101
102namespace slip {
103
104//Indent Level
105#define ILEV 1
106
107//Strings for various indentation amounts
108const std::string SPACE[10] = {
109  "",
110  " ",
111  "  ",
112  "   ",
113  "    ",
114  "     ",
115  "      ",
116  "       ",
117  "        ",
118  "         ",
119};
120
121static const std::string base64_chars =
122             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
123             "abcdefghijklmnopqrstuvwxyz"
124             "0123456789+/";
125
126
127static inline bool is_base64(unsigned char c) {
128  return (isalnum(c) || (c == '+') || (c == '/'));
129}
130
131//Hex Output stuff
132
133struct HexCharStruct {
134  unsigned char c;
135  HexCharStruct(unsigned char _c) : c(_c) { }
136};
137
138inline std::ostream& operator<<(std::ostream& o, const HexCharStruct& hs) {
139  return (o << "0x" << std::hex << (int)hs.c) << std::dec;
140}
141
142inline HexCharStruct hex(unsigned char _c) {
143  return HexCharStruct(_c);
144}
145
146inline void printBytes(char* buff, unsigned nchars) {
147  for(unsigned i = 0; i < nchars; ++i) {
148    std::cout << hex(buff[i]) << " ";
149  }
150  std::cout << std::dec << std::endl;
151}
152
153//Bitwise comparison of 8-bytes array with uint_64
154inline bool same8(char* array, uint64_t other) {
155  return ((*((uint64_t*)array)) ^ other) == 0;
156}
157//Bitwise comparison of 4-bytes array with uint_32
158inline bool same4(char* array, uint32_t other) {
159  return ((*((uint32_t*)array)) ^ other) == 0;
160}
161//Load a big-endian 32-bit unsigned int from an array
162inline uint32_t readBE4U(char* array) { return swap32(*((uint32_t*)array)); }
163//Load a big-endian 16-bit unsigned int from an array
164inline uint16_t readBE2U(char* array) { return swap16(*((uint16_t*)array)); }
165//Load a big-endian 32-bit int from an array
166inline int32_t  readBE4S(char* array) { return swap32(*((int32_t*)array)); }
167//Load a big-endian 16-bit int from an array
168inline int16_t  readBE2S(char* array) { return swap16(*((int16_t*)array)); }
169//Load a big-endian float from an array
170inline float readBE4F(char* array) {
171   float r;
172   char *rc = ( char* ) & r;
173   rc[0] = array[3];
174   rc[1] = array[2];
175   rc[2] = array[1];
176   rc[3] = array[0];
177   return r;
178}
179
180//Write a big-endian 32-bit unsigned int to an array
181inline void  writeBE4F(float f, char* a) {
182  char *wc = ( char* ) & f;
183  a[3] = wc[0];
184  a[2] = wc[1];
185  a[1] = wc[2];
186  a[0] = wc[3];
187}
188
189//Write a big-endian 16-bit unsigned int to an array
190inline void  writeBE2U(uint16_t i, char* a) {
191  a[1] =  i      & 0xff;
192  a[0] = (i>>8)  & 0xff;
193}
194
195//Write a big-endian 32-bit unsigned int to an array
196inline void  writeBE4U(uint32_t i, char* a) {
197  a[3] =  i      & 0xff;
198  a[2] = (i>>8)  & 0xff;
199  a[1] = (i>>16) & 0xff;
200  a[0] = (i>>24) & 0xff;
201}
202
203//Write a big-endian 32-bit signed int to an array
204inline void  writeBE4S(int32_t i, char* a) {
205  a[3] =  i      & 0xff;
206  a[2] = (i>>8)  & 0xff;
207  a[1] = (i>>16) & 0xff;
208  a[0] = (i>>24) & 0xff;
209}
210
211//Base64 encoder / decoder -> https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
212inline std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
213  std::string ret;
214  int i = 0;
215  int j = 0;
216  unsigned char char_array_3[3];
217  unsigned char char_array_4[4];
218
219  while (in_len--) {
220    char_array_3[i++] = *(bytes_to_encode++);
221    if (i == 3) {
222      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
223      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
224      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
225      char_array_4[3] = char_array_3[2] & 0x3f;
226
227      for(i = 0; (i <4) ; i++)
228        ret += base64_chars[char_array_4[i]];
229      i = 0;
230    }
231  }
232
233  if (i)
234  {
235    for(j = i; j < 3; j++)
236      char_array_3[j] = '\0';
237
238    char_array_4[0] = ( char_array_3[0] & 0xfc) >> 2;
239    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
240    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
241
242    for (j = 0; (j < i + 1); j++)
243      ret += base64_chars[char_array_4[j]];
244
245    while((i++ < 3))
246      ret += '=';
247
248  }
249
250  return ret;
251
252}
253
254//Base64 encoder / decoder -> https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp
255inline std::string base64_decode(std::string const& encoded_string) {
256  int in_len = encoded_string.size();
257  int i = 0;
258  int j = 0;
259  int in_ = 0;
260  unsigned char char_array_4[4], char_array_3[3];
261  std::string ret;
262
263  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
264    char_array_4[i++] = encoded_string[in_]; in_++;
265    if (i ==4) {
266      for (i = 0; i <4; i++)
267        char_array_4[i] = base64_chars.find(char_array_4[i]);
268
269      char_array_3[0] = ( char_array_4[0] << 2       ) + ((char_array_4[1] & 0x30) >> 4);
270      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
271      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) +   char_array_4[3];
272
273      for (i = 0; (i < 3); i++)
274        ret += char_array_3[i];
275      i = 0;
276    }
277  }
278
279  if (i) {
280    for (j = 0; j < i; j++)
281      char_array_4[j] = base64_chars.find(char_array_4[j]);
282
283    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
284    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
285
286    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
287  }
288
289  return ret;
290}
291
292// https://stackoverflow.com/questions/7724448/simple-json-string-escape-for-c/33799784#33799784
293inline std::string escape_json(const std::string &s) {
294    std::ostringstream o;
295    for (auto c = s.cbegin(); c != s.cend(); c++) {
296        switch (*c) {
297        case '"' : o << "\\\""; break;
298        case '\\': o << "\\\\"; break;
299        case '\b': o << "\\b"; break;
300        case '\f': o << "\\f"; break;
301        case '\n': o << "\\n"; break;
302        case '\r': o << "\\r"; break;
303        case '\t': o << "\\t"; break;
304        default:
305            if ('\x00' <= *c && *c <= '\x1f') {
306                o << "\\u"
307                  << std::hex << std::setw(4) << std::setfill('0') << (int)*c;
308            } else {
309                o << *c;
310            }
311        }
312    }
313    return o.str();
314}
315
316inline std::string to_utf8(const std::u16string &s) {
317  std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> conv;
318  std::string u = conv.to_bytes(s);
319  u.erase(std::find(u.begin(), u.end(), '\0'), u.end());
320  return u;
321}
322
323inline std::string decode_shift_jis(char* addr) {
324  std::u16string tag;
325  for(unsigned n = 0; n < 16; n+=2) {
326    uint16_t b = (readBE2U(addr+n));
327    if ((b>>8) == 0x82) {
328      if ( (b&0xff) < 0x59) { //Roman numerals
329        b -= 0x821f;
330      } else if ( (b&0xff) < 0x80) { //Roman letters
331        b -= 0x81ff;
332      } else { //Hiragana
333        b -= 0x525e;
334      }
335    } else if ((b>>8) == 0x83) {
336      if ( (b&0xff) < 0x80) { //Katakana, part 1
337        b -= 0x529f;
338      } else { //Katakana, part 2
339        b -= 0x52a0;
340      }
341    } else if ((b>>8) == 0x81) {  //Miscellaneous characters
342      switch(b&0xff) {
343        case(0x81): b = 0x003D; break; // =
344        case(0x5b): b = 0x30FC; break; // Hiragana Wave Dash (lol)
345        case(0x7c): b = 0x002D; break; // -
346        case(0x7b): b = 0x002B; break; // +
347        case(0x49): b = 0x0021; break; // !
348        case(0x48): b = 0x003F; break; // ?
349        case(0x97): b = 0x0040; break; // @
350        case(0x93): b = 0x0025; break; // %
351        case(0x95): b = 0x0026; break; // &
352        case(0x90): b = 0x0024; break; // $
353        case(0x44): b = 0x002E; break; // .
354        case(0x60): b = 0x301C; break; // Japanese tilde
355        case(0x42): b = 0x3002; break; // Japanese period
356        case(0x41): b = 0x3001; break; // Japanese comma
357        case(0x40): b = 0x3000; break; // Space
358        default:
359          // DOUT1("    Encountered unknown character in tag: " << b << std::endl);
360          b = 0;
361          break;
362      }
363    } else {
364      if (b != 0) {
365        // DOUT1("    Encountered unknown character in tag: " << b << std::endl);
366      }
367      b = 0;
368    }
369    tag += b;
370    if (b == 0) {
371      break;
372    }
373  }
374  return to_utf8(tag);
375}
376
377// From: https://stackoverflow.com/questions/33165171/c-shiftjis-to-utf8-conversion
378inline std::string sj2utf8(const std::string &input) {
379    std::string output(3 * input.length(), ' '); //ShiftJis won't give 4byte UTF8, so max. 3 byte per input char are needed
380    size_t indexInput = 0, indexOutput = 0;
381
382    while(indexInput < input.length())
383    {
384        char arraySection = ((uint8_t)input[indexInput]) >> 4;
385
386        size_t arrayOffset;
387        if(arraySection == 0x8) arrayOffset = 0x100; //these are two-byte shiftjis
388        else if(arraySection == 0x9) arrayOffset = 0x1100;
389        else if(arraySection == 0xE) arrayOffset = 0x2100;
390        else arrayOffset = 0; //this is one byte shiftjis
391
392        //determining real array offset
393        if(arrayOffset)
394        {
395            arrayOffset += (((uint8_t)input[indexInput]) & 0xf) << 8;
396            indexInput++;
397            if(indexInput >= input.length()) break;
398        }
399        arrayOffset += (uint8_t)input[indexInput++];
400        arrayOffset <<= 1;
401
402        //unicode number is...
403        uint16_t unicodeValue = (shiftJIS_convTable[arrayOffset] << 8) | shiftJIS_convTable[arrayOffset + 1];
404
405        //converting to UTF8
406        if(unicodeValue < 0x80)
407        {
408            output[indexOutput++] = unicodeValue;
409        }
410        else if(unicodeValue < 0x800)
411        {
412            output[indexOutput++] = 0xC0 | (unicodeValue >> 6);
413            output[indexOutput++] = 0x80 | (unicodeValue & 0x3f);
414        }
415        else
416        {
417            output[indexOutput++] = 0xE0 | (unicodeValue >> 12);
418            output[indexOutput++] = 0x80 | ((unicodeValue & 0xfff) >> 6);
419            output[indexOutput++] = 0x80 | (unicodeValue & 0x3f);
420        }
421    }
422
423    output.resize(indexOutput); //remove the unnecessary bytes
424    return output;
425}
426
427inline std::string parseConnCode(const std::string &input) {
428  std::string  s = sj2utf8(input);
429  size_t index = s.find("#", 0);  //repace 2-byte shift-jis # with ascii one
430  if (index != std::string::npos) {
431    s.replace(index, 3, "#");
432  }
433  return s;
434}
435
436inline std::string floatToBinary(float f) {
437  union { float f; uint32_t i; } u;
438  u.f = f;
439  std::string s;
440  for (int i = 0; i < 32; i++) {
441    if (u.i % 2)  s.push_back('1');
442    else s.push_back('0');
443    u.i >>= 1;
444  }
445  // Reverse the string since now it's backwards
446  std::string temp(s.rbegin(), s.rend());
447  return temp;
448}
449
450// http://ptspts.blogspot.com/2011/11/how-to-simply-compress-c-string-with.html
451inline std::string compressWithLzma(const char* in, const size_t inlen, int level = 6) {
452  std::string result;
453  result.resize(inlen + (inlen >> 2) + 128);
454  size_t out_pos = 0;
455  if (LZMA_OK != lzma_easy_buffer_encode(
456      level, LZMA_CHECK_CRC32, NULL,
457      reinterpret_cast<const uint8_t*>(in), inlen,
458      reinterpret_cast<uint8_t*>(&result[0]), &out_pos, result.size()))
459    abort();
460  result.resize(out_pos);
461  return result;
462}
463
464inline std::string decompressWithLzma(const uint8_t* in, const size_t inlen) {
465  static const size_t kMemLimit = 1 << 30;  // 1 GB.
466  lzma_stream strm = LZMA_STREAM_INIT;
467  std::string result;
468  result.resize(8192);
469  size_t result_used = 0;
470  lzma_ret ret;
471  ret = lzma_stream_decoder(&strm, kMemLimit, LZMA_CONCATENATED);
472  if (ret != LZMA_OK)
473    abort();
474  size_t avail0 = result.size();
475  strm.next_in = in;
476  strm.avail_in = inlen;
477  strm.next_out = reinterpret_cast<uint8_t*>(&result[0]);
478  strm.avail_out = avail0;
479  while (true) {
480    ret = lzma_code(&strm, strm.avail_in == 0 ? LZMA_FINISH : LZMA_RUN);
481    if (ret == LZMA_STREAM_END) {
482      result_used += avail0 - strm.avail_out;
483      if (0 != strm.avail_in)  // Guaranteed by lzma_stream_decoder().
484        abort();
485      result.resize(result_used);
486      lzma_end(&strm);
487      return result;
488    }
489    if (ret != LZMA_OK)
490      abort();
491    if (strm.avail_out == 0) {
492      result_used += avail0 - strm.avail_out;
493      result.resize(result.size() << 1);
494      strm.next_out = reinterpret_cast<uint8_t*>(&result[0] + result_used);
495      strm.avail_out = avail0 = result.size() - result_used;
496    }
497  }
498}
499
500inline std::string decompressWithLzma(const char* in, const size_t inlen) {
501  return decompressWithLzma(reinterpret_cast<const uint8_t*>(&in[0]),inlen);
502}
503
504inline bool fileExists(std::string fname) {
505   std::ifstream i(fname.c_str());
506   return i.good();
507}
508
509// https://stackoverflow.com/questions/667183/padding-stl-strings-in-c
510inline std::string padString(std::string str, const size_t num, const char paddingChar = ' ') {
511    if(num > str.size())
512        str.insert(0, num - str.size(), paddingChar);
513    return str;
514}
515
516inline std::string padString(float f, const size_t num, const char paddingChar = ' ') {
517  return padString(std::to_string(f),num,paddingChar);
518}
519
520inline std::string padString(int i, const size_t num, const char paddingChar = ' ') {
521  return padString(std::to_string(i),num,paddingChar);
522}
523
524
525inline int diffBits(uint16_t u1, uint16_t u2) {
526  int count  = 0;
527  u1        ^= u2;
528  for (int i = 0; i < 16; i++) {
529    if ((u1 >> i) & 1) {
530      ++count;
531    }
532  }
533  return count;
534}
535
536inline int countBits(uint16_t u1) {
537  return diffBits(u1,0);
538}
539
540inline int diffBits(float f1, float f2) {
541  union { float f; uint32_t u; } n1, n2;
542  n1.f       = f1;
543  n2.f       = f2;
544  int count  = 0;
545  n1.u      ^= n2.u;
546  for (int i = 0; i < 32; i++) {
547    if ((n1.u >> i) & 1) {
548      ++count;
549    }
550  }
551  return count;
552}
553
554inline std::string getFileBase(std::string f) {
555  int extpos = f.find_last_of(".");
556  return f.substr(0,extpos);
557}
558
559
560inline std::string getFileExt(std::string f) {
561  int extpos = f.find_last_of(".");
562  return f.substr(extpos+1,f.size()-(extpos+1));
563}
564
565inline void stringtoChars(std::string s, char** c) {
566  *c = new char[s.size()+1];
567  strcpy(*c, s.c_str());
568}
569
570inline std::string md5tostring(unsigned char* digest) {
571  std::stringstream ss;
572  ss << std::hex << std::setfill('0');
573  for (int i = 0; i < 16; ++i) {
574      ss << std::setw(2) << static_cast<unsigned>(digest[i]);
575  }
576  return ss.str();
577}
578
579inline std::string md5data(unsigned char* buffer, size_t length) {
580  picohash_ctx_t ctx;
581  unsigned char digest[PICOHASH_MD5_DIGEST_LENGTH];
582  picohash_init_md5(&ctx);
583  picohash_update(&ctx, buffer, length);
584  picohash_final(&ctx, digest);
585
586  return md5tostring(digest);
587}
588
589inline std::string md5file(std::string fname, bool compressed = false) {
590  FILE* f = fopen(fname.c_str(),"r");
591  fseek(f, 0, SEEK_END);
592  size_t length = ftell(f);
593  fseek(f, 0, SEEK_SET);
594  unsigned char* b = (unsigned char*)malloc(length);
595  fread(b,1,length,f);
596  fclose(f);
597
598  if (compressed) {
599    std::string decomp = decompressWithLzma(b, length);
600    // Get the new file size
601    length = decomp.size();
602    // Delete the old read buffer
603    free(b);
604    // Reallocate it with more spce
605    b = (unsigned char*)malloc(length);
606    // Copy buffer from the decompressed string
607    memcpy(b,decomp.c_str(),length);
608  }
609
610  std::string m = md5data(b, length);
611
612  free(b);
613
614  return m;
615}
616
617inline std::string md5compressed(std::string fname) {
618  return md5file(fname,true);
619}
620
621inline bool isDirectory(const char* path) {
622  struct stat s;
623  if( stat(path,&s) == 0 ) {
624    if( s.st_mode & S_IFDIR ) {
625      return true;
626    }
627  }
628  return false;
629}
630
631inline bool makeDirectoryIfNotExists(const char* path) {
632  struct stat s;
633  if( stat(path,&s) == 0 ) {
634    if( s.st_mode & S_IFDIR ) {
635      return true;  //path exists and is a directory
636    }
637    return false;  //path exists but is not a directory
638  }
639  return std::filesystem::create_directories(path);
640}
641
642inline auto timestamp() {
643  std::time_t time_now = std::time(nullptr);
644  return std::put_time(std::localtime(&time_now), "%Y-%m-%d %OH:%OM:%OS");
645}
646
647inline bool ensureExt(const char* ext, const char* fname) {
648  std::string fs(fname);
649  return (fs.substr(fs.length()-4,4).compare(ext) == 0);
650}
651
652}
653
654#endif /* UTIL_H_ */