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