CARDS 2.4.121
Package manager for the NuTyX GNU/Linux distribution
console_forwarder.h
1 /*
2  * console_forwarder.h
3  *
4  * Copyright 2017 Gianni Peschiutta <artemia@nutyx.org>
5  * Copyright 2017 - 2020 Thierry Nuttens <tnut@nutyx.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20  * MA 02110-1301, USA.
21  *
22  *
23  */
24 
25 #ifndef CONSOLE_FORWARDER_H
26 #define CONSOLE_FORWARDER_H
27 
28 #include <streambuf>
29 #include <iostream>
30 #include <ostream>
31 
32 template <class Elem = char, class Tr = std::char_traits<Elem> >
33 
41 class console_forwarder : public std::basic_streambuf<Elem, Tr>
42 {
43  typedef void (*pfncb)(const Elem *, std::streamsize _Count);
44 
45 protected:
46  std::basic_ostream<Elem, Tr> &m_stream;
47  std::streambuf *m_buf;
48  pfncb m_cb;
49 
50 public:
51  console_forwarder(std::ostream &stream, pfncb cb)
52  : m_stream(stream), m_cb(cb)
53  {
54  // redirect stream
55  m_buf = m_stream.rdbuf(this);
56  };
57 
59  {
60  // restore stream
61  m_stream.rdbuf(m_buf);
62  }
63 
64  // override xsputn and make it forward data to the callback function
65  std::streamsize xsputn(const Elem *_Ptr, std::streamsize _Count)
66  {
67  m_cb(_Ptr, _Count);
68  return _Count;
69  }
70 
71  // override overflow and make it forward data to the callback function
72  typename Tr::int_type overflow(typename Tr::int_type v)
73  {
74  Elem ch = Tr::to_char_type(v);
75  m_cb(&ch, 1);
76  return Tr::not_eof(v);
77  }
78 };
79 
80 #endif
console_forwarder
Forward standard output console to specific listener.
Definition: console_forwarder.h:42