Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions include/iris/string_algo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,49 @@ template<int = 0>
}


// Truncates the tail of the string to `max_length` while replacing the tail with
// `ellipsis` iff `input.size()` exceeded `max_length`.
template<class CharT, class TraitsT>
constexpr void abbreviate(
std::basic_string<CharT, TraitsT>& input,
std::size_t const max_length,
std::type_identity_t<std::basic_string_view<CharT, TraitsT>> ellipsis
)
{
if (max_length < ellipsis.size()) {
throw std::length_error{"ellipsis' length is longer than max_length"};
}

if (input.size() > max_length) {
input.replace(max_length - ellipsis.size(), std::basic_string<CharT, TraitsT>::npos, ellipsis);
}
}

template<int = 0>
constexpr std::string abbreviate_copy(
std::string_view input,
std::size_t const max_length,
std::string_view ellipsis
)
{
std::string buf(input);
iris::abbreviate(buf, max_length, ellipsis);
return buf;
}

template<int = 0>
constexpr std::u32string abbreviate_copy(
std::u32string_view input,
std::size_t const max_length,
std::u32string_view ellipsis
)
{
std::u32string buf(input);
iris::abbreviate(buf, max_length, ellipsis);
return buf;
}


namespace detail {

// Closed range [first, last] of character set
Expand Down
25 changes: 25 additions & 0 deletions test/string_algo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,31 @@ TEST_CASE("string_algo: escape")
#undef IRIS_TEST_ESCAPE
}


TEST_CASE("string_algo: abbreviate")
{
#ifdef _MSC_VER
SetConsoleOutputCP(CP_UTF8);
#endif

{
std::string str;
iris::abbreviate(str, 3, "...");
CHECK(str == ""sv);
}

CHECK_THROWS_AS(iris::abbreviate_copy("", 2, "..."), std::length_error);
CHECK_THROWS_AS(iris::abbreviate_copy("aaaaaa", 2, "..."), std::length_error);

CHECK(iris::abbreviate_copy("fo", 3, "...") == "fo"sv);
CHECK(iris::abbreviate_copy("foo", 3, "...") == "foo"sv);
CHECK(iris::abbreviate_copy("foob", 3, "...") == "..."sv);

CHECK(iris::abbreviate_copy("foo", 4, "...") == "foo"sv);
CHECK(iris::abbreviate_copy("foob", 4, "...") == "foob"sv);
CHECK(iris::abbreviate_copy("fooba", 4, "...") == "f..."sv);
}

TEST_CASE("string_algo: ordinary_normalize")
{
#ifdef _MSC_VER
Expand Down
Loading