]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Fix and test interaction between fmt and nonstd::string_view (#481)
authorThomas Otto <thomas.otto@pdv-fs.de>
Fri, 1 Nov 2019 20:58:21 +0000 (21:58 +0100)
committerJoel Rosdahl <joel@rosdahl.net>
Fri, 1 Nov 2019 20:58:21 +0000 (21:58 +0100)
Empty string_views could not be handled and formatting
did not stop until the first \0 was encountered.

src/FormatNonstdStringView.hpp
unittest/test_Util.cpp

index 63f7ae1bedea0910e241a02918db1f191ba9ee9d..33814e678deefd720b9312fc9c893545379ce352 100644 (file)
@@ -18,6 +18,9 @@
 
 #pragma once
 
+#include "third_party/nonstd/string_view.hpp"
+
+
 // Specialization of fmt::formatter for nonstd::string_view.
 namespace fmt {
 
@@ -35,7 +38,7 @@ template<> struct formatter<nonstd::string_view>
   format(const nonstd::string_view& sv, FormatContext& ctx)
     -> decltype(ctx.out())
   {
-    return format_to(ctx.out(), "{:{}}", sv.data(), sv.length());
+    return format_to(ctx.out(), "{}", fmt::string_view(sv.data(), sv.size()));
   }
 };
 
index 42c7207037952758c79e7ddef19c8b15c191af1a..583de118fceb393f8decede06c67dc8dad9cea9e 100644 (file)
 // Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
 #include "../src/Util.hpp"
+#include "FormatNonstdStringView.hpp"
 
 #include "third_party/catch.hpp"
 
 using Catch::Equals;
 
+TEST_CASE("fmt::format and nonstd::string_view")
+{
+  nonstd::string_view null;
+  CHECK(fmt::format("{}", null) == "");
+
+  const std::string s = "0123456789";
+
+  nonstd::string_view empty(s.data(), 0);
+  CHECK(fmt::format("{}", empty) == "");
+
+  nonstd::string_view empty_end(s.data() + s.length(), 0);
+  CHECK(fmt::format("{}", empty_end) == "");
+
+  nonstd::string_view start(s.data(), 2);
+  CHECK(fmt::format("{}", start) == "01");
+
+  nonstd::string_view middle(s.data() + 3, 4);
+  CHECK(fmt::format("{}", middle) == "3456");
+
+  nonstd::string_view end(s.data() + s.length() - 2, 2);
+  CHECK(fmt::format("{}", end) == "89");
+}
+
 TEST_CASE("Util::base_name")
 {
   CHECK(Util::base_name("") == "");