consecutive_range_visitor.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_
  5. #define COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_
  6. #include <stddef.h>
  7. #include <iterator>
  8. namespace courgette {
  9. // Usage note: First check whether std::unique() would suffice.
  10. //
  11. // ConsecutiveRangeVisitor is a visitor to read equal consecutive items
  12. // ("ranges") between two iterators. The base value of InputIterator must
  13. // implement the == operator.
  14. //
  15. // Example: "AAAAABZZZZOO" consists of ranges ["AAAAA", "B", "ZZZZ", "OO"]. The
  16. // visitor provides accessors to iterate through the ranges, and to access each
  17. // range's value and repeat, i.e., [('A', 5), ('B', 1), ('Z', 4), ('O', 2)].
  18. template <class InputIterator>
  19. class ConsecutiveRangeVisitor {
  20. public:
  21. ConsecutiveRangeVisitor(InputIterator begin, InputIterator end)
  22. : head_(begin), end_(end) {
  23. advance();
  24. }
  25. ConsecutiveRangeVisitor(const ConsecutiveRangeVisitor&) = delete;
  26. ConsecutiveRangeVisitor& operator=(const ConsecutiveRangeVisitor&) = delete;
  27. // Returns whether there are more ranges to traverse.
  28. bool has_more() const { return tail_ != end_; }
  29. // Returns an iterator to an element in the current range.
  30. InputIterator cur() const { return tail_; }
  31. // Returns the number of repeated elements in the current range.
  32. size_t repeat() const { return std::distance(tail_, head_); }
  33. // Advances to the next range.
  34. void advance() {
  35. tail_ = head_;
  36. if (head_ != end_)
  37. while (++head_ != end_ && *head_ == *tail_) {}
  38. }
  39. private:
  40. InputIterator tail_; // The trailing pionter of a range (inclusive).
  41. InputIterator head_; // The leading pointer of a range (exclusive).
  42. InputIterator end_; // Store the end pointer so we know when to stop.
  43. };
  44. } // namespace courgette
  45. #endif // COURGETTE_CONSECUTIVE_RANGE_VISITOR_H_