Rcpp Version 0.12.14
Rstreambuf.h
Go to the documentation of this file.
1 // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
2 //
3 // Rstreambuf.h: Rcpp R/C++ interface class library -- stream buffer
4 //
5 // Copyright (C) 2011 - 2017 Dirk Eddelbuettel, Romain Francois and Jelmer Ypma
6 //
7 // This file is part of Rcpp.
8 //
9 // Rcpp is free software: you can redistribute it and/or modify it
10 // under the terms of the GNU General Public License as published by
11 // the Free Software Foundation, either version 2 of the License, or
12 // (at your option) any later version.
13 //
14 // Rcpp is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with Rcpp. If not, see <http://www.gnu.org/licenses/>.
21 
22 #ifndef RCPP__IOSTREAM__RSTREAMBUF_H
23 #define RCPP__IOSTREAM__RSTREAMBUF_H
24 
25 #include <cstdio>
26 #include <streambuf>
27 
28 namespace Rcpp {
29 
30  template <bool OUTPUT>
31  class Rstreambuf : public std::streambuf {
32  public:
34 
35  protected:
36  virtual std::streamsize xsputn(const char *s, std::streamsize n);
37 
38  virtual int overflow(int c = traits_type::eof());
39 
40  virtual int sync();
41  };
42 
43  template <bool OUTPUT>
44  class Rostream : public std::ostream {
46  Buffer buf;
47  public:
48  Rostream() : std::ostream( &buf ) {}
49  };
50  // #nocov start
51  template <> inline std::streamsize Rstreambuf<true>::xsputn(const char *s, std::streamsize num) {
52  Rprintf("%.*s", num, s);
53  return num;
54  }
55  template <> inline std::streamsize Rstreambuf<false>::xsputn(const char *s, std::streamsize num) {
56  REprintf("%.*s", num, s);
57  return num;
58  }
59 
60  template <> inline int Rstreambuf<true>::overflow(int c) {
61  if (c != traits_type::eof()) {
62  char_type ch = traits_type::to_char_type(c);
63  return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
64  }
65  return c;
66  }
67  template <> inline int Rstreambuf<false>::overflow(int c) {
68  if (c != traits_type::eof()) {
69  char_type ch = traits_type::to_char_type(c);
70  return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
71  }
72  return c;
73  }
74 
75  template <> inline int Rstreambuf<true>::sync() {
76  ::R_FlushConsole();
77  return 0;
78  }
79  template <> inline int Rstreambuf<false>::sync() {
80  ::R_FlushConsole();
81  return 0;
82  } // #nocov end
85 
86 
87 }
88 
89 #endif
virtual int overflow(int c=traits_type::eof())
static Rostream< false > Rcerr
Definition: Rstreambuf.h:84
Rstreambuf< OUTPUT > Buffer
Definition: Rstreambuf.h:45
Definition: swap.h:25
virtual std::streamsize xsputn(const char *s, std::streamsize n)
Rcpp API.
Definition: algo.h:28
static Rostream< true > Rcout
Definition: Rstreambuf.h:83
virtual int sync()