aboutsummaryrefslogtreecommitdiffstats
path: root/util/stream/zerocopy_output.h
blob: a388be04b0428f3fd2c4bb4b2551bc3635ba5e03 (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
#pragma once

#include <util/system/yassert.h>

#include "output.h"

/**
 * @addtogroup Streams
 * @{
 */

/**
 * Output stream with direct access to the output buffer.
 *
 * Derived classes must implement `DoNext` and `DoUndo` methods.
 */
class IZeroCopyOutput: public IOutputStream {
public:
    IZeroCopyOutput() noexcept = default;
    ~IZeroCopyOutput() override = default;

    IZeroCopyOutput(IZeroCopyOutput&&) noexcept = default;
    IZeroCopyOutput& operator=(IZeroCopyOutput&&) noexcept = default;

    /**
     * Returns the next buffer to write to from this output stream.
     *
     * @param ptr[out]                  Pointer to the start of the buffer.
     * @returns                         Size of the returned buffer, in bytes.
     *                                  Return value is always nonzero.
     */
    template <class T>
    inline size_t Next(T** ptr) {
        Y_ASSERT(ptr);

        return DoNext((void**)ptr);
    }

    /**
     * Tells the stream that `len` bytes at the end of the buffer returned previously
     * by Next were actually not written so the current position in stream must be moved backwards.
     * `len` must not be greater than the size of the buffer previously returned by `Next`.
     *
     * @param len[in]                  Number of bytes at the end to move the position by.
     *
     */
    inline void Undo(size_t len) {
        return DoUndo(len);
    }

protected:
    void DoWrite(const void* buf, size_t len) override;
    virtual size_t DoNext(void** ptr) = 0;
    virtual void DoUndo(size_t len) = 0;
};

/** @} */