ladybird/Kernel/KBufferBuilder.h
Gunnar Beutner 93c3b6bdd2 Kernel: Avoid allocations in KBufferBuilder::appendff
This avoids some of the the shortest-lived allocations in the kernel:

StringImpl::create_uninitialized(unsigned long, char*&)
StringImpl::create(char const*, unsigned long, ShouldChomp)
StringBuilder::to_string() const
String::vformatted(StringView, TypeErasedFormatParams)
void Kernel::KBufferBuilder::appendff<unsigned int>(...)
JsonObjectSerializer<Kernel::KBufferBuilder>::add(..., unsigned int)
Kernel::procfs$all(Kernel::InodeIdentifier, ...) const
Kernel::procfs$all(Kernel::InodeIdentifier, Kernel::KBufferBuilder&)
2021-05-13 08:27:42 +02:00

58 lines
1.4 KiB
C++

/*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/String.h>
#include <Kernel/KBuffer.h>
#include <stdarg.h>
namespace Kernel {
class KBufferBuilder {
public:
using OutputType = KBuffer;
explicit KBufferBuilder(bool can_expand = false);
explicit KBufferBuilder(RefPtr<KBufferImpl>&, bool can_expand = false);
KBufferBuilder(KBufferBuilder&&) = default;
~KBufferBuilder() = default;
void append(const StringView&);
void append(char);
void append(const char*, int);
void append_escaped_for_json(const StringView&);
void append_bytes(ReadonlyBytes);
template<typename... Parameters>
void appendff(CheckedFormatString<Parameters...>&& fmtstr, const Parameters&... parameters)
{
// FIXME: This is really not the way to go about it, but vformat expects a
// StringBuilder. Why does this class exist anyways?
StringBuilder builder;
vformat(builder, fmtstr.view(), AK::VariadicFormatParams { parameters... });
append_bytes(builder.string_view().bytes());
}
bool flush();
OwnPtr<KBuffer> build();
private:
bool check_expand(size_t);
u8* insertion_ptr()
{
if (!m_buffer)
return nullptr;
return m_buffer->data() + m_size;
}
RefPtr<KBufferImpl> m_buffer;
size_t m_size { 0 };
bool m_can_expand { false };
};
}