1/***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2013 by Frank Reininghaus <frank78ac@googlemail.com> *
4 * *
5 * Based on the Itemviews NG project from Trolltech Labs: *
6 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
22 ***************************************************************************/
23
24#ifndef KITEMRANGE_H
25#define KITEMRANGE_H
26
27#include <QList>
28
29struct KItemRange
30{
31 KItemRange(int index = 0, int count = 0);
32 int index;
33 int count;
34
35 bool operator == (const KItemRange& other) const;
36};
37
38inline KItemRange::KItemRange(int index, int count) :
39 index(index),
40 count(count)
41{
42}
43
44inline bool KItemRange::operator == (const KItemRange& other) const
45{
46 return index == other.index && count == other.count;
47}
48
49
50class KItemRangeList : public QList<KItemRange>
51{
52public:
53 KItemRangeList() : QList<KItemRange>() {}
54 KItemRangeList(const QList<KItemRange>& list) : QList<KItemRange>(list) {}
55
56 template<class Container>
57 static KItemRangeList fromSortedContainer(const Container& container);
58
59 KItemRangeList& operator<<(const KItemRange& range)
60 {
61 append(range);
62 return *this;
63 }
64};
65
66template<class Container>
67KItemRangeList KItemRangeList::fromSortedContainer(const Container& container)
68{
69 typename Container::const_iterator it = container.constBegin();
70 const typename Container::const_iterator end = container.constEnd();
71
72 if (it == end) {
73 return KItemRangeList();
74 }
75
76 KItemRangeList result;
77
78 int index = *it;
79 int count = 1;
80
81 // Remove duplicates, see https://bugs.kde.org/show_bug.cgi?id=335672
82 while (it != end && *it == index) {
83 ++it;
84 }
85
86 while (it != end) {
87 if (*it == index + count) {
88 ++count;
89 } else {
90 result << KItemRange(index, count);
91 index = *it;
92 count = 1;
93 }
94 ++it;
95
96 // Remove duplicates, see https://bugs.kde.org/show_bug.cgi?id=335672
97 while (it != end && *it == *(it - 1)) {
98 ++it;
99 }
100 }
101
102 result << KItemRange(index, count);
103 return result;
104}
105
106#endif
107