From: Thomas Otto Date: Fri, 1 Nov 2019 20:58:21 +0000 (+0100) Subject: Fix and test interaction between fmt and nonstd::string_view (#481) X-Git-Tag: v4.0~717 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=fc8a7e4185439f5741ccbe50fd3e3f1381216b55;p=thirdparty%2Fccache.git Fix and test interaction between fmt and nonstd::string_view (#481) Empty string_views could not be handled and formatting did not stop until the first \0 was encountered. --- diff --git a/src/FormatNonstdStringView.hpp b/src/FormatNonstdStringView.hpp index 63f7ae1be..33814e678 100644 --- a/src/FormatNonstdStringView.hpp +++ b/src/FormatNonstdStringView.hpp @@ -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 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())); } }; diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index 42c720703..583de118f 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -17,11 +17,35 @@ // 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("") == "");