KString.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/OwnPtr.h>
  9. namespace Kernel {
  10. class KString {
  11. AK_MAKE_NONCOPYABLE(KString);
  12. AK_MAKE_NONMOVABLE(KString);
  13. public:
  14. [[nodiscard]] static OwnPtr<KString> try_create_uninitialized(size_t, char*&);
  15. [[nodiscard]] static NonnullOwnPtr<KString> must_create_uninitialized(size_t, char*&);
  16. [[nodiscard]] static OwnPtr<KString> try_create(StringView const&);
  17. [[nodiscard]] static NonnullOwnPtr<KString> must_create(StringView const&);
  18. void operator delete(void*);
  19. [[nodiscard]] OwnPtr<KString> try_clone() const;
  20. [[nodiscard]] bool is_empty() const { return m_length == 0; }
  21. [[nodiscard]] size_t length() const { return m_length; }
  22. [[nodiscard]] char const* characters() const { return m_characters; }
  23. [[nodiscard]] StringView view() const { return { characters(), length() }; }
  24. private:
  25. explicit KString(size_t length)
  26. : m_length(length)
  27. {
  28. }
  29. size_t m_length { 0 };
  30. char m_characters[0];
  31. };
  32. }
  33. namespace AK {
  34. template<>
  35. struct Formatter<Kernel::KString> : Formatter<StringView> {
  36. void format(FormatBuilder& builder, Kernel::KString const& value)
  37. {
  38. Formatter<StringView>::format(builder, value.view());
  39. }
  40. };
  41. template<>
  42. struct Formatter<OwnPtr<Kernel::KString>> : Formatter<StringView> {
  43. void format(FormatBuilder& builder, OwnPtr<Kernel::KString> const& value)
  44. {
  45. if (value)
  46. Formatter<StringView>::format(builder, value->view());
  47. else
  48. Formatter<StringView>::format(builder, "[out of memory]"sv);
  49. }
  50. };
  51. }