1 // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 // vi: set et ts=4 sw=2 sts=2:
3 
4 #ifndef DUNE_GRID_IO_FILE_VTK_STREAMS_HH
5 #define DUNE_GRID_IO_FILE_VTK_STREAMS_HH
6 
7 #include <ostream>
8 
9 #include <dune/grid/io/file/vtk/b64enc.hh>
10 
11 namespace Dune {
12 
13   //! class to base64 encode a stream of data
14   class Base64Stream {
15     std::ostream& s;
16     b64chunk chunk;
17     char obuf[4];
18 
19   public:
20     //! Construct a Base64Stream
21     /**
22      * \param s_ The stream the resulting base64-encoded text will be written
23      *           to.
24      */
Base64Stream(std::ostream & s_)25     Base64Stream(std::ostream& s_)
26       : s(s_)
27     {
28       // reset chunk
29       chunk.reset();
30     }
31 
32     //! encode a data item
33     /**
34      * The result will be written to the stream, eventually.  This method may
35      * be called multiple times in a row.  After this method has been called,
36      * no one else may write to the underlying stream until flush() has been
37      * called or this writer object has been destroyed.
38      */
39     template <class X>
write(X & data)40     void write(X & data)
41     {
42       char* p = reinterpret_cast<char*>(&data);
43       for (size_t len = sizeof(X); len > 0; len--,p++)
44       {
45         chunk.put(*p);
46         if (chunk.size == 3)
47         {
48           chunk.write(obuf);
49           s.write(obuf,4);
50         }
51       }
52     }
53 
54     //! flush the current unwritten data to the stream.
55     /**
56      * If the size of the received input is not a multiple of three bytes, an
57      * end-marker will be written.
58      *
59      * Calling this function a second time without calling b64enc() or calling
60      * it right after construction has no effect.
61      */
flush()62     void flush()
63     {
64       if (chunk.size > 0)
65       {
66         chunk.write(obuf);
67         s.write(obuf,4);
68       }
69     }
70 
71     //! destroy the object
72     /**
73      * Calls flush()
74      */
~Base64Stream()75     ~Base64Stream() {
76       flush();
77     }
78   };
79 
80   //! write out data in binary
81   class RawStream
82   {
83   public:
84     //! make a new stream
RawStream(std::ostream & theStream)85     inline RawStream (std::ostream& theStream)
86       : s(theStream)
87     {}
88 
89     //! write data to stream
90     template<class T>
write(T data)91     void write (T data)
92     {
93       char* p = reinterpret_cast<char*>(&data);
94       s.write(p,sizeof(T));
95     }
96   private:
97     std::ostream& s;
98   };
99 
100 } // namespace Dune
101 
102 #endif // DUNE_GRID_IO_FILE_VTK_STREAMS_HH
103