From f93b3b78068b7f5b5554d6d948b1a332b66d1765 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 7 Apr 2019 20:19:16 +0200 Subject: [PATCH] AK: Improve StringImpl chomping a bit. Chomp off any number of trailing [\0\n\r] characters and trim the allocation to fit instead of keeping the original size. --- AK/StringImpl.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/AK/StringImpl.cpp b/AK/StringImpl.cpp index eead6a3ea79..5b8e6c742f6 100644 --- a/AK/StringImpl.cpp +++ b/AK/StringImpl.cpp @@ -66,7 +66,7 @@ Retained StringImpl::create_uninitialized(ssize_t length, char*& buf return new_stringimpl; } -RetainPtr StringImpl::create(const char* cstring, ssize_t length, ShouldChomp shouldChomp) +RetainPtr StringImpl::create(const char* cstring, ssize_t length, ShouldChomp should_chomp) { if (!cstring) return nullptr; @@ -74,6 +74,16 @@ RetainPtr StringImpl::create(const char* cstring, ssize_t length, Sh if (!*cstring) return the_empty_stringimpl(); + if (should_chomp) { + while (length) { + char last_ch = cstring[length - 1]; + if (!last_ch || last_ch == '\n' || last_ch == '\r') + --length; + else + break; + } + } + if (!length) return the_empty_stringimpl(); @@ -81,11 +91,6 @@ RetainPtr StringImpl::create(const char* cstring, ssize_t length, Sh auto new_stringimpl = create_uninitialized(length, buffer); memcpy(buffer, cstring, length * sizeof(char)); - if (shouldChomp && buffer[length - 1] == '\n') { - buffer[length - 1] = '\0'; - --new_stringimpl->m_length; - } - return new_stringimpl; }