googletest icon indicating copy to clipboard operation
googletest copied to clipboard

Improve support for printing std::basic_string_view

Open XAMeLeOH opened this issue 1 year ago • 0 comments
trafficstars

Extend printing capabilities for std::basic_string_view

What is std::basic_string_view?

std::basic_string_view (spec) is a relatively new (since C++17) form of manipulating string objects in C++.

The language also provides a suffix for it, so the following line will create and initiate a new std::string_view (synonym for std::basic_string_view<char>) object:

const auto str_view = "hello world"sv;

Does GTest support it?

Currently, GTest has some means of outputting these objects. It will be handled by the ContainerPrinter with one exception.

It will look a bit ugly though. Printing L"w"sv will produce { L'w' (119, 0x77) }.

Exception

GTest declares its own StringView which depending on the build parameters will be either absl::string_view or std::string_view.

Besides that GTest implements printing capability for that StringView type. Unfortunately, in the best case scenario it covers only one of the subtypes of the std::basic_string_view family. That is why in the #4295 author mentioned that the issue appears only for non-char basic_string_view's.

Solution

To improve the way std::basic_string_view is printed, PrintTo function was overloaded with all the available subtypes of the std::basic_string_view (just the way it's done for the std::basic_string):

  • std::string_view
  • std::u8string_view
  • std::u16string_view
  • std::u32string_view
  • std::wstring_view

This should fix #4295.

Notes

  • std::string_view will be added only in case the language level supports it and GTest is built with absl::string_view. Otherwise it skips the implementation, because it should be already done for internal::StringView type.
  • std::u8string_view is implemented only when the flag __cpp_lib_char8_t is defined.
  • std::wstring_view is implemented if the flag GTEST_HAS_STD_WSTRING is defined.

I followed the way it's done for similar std::basic_string<T> types, but I'd like to ask to double check it.

Tests

I added a few tests too.

If more needed, please let me know.

XAMeLeOH avatar Oct 03 '24 16:10 XAMeLeOH