From 2fe8f689fd500874e9dc2d49dc976797de1db7be Mon Sep 17 00:00:00 2001 From: Thomas Otto Date: Wed, 30 Oct 2019 11:21:00 +0100 Subject: [PATCH] Add and test get_extension() Works as a replacement for the legacy util function. --- src/Util.cpp | 24 +++++++++++++++++++++++- src/Util.hpp | 4 ++++ unittest/test_Util.cpp | 15 +++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/Util.cpp b/src/Util.cpp index 42ba9d23c..e9f0b57d4 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -24,6 +24,8 @@ #include #include +using nonstd::string_view; + namespace { void @@ -40,7 +42,7 @@ get_cache_files_internal(const std::string& dir, std::vector directories; dirent* de; while ((de = readdir(d))) { - nonstd::string_view name(de->d_name); + string_view name(de->d_name); if (name == "" || name == "." || name == ".." || name == "CACHEDIR.TAG" || name == "stats" || name.starts_with(".nfs")) { continue; @@ -139,6 +141,26 @@ dir_name(nonstd::string_view path) return n == 0 ? "/" : path.substr(0, n); } +nonstd::string_view +get_extension(nonstd::string_view path) +{ +#ifndef _WIN32 + const char stop_at_chars[] = "./"; +#else + const char stop_at_chars[] = "./\\"; +#endif + size_t pos = path.find_last_of(stop_at_chars); + if (pos == string_view::npos || path.at(pos) == '/') { + return string_view(); +#ifdef _WIN32 + } else if (path.at(pos) == '\\') { + return string_view(); +#endif + } else { + return path.substr(pos); + } +} + nonstd::string_view get_truncated_base_name(nonstd::string_view path, size_t max_length) { diff --git a/src/Util.hpp b/src/Util.hpp index f8876343a..f86c7c1de 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -41,6 +41,10 @@ typedef std::function