Debian Codegraph @

src/App/IndexedName.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /****************************************************************************
4 * Copyright (c) 2022 Zheng, Lei (realthunder) <[email protected]>*
5 * Copyright (c) 2023 FreeCAD Project Association *
6 * *
7 * This file is part of FreeCAD. *
8 * *
9 * FreeCAD is free software: you can redistribute it and/or modify it *
10 * under the terms of the GNU Lesser General Public License as *
11 * published by the Free Software Foundation, either version 2.1 of the *
12 * License, or (at your option) any later version. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, but *
15 * WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
17 * Lesser General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Lesser General Public *
20 * License along with FreeCAD. If not, see *
21 * <https://www.gnu.org/licenses/>. *
22 * *
23 ***************************************************************************/
24
25 #ifndef APP_INDEXEDNAME_H
26 #define APP_INDEXEDNAME_H
27
28 #include <cassert>
29 #include <cstring>
30 #include <ostream>
31 #include <string>
32 #include <vector>
33
34 #include <QByteArray>
35 #include <QHash>
36
37 #include "FCGlobal.h"
38
39
40 namespace Data
41 {
42
43 /// The IndexedName class provides a very memory-efficient data structure to hold a name and an
44 /// index value, and to perform various comparisons and validations of those values. The name must
45 /// only consist of upper- and lower-case ASCII characters and the underscore ('_') character. The
46 /// index must be a positive integer. The string representation of this IndexedName is the name
47 /// followed by the index, with no spaces between: an IndexedName may be constructed from this
48 /// string. For example "EDGE1" or "FACE345" might be the names of elements that use an IndexedName.
49 /// If there is then an "EDGE2", only a pointer to the original stored name "EDGE" is retained.
50 ///
51 /// The memory efficiency of the class comes from reusing the same character storage for names that
52 /// match, while retaining their differing indices. This is achieved by either using user-provided
53 /// const char * names (provided as a list of typeNames and presumed to never be deallocated), or by
54 /// maintaining an internal list of names that have been used before, and can be reused later.
55 class AppExport IndexedName
56 {
57 public:
58 /// Construct from a name and an optional index. If the name contains an index it is read, but
59 /// is used as the index *only* if _index parameter is unset. If the _index parameter is given
60 /// it overrides any trailing integer in the name. Index must be positive, and name must contain
61 /// only ASCII letters and the underscore character. If these conditions are not met, name is
62 /// set to the empty string, and isNull() will return true.
63 ///
64 /// \param name The new name - ASCII letters and underscores only, with optional integer suffix.
65 /// This memory will be copied into a new internal storage location and need not be persistent.
66 /// \param _index The new index - if provided, it overrides any suffix provided by name
67 explicit IndexedName(const char* name = nullptr, int _index = 0)
68 : index(0)
69 {
70 assert(_index >= 0);
71 if (!name) {
72 this->type = "";
73 }
74 else {
75 set(name);
76 if (_index > 0) {
77 this->index = _index;
78 }
79 }
80 }
81
82 /// Create an indexed name that is restricted to a list of preset type names. If it appears in
83 /// that list, only a pointer to the character storage in the list is retained: the memory
84 /// locations pointed at by the list must never be destroyed once they have been used to create
85 /// names. If allowOthers is true (the default) then a requested name that is not in the list
86 /// will be added to a static internal storage table, and its memory then reused for later
87 /// objects with the same name. If allowOthers is false, then the name request is rejected, and
88 /// the name is treated as null.
89 ///
90 /// \param name The new name - ASCII letters and underscores only, with optional integer suffix
91 /// \param allowedTypeNames A vector of allowed names. Storage locations must persist for the
92 /// entire run of the program.
93 /// \param allowOthers Whether a name not in allowedTypeNames is permitted. If true (the
94 /// default) then a name not in allowedTypeNames is added to a static internal storage vector
95 /// so that it can be reused later without additional memory allocation.
96 IndexedName(const char* name,
97 const std::vector<const char*>& allowedTypeNames,
98 bool allowOthers = true)
99 : type("")
100 , index(0)
101 {
102 set(name, -1, allowedTypeNames, allowOthers);
103 }
104
105 /// Construct from a QByteArray, but explicitly making a copy of the name on its first
106 /// occurrence. If this is a name that has already been stored internally, no additional copy
107 /// is made.
108 ///
109 /// \param data The QByteArray to copy the data from
110 explicit IndexedName(const QByteArray& data)
111 : type("")
112 , index(0)
113 {
114 set(data.constData(), data.size());
115 }
116
117 /// Given constant name and an index, reuse the existing memory for the name, not making a copy
118 /// of it, or scanning any existing storage for it. The name must never become invalid for the
119 /// lifetime of the object it names. This memory will never be reused by another object.
120 ///
121 /// \param name The name of the object. This memory is NOT copied and must be persistent.
122 /// \param index A positive, non-zero integer
123 /// \return An IndexedName with the given name and index, reusing the existing memory for name
124 static IndexedName fromConst(const char* name, int index)
125 {
126 assert(index >= 0);
127 IndexedName res;
128 res.type = name;
129 res.index = index;
130 return res;
131 }
132
133 /// Given an existing std::string, *append* this name to it. If index is not zero, this will
134 /// include the index.
135 ///
136 /// \param buffer A (possibly non-empty) string buffer to append the name to.
137 /// \return A const char pointer to the name we appended to the buffer.
138 const char* appendToStringBuffer(std::string& buffer) const
139 {
140 // Note! buffer is not cleared on purpose.
141 std::size_t offset = buffer.size();
142 buffer += this->type;
143 if (this->index > 0) {
144 buffer += std::to_string(this->index);
145 }
146 return buffer.c_str() + offset;
147 }
148
149 /// Create and return a new std::string with this name in it.
150 ///
151 /// \return A newly-created string with the IndexedName in it (e.g. "EDGE42")
152 std::string toString() const
153 {
154 std::string result;
155 this->appendToStringBuffer(result);
156 return result;
157 }
158
159 /// An indexedName is represented as the simple concatenation of the name and its index, e.g.
160 /// "EDGE1" or "FACE42".
161 friend std::ostream& operator<<(std::ostream& stream, const IndexedName& indexedName)
162 {
163 stream << indexedName.type;
164 if (indexedName.index > 0) {
165 stream << indexedName.index;
166 }
167 return stream;
168 }
169
170 /// True only if both the name and index compare exactly equal.
171 bool operator==(const IndexedName& other) const
172 {
173 return this->index == other.index
174 && (this->type == other.type || std::strcmp(this->type, other.type) == 0);
175 }
176
177 /// Increments the index by the given offset. Does not affect the text part of the name.
178 IndexedName& operator+=(int offset)
179 {
180 this->index += offset;
181 assert(this->index >= 0);
182 return *this;
183 }
184
185 /// Pre-increment operator: increases the index of this element by one.
186 IndexedName& operator++()
187 {
188 ++this->index;
189 return *this;
190 }
191
192 /// Pre-decrement operator: decreases the index of this element by one. Must not make the index
193 /// negative (only checked when compiled in debug mode).
194 IndexedName& operator--()
195 {
196 --this->index;
197 assert(this->index >= 0);
198 return *this;
199 }
200
201 /// True if either the name or the index compare not equal.
202 bool operator!=(const IndexedName& other) const
203 {
204 return !(this->operator==(other));
205 }
206
207 /// Equivalent to C++20's operator <=>
208 int compare(const IndexedName& other) const
209 {
210 int res = std::strcmp(this->type, other.type);
211 if (res != 0) {
212 return res;
213 }
214 if (this->index < other.index) {
215 return -1;
216 }
217 if (this->index > other.index) {
218 return 1;
219 }
220 return 0;
221 }
222
223 /// Provided to enable sorting operations: the comparison is first lexicographical for the text
224 /// element of the names, then numerical for the indices.
225 bool operator<(const IndexedName& other) const
226 {
227 return compare(other) < 0;
228 }
229
230 /// Allow direct memory access to the individual characters of the text portion of the name.
231 /// NOTE: input is not range-checked when compiled in release mode.
232 char operator[](int input) const
233 {
234 assert(input >= 0);
235 assert(input < static_cast<int>(std::strlen(this->type)));
236 // When we support C++20 we can use std::span<> to eliminate the clang-tidy warning
237 // NOLINTNEXTLINE cppcoreguidelines-pro-bounds-pointer-arithmetic
238 return this->type[input];
239 }
240
241 /// Get a pointer to text part of the name - does NOT make a copy, returns direct memory access
242 const char* getType() const
243 {
244 return this->type;
245 }
246
247 /// Get the numerical part of the name
248 int getIndex() const
249 {
250 return this->index;
251 }
252
253 /// Set the numerical part of the name (note that there is no equivalent function to allow
254 /// changing the text part of the name, which is immutable once created).
255 ///
256 /// \param input The new index. Must be a positive non-zero integer
257 void setIndex(int input)
258 {
259 assert(input >= 0);
260 this->index = input;
261 }
262
263 /// A name is considered "null" if its text component is an empty string.
264 // When we support C++20 we can use std::span<> to eliminate the clang-tidy warning
265 // NOLINTNEXTLINE cppcoreguidelines-pro-bounds-pointer-arithmetic
266 bool isNull() const
267 {
268 return this->type[0] == '\0';
269 }
270
271 /// Boolean conversion provides the opposite of isNull(), yielding true when the text part of
272 /// the name is NOT the empty string.
273 explicit operator bool() const
274 {
275 return !isNull();
276 }
277
278 protected:
279 /// Apply the IndexedName rules and either store the characters of a new type or a reference to
280 /// the characters in a type named in types, or stored statically within this function. If len
281 /// is not set, or set to -1 (the default), then the provided string in name is scanned for its
282 /// length using strlen (e.g. it must be null-terminated).
283 ///
284 /// \param name The new name. If necessary a copy is made, this char * need not be persistent
285 /// \param length The length of name
286 /// \param allowedNames A vector of storage locations of allowed names. These storage locations
287 /// must be persistent for the duration of the program run.
288 /// \param allowOthers If true (the default), then if name is not in allowedNames it is allowed,
289 /// and it is added to internal storage (making a copy of the name if this is its first
290 /// occurrence).
291 void set(const char* name,
292 int length = -1,
293 const std::vector<const char*>& allowedNames = {},
294 bool allowOthers = true);
295
296 private:
297 const char* type;
298 int index;
299 };
300
301
302 /// A thin wrapper around a QByteArray providing the ability to force a copy of the data at any
303 /// time, even if it isn't being written to. The standard assignment operator for this class *does*
304 /// make a copy of the data, unlike the standard assignment operator for QByteArray.
305 struct ByteArray
306 {
307 explicit ByteArray(QByteArray other)
308 : bytes(std::move(other))
309 {}
310
311 ByteArray(const ByteArray& other) = default;
312
313 ByteArray(ByteArray&& other) noexcept
314 : bytes(std::move(other.bytes))
315 {}
316
317 ~ByteArray() = default;
318
319 /// Guarantee that the stored QByteArray does not share its memory with another instance.
320 void ensureUnshared() const
321 {
322 QByteArray copy;
323 copy.append(bytes.constData(), bytes.size());
324 bytes = copy;
325 }
326
327 bool operator==(const ByteArray& other) const
328 {
329 return bytes == other.bytes;
330 }
331
332 ByteArray& operator=(const ByteArray& other)
333 {
334 bytes.clear();
335 bytes.append(other.bytes.constData(), other.bytes.size());
336 return *this;
337 }
338
339 ByteArray& operator=(ByteArray&& other) noexcept
340 {
341 bytes = std::move(other.bytes);
342 return *this;
343 }
344
345 mutable QByteArray bytes;
346 };
347
348
349 struct ByteArrayHasher
350 {
351 std::size_t operator()(const ByteArray& bytes) const
352 {
353 return qHash(bytes.bytes);
354 }
355
356 std::size_t operator()(const QByteArray& bytes) const
357 {
358 return qHash(bytes);
359 }
360 };
361
362 } // namespace Data
363
364 #endif // APP_INDEXEDNAME_H