KString.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/KString.h>
  7. extern bool g_in_early_boot;
  8. namespace Kernel {
  9. OwnPtr<KString> KString::try_create(StringView const& string)
  10. {
  11. char* characters = nullptr;
  12. size_t length = string.length();
  13. auto new_string = KString::try_create_uninitialized(length, characters);
  14. if (!new_string)
  15. return {};
  16. if (!string.is_empty())
  17. __builtin_memcpy(characters, string.characters_without_null_termination(), length);
  18. characters[length] = '\0';
  19. return new_string;
  20. }
  21. NonnullOwnPtr<KString> KString::must_create(StringView const& string)
  22. {
  23. // We can only enforce success during early boot.
  24. VERIFY(g_in_early_boot);
  25. auto kstring = KString::try_create(string);
  26. VERIFY(kstring != nullptr);
  27. return kstring.release_nonnull();
  28. }
  29. OwnPtr<KString> KString::try_create_uninitialized(size_t length, char*& characters)
  30. {
  31. size_t allocation_size = sizeof(KString) + (sizeof(char) * length) + sizeof(char);
  32. auto* slot = kmalloc(allocation_size);
  33. if (!slot)
  34. return {};
  35. auto* new_string = new (slot) KString(length);
  36. characters = new_string->m_characters;
  37. return adopt_own_if_nonnull(new_string);
  38. }
  39. NonnullOwnPtr<KString> KString::must_create_uninitialized(size_t length, char*& characters)
  40. {
  41. // We can only enforce success during early boot.
  42. VERIFY(g_in_early_boot);
  43. auto kstring = KString::try_create_uninitialized(length, characters);
  44. VERIFY(kstring != nullptr);
  45. return kstring.release_nonnull();
  46. }
  47. OwnPtr<KString> KString::try_clone() const
  48. {
  49. return try_create(view());
  50. }
  51. void KString::operator delete(void* string)
  52. {
  53. if (!string)
  54. return;
  55. size_t allocation_size = sizeof(KString) + (sizeof(char) * static_cast<KString*>(string)->m_length) + sizeof(char);
  56. kfree_sized(string, allocation_size);
  57. }
  58. }