From 072dc9d24302fd7a92067ee1e5221cb0c29108c9 Mon Sep 17 00:00:00 2001 From: Ryan Blue Date: Thu, 21 Nov 2024 00:52:56 -0500 Subject: [PATCH] optimize FileLogger::Buffer only search the new data for newline (we know the buffer doesn't have any), and only search once --- wpiutil/src/main/native/cpp/FileLogger.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/wpiutil/src/main/native/cpp/FileLogger.cpp b/wpiutil/src/main/native/cpp/FileLogger.cpp index 70ee9f95ec3..80f89208ddd 100644 --- a/wpiutil/src/main/native/cpp/FileLogger.cpp +++ b/wpiutil/src/main/native/cpp/FileLogger.cpp @@ -29,6 +29,8 @@ FileLogger::FileLogger(std::string_view file, m_inotifyHandle{inotify_init()}, m_inotifyWatchHandle{ inotify_add_watch(m_inotifyHandle, file.data(), IN_MODIFY)}, + // capturing this is not safe here... + // also need to think harder about if synchronization is needed here m_thread{[=, this] { char buf[8000]; char eventBuf[sizeof(struct inotify_event) + NAME_MAX + 1]; @@ -87,18 +89,16 @@ FileLogger::~FileLogger() { std::function FileLogger::Buffer( std::function callback) { - return [callback, - buf = wpi::SmallVector{}](std::string_view data) mutable { - buf.append(data.begin(), data.end()); - if (!wpi::contains({data.data(), data.size()}, "\n")) { - return; + return [callback, buf = wpi::SmallVector{}]( + std::string_view newData) mutable { + size_t newlineLocation = newData.rfind("\n"); + if (newlineLocation != std::string_view::npos) { + buf.append(newData.begin(), newData.begin() + newlineLocation); + callback({buf.data(), buf.size()}); + buf.clear(); + newData = newData.substr(newlineLocation + 1); } - auto [wholeData, extra] = wpi::rsplit({buf.data(), buf.size()}, "\n"); - std::string leftover{extra}; - - callback(wholeData); - buf.clear(); - buf.append(leftover.begin(), leftover.end()); + buf.append(newData.begin(), newData.end()); }; } } // namespace wpi