Skip to content

Commit

Permalink
Implement fmt::format_to into std::vector<char>
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <vladislav@shchapov.ru>
  • Loading branch information
phprus committed Oct 21, 2024
1 parent e9eaa27 commit b42b981
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
22 changes: 21 additions & 1 deletion include/fmt/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -1971,12 +1971,32 @@ template <typename T = char> class counting_buffer : public buffer<T> {
template <typename T>
struct is_back_insert_iterator<basic_appender<T>> : std::true_type {};

template <typename T, typename It, typename = void>
struct has_container_append : std::false_type {};
template <typename T, typename It>
struct has_container_append<T, It,
void_t<decltype(std::declval<T>().append(
std::declval<It>(), std::declval<It>()))>>
: std::true_type {};

// An optimized version of std::copy with the output value type (T).
template <typename T, typename It,
FMT_ENABLE_IF(has_container_append<T, It>::value)>
FMT_CONSTEXPR20 void copy_container_append(T& container, It begin, It end) {
container.append(begin, end);
}

template <typename T, typename It,
FMT_ENABLE_IF(!has_container_append<T, It>::value)>
FMT_CONSTEXPR20 void copy_container_append(T& container, It begin, It end) {
container.insert(container.end(), begin, end);
}

template <typename T, typename InputIt, typename OutputIt,
FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value)>
FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
-> OutputIt {
get_container(out).append(begin, end);
copy_container_append(get_container(out), begin, end);
return out;
}

Expand Down
11 changes: 8 additions & 3 deletions test/compile-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "fmt/compile.h"

#include <type_traits>
#include <vector>

#include "fmt/chrono.h"
#include "fmt/ranges.h"
Expand Down Expand Up @@ -229,10 +230,14 @@ TEST(compile_test, unknown_format_fallback) {
EXPECT_EQ(" 42 ",
fmt::format(FMT_COMPILE("{name:^4}"), fmt::arg("name", 42)));

std::vector<char> v;
fmt::format_to(std::back_inserter(v), FMT_COMPILE("{name:^4}"),
std::vector<char> v1;
fmt::format_to(std::back_inserter(v1), FMT_COMPILE("{}"), 42);
EXPECT_EQ("42", fmt::string_view(v1.data(), v1.size()));

std::vector<char> v2;
fmt::format_to(std::back_inserter(v2), FMT_COMPILE("{name:^4}"),
fmt::arg("name", 42));
EXPECT_EQ(" 42 ", fmt::string_view(v.data(), v.size()));
EXPECT_EQ(" 42 ", fmt::string_view(v2.data(), v2.size()));

char buffer[4];
auto result = fmt::format_to_n(buffer, 4, FMT_COMPILE("{name:^5}"),
Expand Down

0 comments on commit b42b981

Please sign in to comment.