]> git.lizzy.rs Git - minetest.git/blobdiff - src/util/string.h
Modernize source code: last part (#6285)
[minetest.git] / src / util / string.h
index 572c371502c5965167c764d3110cd72488034b2d..122262af85348d227c10ba94c3fd5fb902df9f89 100644 (file)
@@ -17,12 +17,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
 
-#ifndef UTIL_STRING_HEADER
-#define UTIL_STRING_HEADER
+#pragma once
 
 #include "irrlichttypes_bloated.h"
-#include "cpp11_container.h"
-#include <stdlib.h>
+#include <cstdlib>
 #include <string>
 #include <cstring>
 #include <vector>
@@ -30,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include <sstream>
 #include <iomanip>
 #include <cctype>
+#include <unordered_map>
 
 #define STRINGIFY(x) #x
 #define TOSTRING(x) STRINGIFY(x)
@@ -55,7 +54,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
        (((unsigned char)(x) < 0xe0) ? 2 :     \
        (((unsigned char)(x) < 0xf0) ? 3 : 4))
 
-typedef UNORDERED_MAP<std::string, std::string> StringMap;
+typedef std::unordered_map<std::string, std::string> StringMap;
 
 struct FlagDesc {
        const char *name;
@@ -236,8 +235,8 @@ inline std::string lowercase(const std::string &str)
 
        s2.reserve(str.size());
 
-       for (size_t i = 0; i < str.size(); i++)
-               s2 += tolower(str[i]);
+       for (char i : str)
+               s2 += tolower(i);
 
        return s2;
 }
@@ -422,6 +421,18 @@ inline void str_replace(std::string &str, const std::string &pattern,
        }
 }
 
+/**
+ * Escapes characters [ ] \ , ; that can not be used in formspecs
+ */
+inline void str_formspec_escape(std::string &str)
+{
+       str_replace(str, "\\", "\\\\");
+       str_replace(str, "]", "\\]");
+       str_replace(str, "[", "\\[");
+       str_replace(str, ";", "\\;");
+       str_replace(str, ",", "\\,");
+}
+
 /**
  * Replace all occurrences of the character \p from in \p str with \p to.
  *
@@ -596,8 +607,8 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
  */
 inline bool is_number(const std::string &to_check)
 {
-       for (size_t i = 0; i < to_check.size(); i++)
-               if (!std::isdigit(to_check[i]))
+       for (char i : to_check)
+               if (!std::isdigit(i))
                        return false;
 
        return !to_check.empty();
@@ -614,4 +625,25 @@ inline const char *bool_to_cstr(bool val)
        return val ? "true" : "false";
 }
 
-#endif
+inline const std::string duration_to_string(int sec)
+{
+       int min = sec / 60;
+       sec %= 60;
+       int hour = min / 60;
+       min %= 60;
+
+       std::stringstream ss;
+       if (hour > 0) {
+               ss << hour << "h ";
+       }
+
+       if (min > 0) {
+               ss << min << "m ";
+       }
+
+       if (sec > 0) {
+               ss << sec << "s ";
+       }
+
+       return ss.str();
+}