TMB Documentation  v1.9.11
Rstream.hpp
1 /*
2  Borrowed from Rcpp package.
3  Copyright (C) 2011 - 2013 Dirk Eddelbuettel, Romain Francois and Jelmer Ypma
4  License: GPL-2
5 
6  After including this file we can replace "std::cout" by "Rcout", and it
7  will be possible to correctly capture the text output from R.
8 */
9 
10 #include <iostream>
11 #include <cstdio>
12 #include <streambuf>
13 
14 template <bool OUTPUT>
15 class Rstreambuf : public std::streambuf {
16 public:
17  Rstreambuf(){}
18 
19 protected:
20  virtual std::streamsize xsputn(const char *s, std::streamsize n );
21  virtual int overflow(int c = EOF );
22  virtual int sync();
23 };
24 
25 template <bool OUTPUT>
26 class Rostream : public std::ostream {
27  typedef Rstreambuf<OUTPUT> Buffer ;
28  Buffer* buf ;
29 public:
30  Rostream() :
31  std::ostream( new Buffer ),
32  buf( static_cast<Buffer*>( rdbuf() ) )
33  {}
34  ~Rostream() {
35  if (buf != NULL) {
36  delete buf;
37  buf = NULL;
38  }
39  }
40 };
41 
42 template <> inline std::streamsize Rstreambuf<true>::xsputn(const char *s, std::streamsize num ) {
43  Rprintf( "%.*s", static_cast<int>(num), s ) ;
44  return num ;
45 }
46 template <> inline std::streamsize Rstreambuf<false>::xsputn(const char *s, std::streamsize num ) {
47  REprintf( "%.*s", static_cast<int>(num), s ) ;
48  return num ;
49 }
50 template <> inline int Rstreambuf<true>::overflow(int c) {
51  if (c != traits_type::eof()) {
52  char_type ch = traits_type::to_char_type(c);
53  return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
54  }
55  return c;
56 }
57 template <> inline int Rstreambuf<false>::overflow(int c) {
58  if (c != traits_type::eof()) {
59  char_type ch = traits_type::to_char_type(c);
60  return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
61  }
62  return c;
63 }
64 template <> inline int Rstreambuf<true>::sync(){
65  //::R_FlushConsole() ;
66  return 0 ;
67 }
68 template <> inline int Rstreambuf<false>::sync(){
69  //::R_FlushConsole() ;
70  return 0 ;
71 }
72 TMB_EXTERN Rostream<true> Rcout;
73 TMB_EXTERN Rostream<false> Rcerr;
License: GPL v2