aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/apache/avro/api/buffer/Buffer.hh
blob: 7d7aaf8679c6f6940c1b3bb9ec7f4e767b2e42d0 (plain) (blame)
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef avro_Buffer_hh__
#define avro_Buffer_hh__

#ifndef _WIN32
#include <sys/uio.h>
#endif
#include <vector>

#include "../Config.hh"
#include "detail/BufferDetail.hh"
#include "detail/BufferDetailIterator.hh"

/**
 * \file Buffer.hh
 *
 * \brief Definitions for InputBuffer and OutputBuffer classes
 *
 **/

namespace avro {

class OutputBuffer;
class InputBuffer;


/**
 * The OutputBuffer (write-only buffer)
 *
 * Use cases for OutputBuffer
 *
 * - write message to buffer using ostream class or directly
 * - append messages to headers
 * - building up streams of messages via append
 * - converting to read-only buffers for sending
 * - extracting parts of the messages into read-only buffers
 *
 * -# ASIO access:
 *     - write to a buffer(s) by asio using iterator
 *     - convert to read buffer for deserializing
 *
 * OutputBuffer is assignable and copy-constructable.  On copy or assignment,
 * only a pointer is copied, so the two resulting copies are identical, so
 * modifying one will modify both.
 **/

class AVRO_DECL OutputBuffer
{

  public:

    typedef detail::size_type size_type;
    typedef detail::data_type data_type;

    /**
     * The asio library expects a const_iterator (the const-ness refers to the
     * fact that the underlying avro of buffers will not be modified, even
     * though the data in those buffers is being modified).  The iterator
     * provides the list of addresses an operation can write to.
     **/

    typedef detail::OutputBufferIterator const_iterator;

    /**
     * Default constructor.  Will pre-allocate at least the requested size, but
     * can grow larger on demand.
     *
     * Destructor uses the default, which resets a shared pointer, deleting the
     * underlying data if no other copies of exist.
     *
     * Copy and assignment operators are not explicitly provided because the
     * default ones work fine.  The default makes only a shallow copy, so the
     * copies will refer to the same memory.  This is required by asio
     * functions, which will implicitly make copies for asynchronous
     * operations.  Therefore, the user must be careful that if they create
     * multiple copies of the same OutputBuffer, only one is being modified
     * otherwise undefined behavior may occur.
     *
     **/

    OutputBuffer(size_type reserveSize = 0) :
        pimpl_(new detail::BufferImpl)
    {
        if(reserveSize) {
            reserve(reserveSize);
        }
    }

    /**
     * Reserve enough space for a wroteTo() operation.  When using writeTo(),
     * the buffer will grow dynamically as needed.  But when using the iterator
     * to write (followed by wroteTo()), data may only be written to the space
     * available,  so this ensures there is enough room in the buffer before
     * the write operation.
     **/

    void reserve(size_type reserveSize)
    {
        pimpl_->reserveFreeSpace(reserveSize);
    }

    /**
     * Write a block of data to the buffer.  The buffer size will automatically
     * grow if the size is larger than what is currently free.
     **/

    size_type writeTo(const data_type *data, size_type size) {
        return pimpl_->writeTo(data, size);
    }

    /**
     * Write a single value to the buffer. The buffer size will automatically
     * grow if there is not room for the byte.  The value must be a
     * "fundamental" type, e.g. int, float, etc.  (otherwise use the other
     * writeTo tests).
     **/

    template<typename T>
    void writeTo(T val) {
        pimpl_->writeTo(val, std::is_fundamental<T>());
    }

    /**
     * Update the state of the buffer after writing through the iterator
     * interface.  This function exists primarily for the boost:asio which
     * writes directly to the buffer using its iterator.  In this case, the
     * internal state of the buffer does not reflect that the data was written
     * This informs the buffer how much data was written.
     *
     * The buffer does not automatically resize in this case, the bytes written
     * cannot exceed the amount of free space.  Attempting to write more will
     * throw a std::length_error exception.
     **/

    size_type wroteTo(size_type size)
    {
        int wrote = 0;
        if(size) {
            if(size > freeSpace()) {
                throw std::length_error("Impossible to write more data than free space");
            }
            wrote = pimpl_->wroteTo(size);
        }
        return wrote;
    }

    /**
     * Does the buffer have any data?
     **/

    bool empty() const {
        return  (pimpl_->size()==0);
    }

    /**
     *  Returns the size of the buffer, in bytes.
     */

    size_type size() const {
        return  pimpl_->size();
    }

    /**
     * Returns the current free space that is available to write to in the
     * buffer, in bytes.  This is not a strict limit in size, as writeTo() can
     * automatically increase capacity if necessary.
     **/

    size_type freeSpace() const {
        return  pimpl_->freeSpace();
    }

    /**
     * Appends the data in the argument to the end of this buffer.  The
     * argument can be either an InputBuffer or OutputBuffer.
     *
     **/

    template <class BufferType>
    void append(const BufferType &buf) {
        // don't append an empty buffer
        if(buf.size()) {
            pimpl_->append(*(buf.pimpl_.get()));
        }
    }

    /**
     * Return an iterator pointing to the first data chunk of this buffer
     * that may be written to.
     **/

    const_iterator begin() const {
        return const_iterator(pimpl_->beginWrite());
    }

    /**
     * Return the end iterator for writing.
     **/

    const_iterator end() const {
        return const_iterator(pimpl_->endWrite());
    }

    /**
     * Discard any data in this buffer.
     **/

    void discardData()
    {
        pimpl_->discardData();
    }

    /**
     * Discard the specified number of bytes from this data, starting at the beginning.
     * Throws if the size is greater than the number of bytes.
     **/

    void discardData(size_t bytes)
    {
        if(bytes > 0) {
            if(bytes < pimpl_->size()) {
                pimpl_->discardData(bytes);
            }
            else if(bytes == pimpl_->size()) {
                pimpl_->discardData();
            }
            else {
                throw std::out_of_range("trying to discard more data than exists");
            }
        }
    }

    /**
     * Remove bytes from this buffer, starting from the beginning, and place
     * them into a new buffer.  Throws if the number of requested bytes exceeds
     * the size of the buffer.  Data and freeSpace in the buffer after bytes
     * remains in this buffer.
     **/

    InputBuffer extractData(size_type bytes);

    /**
     * Remove all bytes from this buffer, returning them in a new buffer.
     * After removing data, some freeSpace may remain in this buffer.
     **/

    InputBuffer extractData();

    /**
     * Clone this buffer, creating a copy that contains the same data.
     **/

    OutputBuffer clone() const
    {
        detail::BufferImpl::SharedPtr newImpl(new detail::BufferImpl(*pimpl_));
        return OutputBuffer(newImpl);
    }

    /**
     * Add unmanaged data to the buffer.  The buffer will not automatically
     * free the data, but it will call the supplied function when the data is
     * no longer referenced by the buffer (or copies of the buffer).
     **/

    void appendForeignData(const data_type *data, size_type size, const detail::free_func &func) {
        pimpl_->appendForeignData(data, size, func);
    }

    /**
     * Returns the number of chunks that contain free space.
     **/

    int numChunks() const {
        return  pimpl_->numFreeChunks();
    }

    /**
     * Returns the number of chunks that contain data
     **/

    int numDataChunks() const {
        return  pimpl_->numDataChunks();
    }

  private:

    friend class InputBuffer;
    friend class BufferReader;

    explicit OutputBuffer(const detail::BufferImpl::SharedPtr &pimpl) :
        pimpl_(pimpl)
    { }

    detail::BufferImpl::SharedPtr pimpl_; ///< Must never be null.
};

/**
 * The InputBuffer (read-only buffer)
 *
 * InputBuffer is an immutable buffer which that may be constructed from an
 * OutputBuffer, or several of OutputBuffer's methods.  Once the data is
 * transfered to an InputBuffer it cannot be modified, only read (via
 * BufferReader, istream, or its iterator).
 *
 * Assignments and copies are shallow copies.
 *
 * -# ASIO access: - iterate using const_iterator for sending messages
 *
 **/

class AVRO_DECL InputBuffer
{

  public:

    typedef detail::size_type size_type;
    typedef detail::data_type data_type;

    // needed for asio
    typedef detail::InputBufferIterator const_iterator;

    /**
     * Default InputBuffer creates an empty buffer.
     *
     * Copy/assignment functions use the default ones.  They will do a shallow
     * copy, and because InputBuffer is immutable, the copies will be
     * identical.
     *
     * Destructor also uses the default, which resets a shared pointer,
     * deleting the underlying data if no other copies of exist.
     **/

    InputBuffer() :
        pimpl_(new detail::BufferImpl)
    { }

    /**
     * Construct an InputBuffer that contains the contents of an OutputBuffer.
     * The two buffers will have the same contents, but this copy will be
     * immutable, while the the OutputBuffer may still be written to.
     *
     * If you wish to move the data from the OutputBuffer to a new InputBuffer
     * (leaving only free space in the OutputBuffer),
     * OutputBuffer::extractData() will do this more efficiently.
     *
     * Implicit conversion is allowed.
     **/

    InputBuffer(const OutputBuffer &src) :
        pimpl_(new detail::BufferImpl(*src.pimpl_))
    { }

    /**
     * Does the buffer have any data?
     **/

    bool empty() const {
        return (pimpl_->size() == 0);
    }

    /**
     * Returns the size of the buffer, in bytes.
     **/

    size_type size() const {
        return pimpl_->size();
    }

    /**
     * Return an iterator pointing to the first data chunk of this buffer
     * that contains data.
     **/

    const_iterator begin() const {
        return const_iterator(pimpl_->beginRead());
    }

    /**
     * Return the end iterator.
     **/

    const_iterator end() const {
        return const_iterator(pimpl_->endRead());
    }

    /**
     * Returns the number of chunks containing data.
     **/

    int numChunks() const {
        return pimpl_->numDataChunks();
    }


  private:

    friend class OutputBuffer; // for append function
    friend class istreambuf;
    friend class BufferReader;

    explicit InputBuffer(const detail::BufferImpl::SharedPtr &pimpl) :
        pimpl_(pimpl)
    { }

    /**
     * Class to indicate that a copy of a OutputBuffer to InputBuffer should be
     * a shallow copy, used to enable reading of the contents of an
     * OutputBuffer without need to convert it to InputBuffer using a deep
     * copy.  It is private and only used by BufferReader and istreambuf
     * classes.
     *
     * Writing to an OutputBuffer while it is being read may lead to undefined
     * behavior.
     **/

    class ShallowCopy {};

    /**
     * Make a shallow copy of an OutputBuffer in order to read it without
     * causing conversion overhead.
     **/
    InputBuffer(const OutputBuffer &src, const ShallowCopy &) :
        pimpl_(src.pimpl_)
    { }

    /**
     * Make a shallow copy of an InputBuffer.  The default copy constructor
     * already provides shallow copy, this is just provided for generic
     * algorithms that wish to treat InputBuffer and OutputBuffer in the same
     * manner.
     **/

     InputBuffer(const InputBuffer &src, const ShallowCopy &) :
        pimpl_(src.pimpl_)
    { }


    detail::BufferImpl::ConstSharedPtr pimpl_; ///< Must never be null.
};


/*
 * Implementations of some OutputBuffer functions are inlined here
 * because InputBuffer definition was required before.
 */

inline InputBuffer OutputBuffer::extractData()
{
    detail::BufferImpl::SharedPtr newImpl(new detail::BufferImpl);
    if(pimpl_->size()) {
        pimpl_->extractData(*newImpl);
    }
    return InputBuffer(newImpl);
}

inline InputBuffer OutputBuffer::extractData(size_type bytes)
{
    if(bytes > pimpl_->size()) {
        throw std::out_of_range("trying to extract more data than exists");
    }

    detail::BufferImpl::SharedPtr newImpl(new detail::BufferImpl);
    if(bytes > 0) {
        if(bytes < pimpl_->size()) {
            pimpl_->extractData(*newImpl, bytes);
        }
        else {
            pimpl_->extractData(*newImpl);
        }
    }

    return InputBuffer(newImpl);
}

#ifndef _WIN32
/**
 * Create an array of iovec structures from the buffer.  This utility is used
 * to support writev and readv function calls.  The caller should ensure the
 * buffer object is not deleted while using the iovec vector.
 *
 * If the BufferType is an InputBuffer, the iovec will point to the data that
 * already exists in the buffer, for reading.
 *
 * If the BufferType is an OutputBuffer, the iovec will point to the free
 * space, which may be written to.  Before writing, the caller should call
 * OutputBuffer::reserve() to create enough room for the desired write (which
 * can be verified by calling OutputBuffer::freeSpace()), and after writing,
 * they MUST call OutputBuffer::wroteTo(), otherwise the buffer will not know
 * the space is not free anymore.
 *
 **/

template<class BufferType>
inline void toIovec(BufferType &buf, std::vector<struct iovec> &iov)
{
    const int chunks = buf.numChunks();
    iov.resize(chunks);
    typename BufferType::const_iterator iter = buf.begin();
    for (int i = 0; i < chunks; ++i) {
        iov[i].iov_base = const_cast<typename BufferType::data_type *>(iter->data());
        iov[i].iov_len = iter->size();
        ++iter;
    }
}
#endif

} // namespace

#endif