From 8d40341ade21f51a0f7a111f317169aa019534cc Mon Sep 17 00:00:00 2001 From: Robbert van der Helm Date: Thu, 14 Apr 2022 18:00:11 +0200 Subject: [PATCH] Add a function for splitting search paths --- src/common/process.cpp | 24 ++++++++++++++++++++++++ src/common/process.h | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/src/common/process.cpp b/src/common/process.cpp index 54b308c8..f05b5723 100644 --- a/src/common/process.cpp +++ b/src/common/process.cpp @@ -42,6 +42,30 @@ bool pid_running(pid_t pid) { return !err || err.value() == EACCES; } +std::vector split_path( + const std::string_view& path_env) { + // C++ has these great split range adapters. That are completely usless. + std::vector search_path; + + size_t segment_begin = 0; + while (segment_begin != path_env.size()) { + const size_t segment_end = path_env.find(':', segment_begin); + if (segment_end == std::string_view::npos) { + search_path.push_back(path_env.substr( + segment_begin, path_env.size() - segment_begin)); + break; + } else { + search_path.push_back( + path_env.substr(segment_begin, segment_end - segment_begin)); + + // Restart after the colon + segment_begin = segment_end + 1; + } + } + + return search_path; +} + ProcessEnvironment::ProcessEnvironment(char** initial_env) { // We'll need to read all strings from `initial_env`. They _should_ all be // zero-terminated strings, with a null pointer to indicate the end of the diff --git a/src/common/process.h b/src/common/process.h index 922d8231..4adc3789 100644 --- a/src/common/process.h +++ b/src/common/process.h @@ -41,6 +41,12 @@ */ bool pid_running(pid_t pid); +/** + * Split a `PATH`-like environment variable on colons. These environment + * variables don't support escaping, which makes this a lot simpler. + */ +std::vector split_path(const std::string_view& path_env); + /** * Helper to create an `environ`-like environment object for passing to the * `exec*e()` family of functions.