KString.cpp 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. namespace Kernel {
  8. OwnPtr<KString> KString::try_create(StringView const& string)
  9. {
  10. char* characters = nullptr;
  11. size_t length = string.length();
  12. auto new_string = KString::try_create_uninitialized(length, characters);
  13. if (!new_string)
  14. return {};
  15. if (!string.is_empty())
  16. __builtin_memcpy(characters, string.characters_without_null_termination(), length);
  17. characters[length] = '\0';
  18. return new_string;
  19. }
  20. OwnPtr<KString> KString::try_create_uninitialized(size_t length, char*& characters)
  21. {
  22. size_t allocation_size = sizeof(KString) + (sizeof(char) * length) + sizeof(char);
  23. auto* slot = kmalloc(allocation_size);
  24. if (!slot)
  25. return {};
  26. auto* new_string = new (slot) KString(length);
  27. characters = new_string->m_characters;
  28. return adopt_own(*new_string);
  29. }
  30. OwnPtr<KString> KString::try_clone() const
  31. {
  32. return try_create(view());
  33. }
  34. }