]> git.tdb.fi Git - libs/core.git/blob - source/filtered.h
98cda4740a1700c3e41903156fce1de3c088f9b2
[libs/core.git] / source / filtered.h
1 #ifndef MSP_IO_FILTERED_H_
2 #define MSP_IO_FILTERED_H_
3
4 namespace Msp {
5 namespace IO {
6
7 template<typename B, typename F>
8 class Filtered: public B
9 {
10 private:
11         struct Activator
12         {
13                 Filtered &f;
14
15                 Activator(Filtered &f_): f(f_) { f.active = true; }
16                 ~Activator() { f.active = false; }
17         };
18
19         F filter;
20         bool active;
21
22 public:
23         Filtered(): filter(*this), active(false) { }
24         ~Filtered() { active = true; }
25
26         template<typename A0>
27         Filtered(A0 a0): B(a0), filter(*this), active(false) { }
28
29         template<typename A0, typename A1>
30         Filtered(A0 a0, A1 a1): B(a0, a1), filter(*this), active(false) { }
31
32         virtual unsigned put(char c) { return filter.put(c); }
33         virtual bool getline(std::string &l) { return filter.getline(l); }
34         virtual int get() { return filter.get(); }
35
36         F &get_filter() { return filter; }
37 protected:
38         virtual unsigned do_write(const char *b, unsigned s)
39         {
40                 if(!active)
41                 {
42                         Activator a(*this);
43                         return filter.write(b, s);
44                 }
45                 else
46                         return B::do_write(b, s);
47         }
48
49         virtual unsigned do_read(char *b, unsigned s)
50         {
51                 if(!active)
52                 {
53                         Activator a(*this);
54                         return filter.read(b, s);
55                 }
56                 else
57                         return B::do_read(b, s);
58         }
59 };
60
61 } // namespace IO
62 } // namespace Msp
63
64 #endif