fml  0.1-0
Fused Matrix Library
utils.hh
1 // This file is part of fml which is released under the Boost Software
2 // License, Version 1.0. See accompanying file LICENSE or copy at
3 // https://www.boost.org/LICENSE_1_0.txt
4 
5 #ifndef FML__INTERNALS_UTILS_H
6 #define FML__INTERNALS_UTILS_H
7 #pragma once
8 
9 
10 #include <cstdarg>
11 #include <cstdio>
12 #include <stdexcept>
13 
14 
15 namespace utils
16 {
17  namespace
18  {
19  std::string format(const char *fmt, ...)
20  {
21  char buf[256];
22 
23  va_list args;
24  va_start(args, fmt);
25  const auto r = std::vsnprintf(buf, sizeof buf, fmt, args);
26  va_end(args);
27 
28  if (r < 0) // conversion failed
29  return {};
30 
31  const size_t len = r;
32  if (len < sizeof buf) // we fit in the buffer
33  return { buf, len };
34 
35  // C++17: Create a string and write to its underlying array
36  std::string s(len, '\0');
37  va_start(args, fmt);
38  std::vsnprintf(s.data(), len+1, fmt, args);
39  va_end(args);
40 
41  return s;
42  }
43  }
44 
45  inline void log(const char *fmt, ...)
46  {
47  va_list args;
48  va_start(args, fmt);
49  vfprintf(stdout, fmt, args);
50  va_end(args);
51  }
52 
53  inline void warn(const char *fmt, ...)
54  {
55  va_list args;
56  va_start(args, fmt);
57  vfprintf(stderr, fmt, args);
58  va_end(args);
59  }
60 
61  inline void oom(const char *fmt, ...)
62  {
63  throw std::bad_alloc();
64  }
65 
66  inline void error(const char *fmt, ...)
67  {
68  throw std::runtime_error("invalid dimensions");
69  }
70 }
Definition: utils.hh:15