summaryrefslogtreecommitdiff
path: root/Kernel/KString.cpp
blob: d20fd6e374c71778903f34fd5c8c14c9d26f9f21 (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
/*
 * 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 {

ErrorOr<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();
}

ErrorOr<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();
}

ErrorOr<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);
}

}