Skip to content

Commit

Permalink
Make truncating_iterator an output_iterator (#2158)
Browse files Browse the repository at this point in the history
  • Loading branch information
randomnetcat authored Mar 4, 2021
1 parent 772aeca commit e718ec3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
12 changes: 9 additions & 3 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -469,15 +469,17 @@ template <typename OutputIt> class truncating_iterator_base {
protected:
OutputIt out_;
size_t limit_;
size_t count_;
size_t count_ = 0;

truncating_iterator_base() : out_(), limit_(0) {}

truncating_iterator_base(OutputIt out, size_t limit)
: out_(out), limit_(limit), count_(0) {}
: out_(out), limit_(limit) {}

public:
using iterator_category = std::output_iterator_tag;
using value_type = typename std::iterator_traits<OutputIt>::value_type;
using difference_type = void;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = void;
using _Unchecked_type =
Expand All @@ -502,6 +504,8 @@ class truncating_iterator<OutputIt, std::false_type>
public:
using value_type = typename truncating_iterator_base<OutputIt>::value_type;

truncating_iterator() = default;

truncating_iterator(OutputIt out, size_t limit)
: truncating_iterator_base<OutputIt>(out, limit) {}

Expand All @@ -525,6 +529,8 @@ template <typename OutputIt>
class truncating_iterator<OutputIt, std::true_type>
: public truncating_iterator_base<OutputIt> {
public:
truncating_iterator() = default;

truncating_iterator(OutputIt out, size_t limit)
: truncating_iterator_base<OutputIt>(out, limit) {}

Expand Down
20 changes: 20 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
#include <climits>
#include <cmath>
#include <cstring>
#include <iterator>
#include <list>
#include <memory>
#include <string>
#include <type_traits>

// Check if fmt/format.h compiles with windows.h included before it.
#ifdef _WIN32
Expand Down Expand Up @@ -157,6 +159,24 @@ TEST(IteratorTest, TruncatingIterator) {
EXPECT_EQ(it.base(), p + 1);
}


TEST(IteratorTest, TruncatingIteratorDefaultConstruct) {
static_assert(
std::is_default_constructible<fmt::detail::truncating_iterator<char*>>::value,
"");

fmt::detail::truncating_iterator<char*> it;
EXPECT_EQ(nullptr, it.base());
EXPECT_EQ(std::size_t{0}, it.count());
}

#ifdef __cpp_lib_ranges
TEST(IteratorTest, TruncatingIteratorOutputIterator) {
static_assert(std::output_iterator<fmt::detail::truncating_iterator<char*>,
char>);
}
#endif

TEST(IteratorTest, TruncatingBackInserter) {
std::string buffer;
auto bi = std::back_inserter(buffer);
Expand Down

0 comments on commit e718ec3

Please sign in to comment.