File indexing completed on 2024-04-28 05:45:10

0001 /*
0002  * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
0003  * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
0004  *
0005  * Based on the Itemviews NG project from Trolltech Labs
0006  *
0007  * SPDX-License-Identifier: GPL-2.0-or-later
0008  */
0009 
0010 #ifndef KITEMRANGE_H
0011 #define KITEMRANGE_H
0012 
0013 #include <QList>
0014 
0015 struct KItemRange {
0016     KItemRange(int index = 0, int count = 0);
0017     int index;
0018     int count;
0019 
0020     bool operator==(const KItemRange &other) const;
0021 };
0022 
0023 inline KItemRange::KItemRange(int index, int count)
0024     : index(index)
0025     , count(count)
0026 {
0027 }
0028 
0029 inline bool KItemRange::operator==(const KItemRange &other) const
0030 {
0031     return index == other.index && count == other.count;
0032 }
0033 
0034 class KItemRangeList : public QList<KItemRange>
0035 {
0036 public:
0037     KItemRangeList()
0038         : QList<KItemRange>()
0039     {
0040     }
0041     explicit KItemRangeList(const QList<KItemRange> &list)
0042         : QList<KItemRange>(list)
0043     {
0044     }
0045 
0046     template<class Container>
0047     static KItemRangeList fromSortedContainer(const Container &container);
0048 
0049     KItemRangeList &operator<<(const KItemRange &range)
0050     {
0051         append(range);
0052         return *this;
0053     }
0054 };
0055 
0056 template<class Container>
0057 KItemRangeList KItemRangeList::fromSortedContainer(const Container &container)
0058 {
0059     typename Container::const_iterator it = container.constBegin();
0060     const typename Container::const_iterator end = container.constEnd();
0061 
0062     if (it == end) {
0063         return KItemRangeList();
0064     }
0065 
0066     KItemRangeList result;
0067 
0068     int index = *it;
0069     int count = 1;
0070 
0071     // Remove duplicates, see https://bugs.kde.org/show_bug.cgi?id=335672
0072     while (it != end && *it == index) {
0073         ++it;
0074     }
0075 
0076     while (it != end) {
0077         if (*it == index + count) {
0078             ++count;
0079         } else {
0080             result << KItemRange(index, count);
0081             index = *it;
0082             count = 1;
0083         }
0084         ++it;
0085 
0086         // Remove duplicates, see https://bugs.kde.org/show_bug.cgi?id=335672
0087         while (it != end && *it == *(it - 1)) {
0088             ++it;
0089         }
0090     }
0091 
0092     result << KItemRange(index, count);
0093     return result;
0094 }
0095 
0096 #endif