From 4c559f50a4b7009d7ddb862f6553b399a5b0dfb4 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Tue, 20 Dec 2022 11:37:28 +0200 Subject: [PATCH] BAN: StringView::Split() now precomputes number of elements We dont have to resize vector on PushBack()'s if we reserve required size --- BAN/BAN/StringView.cpp | 20 +++++++++++++++++++- BAN/include/BAN/Errors.h | 1 + BAN/include/BAN/StringView.h | 2 +- kernel/kernel/Shell.cpp | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/BAN/BAN/StringView.cpp b/BAN/BAN/StringView.cpp index 2881d2e9b..760933319 100644 --- a/BAN/BAN/StringView.cpp +++ b/BAN/BAN/StringView.cpp @@ -62,9 +62,27 @@ namespace BAN return result; } - Vector StringView::Split(char delim, bool allow_empties) + ErrorOr> StringView::Split(char delim, bool allow_empties) { + size_type count = 0; + { + size_type start = 0; + for (size_type i = 0; i < m_size; i++) + { + if (m_data[i] == delim) + { + if (allow_empties || start != i) + count++; + start = i + 1; + } + } + if (start != m_size) + count++; + } + Vector result; + TRY(result.Reserve(count)); + size_type start = 0; for (size_type i = 0; i < m_size; i++) { diff --git a/BAN/include/BAN/Errors.h b/BAN/include/BAN/Errors.h index 6ed44afa9..bc89e3bc9 100644 --- a/BAN/include/BAN/Errors.h +++ b/BAN/include/BAN/Errors.h @@ -40,6 +40,7 @@ class ErrorOr public: ErrorOr(const T& value) : m_has_error(false) { m_data = (void*)new T(value); } ErrorOr(const Error& error) : m_has_error(true) { m_data = (void*)new Error(error); } + template ErrorOr(const ErrorOr& other) : ErrorOr(other.GetError()) {} ~ErrorOr() { IsError() ? (delete reinterpret_cast(m_data)) : (delete reinterpret_cast(m_data)); } bool IsError() const { return m_has_error; } diff --git a/BAN/include/BAN/StringView.h b/BAN/include/BAN/StringView.h index 0bc531a56..3db5c8e2f 100644 --- a/BAN/include/BAN/StringView.h +++ b/BAN/include/BAN/StringView.h @@ -24,7 +24,7 @@ namespace BAN StringView Substring(size_type, size_type = -1) const; - Vector Split(char, bool = false); + ErrorOr> Split(char, bool = false); size_type Count(char) const; diff --git a/kernel/kernel/Shell.cpp b/kernel/kernel/Shell.cpp index b79902765..b6978314f 100644 --- a/kernel/kernel/Shell.cpp +++ b/kernel/kernel/Shell.cpp @@ -228,7 +228,7 @@ namespace Kernel case Keyboard::Key::NumpadEnter: { kprint("\n"); - ProcessCommand(m_buffer.SV().Split(' ')); + ProcessCommand(MUST(m_buffer.SV().Split(' '))); m_buffer.Clear(); PrintPrompt(); break;