PetaVision  Alpha
PrintStream.hpp
1 #ifndef __PRINTSTREAM_HPP_
2 #define __PRINTSTREAM_HPP_
3 
4 extern "C" {
5 #include <unistd.h>
6 }
7 
8 #include <cstdarg>
9 #include <cstdio>
10 #include <cstring>
11 
12 #include "io/io.hpp"
13 #include "utils/PVAssert.hpp"
14 #include "utils/PVLog.hpp"
15 
16 namespace PV {
17 
18 class PrintStream {
19  public:
20  PrintStream(std::ostream &stream) { setOutStream(stream); }
21  virtual ~PrintStream() {}
22 
23  int printf(const char *fmt, ...) {
24  va_list args1, args2;
25  va_start(args1, fmt);
26  va_copy(args2, args1);
27  char c;
28  int chars_needed = vsnprintf(&c, 1, fmt, args1);
29  chars_needed++;
30  char output_string[chars_needed];
31  int chars_printed = vsnprintf(output_string, chars_needed, fmt, args2);
32  pvAssert(chars_printed + 1 == chars_needed);
33  (*mOutStream) << std::string(output_string);
34  va_end(args1);
35  va_end(args2);
36  return chars_needed;
37  }
38 
39  void flush() { mOutStream->flush(); }
40 
41  // Operator overloads to allow using << like cout
42  template <typename T>
43  PrintStream &operator<<(const T &x) {
44  (*mOutStream) << x;
45  return *this;
46  }
47  PrintStream &operator<<(std::ostream &(*f)(std::ostream &)) {
48  f(*mOutStream);
49  return *this;
50  }
51  PrintStream &operator<<(std::ostream &(*f)(std::ios &)) {
52  f(*mOutStream);
53  return *this;
54  }
55  PrintStream &operator<<(std::ostream &(*f)(std::ios_base &)) {
56  f(*mOutStream);
57  return *this;
58  }
59 
60  protected:
61  PrintStream() {}
62  void setOutStream(std::ostream &stream) { mOutStream = &stream; }
63 
64  private:
65  std::ostream *mOutStream = nullptr;
66 };
67 } /* namespace PV */
68 
69 #endif