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