Debian Codegraph @

src/App/StringHasher.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************************************
4 * *
5 * Copyright (c) 2022 Zheng, Lei (realthunder) <[email protected]> *
6 * Copyright (c) 2023 FreeCAD Project Association *
7 * *
8 * This file is part of FreeCAD. *
9 * *
10 * FreeCAD is free software: you can redistribute it and/or modify it under the terms of the *
11 * GNU Lesser General Public License as published by the Free Software Foundation, either *
12 * version 2.1 of the License, or (at your option) any later version. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; *
15 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
16 * See the GNU Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public License along with *
19 * FreeCAD. If not, see <https://www.gnu.org/licenses/>. *
20 * *
21 **************************************************************************************************/
22
23 #ifndef APP_STRING_ID_H
24 #define APP_STRING_ID_H
25
26 #include <FCConfig.h>
27
28 #include <bitset>
29 #include <memory>
30
31 #include <QByteArray>
32 #include <QVector>
33
34 #include <Base/Bitmask.h>
35 #include <Base/Handle.h>
36 #include <Base/Persistence.h>
37 #include <CXX/Objects.hxx>
38 #include <utility>
39
40 #include <Base/PyObjectBase.h>
41
42
43 namespace Data
44 {
45 class MappedName;
46 }
47
48 namespace App
49 {
50
51 class StringHasher;
52 class StringID;
53 class StringIDRef;
54 using StringHasherRef = Base::Reference<StringHasher>;
55
56 /** Class to store a string
57 *
58 * The main purpose of this class is to provide an efficient storage of the
59 * mapped geometry element name (i.e. the new Topological Naming), but it can
60 * also be used as a general purpose string table.
61 *
62 * The StringID is to be stored in a string table (StringHasher), and be
63 * referred to by an integer ID. The stored data can be optionally divided into
64 * two parts, prefix and postfix. This is because a new mapped name is often
65 * created by adding some common postfix to an existing name, so data sharing
66 * can be improved using the following techniques:
67 *
68 * a) reference count (through QByteArray) the main data part,
69 *
70 * b) (recursively) encode prefix and/or postfix as an integer (in the
71 * format of #<hex>, e.g. #1b) that references another StringID,
72 *
73 * c) Check index based name in prefix, e.g. Edge1, Vertex2, and encode
74 * only the text part as StringID. The index is stored separately in
75 * reference class StringIDRef to maximize data sharing.
76 */
77 class AppExport StringID: public Base::BaseClass, public Base::Handled
78 {
79 TYPESYSTEM_HEADER_WITH_OVERRIDE(); // NOLINT
80
81 public:
82 /// Flag of the stored string data
83 enum class Flag
84 {
85 /// No flag
86 None = 0,
87 /// The stored data is binary
88 Binary = 1 << 0,
89 /// The stored data is the sha1 hash of the original content
90 Hashed = 1 << 1,
91 /** Postfix is encoded as #<hex>, e.g. #1b, where the hex integer part
92 * refers to another StringID.
93 */
94 PostfixEncoded = 1 << 2,
95 /// The data is split as prefix and postfix
96 Postfixed = 1 << 3,
97 /// The prefix data is split as text + index
98 Indexed = 1 << 4,
99 /** The prefix data is encoded as #<hex>, e.g. #1b, where the hex
100 * integer part refers to another StringID.
101 */
102 PrefixID = 1 << 5,
103 /** The prefix split as text + index, where the text is encoded
104 * using another StringID.
105 */
106 PrefixIDIndex = 1 << 6,
107 /// The string ID is persistent regardless of internal mark
108 Persistent = 1 << 7,
109 /// Internal marked used to check if the string ID is used
110 Marked = 1 << 8,
111 };
112 using Flags = Base::Flags<Flag>;
113
114 /** Constructor
115 * @param id: integer ID of this StringID
116 * @param data: input data
117 * @param flags: flags describes the data
118 *
119 * User code is not supposed to create StringID directly, but through StringHasher::getID()
120 */
121 StringID(long id, QByteArray data, const Flags& flags = Flag::None)
122 : _id(id)
123 , _data(std::move(data))
124 , _flags(flags)
125 {}
126
127 /// Constructs an empty StringID
128 StringID()
129 : _id(0)
130 , _flags(Flag::None)
131 {}
132
133 StringID(const StringID& other) = delete;
134 StringID(StringID&& other) noexcept = delete;
135 StringID& operator=(const StringID& rhs) = delete;
136 StringID& operator=(StringID&& rhs) noexcept = delete;
137
138 ~StringID() override;
139
140 /// Returns the ID of this StringID
141 long value() const
142 {
143 return _id;
144 }
145
146 /// Returns all related StringIDs that used to encode this StringID
147 const QVector<StringIDRef>& relatedIDs() const
148 {
149 return _sids;
150 }
151
152 /// @name Flag accessors
153 //@{
154 inline bool isBinary() const;
155 inline bool isHashed() const;
156 inline bool isPostfixed() const;
157 inline bool isPostfixEncoded() const;
158 inline bool isIndexed() const;
159 inline bool isPrefixID() const;
160 inline bool isPrefixIDIndex() const;
161 inline bool isMarked() const;
162 inline bool isPersistent() const;
163 //@}
164
165 /// Checks if this StringID is from the input hasher
166 bool isFromSameHasher(const StringHasherRef& hasher) const
167 {
168 return this->_hasher == hasher;
169 }
170
171 /// Returns the owner hasher
172 StringHasherRef getHasher() const
173 {
174 return {_hasher};
175 }
176
177 /// Returns the data (prefix)
178 const QByteArray& data() const
179 {
180 return _data;
181 }
182
183 /// Returns the postfix
184 QByteArray postfix() const
185 {
186 return _postfix;
187 }
188
189 /// Sets the postfix
190 void setPostfix(QByteArray postfix)
191 {
192 _postfix = std::move(postfix);
193 }
194
195 PyObject* getPyObject() override;
196 /// Returns a Python tuple containing both the text and index
197 PyObject* getPyObjectWithIndex(int index);
198
199 /** Convert to string representation of this StringID
200 * @param index: optional index
201 *
202 * The format is #<id>. And if index is non zero, then #<id>:<index>. Both
203 * <id> and <index> are in hex format.
204 */
205 std::string toString(int index = 0) const;
206
207 /// Light weight structure of holding a string ID and associated index
208 struct IndexID
209 {
210 long id;
211 int index;
212
213 explicit operator bool() const
214 {
215 return id > 0;
216 }
217
218 friend std::ostream& operator<<(std::ostream& stream, const IndexID& indexID)
219 {
220 stream << indexID.id;
221 if (indexID.index != 0) {
222 stream << ':' << indexID.index;
223 }
224 return stream;
225 }
226 };
227
228 /** Parse string to get ID and index
229 * @param name: input string
230 * @param eof: Whether to check the end of string. If true, then the input
231 * string must contain only the string representation of this
232 * StringID
233 * @param size: input string size, or -1 if the input string is zero terminated.
234 * @return Return the integer ID and index.
235 *
236 * The input string is expected to be in the format of #<id> or with index
237 * #<id>:<index>, where both id and index are in hex digits.
238 */
239 static IndexID fromString(const char* name, bool eof = true, int size = -1);
240
241 /** Parse string to get ID and index
242 * @param bytes: input data
243 * @param eof: Whether to check the end of string. If true, then the input
244 * string must contain only the string representation of this
245 * StringID
246 *
247 * The input string is expected to be in the format of #<id> or with index
248 * #<id>:<index>, where both id and index are in hex digits.
249 */
250 static IndexID fromString(const QByteArray& bytes, bool eof = true)
251 {
252 return fromString(bytes.constData(), eof, bytes.size());
253 }
254
255 /** Get the text content of this StringID
256 * @param index: optional index
257 * @return Return the text content of this StringID. If the data is binary,
258 * then output in base64 encoded string.
259 */
260 std::string dataToText(int index = 0) const;
261
262 /** Get the content of this StringID as QByteArray
263 * @param index: optional index.
264 */
265 QByteArray dataToBytes(int index = 0) const
266 {
267 QByteArray res(_data);
268 if (index != 0) {
269 res += QByteArray::number(index);
270 }
271 if (_postfix.size() != 0) {
272 res += _postfix;
273 }
274 return res;
275 }
276
277 /// Mark this StringID as used
278 void mark() const;
279
280 /// Mark the StringID as persistent regardless of usage mark
281 inline void setPersistent(bool enable);
282
283 bool operator<(const StringID& other) const
284 {
285 return compare(other) < 0;
286 }
287
288 /** Compare StringID
289 * @param other: the other StringID for comparison
290 * @return Returns -1 if less than the other StringID, 1 if greater, or 0 if equal
291 */
292 int compare(const StringID& other) const
293 {
294 if (_hasher < other._hasher) {
295 return -1;
296 }
297 if (_hasher > other._hasher) {
298 return 1;
299 }
300 if (_id < other._id) {
301 return -1;
302 }
303 if (_id > other._id) {
304 return 1;
305 }
306 return 0;
307 }
308
309 friend class StringHasher;
310
311 private:
312 long _id;
313 QByteArray _data;
314 QByteArray _postfix;
315 StringHasher* _hasher = nullptr;
316 mutable Flags _flags;
317 mutable QVector<StringIDRef> _sids;
318 };
319
320 //////////////////////////////////////////////////////////////////////////
321
322 /** Counted reference to a StringID instance
323 */
324 class StringIDRef
325 {
326 public:
327 /// Default construction results in an empty StringIDRef object: it will evaluate to boolean
328 /// "false" if queried.
329 StringIDRef()
330 : _sid(nullptr)
331 , _index(0)
332 {}
333
334 /// Standard construction from a heap-allocated StringID. This reference-counting class manages
335 /// the lifetime of the StringID, ensuring it is deallocated when its reference count goes to
336 /// zero.
337 /// \param stringID A pointer to a StringID allocated with "new"
338 /// \param index (optional) An index value to store along with the StringID. Defaults to zero.
339 StringIDRef(StringID* stringID, int index = 0)
340 : _sid(stringID)
341 , _index(index)
342 {
343 if (_sid) {
344 _sid->ref();
345 }
346 }
347
348 /// Copy construction results in an incremented reference count for the stored StringID
349 StringIDRef(const StringIDRef& other)
350 : _sid(other._sid)
351 , _index(other._index)
352 {
353 if (_sid) {
354 _sid->ref();
355 }
356 }
357
358 /// Move construction does NOT increase the reference count of the StringID (instead, it
359 /// invalidates the pointer in the moved object).
360 StringIDRef(StringIDRef&& other) noexcept
361 : _sid(other._sid)
362 , _index(other._index)
363 {
364 other._sid = nullptr;
365 }
366
367 StringIDRef(const StringIDRef& other, int index)
368 : _sid(other._sid)
369 , _index(index)
370 {
371 if (_sid) {
372 _sid->ref();
373 }
374 }
375
376 ~StringIDRef()
377 {
378 if (_sid) {
379 _sid->unref();
380 }
381 }
382
383 void reset(const StringIDRef& stringID = StringIDRef())
384 {
385 *this = stringID;
386 }
387
388 void reset(const StringIDRef& stringID, int index)
389 {
390 *this = stringID;
391 this->_index = index;
392 }
393
394 void swap(StringIDRef& stringID)
395 {
396 if (*this != stringID) {
397 auto tmp = stringID;
398 stringID = *this;
399 *this = tmp;
400 }
401 }
402
403 StringIDRef& operator=(StringID* stringID)
404 {
405 if (_sid == stringID) {
406 return *this;
407 }
408 if (_sid) {
409 _sid->unref();
410 }
411 _sid = stringID;
412 if (_sid) {
413 _sid->ref();
414 }
415 this->_index = 0;
416 return *this;
417 }
418
419 StringIDRef& operator=(const StringIDRef& stringID)
420 {
421 if (&stringID == this) {
422 return *this;
423 }
424 if (_sid != stringID._sid) {
425 if (_sid) {
426 _sid->unref();
427 }
428 _sid = stringID._sid;
429 if (_sid) {
430 _sid->ref();
431 }
432 }
433 this->_index = stringID._index;
434 return *this;
435 }
436
437 StringIDRef& operator=(StringIDRef&& stringID) noexcept
438 {
439 if (_sid != stringID._sid) {
440 if (_sid) {
441 _sid->unref();
442 }
443 _sid = stringID._sid;
444 stringID._sid = nullptr;
445 }
446 this->_index = stringID._index;
447 return *this;
448 }
449
450 bool operator<(const StringIDRef& stringID) const
451 {
452 if (!stringID._sid) {
453 return false;
454 }
455 if (!_sid) {
456 return true;
457 }
458 int res = _sid->compare(*stringID._sid);
459 if (res < 0) {
460 return true;
461 }
462 if (res > 0) {
463 return false;
464 }
465 return _index < stringID._index;
466 }
467
468 bool operator==(const StringIDRef& stringID) const
469 {
470 if (_sid && stringID._sid) {
471 return _sid->compare(*stringID._sid) == 0 && _index == stringID._index;
472 }
473 return _sid == stringID._sid;
474 }
475
476 bool operator!=(const StringIDRef& stringID) const
477 {
478 return !(*this == stringID);
479 }
480
481 explicit operator bool() const
482 {
483 return _sid != nullptr;
484 }
485
486 int getRefCount() const
487 {
488 if (_sid) {
489 return _sid->getRefCount();
490 }
491 return 0;
492 }
493
494 std::string toString() const
495 {
496 if (_sid) {
497 return _sid->toString(_index);
498 }
499 return {};
500 }
501
502 std::string dataToText() const
503 {
504 if (_sid) {
505 return _sid->dataToText(_index);
506 }
507 return {};
508 }
509
510 /// Get a reference to the data: only makes sense if index and postfix are both empty, but
511 /// calling code is responsible for ensuring that.
512 const char* constData() const
513 {
514 if (_sid) {
515 assert(_index == 0);
516 assert(_sid->postfix().isEmpty());
517 return _sid->data().constData();
518 }
519 return "";
520 }
521
522 const StringID& deref() const
523 {
524 return *_sid;
525 }
526
527 long value() const
528 {
529 if (_sid) {
530 return _sid->value();
531 }
532 return 0;
533 }
534
535 QVector<StringIDRef> relatedIDs() const
536 {
537 if (_sid) {
538 return _sid->relatedIDs();
539 }
540 return {};
541 }
542
543 bool isBinary() const
544 {
545 if (_sid) {
546 return _sid->isBinary();
547 }
548 return false;
549 }
550
551 bool isHashed() const
552 {
553 if (_sid) {
554 return _sid->isHashed();
555 }
556 return false;
557 }
558
559 void toBytes(QByteArray& bytes) const
560 {
561 // TODO: return the QByteArray instead of passing in by reference
562 if (_sid) {
563 bytes = _sid->dataToBytes(_index);
564 }
565 }
566
567 PyObject* getPyObject()
568 {
569 if (_sid) {
570 return _sid->getPyObjectWithIndex(_index);
571 }
572 Py_INCREF(Py_None);
573 return Py_None;
574 }
575
576 void mark() const
577 {
578 if (_sid) {
579 _sid->mark();
580 }
581 }
582
583 bool isMarked() const
584 {
585 return _sid && _sid->isMarked(); // NOLINT
586 }
587
588 bool isFromSameHasher(const StringHasherRef& hasher) const
589 {
590 return _sid && _sid->isFromSameHasher(hasher); // NOLINT
591 }
592
593 StringHasherRef getHasher() const
594 {
595 if (_sid) {
596 return _sid->getHasher();
597 }
598 return {};
599 }
600
601 void setPersistent(bool enable)
602 {
603 if (_sid) {
604 _sid->setPersistent(enable);
605 }
606 }
607
608 /// Used predominantly by the unit test code to verify that index is set correctly. In general
609 /// user code should not need to call this function.
610 int getIndex() const
611 {
612 return _index;
613 }
614
615 friend class StringHasher;
616
617 private:
618 StringID* _sid;
619 int _index;
620 };
621
622
623 /// \brief A bidirectional map of strings and their integer identifier.
624 ///
625 /// Maps an arbitrary text string to a unique integer ID, maintaining a reference-counted shared
626 /// pointer for each. This permits elimination of unused strings based on their reference
627 /// count. If a duplicate string is added, no additional copy is made, and a new reference to the
628 /// original storage is returned (incrementing the reference counter of the instance).
629 ///
630 /// If the string is longer than a given threshold, instead of storing the string, its SHA1 hash is
631 /// stored (and the original string discarded). This allows an upper threshold on the length of a
632 /// stored string, while still effectively guaranteeing uniqueness in the table.
633 class AppExport StringHasher: public Base::Persistence, public Base::Handled
634 {
635
636 TYPESYSTEM_HEADER_WITH_OVERRIDE(); // NOLINT
637
638 public:
639 StringHasher();
640 ~StringHasher() override;
641
642 StringHasher(const StringHasher&) = delete;
643 StringHasher(StringHasher&&) noexcept = delete;
644 StringHasher& operator=(StringHasher& other) = delete;
645 StringHasher& operator=(StringHasher&& other) noexcept = delete;
646
647 unsigned int getMemSize() const override;
648 void Save(Base::Writer& /*writer*/) const override;
649 void Restore(Base::XMLReader& /*reader*/) override;
650 void SaveDocFile(Base::Writer& /*writer*/) const override;
651 void RestoreDocFile(Base::Reader& /*reader*/) override;
652 void setPersistenceFileName(const char* name) const;
653 const std::string& getPersistenceFileName() const;
654
655 /** Maps an arbitrary string to an integer
656 *
657 * @param text: input string.
658 * @param len: length of the string: optional if the string is null-terminated.
659 * @param hashable: whether hashing the string is permitted.
660 * @return A shared pointer to the internally-stored StringID.
661 *
662 * Maps an arbitrary text string to a unique integer ID, returning a reference-counted shared
663 * pointer to the StringID. This permits elimination of unused strings based on their reference
664 * count. If a duplicate string is added, no additional copy is made, and a new reference to the
665 * original storage is returned (incrementing the reference counter of the instance).
666 *
667 * If \c hashable is true and the string is longer than the threshold setting of this
668 * StringHasher, only the SHA1 hash of the string is stored: the original content of the string
669 * is discarded. If \c hashable is false, the string is copied and stored inside a StringID
670 * instance.
671 *
672 * The purpose of this function is to provide a short form of a stable string identification.
673 */
674 StringIDRef getID(const char* text, int len = -1, bool hashable = false);
675
676 /// Options for string string data
677 enum class Option
678 {
679 /// No option is set
680 None = 0,
681
682 /// The input data is binary
683 Binary = 1 << 0,
684
685 /// Hashing is permitted for this input data. If the data length is longer than the
686 /// threshold setting of the StringHasher, it will be sha1 hashed before storing, and the
687 /// original content of the string is discarded.
688 Hashable = 1 << 1,
689
690 /// Do not copy the data: assume it is constant and exists for the lifetime of this hasher.
691 /// If this option is not set, the data will be copied before storing.
692 NoCopy = 1 << 2,
693 };
694 using Options = Base::Flags<Option>;
695
696 /** Map text or binary data to an integer
697 *
698 * @param data: input data.
699 * @param options: options describing how to store the data.
700 * @return A shared pointer to the internally stored StringID.
701 *
702 * \sa getID (const char*, int, bool);
703 */
704 StringIDRef getID(const QByteArray& data, Options options = Option::Hashable);
705
706 /** Map geometry element name to an integer */
707 StringIDRef getID(const Data::MappedName& name, const QVector<StringIDRef>& sids);
708
709 /** Obtain the reference counted StringID object from numerical id
710 *
711 * @param id: string ID
712 * @param index: optional index of the string ID
713 * @return Return a shared pointer to the internally stored StringID.
714 *
715 * This function exists because the stored string may be one way hashed,
716 * and the original text is not persistent. The caller use this function to
717 * retrieve the reference count ID object after restore
718 */
719 StringIDRef getID(long id, int index = 0) const;
720
721 /** Obtain the reference counted StringID object from numerical id and index
722 *
723 * @param id: string ID with index
724 * @return Return a shared pointer to the internally stored StringID.
725 */
726 StringIDRef getID(const StringID::IndexID& id) const
727 {
728 return getID(id.id, id.index);
729 }
730
731 std::map<long, StringIDRef> getIDMap() const;
732
733 /// Clear all string hashes
734 void clear();
735
736 /// Size of the hash table
737 size_t size() const;
738
739 /// Return the number of hashes that are used by others
740 size_t count() const;
741
742 PyObject* getPyObject() override;
743
744 /** Enable/disable saving all string ID
745 *
746 * If saveAll is true, then compact() does nothing even when called explicitly. Setting
747 * saveAll it to false causes compact() to be run immediately.
748 */
749 void setSaveAll(bool enable);
750 bool getSaveAll() const;
751
752 /** Set threshold of string hashing
753 *
754 * For hashable strings that are longer than this threshold, the string will
755 * be replaced by its sha1 hash.
756 */
757 void setThreshold(int threshold);
758 int getThreshold() const;
759
760 /** Clear internal marks
761 *
762 * The internal marks on internally stored StringID instances are used to
763 * check if the StringID is used.
764 */
765 void clearMarks() const;
766
767 /// Compact string storage by eliminating unused strings from the table.
768 void compact();
769
770 class HashMap;
771 friend class StringID;
772
773 protected:
774 StringID* insert(const StringIDRef& sid);
775 long lastID() const;
776 void saveStream(std::ostream& stream) const;
777 void restoreStream(std::istream& stream, std::size_t count);
778 void restoreStreamNew(std::istream& stream, std::size_t count);
779
780 private:
781 std::unique_ptr<HashMap>
782 _hashes; ///< Bidirectional map of StringID and its index (a long int).
783 mutable std::string _filename;
784 };
785 } // namespace App
786
787 ENABLE_BITMASK_OPERATORS(App::StringID::Flag)
788 ENABLE_BITMASK_OPERATORS(App::StringHasher::Option)
789
790 namespace App
791 {
792 inline bool StringID::isBinary() const
793 {
794 return _flags.testFlag(Flag::Binary);
795 }
796 inline bool StringID::isHashed() const
797 {
798 return _flags.testFlag(Flag::Hashed);
799 }
800 inline bool StringID::isPostfixed() const
801 {
802 return _flags.testFlag(Flag::Postfixed);
803 }
804 inline bool StringID::isPostfixEncoded() const
805 {
806 return _flags.testFlag(Flag::PostfixEncoded);
807 }
808 inline bool StringID::isIndexed() const
809 {
810 return _flags.testFlag(Flag::Indexed);
811 }
812 inline bool StringID::isPrefixID() const
813 {
814 return _flags.testFlag(Flag::PrefixID);
815 }
816 inline bool StringID::isPrefixIDIndex() const
817 {
818 return _flags.testFlag(Flag::PrefixIDIndex);
819 }
820 inline bool StringID::isMarked() const
821 {
822 return _flags.testFlag(Flag::Marked);
823 }
824 inline bool StringID::isPersistent() const
825 {
826 return _flags.testFlag(Flag::Persistent);
827 }
828 inline void StringID::setPersistent(bool enable)
829 {
830 _flags.setFlag(Flag::Persistent, enable);
831 }
832 } // namespace App
833
834 #endif // APP_STRING_ID_H