From 8209c2b5707db24a8552c6ce8f361f9c49804dec Mon Sep 17 00:00:00 2001 From: Tim Schumacher Date: Tue, 29 Mar 2022 02:52:20 +0200 Subject: [PATCH] AK: Add `StringView::copy_characters_to_buffer()` --- AK/StringView.cpp | 12 ++++++++++++ AK/StringView.h | 2 ++ 2 files changed, 14 insertions(+) diff --git a/AK/StringView.cpp b/AK/StringView.cpp index fdcb6f4b8ff..e1fd99809f5 100644 --- a/AK/StringView.cpp +++ b/AK/StringView.cpp @@ -182,6 +182,18 @@ StringView StringView::substring_view_starting_after_substring(StringView substr return { remaining_characters, remaining_length }; } +bool StringView::copy_characters_to_buffer(char* buffer, size_t buffer_size) const +{ + // We must fit at least the NUL-terminator. + VERIFY(buffer_size > 0); + + size_t characters_to_copy = min(m_length, buffer_size - 1); + __builtin_memcpy(buffer, m_characters, characters_to_copy); + buffer[characters_to_copy] = 0; + + return characters_to_copy == m_length; +} + template Optional StringView::to_int() const { diff --git a/AK/StringView.h b/AK/StringView.h index 05331e05804..7bc7985802b 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -192,6 +192,8 @@ public: [[nodiscard]] StringView substring_view_starting_from_substring(StringView substring) const; [[nodiscard]] StringView substring_view_starting_after_substring(StringView substring) const; + [[nodiscard]] bool copy_characters_to_buffer(char* buffer, size_t buffer_size) const; + constexpr bool operator==(char const* cstring) const { if (is_null())