Imported Upstream version 17.22.0
[platform/upstream/libzypp.git] / zypp / base / fXstream.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 #ifndef ZYPP_BASE_FXSTREAM_H
10 #define ZYPP_BASE_FXSTREAM_H
11
12 #include <iosfwd>
13 #include <iostream>
14
15 namespace zypp {
16   namespace detail {
17     /**
18      * @short Common template to define ifgzstream/ofgzstream
19      * reading/writing compressed files.
20      *
21      * Don't use fXstream directly, but @ref ifgzstream or
22      * @ref ofgzstream. fXstream is just to avoid almost
23      * duplicate code.
24      **/
25     template<class TBStream,class TStreamBuf>
26     class fXstream : public TBStream
27     {
28     public:
29
30       using ZlibError = typename TStreamBuf::error_type;
31       using stream_type = TBStream;
32       using streambuf_type = TStreamBuf;
33
34       fXstream()
35         : stream_type( nullptr )
36       { this->init( &_streambuf ); }
37
38       explicit
39         fXstream( const char * file_r )
40         : stream_type( nullptr )
41       { this->init( &_streambuf ); this->open( file_r ); }
42
43       virtual
44         ~fXstream()
45       {}
46
47       bool
48       is_open() const
49       { return _streambuf.isOpen(); }
50
51       void
52       open( const char * file_r )
53       {
54         if ( !_streambuf.open( file_r, defMode(*this) ) )
55           this->setstate(std::ios_base::failbit);
56         else
57           this->clear();
58       }
59
60       void
61       close()
62       {
63         if ( !_streambuf.close() )
64           this->setstate(std::ios_base::failbit);
65       }
66
67       /**
68              * The last error returned retuned from zlib.
69              **/
70       ZlibError
71       zError() const
72       { return _streambuf.error(); }
73
74       //! Similar to ios::rdbuf.
75       //! But it returns our specific type, not the generic streambuf *.
76       const streambuf_type&
77       getbuf() const
78       { return _streambuf; }
79
80     private:
81
82       streambuf_type _streambuf;
83
84       std::ios_base::openmode
85       defMode( const std::istream & )
86       { return std::ios_base::in; }
87
88       std::ios_base::openmode
89       defMode( const std::ostream & )
90       { return std::ios_base::out; }
91
92     };
93   }
94 }
95
96 #endif