diff dmutil.cpp @ 19:a329f0216491

Implement PLY file format parsing and extremely simplistic scene setup file format. Not finished yet.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 07 Nov 2019 20:15:33 +0200
parents
children 1404dfcee7b8
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/dmutil.cpp	Thu Nov 07 20:15:33 2019 +0200
@@ -0,0 +1,109 @@
+//
+//
+//
+#include "dmutil.h"
+#include <fstream>
+
+
+std::string dmStrLTrim(const std::string& str, const std::string& delim)
+{
+    return str.substr(str.find_first_not_of(delim));
+}
+
+
+std::string dmStrRTrim(const std::string& str, const std::string& delim)
+{
+    return str.substr(0, str.find_last_not_of(delim));
+}
+
+
+std::string dmStrTrim(const std::string& str, const std::string& delim)
+{
+    if (str.empty())
+        return str;
+
+    size_t start = str.find_first_not_of(delim);
+    return str.substr(start, str.find_last_not_of(delim) - start + 1);
+}
+
+
+std::vector<std::string> dmStrSplit(const std::string& str, const std::string& delim)
+{
+    std::vector<std::string> result;
+    size_t oldpos = 0, newpos;
+
+    do
+    {
+        newpos = str.find_first_of(delim, oldpos);
+        std::string tmp = dmStrTrim(str.substr(oldpos, newpos - oldpos));
+
+        if (!tmp.empty())
+            result.push_back(tmp);
+
+        oldpos = newpos + 1;
+    } while (newpos != std::string::npos);
+
+    return result;
+}
+
+
+std::string dmStrJoin(const std::vector<std::string> &list, const std::string &delim)
+{
+    switch (list.size())
+    {
+        case 0:
+            return "";
+
+        case 1:
+            return list[0];
+
+        default:
+            std::string result;
+            bool first = true;
+            for (const auto &elem : list)
+            {
+                if (!first)
+                    result += delim;
+                else
+                    first = false;
+                result += elem;
+            }
+            return result;
+    }
+}
+
+
+bool dmReadText(const std::string &filename, std::string &buf, const int maxSize)
+{
+    std::ifstream in(filename.c_str(), std::fstream::in);
+
+    if (!in.is_open())
+    {
+        printf("ERROR: Unable to open file '%s'.\n",
+            filename.c_str());
+        return false;
+    }
+
+    in.seekg(0, std::ios::end);
+
+    if (in.tellg() > maxSize)
+    {
+        printf("ERROR: File '%s' is too large.\n",
+            filename.c_str());
+        return false;
+    }
+
+    buf.reserve(in.tellg());
+    in.seekg(0, std::ios::beg);
+
+    buf.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
+
+    return true;
+}
+
+
+bool dmFileExists(const std::string &filename, std::ios_base::openmode mode)
+{
+    std::ifstream infile(filename.c_str(), mode);
+    return infile.good();
+}