Parcourir la source

[Trac901] Allow multiple replacements

Michal 'vorner' Vaner il y a 14 ans
Parent
commit
0709f8b56d
2 fichiers modifiés avec 25 ajouts et 1 suppressions
  1. 4 1
      src/lib/log/log_formatter.cc
  2. 21 0
      src/lib/log/tests/log_formatter_unittest.cc

+ 4 - 1
src/lib/log/log_formatter.cc

@@ -27,7 +27,10 @@ replacePlaceholder(string* message, const string& arg,
     string mark("%" + lexical_cast<string>(placeholder));
     size_t pos(message->find(mark));
     if (pos != string::npos) {
-        message->replace(pos, mark.size(), arg);
+        do {
+            message->replace(pos, mark.size(), arg);
+            pos = message->find(mark, pos + arg.size());
+        } while (pos != string::npos);
     } else {
         // We're missing the placeholder, so add some complain
         message->append(" @@Missing placeholder " + mark + " for '" + arg +

+ 21 - 0
src/lib/log/tests/log_formatter_unittest.cc

@@ -109,4 +109,25 @@ TEST_F(FormatterTest, missingPlace) {
               "@@Missing placeholder %1 for 'missing'@@", outputs[0].second);
 }
 
+// Can replace multiple placeholders
+TEST_F(FormatterTest, multiPlaceholder) {
+    Formatter("TEST", s("The %1 is the %1"), 1, *this).
+        arg("first rule of tautology club");
+    ASSERT_LE(1, outputs.size());
+    EXPECT_EQ(1, outputs.size());
+    EXPECT_STREQ("TEST", outputs[0].first);
+    EXPECT_EQ("The first rule of tautology club is "
+              "the first rule of tautology club", outputs[0].second);
+}
+
+// Test we can cope with replacement containing the placeholder
+TEST_F(FormatterTest, noRecurse) {
+    // If we recurse, this will probably eat all the memory and crash
+    Formatter("TEST", s("%1"), 1, *this).arg("%1 %1");
+    ASSERT_LE(1, outputs.size());
+    EXPECT_EQ(1, outputs.size());
+    EXPECT_STREQ("TEST", outputs[0].first);
+    EXPECT_EQ("%1 %1", outputs[0].second);
+}
+
 }