From 10f3b3a0837735d9f31b3355e1621a0f068a2bfd Mon Sep 17 00:00:00 2001
From: Thomas Fischer <thomas.fischer@ufz.de>
Date: Thu, 11 Jun 2020 10:31:28 +0200
Subject: [PATCH] [BL] Implement getUniqueName.

---
 BaseLib/StringTools.cpp | 15 +++++++++++++++
 BaseLib/StringTools.h   |  3 +++
 2 files changed, 18 insertions(+)

diff --git a/BaseLib/StringTools.cpp b/BaseLib/StringTools.cpp
index a881a25c0d3..0c00e867c1b 100644
--- a/BaseLib/StringTools.cpp
+++ b/BaseLib/StringTools.cpp
@@ -119,4 +119,19 @@ std::string randomString(std::size_t const length)
     return s;
 }
 
+std::string getUniqueName(std::vector<std::string> const& existing_names,
+                          std::string const& input_name)
+{
+    std::string result_name = input_name;
+    std::size_t count = 1;
+    while (std::find(existing_names.cbegin(),
+                     existing_names.cend(),
+                     result_name) != existing_names.end())
+    {
+        count++;
+        result_name = input_name + "-" + std::to_string(count);
+    }
+    return result_name;
+}
+
 }  // end namespace BaseLib
diff --git a/BaseLib/StringTools.h b/BaseLib/StringTools.h
index 23be7a0415e..dfe5487710e 100644
--- a/BaseLib/StringTools.h
+++ b/BaseLib/StringTools.h
@@ -75,4 +75,7 @@ void simplify(std::string &str);
 //! Returns a random string of the given length containing just a-z,A-Z,0-9
 std::string randomString(std::size_t length);
 
+//! Append '-' and a number such that the name is unique.
+std::string getUniqueName(std::vector<std::string> const& existing_names,
+                          std::string const& input_name);
 } // end namespace BaseLib
-- 
GitLab