Debian Codegraph @

src/Base/UniqueNameManager.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2024 Kevin Martin <[email protected]> *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 ***************************************************************************/
23
24
25 #ifndef SRC_BASE_UNIQUENAMEMANAGER_H_
26 #define SRC_BASE_UNIQUENAMEMANAGER_H_
27
28 #ifndef FC_GLOBAL_H
29 # include <FCGlobal.h>
30 #endif
31 #include <vector>
32 #include <string>
33 #include <set>
34 #include <map>
35 #include <utility> // Forward declares std::tuple
36 #include <stdexcept>
37 #include <algorithm>
38 #include <tuple>
39 #include "UnlimitedUnsigned.h"
40
41 // ----------------------------------------------------------------------------
42
43 namespace Base
44 {
45 /// @brief
46 /// This class acts as a multiset of strings with the capability of generating
47 /// other names that are not in the collection. Unique names are generated
48 /// by inserting digits into a base name. Normally these are appended to the
49 /// base name, but a derived class can override getNameSuffixStartPosition
50 /// to place the digits elsewhere in the base name.
51 // This class does not support copy-/move-construction
52 // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
53 class BaseExport UniqueNameManager
54 {
55 protected:
56 // This method returns a reverse const iterator on name that references the position
57 // of the start of the suffix (or name.crbegin() if no suffix).
58 // It must return the same suffix length (name.crbegin() - returnValue) for both
59 // unique names (one containing digits) and the corresponding base name (with no digits).
60 virtual std::string::const_reverse_iterator getNameSuffixStartPosition(const std::string& name) const
61 {
62 return name.crbegin();
63 }
64
65 private:
66 template<typename IT>
67 class PiecewiseSparseIntegerSet
68 {
69 public:
70 PiecewiseSparseIntegerSet() = default;
71
72 private:
73 // Each pair being <lowest, count> represents the span of integers from lowest to
74 // (lowest+count-1) inclusive
75 using SpanType = std::pair<IT, IT>;
76 // This span Comparer class is analogous to std::less and treats overlapping spans as being
77 // neither greater nor less than each other
78 class Comparer
79 {
80 public:
81 bool operator()(SpanType lhs, SpanType rhs) const
82 {
83 // The equality case here is when lhs is below and directly adjacent to rhs.
84 return lhs.second + lhs.first <= rhs.first;
85 }
86 };
87 // spans is the set of spans. Adjacent spans are coalesced so there are always gaps between
88 // the entries.
89 std::set<SpanType, Comparer> spans;
90 using SpanSetIterator = typename std::set<SpanType, Comparer>::iterator;
91
92 public:
93 void add(IT value)
94 {
95 SpanType newSpan(value, 1);
96 // Look for the smallest entry not less than newSpan.
97 // Bear in mind that overlapping spans are neither less than nor greater than ech other.
98 auto above = spans.lower_bound(newSpan);
99 if (above != spans.end() && above->first <= value) {
100 // A span was found that includes value so there is nothing to do as it is already
101 // in the set.
102 return;
103 }
104
105 // Set below to the next span below 'after', if any, otherwise to spans.end().
106 // Logically, we want spans.begin()-1 so 'below' is always the entry before 'after',
107 // but that is not an allowed reference so spans.end() is used
108 SpanSetIterator below;
109 if (above == spans.begin()) {
110 // No spans are less than newSpan
111 // (possibly spans is empty, in which case above == spans.end() too)
112 below = spans.end();
113 }
114 else {
115 // At least one span is less than newSpan,
116 // and 'above' is the next span above that
117 // (or above == spans.end() if all spans are below newSpan)
118 below = above;
119 --below;
120 }
121
122 // Determine whether the span above (if any) and/or the span below (if any)
123 // are adjacent to newSpan and if so, merge them appropriately and remove the
124 // original span(s) that was/were merged, updating newSpan to be the new merged
125 // span.
126 if (above != spans.end() && below != spans.end()
127 && above->first - below->first + 1 == below->second) {
128 // below and above have a gap of exactly one between them, and this must be value
129 // so we coalesce the two spans (and the gap) into one.
130 newSpan = SpanType(below->first, below->second + above->second + 1);
131 spans.erase(above);
132 above = spans.erase(below);
133 }
134 else if (below != spans.end() && value - below->first == below->second) {
135 // value is adjacent to the end of below, so just expand below by one
136 newSpan = SpanType(below->first, below->second + 1);
137 above = spans.erase(below);
138 }
139 else if (above != spans.end() && above->first - value == 1) {
140 // value is adjacent to the start of above, so just expand above down by one
141 newSpan = SpanType(above->first - 1, above->second + 1);
142 above = spans.erase(above);
143 }
144 // else value is not adjacent to any existing span, so just make anew span for it
145 spans.insert(above, newSpan);
146 }
147 void remove(IT value)
148 {
149 SpanType newSpan(value, 1);
150 auto at = spans.lower_bound(newSpan);
151 if (at == spans.end() || at->first > value) {
152 // The found span does not include value so there is nothing to do, as it is already
153 // not in the set.
154 return;
155 }
156 if (at->second == 1) {
157 // value is the only in this span, just remove the span
158 spans.erase(at);
159 }
160 else if (at->first == value) {
161 // value is the first in this span, trim the lower end
162 SpanType replacement(at->first + 1, at->second - 1);
163 spans.insert(spans.erase(at), replacement);
164 }
165 else if (value - at->first == at->second - 1) {
166 // value is the last in this span, trim the upper end
167 SpanType replacement(at->first, at->second - 1);
168 spans.insert(spans.erase(at), replacement);
169 }
170 else {
171 // value is in the moddle of the span, so we must split it.
172 SpanType firstReplacement(at->first, value - at->first);
173 SpanType secondReplacement(value + 1, at->second - ((value + 1) - at->first));
174 // Because erase returns the iterator after the erased element, and insert returns
175 // the iterator for the inserted item, we want to insert secondReplacement first.
176 spans.insert(spans.insert(spans.erase(at), secondReplacement), firstReplacement);
177 }
178 }
179 bool contains(IT value) const
180 {
181 auto at = spans.lower_bound(SpanType(value, IT(1)));
182 return at != spans.end() && at->first <= value;
183 }
184 bool empty() const
185 {
186 return spans.empty();
187 }
188 void clear()
189 {
190 spans.clear();
191 }
192 IT next() const
193 {
194 if (spans.empty()) {
195 return IT(0);
196 }
197 auto last = spans.end();
198 --last;
199 return last->first + last->second;
200 }
201 };
202 // Keyed as uniqueSeeds[baseName][digitCount][digitValue] iff that seed is taken.
203 // We need the double-indexing so that Name01 and Name001 can both be indexed, although we only
204 // ever allocate off the longest for each name i.e. uniqueSeeds[baseName].size()-1 digits.
205 std::map<std::string, std::vector<PiecewiseSparseIntegerSet<UnlimitedUnsigned>>> uniqueSeeds;
206 // Counts of inserted strings that have duplicates, i.e. more than one instance in the
207 // collection. This does not contain entries for singleton names.
208 std::map<std::string, unsigned int> duplicateCounts;
209
210 /// @brief Break a uniquified name into its parts
211 /// @param name The name to break up
212 /// @return a tuple(basePrefix, nameSuffix, uniqueDigitCount, uniqueDigitsValue);
213 /// The two latter values will be (0,0) if name is a base name without uniquifying digits.
214 std::tuple<std::string, std::string, unsigned int, UnlimitedUnsigned> decomposeName(
215 const std::string& name
216 ) const;
217
218 public:
219 UniqueNameManager() = default;
220 virtual ~UniqueNameManager() = default;
221
222 /// Check if two names are unique forms of the same base name
223 bool haveSameBaseName(const std::string& first, const std::string& second) const;
224
225 /// Register a name in the collection.
226 /// This collection acts as a multiset, so multiple registrations of the same
227 /// name are counted, and an equal number of removals is necessary to fully
228 /// remove the name, allowing it to be returned by makeUniqueName
229 void addExactName(const std::string& name);
230 /// Using the given modelName as a model, generate a name that is not already
231 /// in the collection of names. The model name may already contain uniquifying digits
232 /// which will be stripped and replaced with other digits as needed.
233 std::string makeUniqueName(const std::string& modelName, std::size_t minDigits = 0) const;
234 /// Remove a registered name so it can be generated again. If the name was added
235 /// several times this decrements the count, and the name is only fully removed when
236 /// the count of removes equals or exceeds the count of adds.
237 void removeExactName(const std::string& name);
238 /// Test if the given name is already in the collection
239 bool containsName(const std::string& name) const;
240 /// @brief Empty (clear) out the contents from this collection
241 void clear()
242 {
243 uniqueSeeds.clear();
244 duplicateCounts.clear();
245 }
246 };
247 } // namespace Base
248
249 #endif // SRC_BASE_UNIQUENAMEMANAGER_H_