File: streams.hh

package info (click to toggle)
psurface 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,092 kB
  • sloc: cpp: 12,339; makefile: 111; awk: 38
file content (102 lines) | stat: -rw-r--r-- 2,264 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:

#ifndef PSURFACE_STREAMS_HH
#define PSURFACE_STREAMS_HH

#include <ostream>

#include "b64enc.hh"

namespace psurface {

  //! class to base64 encode a stream of data
  class Base64Stream {
    std::ostream& s;
    b64chunk chunk;
    char obuf[4];

  public:
    //! Construct a Base64Stream
    /**
     * \param s_ The stream the resulting base64-encoded text will be written
     *           to.
     */
    Base64Stream(std::ostream& s_)
      : s(s_)
    {
      // reset chunk
      chunk.txt.read(0,0);
    }

    //! encode a data item
    /**
     * The result will be written to the stream, eventually.  This method may
     * be called multiple times in a row.  After this method has been called,
     * noone else may write to the undelying stream until flush() has been
     * called or this writer object has been destroyed.
     */
    template <class X>
    void write(X & data)
    {
      char* p = reinterpret_cast<char*>(&data);
      for (size_t len = sizeof(X); len > 0; len--,p++)
      {
        chunk.txt.put(*p);
        if (chunk.txt.size == 3)
        {
          chunk.data.write(obuf);
          s.write(obuf,4);
        }
      }
    }

    //! flush the current unwritten data to the stream.
    /**
     * If the size of the received input is not a multiple of three bytes, an
     * end-marker will be written.
     *
     * Calling this function a second time without calling b64enc() or calling
     * it right after construction has no effect.
     */
    void flush()
    {
      if (chunk.txt.size > 0)
      {
        chunk.data.write(obuf);
        s.write(obuf,4);
      }
    }

    //! destroy the object
    /**
     * Calls flush()
     */
    ~Base64Stream() {
      flush();
    }
  };

  //! write out data in binary
  class RawStream
  {
  public:
    //! make a new stream
    inline RawStream (std::ostream& theStream)
      : s(theStream)
    {}

    //! write data to stream
    template<class T>
    void write (T data)
    {
      char* p = reinterpret_cast<char*>(&data);
      s.write(p,sizeof(T));
    }
  private:
    std::ostream& s;
  };

} // namespace Dune

#endif // DUNE_GRID_IO_FILE_VTK_STREAMS_HH