mirror of
https://github.com/RGBCube/serenity
synced 2025-05-19 00:15:08 +00:00
Kernel: Add KString, a single-owner string with OOM failure exposion
This is a simple string class for use in the kernel. It encapsulates a length + character array in a single-allocation object. Main differences from AK::String: - Single-owner (no reference counting.) - Allocation failures are exposed, not hidden. The basic idea is to allow better and more precise string management in the kernel.
This commit is contained in:
parent
377b06c8ac
commit
279383a8f3
3 changed files with 89 additions and 0 deletions
40
Kernel/KString.cpp
Normal file
40
Kernel/KString.cpp
Normal file
|
@ -0,0 +1,40 @@
|
|||
/*
|
||||
* Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <Kernel/KString.h>
|
||||
|
||||
namespace Kernel {
|
||||
|
||||
OwnPtr<KString> KString::try_create(StringView const& string)
|
||||
{
|
||||
char* characters = nullptr;
|
||||
size_t length = string.length();
|
||||
auto new_string = KString::try_create_uninitialized(length, characters);
|
||||
if (!new_string)
|
||||
return {};
|
||||
if (!string.is_empty())
|
||||
__builtin_memcpy(characters, string.characters_without_null_termination(), length);
|
||||
characters[length] = '\0';
|
||||
return new_string;
|
||||
}
|
||||
|
||||
OwnPtr<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 {};
|
||||
auto* new_string = new (slot) KString(length);
|
||||
characters = new_string->m_characters;
|
||||
return adopt_own(*new_string);
|
||||
}
|
||||
|
||||
OwnPtr<KString> KString::try_clone() const
|
||||
{
|
||||
return try_create(view());
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue