WvStreams
wvfunctorencoder.h
00001 /* -*- Mode: C++ -*-
00002  * Worldvisions Weaver Software:
00003  *   Copyright (C) 1997-2002 Net Integration Technologies, Inc.
00004  *
00005  * Provides an encoder for applying a functor to data extracted
00006  * from a buffer and stored in another.
00007  * Assumes binary input is in machine order.
00008  */
00009 #ifndef __WVFUNCTORENCODER_H
00010 #define __WVFUNCTORENCODER_H
00011 
00012 #include "wvtypedencoder.h"
00013 
00030 template<class IT, class OT, class FT>
00031 class WvFunctorEncoder : public WvTypedEncoder<IT, OT>
00032 {
00033 protected:
00034     FT f;
00035     
00036 public:
00037     typedef FT FType;
00038     typedef IT IType;
00039     typedef OT OType;
00040     typedef WvBufBase<IType> IBuffer;
00041     typedef WvBufBase<OType> OBuffer;  
00042     WvFunctorEncoder(const FType &f) : f(f) { }
00043     virtual ~WvFunctorEncoder() { }
00044 
00045 protected:
00046     virtual bool _typedencode(IBuffer &inbuf, OBuffer &outbuf,
00047         bool flush)
00048     {
00049         size_t count;
00050         while ( (count = inbuf.optgettable()) )
00051         {
00052             size_t avail = outbuf.optallocable();
00053             if (avail == 0)
00054                 return ! flush;
00055             if (avail < count)
00056                 count = avail;
00057             const IType *indata = inbuf.get(count);
00058             OType *outdata = outbuf.alloc(count);
00059             while (count-- > 0)
00060                 *(outdata++) = f(*(indata++));
00061         }
00062         return true;
00063     }
00064     virtual bool _reset()
00065     {
00066         // Assume most functor encoders will be stateless and therefore
00067         // support reset() implicitly.
00068         // If this is not the case, then override this method for
00069         // particular subclasses to return false.
00070         return true;
00071     }
00072 };
00073 
00074 #endif // __WVFUNCTORENCODER_H