summaryrefslogtreecommitdiff
path: root/Kernel/KBufferBuilder.h
blob: 83450515f08de4e53678adb2fb9092f2ba5aaefa (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
/*
 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <Kernel/KBuffer.h>
#include <stdarg.h>

namespace Kernel {

class KBufferBuilder {
    AK_MAKE_NONCOPYABLE(KBufferBuilder);

public:
    using OutputType = KBuffer;

    static ErrorOr<KBufferBuilder> try_create();

    KBufferBuilder(KBufferBuilder&&) = default;
    KBufferBuilder& operator=(KBufferBuilder&&) = default;
    ~KBufferBuilder() = default;

    ErrorOr<void> append(StringView);
    ErrorOr<void> append(char);
    ErrorOr<void> append(const char*, int);

    ErrorOr<void> append_escaped_for_json(StringView);
    ErrorOr<void> append_bytes(ReadonlyBytes);

    template<typename... Parameters>
    ErrorOr<void> appendff(CheckedFormatString<Parameters...>&& fmtstr, const Parameters&... parameters)
    {
        // FIXME: This really not ideal, but vformat expects StringBuilder.
        StringBuilder builder;
        AK::VariadicFormatParams variadic_format_params { parameters... };
        TRY(vformat(builder, fmtstr.view(), variadic_format_params));
        return append_bytes(builder.string_view().bytes());
    }

    bool flush();
    OwnPtr<KBuffer> build();

    ReadonlyBytes bytes() const
    {
        if (!m_buffer)
            return {};
        return m_buffer->bytes();
    }

private:
    explicit KBufferBuilder(NonnullOwnPtr<KBuffer>);

    bool check_expand(size_t);
    u8* insertion_ptr()
    {
        if (!m_buffer)
            return nullptr;
        return m_buffer->data() + m_size;
    }

    OwnPtr<KBuffer> m_buffer;
    size_t m_size { 0 };
};

}