summaryrefslogtreecommitdiff
path: root/xsd-examples/cxx/tree/compression/compressed-format-target.hxx
blob: 0061cfa36d8fea1522b42b2bb2c1205cac87f8e5 (plain)
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
// file      : cxx/tree/compression/compressed-format-target.hxx
// copyright : not copyrighted - public domain

#ifndef COMPRESSED_FORMAT_TARGET_HXX
#define COMPRESSED_FORMAT_TARGET_HXX

#include <zlib.h>

#include <iosfwd>
#include <cstddef>   // std::size_t
#include <exception>

#include <xercesc/framework/XMLFormatter.hpp>

struct compression_failure: std::exception
{
  explicit
  compression_failure (int code)
      : code_ (code)
  {
  }

  int
  code () const
  {
    return code_;
  }

  const char*
  message () const
  {
    return zError (code_);
  }

  virtual const char*
  what () const throw ();

private:
  int code_;
};

// Xerces-C++ XMLFormatTarget interface implementation with on-the-fly,
// zlib-based compression.
//
class compressed_format_target: public xercesc::XMLFormatTarget
{
public:
  enum compression_type
  {
    raw,
    zlib,
    gzip
  };

  compressed_format_target (std::ostream&, compression_type);

  virtual
  ~compressed_format_target ();

  virtual void
  writeChars (const XMLByte* const buf,
              const XMLSize_t size,
              xercesc::XMLFormatter* const);

  virtual void
  flush ();

  // Close the compressed stream by writing out the zlib or gzip trailer.
  // This function is automatically called from the destructor but you
  // may want to call it explicitly to be able to catch any exceptions
  // that it might throw.
  //
  void
  close ();

private:
  void
  write (const char* buf, std::size_t size, bool flush = false);

private:
  std::ostream& os_;
  z_stream zs_;
  bool closed_;

  static const std::size_t buf_size_ = 65536;
  char in_[buf_size_];
  char out_[buf_size_];
  size_t n_;
};

#endif // COMPRESSED_FORMAT_TARGET_HXX