aboutsummaryrefslogtreecommitdiff
path: root/libbutl/lz4-stream.cxx
blob: 9d0ac991e0885063da9cfd67b8ed9391f3287b84 (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// file      : libbutl/lz4-stream.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbutl/lz4-stream.hxx>

#include <cstring>   // memcpy()
#include <stdexcept> // invalid_argument

#include <libbutl/utility.mxx> // eof()

using namespace std;

namespace butl
{
  namespace lz4
  {
    // istream
    //

    // Read into the specified buffer returning the number of bytes read and
    // the eof flag.
    //
    pair<size_t, bool> istreambuf::
    read (char* b, size_t c)
    {
      size_t n (0);
      bool e (false);

      // @@ TODO: would it be faster to do a direct buffer copy if input
      //    stream is bufstreabuf-based (see sha*.cxx for code)?
      do
      {
        e = eof (is_->read (b + n, c - n));
        n += static_cast<size_t> (is_->gcount ());
      }
      while (!e && n != c);

      return make_pair (n, e);
    }

    optional<uint64_t> istreambuf::
    open (std::istream& is, bool end)
    {
      assert (is.exceptions () == std::istream::badbit);

      is_ = &is;
      end_ = end;

      // Read in the header and allocate the buffers.
      //
      // What if we hit EOF here? And could begin() return 0? Turns out the
      // answer to both questions is yes: 0-byte content compresses to 15
      // bytes (with or without content size; 1-byte -- to 20/28 bytes). We
      // can ignore EOF here since an attempt to read more will result in
      // another EOF. And our load() is prepared to handle 0 hint.
      //
      // @@ We could end up leaving some of the input content from the header
      //    in the input buffer which the caller will have to way of using
      //    (e.g., in a stream of compressed contents). Doesn't look like
      //    there is much we can do (our streams don't support putback) other
      //    than document this limitation.
      //
      optional<uint64_t> r;

      d_.hn = read (d_.hb, sizeof (d_.hb)).first;
      h_ = d_.begin (&r);

      ib_.reset ((d_.ib = new char[d_.ic]));
      ob_.reset ((d_.ob = new char[d_.oc]));

      // Copy over whatever is left in the header buffer.
      //
      memcpy (d_.ib, d_.hb, (d_.in = d_.hn));

      setg (d_.ob, d_.ob, d_.ob);
      return r;
    }

    void istreambuf::
    close ()
    {
      if (is_open ())
      {
        is_ = nullptr;
      }
    }

    istreambuf::int_type istreambuf::
    underflow ()
    {
      int_type r (traits_type::eof ());

      if (is_open ())
      {
        if (gptr () < egptr () || load ())
          r = traits_type::to_int_type (*gptr ());
      }

      return r;
    }

    bool istreambuf::
    load ()
    {
      // Note that the first call to this function may be with h_ == 0 (see
      // open() for details). In which case we just need to verify there is
      // no just after the compressed content.
      //
      bool r;

      if (h_ == 0)
        r = false; // EOF
      else
      {
        // Note: next() may just buffer the data.
        //
        do
        {
          // Note that on the first call we may already have some data in the
          // input buffer (leftover header data).
          //
          if (h_ > d_.in)
          {
            pair<size_t, bool> p (read (d_.ib + d_.in, h_ - d_.in));

            d_.in += p.first;

            if (p.second && d_.in != h_)
              throw invalid_argument ("incomplete LZ4 compressed content");
          }

          h_ = d_.next (); // Clears d_.in.

        } while (d_.on == 0 && h_ != 0);

        setg (d_.ob, d_.ob, d_.ob + d_.on);
        off_ += d_.on;
        r = (d_.on != 0);
      }

      // If we don't expect any more compressed content and we were asked to
      // end the underlying input stream, then verify there is no more input.
      //
      if (h_ == 0 && end_)
      {
        end_ = false;

        if (d_.in != 0 ||
            (!is_->eof () &&
             is_->good () &&
             is_->peek () != istream::traits_type::eof ()))
          throw invalid_argument ("junk after LZ4 compressed content");
      }

      return r;
    }

    // ostream
    //

    void ostreambuf::
    write (char* b, std::size_t n)
    {
      os_->write (b, static_cast<streamsize> (n));
    }

    void ostreambuf::
    open (std::ostream& os,
          int level,
          int block_id,
          optional<std::uint64_t> content_size)
    {
      assert (os.exceptions () == (std::ostream::badbit |
                                   std::ostream::failbit));

      os_ = &os;

      // Determine required buffer capacities.
      //
      c_.begin (level, block_id, content_size);

      ib_.reset ((c_.ib = new char[c_.ic]));
      ob_.reset ((c_.ob = new char[c_.oc]));

      setp (c_.ib, c_.ib + c_.ic - 1); // Keep space for overflow's char.
      end_ = false;
    }

    void ostreambuf::
    close ()
    {
      if (is_open ())
      {
        if (!end_)
          save ();

        os_ = nullptr;
      }
    }

    ostreambuf::
    ~ostreambuf ()
    {
      close ();
    }

    ostreambuf::int_type ostreambuf::
    overflow (int_type c)
    {
      int_type r (traits_type::eof ());

      if (is_open () && c != traits_type::eof ())
      {
        // Store last character in the space we reserved in open(). Note
        // that pbump() doesn't do any checks.
        //
        *pptr () = traits_type::to_char_type (c);
        pbump (1);

        save ();
        r = c;
      }

      return r;
    }

    void ostreambuf::
    save ()
    {
      c_.in = pptr () - pbase ();
      off_ += c_.in;

      // We assume this is the end if the input buffer is not full.
      //
      end_ = (c_.in != c_.ic);
      c_.next (end_);

      if (c_.on != 0) // next() may just buffer the data.
        write (c_.ob, c_.on);

      setp (c_.ib, c_.ib + c_.ic - 1);
    }

    streamsize ostreambuf::
    xsputn (const char_type* s, streamsize sn)
    {
      if (!is_open () || end_)
        return 0;

      // To avoid futher 'signed/unsigned comparison' compiler warnings.
      //
      size_t n (static_cast<size_t> (sn));

      // The plan is to keep copying the data into the input buffer and
      // calling save() (our compressor API currently has no way of avoiding
      // the copy).
      //
      while (n != 0)
      {
        // Amount of free space in the buffer (including the extra byte
        // we've reserved).
        //
        size_t an (epptr () - pptr () + 1);

        size_t m (n > an ? an : n);
        memcpy (pptr (), s, m);
        pbump (static_cast<int> (m));

        if (n < an)
          break; // All fitted with at least 1 byte left.

        save ();

        s += m;
        n -= m;
      }

      return sn;
    }
  }
}