summaryrefslogtreecommitdiff
path: root/AK
diff options
context:
space:
mode:
authorTim Schumacher <timschumi@gmx.de>2022-03-29 02:52:20 +0200
committerAndreas Kling <kling@serenityos.org>2022-04-03 19:15:14 +0200
commit8209c2b5707db24a8552c6ce8f361f9c49804dec (patch)
treeead2fb7fbbd75088862fa24c22ab30c56dd5a5a1 /AK
parent3237efc661a2304eef12a86c2f581a26c1c440c2 (diff)
downloadserenity-8209c2b5707db24a8552c6ce8f361f9c49804dec.zip
AK: Add `StringView::copy_characters_to_buffer()`
Diffstat (limited to 'AK')
-rw-r--r--AK/StringView.cpp12
-rw-r--r--AK/StringView.h2
2 files changed, 14 insertions, 0 deletions
diff --git a/AK/StringView.cpp b/AK/StringView.cpp
index fdcb6f4b8f..e1fd99809f 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<typename T>
Optional<T> StringView::to_int() const
{
diff --git a/AK/StringView.h b/AK/StringView.h
index 05331e0580..7bc7985802 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())