Main Page   Class Hierarchy   Compound List   File List   Compound Members   File Members  

filterstreambuf.h

Go to the documentation of this file.
00001 #ifndef DEMO_FILTERSTREAMBUF_H
00002 #define DEMO_FILTERSTREAMBUF_H
00003 // $Id: filterstreambuf.h,v 1.1 2001/08/07 09:15:59 dvermeir Exp $
00004 
00005 #include        <iostream>
00006 
00007 //  This file defines a simple streambuf specialization. A class
00008 //  object of type FilterStreambuf delegates all I/O to a Filter
00009 //  object.  Filter will be a template parameter for the
00010 //  FilterStreambuf class.
00011 //
00012 //
00013 // The requirements on Filter are as follows:
00014 //
00015 //   class Filter {
00016 //   public:
00017 //     int get(); // return next input char or EOF (-1 for char in C locale)
00018 //     int put(int c); // output c if c!=EOF, return EOF if error
00019 //     int sync(); // synchronize filter, return 0 (ok) or -1 (EOF)
00020 //     void close(); // close filter, no obligations..
00021 //   };
00022 
00023 template <class Filter>
00024 class FilterStreambuf: public std::streambuf {
00025 public:
00026 
00027   // The constructor remembers the filter to which I/O will be forwarded.
00028   // Note that the filter is not copied, the management of the filter is
00029   // not the FilterStreambuf's responsibility.
00030 
00031   explicit FilterStreambuf(Filter& filter): filter_(filter) {
00032     setg(inbuf_,inbuf_+1,inbuf_+1); // very small input buffer
00033     setp(0,0); // no output buffer
00034     }
00035 
00036   // The destructor is already virtual in streambuf.
00037   virtual ~FilterStreambuf() {}
00038 
00039   // Return underlying Filter object, const and non-const version.
00040   const Filter& filter() const { return filter_; }
00041   Filter&       filter() { return filter_; }
00042 
00043   // Set underlying filter.
00044   FilterStreambuf& filter(Filter& filter) { filter_ = filter; return *this; }
00045 
00046   // Indicate the intention not to use the filter anymore.
00047   bool close() { int tmp=sync(); filter_.close(); return tmp; }
00048 
00049 protected:
00050   // The following function simply delegate all I/O operations to the
00051   // underlying Filter object.
00052   virtual int  sync() { return filter_.sync(); }
00053   virtual int  underflow() { 
00054     if (gptr()<egptr()) // buffer not empty
00055       return *gptr();
00056     if ( (inbuf_[0] = filter_.get()) != EOF)
00057       setg(inbuf_,inbuf_,inbuf_+1);
00058     return inbuf_[0];
00059     }  
00060   virtual int  overflow(int c) { return filter_.put(c); }
00061 
00062 private:
00063   char          inbuf_[1];
00064   Filter&       filter_;
00065 };
00066 
00067 #endif

FSM [ August, 2001]