]> git.tdb.fi Git - libs/core.git/blob - source/io/filtered.h
Better method of preventing duplicate applications
[libs/core.git] / source / io / filtered.h
1 #ifndef MSP_IO_FILTERED_H_
2 #define MSP_IO_FILTERED_H_
3
4 namespace Msp {
5 namespace IO {
6
7 // XXX This needs a redesign
8 template<typename B, typename F>
9 class Filtered: public B
10 {
11 private:
12         struct Activator
13         {
14                 Filtered &f;
15
16                 Activator(Filtered &f_): f(f_) { f.active = true; }
17                 ~Activator() { f.active = false; }
18         };
19
20         F filter;
21         bool active;
22
23 public:
24         Filtered(): filter(*this), active(false) { }
25         ~Filtered() { active = true; }
26
27         template<typename A0>
28         Filtered(A0 a0): B(a0), filter(*this), active(false) { }
29
30         template<typename A0, typename A1>
31         Filtered(A0 a0, A1 a1): B(a0, a1), filter(*this), active(false) { }
32
33 protected:
34         virtual unsigned do_write(const char *b, unsigned s)
35         {
36                 if(!active)
37                 {
38                         Activator a(*this);
39                         return filter.write(b, s);
40                 }
41                 else
42                         return B::do_write(b, s);
43         }
44
45         virtual unsigned do_read(char *b, unsigned s)
46         {
47                 if(!active)
48                 {
49                         Activator a(*this);
50                         return filter.read(b, s);
51                 }
52                 else
53                         return B::do_read(b, s);
54         }
55
56 public:
57         virtual unsigned put(char c)
58         {
59                 if(active)
60                         return B::put(c);
61
62                 Activator a(*this);
63                 return filter.put(c);
64         }
65
66         virtual bool getline(std::string &l)
67         {
68                 if(active)
69                         return B::getline(l);
70
71                 Activator a(*this);
72                 return filter.getline(l);
73         }
74
75         virtual int get()
76         {
77                 if(active)
78                         return B::get();
79                         
80                 Activator a(*this);
81                 return filter.get();
82         }
83
84         F &get_filter() { return filter; }
85 };
86
87 } // namespace IO
88 } // namespace Msp
89
90 #endif