Browse Source

String: Add 'borrow' member to construct borrowing instances

This will allow creation of `cm::String` instances that borrow from
non-owned storage.  It is the caller's responsibility to ensure that
no copy of the instance outlives the borrowed buffer.
Brad King 7 years ago
parent
commit
9d5fe8e96a
2 changed files with 36 additions and 0 deletions
  1. 4 0
      Source/cmString.hxx
  2. 32 0
      Tests/CMakeLib/testString.cxx

+ 4 - 0
Source/cmString.hxx

@@ -272,6 +272,10 @@ public:
 
   ~String() = default;
 
+  /** Construct by borrowing an externally-owned buffer.  The buffer
+      must outlive the returned instance and all copies of it.  */
+  static String borrow(string_view v) { return String(v, Private()); }
+
   /** Assign by moving from another String instance.
       The other instance is left as a null string.  */
   String& operator=(String&& s) noexcept

+ 32 - 0
Tests/CMakeLib/testString.cxx

@@ -469,6 +469,17 @@ static bool testOperatorStdStringPlusEqual()
   return true;
 }
 
+static bool testMethod_borrow()
+{
+  std::cout << "testMethod_borrow()\n";
+  std::string s = "abc";
+  cm::String str = cm::String::borrow(s);
+  ASSERT_TRUE(str.data() == s.data());
+  ASSERT_TRUE(str.size() == s.size());
+  ASSERT_TRUE(str == s);
+  return true;
+}
+
 static bool testMethod_view()
 {
   std::cout << "testMethod_view()\n";
@@ -716,6 +727,12 @@ static bool testMethod_substr_AtEnd(cm::String str)
   return true;
 }
 
+static bool testMethod_substr_AtEndBorrowed()
+{
+  std::cout << "testMethod_substr_AtEndBorrowed()\n";
+  return testMethod_substr_AtEnd(cm::String::borrow("abc"));
+}
+
 static bool testMethod_substr_AtEndOwned()
 {
   std::cout << "testMethod_substr_AtEndOwned()\n";
@@ -764,6 +781,12 @@ static bool testMethod_substr_AtStart(cm::String str)
   return true;
 }
 
+static bool testMethod_substr_AtStartBorrowed()
+{
+  std::cout << "testMethod_substr_AtStartBorrowed()\n";
+  return testMethod_substr_AtStart(cm::String::borrow("abc"));
+}
+
 static bool testMethod_substr_AtStartOwned()
 {
   std::cout << "testMethod_substr_AtStartOwned()\n";
@@ -1132,6 +1155,9 @@ int testString(int /*unused*/, char* /*unused*/ [])
   if (!testOperatorStdStringPlusEqual()) {
     return 1;
   }
+  if (!testMethod_borrow()) {
+    return 1;
+  }
   if (!testMethod_view()) {
     return 1;
   }
@@ -1177,9 +1203,15 @@ int testString(int /*unused*/, char* /*unused*/ [])
   if (!testMethodIterators()) {
     return 1;
   }
+  if (!testMethod_substr_AtEndBorrowed()) {
+    return 1;
+  }
   if (!testMethod_substr_AtEndOwned()) {
     return 1;
   }
+  if (!testMethod_substr_AtStartBorrowed()) {
+    return 1;
+  }
   if (!testMethod_substr_AtStartOwned()) {
     return 1;
   }