Skip to content

Commit

Permalink
add a retrieveAllMatches function as a multi result optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
noah1510 committed Dec 15, 2023
1 parent 03fc1ee commit 8b0b7ea
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions include/rs232.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,21 @@ namespace sakurajin {
[[nodiscard]] [[maybe_unused]]
std::string retrieveFirstMatch(const std::regex& pattern);

/**
* @brief load the read buffer and return all matches with a regex
* This does essentially the same as retrieveFirstMatch but returns all matches instead of just the first one.
* If care about more than one result use this function since it is more efficient than calling retrieveFirstMatch multiple
* times. If no match is found or no data is in the read buffer, an empty vector is returned.
* @note this function clears the read buffer until the end of the last match.
* @note The read buffer is not updated during this function call. If the read buffer is large and many pattern matches are
* found this function might take a long time to complete. During this time more data might be queued for adding to the
* read buffer. This data will not be considered by this function.
* @param pattern the regex pattern that should be used
* @return std::vector<std::string> all matches of the read buffer
*/
[[nodiscard]] [[maybe_unused]]
std::vector<std::string> retrieveAllMatches(const std::regex& pattern);

/**
* @brief print a string to the currently connected device
* This function adds the string to the write buffer and then returns.
Expand Down
22 changes: 22 additions & 0 deletions src/rs232.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,28 @@ std::string sakurajin::RS232::retrieveFirstMatch(const std::regex& pattern) {
return s_match_result.str();
}

std::vector<std::string> sakurajin::RS232::retrieveAllMatches(const std::regex& pattern) {
if (!readBufferHasData) {
return std::vector<std::string>{};
}

std::scoped_lock lock(readBufferMutex);

std::string searchString = readBuffer;
std::smatch curr_match;
std::vector<std::string> matches{};

std::regex_search(searchString, curr_match, pattern);
while(!curr_match.empty()){
matches.emplace_back(curr_match.str());
searchString = curr_match.suffix();
std::regex_search(searchString, curr_match, pattern);
}

readBuffer = searchString;
return matches;
}

// device access functions
std::shared_ptr<sakurajin::RS232_native> sakurajin::RS232::getNativeDevice(size_t index) const {
if (rs232Devices.empty()) {
Expand Down

0 comments on commit 8b0b7ea

Please sign in to comment.