]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add from_owned_cstr/from_cstr functions
authorThomas Otto <thomas.otto@pdv-fs.de>
Sun, 19 Jan 2020 16:49:19 +0000 (17:49 +0100)
committerThomas Otto <thomas.otto@pdv-fs.de>
Sun, 26 Jan 2020 19:25:10 +0000 (20:25 +0100)
src/legacy_util.cpp
src/legacy_util.hpp
unittest/test_legacy_util.cpp

index b767ad84eb3e1e8fe687d46764628b2fcff7adc5..9ff9c835745ba3db9a5ccf29abab3ef575a59a75 100644 (file)
@@ -1543,3 +1543,20 @@ time_seconds(void)
   return (double)time(NULL);
 #endif
 }
+
+std::string
+from_owned_cstr(char* str)
+{
+  std::string result;
+  if (str) {
+    result = str;
+    free(str);
+  }
+  return result;
+}
+
+std::string
+from_cstr(const char* str)
+{
+  return str ? str : std::string{};
+}
index d6069b3876837dfdd91069f4f5d8b14b1b65ed6d..37e909fbc2f6eb04a5202f19e533e7b72dfa803f 100644 (file)
@@ -20,6 +20,8 @@
 
 #include "system.hpp"
 
+#include <string>
+
 void cc_log(const char* format, ...) ATTR_FORMAT(printf, 1, 2);
 void cc_bulklog(const char* format, ...) ATTR_FORMAT(printf, 1, 2);
 void cc_log_argv(const char* prefix, char** argv);
@@ -78,3 +80,9 @@ char* read_text_file(const char* path, size_t size_hint);
 char* subst_env_in_string(const char* str, char** errmsg);
 void set_cloexec_flag(int fd);
 double time_seconds();
+
+// Convert an owned char* string `str` to an std::string and free `str`.
+std::string from_owned_cstr(char* str);
+
+// Convert a char* string `str` to an std::string, if `str` is NULL return "".
+std::string from_cstr(const char* str);
index d46117e35776762a085fd8228067e2c804fc9f67..c79f475d2e2a428baa70a8e1724f3c5408e6cdfe 100644 (file)
@@ -194,4 +194,42 @@ TEST(format_hex)
   CHECK_STR_EQ("00010203", result);
 }
 
+TEST(from_cstr)
+{
+  char* cstr1 = x_strdup("foo");
+  const char* cstr2 = "bar";
+  const char* cstr3 = nullptr;
+  const char* cstr4 = "";
+
+  std::string str1 = from_cstr(cstr1);
+  std::string str2 = from_cstr(cstr2);
+  std::string str3 = from_cstr(cstr3);
+  std::string str4 = from_cstr(cstr4);
+
+  CHECK(str1 == "foo");
+  CHECK(str2 == "bar");
+  CHECK(str3 == "");
+  CHECK(str4 == "");
+
+  free(cstr1);
+}
+
+TEST(from_owned_cstr)
+{
+  char* cstr1 = x_strdup("foo");
+  char* cstr2 = x_strdup("bar");
+  char* cstr3 = nullptr;
+  char* cstr4 = x_strdup("");
+
+  std::string str1 = from_owned_cstr(cstr1);
+  std::string str2 = from_owned_cstr(cstr2);
+  std::string str3 = from_owned_cstr(cstr3);
+  std::string str4 = from_owned_cstr(cstr4);
+
+  CHECK(str1 == "foo");
+  CHECK(str2 == "bar");
+  CHECK(str3 == "");
+  CHECK(str4 == "");
+}
+
 TEST_SUITE_END