ladybird/Kernel/KString.cpp
Andreas Kling 56a2594de7 Kernel: Make KString factories return KResultOr + use TRY() everywhere
There are a number of places that don't have an error propagation path
right now, so I've added FIXME's about that.
2021-09-06 19:25:36 +02:00

63 lines
1.8 KiB
C++

/*
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <Kernel/KString.h>
extern bool g_in_early_boot;
namespace Kernel {
KResultOr<NonnullOwnPtr<KString>> KString::try_create(StringView string)
{
char* characters = nullptr;
size_t length = string.length();
auto new_string = TRY(KString::try_create_uninitialized(length, characters));
if (!string.is_empty())
__builtin_memcpy(characters, string.characters_without_null_termination(), length);
characters[length] = '\0';
return new_string;
}
NonnullOwnPtr<KString> KString::must_create(StringView string)
{
// We can only enforce success during early boot.
VERIFY(g_in_early_boot);
return KString::try_create(string).release_value();
}
KResultOr<NonnullOwnPtr<KString>> KString::try_create_uninitialized(size_t length, char*& characters)
{
size_t allocation_size = sizeof(KString) + (sizeof(char) * length) + sizeof(char);
auto* slot = kmalloc(allocation_size);
if (!slot)
return ENOMEM;
auto new_string = TRY(adopt_nonnull_own_or_enomem(new (slot) KString(length)));
characters = new_string->m_characters;
return new_string;
}
NonnullOwnPtr<KString> KString::must_create_uninitialized(size_t length, char*& characters)
{
// We can only enforce success during early boot.
VERIFY(g_in_early_boot);
return KString::try_create_uninitialized(length, characters).release_value();
}
KResultOr<NonnullOwnPtr<KString>> KString::try_clone() const
{
return try_create(view());
}
void KString::operator delete(void* string)
{
if (!string)
return;
size_t allocation_size = sizeof(KString) + (sizeof(char) * static_cast<KString*>(string)->m_length) + sizeof(char);
kfree_sized(string, allocation_size);
}
}