From 178eb1dd8434a359de7797a288b7eb9a8869deb7 Mon Sep 17 00:00:00 2001 From: wmayer Date: Sat, 31 Dec 2022 00:18:59 +0100 Subject: [PATCH] Base: fix and refactor Tools::getUniqueName --- src/Base/Tools.cpp | 85 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 63 insertions(+), 22 deletions(-) diff --git a/src/Base/Tools.cpp b/src/Base/Tools.cpp index 0f65a86a0f..32a02708fb 100644 --- a/src/Base/Tools.cpp +++ b/src/Base/Tools.cpp @@ -68,35 +68,76 @@ struct string_comp return n; } }; + +class unique_name +{ +public: + unique_name(const std::string& name, const std::vector& names, int padding) + : base_name{name} + , padding{padding} + { + removeDigitsFromEnd(); + findHighestSuffix(names); + } + + std::string get() const + { + return appendSuffix(); + } + +private: + void removeDigitsFromEnd() + { + std::string::size_type pos = base_name.find_last_not_of("0123456789"); + if (pos != std::string::npos && (pos +1) < base_name.size()) { + num_suffix = base_name.substr(pos + 1); + base_name.erase(pos + 1); + } + } + + void findHighestSuffix(const std::vector& names) + { + for (std::vector::const_iterator it = names.begin(); it != names.end(); ++it) { + if (it->substr(0, base_name.length()) == base_name) { // same prefix + std::string suffix(it->substr(base_name.length())); + if (suffix.size() > 0) { + std::string::size_type pos = suffix.find_first_not_of("0123456789"); + if (pos == std::string::npos) { + num_suffix = std::max(num_suffix, suffix, Base::string_comp()); + } + } + } + } + } + + std::string appendSuffix() const + { + std::stringstream str; + str << base_name; + if (padding > 0) { + str.fill('0'); + str.width(padding); + } + str << Base::string_comp::increment(num_suffix); + return str.str(); + } + +private: + std::string num_suffix; + std::string base_name; + int padding; +}; + } -std::string Base::Tools::getUniqueName(const std::string& name, const std::vector& names, int d) +std::string Base::Tools::getUniqueName(const std::string& name, const std::vector& names, int pad) { if (names.empty()) { return name; } - // find highest suffix - std::string num_suffix; - for (std::vector::const_iterator it = names.begin(); it != names.end(); ++it) { - if (it->substr(0, name.length()) == name) { // same prefix - std::string suffix(it->substr(name.length())); - if (suffix.size() > 0) { - std::string::size_type pos = suffix.find_first_not_of("0123456789"); - if (pos==std::string::npos) - num_suffix = std::max(num_suffix, suffix, Base::string_comp()); - } - } - } - - std::stringstream str; - str << name; - if (d > 0) { - str.fill('0'); - str.width(d); - } - str << Base::string_comp::increment(num_suffix); - return str.str(); + Base::unique_name unique(name, names, pad); + return unique.get(); } std::string Base::Tools::addNumber(const std::string& name, unsigned int num, int d)