1
// SPDX-License-Identifier: LGPL-2.1-or-later
3
/***************************************************************************************************
5
* Copyright (c) 2022 Zheng, Lei (realthunder) <realthunder.dev@gmail.com> *
6
* Copyright (c) 2023 FreeCAD Project Association *
8
* This file is part of FreeCAD. *
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. *
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. *
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/>. *
21
**************************************************************************************************/
23
#include "PreCompiled.h"
25
#include <QCryptographicHash>
29
#include <Base/Console.h>
30
#include <Base/Reader.h>
31
#include <Base/Stream.h>
32
#include <Base/Writer.h>
34
#include <boost/algorithm/string/classification.hpp>
35
#include <boost/algorithm/string/split.hpp>
36
#include <boost/bimap.hpp>
37
#include <boost/bimap/set_of.hpp>
38
#include <boost/bimap/unordered_set_of.hpp>
39
#include <boost/iostreams/stream.hpp>
41
#include "MappedElement.h"
42
#include "StringHasher.h"
43
#include "StringHasherPy.h"
44
#include "StringIDPy.h"
47
FC_LOG_LEVEL_INIT("App", true, true)
49
namespace bio = boost::iostreams;
52
///////////////////////////////////////////////////////////
56
std::size_t operator()(const StringID* sid) const
61
return qHash(sid->data(), qHash(sid->postfix()));
64
bool operator()(const StringID* IDa, const StringID* IDb) const
72
return IDa->data() == IDb->data() && IDa->postfix() == IDb->postfix();
77
boost::bimap<boost::bimaps::unordered_set_of<StringID*, StringIDHasher, StringIDHasher>,
78
boost::bimaps::set_of<long>>;
80
class StringHasher::HashMap: public HashMapBase
87
///////////////////////////////////////////////////////////
89
TYPESYSTEM_SOURCE_ABSTRACT(App::StringID, Base::BaseClass)
94
_hasher->_hashes->right.erase(_id);
98
PyObject* StringID::getPyObject()
100
return new StringIDPy(this);
103
PyObject* StringID::getPyObjectWithIndex(int index)
105
auto res = new StringIDPy(this);
110
std::string StringID::toString(int index) const
112
std::ostringstream ss;
113
ss << '#' << std::hex << value();
120
StringID::IndexID StringID::fromString(const char* name, bool eof, int size)
130
size = static_cast<int>(std::strlen(name));
132
bio::stream<bio::array_source> iss(name, size);
135
iss >> sep >> std::hex >> res.id >> sep2 >> res.index;
136
if ((eof && !iss.eof()) || sep != '#' || (sep2 != 0 && sep2 != ':')) {
143
std::string StringID::dataToText(int index) const
145
if (isHashed() || isBinary()) {
146
return _data.toBase64().constData();
149
std::string res(_data.constData());
151
res += std::to_string(index);
153
if (_postfix.size() != 0) {
154
res += _postfix.constData();
159
void StringID::mark() const
164
_flags.setFlag(Flag::Marked);
165
for (auto& sid : _sids) {
170
///////////////////////////////////////////////////////////
172
TYPESYSTEM_SOURCE(App::StringHasher, Base::Persistence)
174
StringHasher::StringHasher()
175
: _hashes(new HashMap)
178
StringHasher::~StringHasher()
183
void StringHasher::setSaveAll(bool enable)
185
if (_hashes->SaveAll == enable) {
188
_hashes->SaveAll = enable;
192
void StringHasher::compact()
194
if (_hashes->SaveAll) {
198
// Make a list of all the table entries that have only a single reference and are not marked
200
std::deque<StringIDRef> pendings;
201
for (auto& hasher : _hashes->right) {
202
if (!hasher.second->isPersistent() && hasher.second->getRefCount() == 1) {
203
pendings.emplace_back(hasher.second);
207
// Recursively remove the unused StringIDs
208
while (!pendings.empty()) {
209
StringIDRef sid = pendings.front();
210
pendings.pop_front();
211
// Try to erase the map entry for this StringID
212
if (_hashes->right.erase(sid.value()) == 0U) {
213
continue;// If nothing was erased, there's nothing more to do
215
sid._sid->_hasher = nullptr;
217
for (auto& hasher : sid._sid->_sids) {
218
if (hasher._sid->_hasher == this && !hasher._sid->isPersistent()
219
&& hasher._sid->getRefCount() == 2) {
220
// If the related StringID also uses this hasher, is not marked persistent, and has
221
// a current reference count of 2 (which will be its hasher reference and its entry
222
// in the related SIDs list), then prep it for removal as well.
223
pendings.push_back(hasher);
229
bool StringHasher::getSaveAll() const
231
return _hashes->SaveAll;
234
void StringHasher::setThreshold(int threshold)
236
_hashes->Threshold = threshold;
239
int StringHasher::getThreshold() const
241
return _hashes->Threshold;
244
long StringHasher::lastID() const
246
if (_hashes->right.empty()) {
249
auto it = _hashes->right.end();
254
StringIDRef StringHasher::getID(const char* text, int len, bool hashable)
257
len = static_cast<int>(strlen(text));
259
return getID(QByteArray::fromRawData(text, len), hashable ? Option::Hashable : Option::None);
262
StringIDRef StringHasher::getID(const QByteArray& data, Options options)
264
bool binary = options.testFlag(Option::Binary);
265
bool hashable = options.testFlag(Option::Hashable);
266
bool nocopy = options.testFlag(Option::NoCopy);
268
bool hashed = hashable && _hashes->Threshold > 0 && (int)data.size() > _hashes->Threshold;
272
QCryptographicHash hasher(QCryptographicHash::Sha1);
273
hasher.addData(data);
274
dataID._data = hasher.result();
280
auto it = _hashes->left.find(&dataID);
281
if (it != _hashes->left.end()) {
285
if (!hashed && !nocopy) {
286
// if not hashed, make a deep copy of the data
287
dataID._data = QByteArray(data.constData(), data.size());
290
StringID::Flags flags(StringID::Flag::None);
292
flags.setFlag(StringID::Flag::Binary);
295
flags.setFlag(StringID::Flag::Hashed);
297
StringIDRef sid(new StringID(lastID() + 1, dataID._data, flags));
298
return {insert(sid)};
301
StringIDRef StringHasher::getID(const Data::MappedName& name, const QVector<StringIDRef>& sids)
304
tempID._postfix = name.postfixBytes();
306
Data::IndexedName indexed;
307
if (tempID._postfix.size() != 0) {
308
// Only check for IndexedName if there is postfix, because of the way
309
// we restore the StringID. See StringHasher::saveStream/restoreStreamNew()
310
indexed = Data::IndexedName(name.dataBytes());
313
// If this is an IndexedName, then _data only stores the base part of the name, without the
316
QByteArray::fromRawData(indexed.getType(), static_cast<int>(strlen(indexed.getType())));
319
// Store the entire name in _data, but temporarily re-use the existing memory
320
tempID._data = name.dataBytes();
323
// Check to see if there is already an entry in the hash table for this StringID
324
auto it = _hashes->left.find(&tempID);
325
if (it != _hashes->left.end()) {
326
auto res = StringIDRef(it->first);
328
res._index = indexed.getIndex();
333
if (!indexed && name.isRaw()) {
334
// Make a copy of the memory if we didn't do so earlier
335
tempID._data = QByteArray(name.dataBytes().constData(), name.dataBytes().size());
338
// If the postfix is not already encoded, use getID to encode it:
339
StringIDRef postfixRef;
340
if ((tempID._postfix.size() != 0) && tempID._postfix.indexOf("#") < 0) {
341
postfixRef = getID(tempID._postfix);
342
postfixRef.toBytes(tempID._postfix);
345
// If _data is an IndexedName, use getID to encode it:
346
StringIDRef indexRef;
348
indexRef = getID(tempID._data);
351
// The real StringID object that we are going to insert
352
StringIDRef newStringIDRef(new StringID(lastID() + 1, tempID._data));
353
StringID& newStringID = *newStringIDRef._sid;
354
if (tempID._postfix.size() != 0) {
355
newStringID._flags.setFlag(StringID::Flag::Postfixed);
356
newStringID._postfix = tempID._postfix;
359
// Count the related SIDs that use this hasher
361
for (const auto& relatedID : sids) {
362
if (relatedID && relatedID._sid->_hasher == this) {
367
int numAddedSIDs = (postfixRef ? 1 : 0) + (indexRef ? 1 : 0);
368
if (numSIDs == sids.size() && !postfixRef && !indexRef) {
369
// The simplest case: just copy the whole list
370
newStringID._sids = sids;
373
// Put the added SIDs at the front of the SID list
374
newStringID._sids.reserve(numSIDs + numAddedSIDs);
376
newStringID._flags.setFlag(StringID::Flag::PostfixEncoded);
377
newStringID._sids.push_back(postfixRef);
380
newStringID._flags.setFlag(StringID::Flag::Indexed);
381
newStringID._sids.push_back(indexRef);
383
// Append the sids from the input list whose hasher is this one
384
for (const auto& relatedID : sids) {
385
if (relatedID && relatedID._sid->_hasher == this) {
386
newStringID._sids.push_back(relatedID);
391
// If the number of related IDs is larger than some threshold (hardcoded to 10 right now), then
392
// remove any duplicates (ignoring the new SIDs we may have just added)
393
const int relatedIDSizeThreshold {10};
394
if (newStringID._sids.size() > relatedIDSizeThreshold) {
395
std::sort(newStringID._sids.begin() + numAddedSIDs, newStringID._sids.end());
396
newStringID._sids.erase(
397
std::unique(newStringID._sids.begin() + numAddedSIDs, newStringID._sids.end()),
398
newStringID._sids.end());
401
// If the new StringID has a postfix, but is not indexed, see if the data string itself
402
// contains an index.
403
if ((newStringID._postfix.size() != 0) && !indexed) {
404
// Use the fromString function to parse the new StringID's data field for a possible index
405
StringID::IndexID res = StringID::fromString(newStringID._data);
406
if (res.id > 0) {// If the data had an index
407
if (res.index != 0) {
408
indexed.setIndex(res.index);
409
newStringID._data.resize(newStringID._data.lastIndexOf(':')+1);
411
int offset = newStringID.isPostfixEncoded() ? 1 : 0;
412
// Search for the SID with that index
413
for (int i = offset; i < newStringID._sids.size(); ++i) {
414
if (newStringID._sids[i].value() == res.id) {
416
// If this SID is not already the first element in sids, move it there by
417
// swapping it with whatever WAS there
418
std::swap(newStringID._sids[offset], newStringID._sids[i]);
420
if (res.index != 0) {
421
newStringID._flags.setFlag(StringID::Flag::PrefixIDIndex);
424
newStringID._flags.setFlag(StringID::Flag::PrefixID);
432
return {insert(newStringIDRef), indexed.getIndex()};
435
StringIDRef StringHasher::getID(long id, int index) const
440
auto it = _hashes->right.find(id);
441
if (it == _hashes->right.end()) {
444
StringIDRef res(it->second);
449
void StringHasher::setPersistenceFileName(const char* filename) const
454
_filename = filename;
457
const std::string& StringHasher::getPersistenceFileName() const
462
void StringHasher::Save(Base::Writer& writer) const
466
if (_hashes->SaveAll) {
467
count = _hashes->size();
471
for (auto& hasher : _hashes->right) {
472
if (hasher.second->isMarked() || hasher.second->isPersistent()) {
478
writer.Stream() << writer.ind() << "<StringHasher saveall=\"" << _hashes->SaveAll
479
<< "\" threshold=\"" << _hashes->Threshold << "\"";
482
writer.Stream() << " count=\"0\"></StringHasher>\n";
486
writer.Stream() << " count=\"0\" new=\"1\"/>\n";
488
writer.Stream() << writer.ind() << "<StringHasher2 ";
489
if (!_filename.empty()) {
490
writer.Stream() << " file=\"" << writer.addFile((_filename + ".txt").c_str(), this)
495
writer.Stream() << " count=\"" << count << "\">\n";
496
saveStream(writer.beginCharStream() << '\n');
497
writer.endCharStream() << '\n';
498
writer.Stream() << writer.ind() << "</StringHasher2>\n";
501
void StringHasher::SaveDocFile(Base::Writer& writer) const
503
std::size_t count = _hashes->SaveAll ? this->size() : this->count();
504
writer.Stream() << "StringTableStart v1 " << count << '\n';
505
saveStream(writer.Stream());
508
void StringHasher::saveStream(std::ostream& stream) const
510
boost::io::ios_flags_saver ifs(stream);
514
const StringID* last = nullptr;
516
bool relative = false;
518
for (auto& hasher : _hashes->right) {
519
auto& d = *hasher.second;
521
if (!_hashes->SaveAll && !d.isMarked() && !d.isPersistent()) {
525
// We use relative coding to save space. But in order to have some
526
// minimum protection against corruption, write an absolute value every
528
relative = (id - anchor) < 1000;
530
stream << '-' << id - lastID;
538
int offset = d.isPostfixEncoded() ? 1 : 0;
540
StringID::IndexID prefixID {};
543
if (d.isPrefixID()) {
544
assert(d._sids.size() > offset);
545
prefixID.id = d._sids[offset].value();
547
else if (d.isPrefixIDIndex()) {
548
prefixID = StringID::fromString(d._data);
549
assert(d._sids.size() > offset && d._sids[offset].value() == prefixID.id);
552
auto flags = d._flags;
553
flags.setFlag(StringID::Flag::Marked, false);
554
stream << '.' << flags.toUnderlyingType();
558
for (; position < d._sids.size(); ++position) {
559
stream << '.' << d._sids[position].value();
564
for (; position < d._sids.size() && position < last->_sids.size(); ++position) {
565
long m = last->_sids[position].value();
566
long n = d._sids[position].value();
568
stream << ".-" << m - n;
571
stream << '.' << n - m;
575
for (; position < d._sids.size(); ++position) {
576
stream << '.' << id - d._sids[position].value();
582
// Having postfix means it is a geometry element name, which
583
// guarantees to be a single line without space. So it is safe to
584
// store in raw stream.
585
if (d.isPostfixed()) {
586
if (!d.isPrefixIDIndex() && !d.isIndexed() && !d.isPrefixID()) {
587
stream << ' ' << d._data.constData();
590
if (!d.isPostfixEncoded()) {
591
stream << ' ' << d._postfix.constData();
596
// Reaching here means the string may contain space and newlines
598
stream << std::dec << d._data.constData() << std::hex;
603
void StringHasher::RestoreDocFile(Base::Reader& reader)
608
std::size_t count = 0;
610
if (marker == "StringTableStart") {
611
reader >> ver >> count;
613
FC_WARN("Unknown string table format");
615
restoreStreamNew(reader, count);
618
count = atoi(marker.c_str());
619
restoreStream(reader, count);
622
void StringHasher::restoreStreamNew(std::istream& stream, std::size_t count)
624
Base::TextInputStream asciiStream (stream);
627
boost::io::ios_flags_saver ifs(stream);
629
std::vector<std::string> tokens;
631
const StringID* last = nullptr;
635
for (uint32_t i = 0; i < count; ++i) {
636
if (!(stream >> tmp)) {
637
FC_THROWM(Base::RuntimeError, "Invalid string table");
641
boost::split(tokens, tmp, boost::is_any_of("."));
642
if (tokens.size() < 2) {
643
FC_THROWM(Base::RuntimeError, "Invalid string table");
647
bool relative = false;
648
if (tokens[0][0] == '-') {
650
id = lastid + strtol(tokens[0].c_str() + 1, nullptr, 16);
653
id = strtol(tokens[0].c_str(), nullptr, 16);
658
unsigned long flag = strtol(tokens[1].c_str(), nullptr, 16);
659
StringIDRef sid(new StringID(id, QByteArray(), static_cast<StringID::Flag>(flag)));
661
StringID& d = *sid._sid;
662
d._sids.reserve(tokens.size() - 2);
665
if (relative && last) {
666
for (; j < (int)tokens.size() && j - 2 < last->_sids.size(); ++j) {
667
long m = last->_sids[j - 2].value();
669
if (tokens[j][0] == '-') {
670
n = -strtol(&tokens[j][1], nullptr, 16);
673
n = strtol(&tokens[j][0], nullptr, 16);
675
StringIDRef sid = getID(m + n);
677
FC_THROWM(Base::RuntimeError, "Invalid string id reference");
679
d._sids.push_back(sid);
682
for (; j < (int)tokens.size(); ++j) {
683
long n = strtol(tokens[j].data(), nullptr, 16);
684
StringIDRef sid = getID(relative ? id - n : n);
686
FC_THROWM(Base::RuntimeError, "Invalid string id reference");
688
d._sids.push_back(sid);
691
if (!d.isPostfixed()) {
692
asciiStream >> content;
693
if (d.isHashed() || d.isBinary()) {
694
d._data = QByteArray::fromBase64(content.c_str());
697
d._data = content.c_str();
702
if (d.isPostfixEncoded()) {
704
if (d._sids.empty()) {
705
FC_THROWM(Base::RuntimeError, "Missing string postfix");
707
d._postfix = d._sids[0]._sid->_data;
710
if (d._sids.size() <= offset) {
711
FC_THROWM(Base::RuntimeError, "Missing string prefix");
713
d._data = d._sids[offset]._sid->_data;
715
else if (d.isPrefixID() || d.isPrefixIDIndex()) {
716
if (d._sids.size() <= offset) {
717
FC_THROWM(Base::RuntimeError, "Missing string prefix id");
719
d._data = d._sids[offset]._sid->toString(0).c_str();
720
if (d.isPrefixIDIndex())
725
d._data = content.c_str();
727
if (!d.isPostfixEncoded()) {
729
d._postfix = content.c_str();
737
StringID* StringHasher::insert(const StringIDRef& sid)
739
assert(sid && sid._sid->_hasher == nullptr);
740
auto& hasher = *sid._sid;
741
hasher._hasher = this;
743
auto res = _hashes->right.insert(_hashes->right.end(),
744
HashMap::right_map::value_type(sid.value(), &hasher));
745
if (res->second != &hasher) {
746
hasher._hasher = nullptr;
752
void StringHasher::restoreStream(std::istream& stream, std::size_t count)
756
for (uint32_t i = 0; i < count; ++i) {
759
stream >> id >> type >> content;
760
StringIDRef sid = new StringID(id, QByteArray(), static_cast<StringID::Flag>(type));
761
if (sid.isHashed() || sid.isBinary()) {
762
sid._sid->_data = QByteArray::fromBase64(content.c_str());
765
sid._sid->_data = QByteArray(content.c_str());
771
void StringHasher::clear()
773
for (auto& hasher : _hashes->right) {
774
hasher.second->_hasher = nullptr;
775
hasher.second->unref();
780
size_t StringHasher::size() const
782
return _hashes->size();
785
size_t StringHasher::count() const
788
for (auto& hasher : _hashes->right) {
789
if (hasher.second->getRefCount() > 1) {
796
void StringHasher::Restore(Base::XMLReader& reader)
799
reader.readElement("StringHasher");
800
_hashes->SaveAll = reader.getAttributeAsInteger("saveall") != 0L;
801
_hashes->Threshold = static_cast<int>(reader.getAttributeAsInteger("threshold"));
804
if (reader.hasAttribute("new") && reader.getAttributeAsInteger("new") > 0) {
805
reader.readElement("StringHasher2");
809
if (reader.hasAttribute("file")) {
810
const char* file = reader.getAttribute("file");
812
reader.addFile(file, this);
817
std::size_t count = reader.getAttributeAsUnsigned("count");
820
restoreStreamNew(reader.beginCharStream(), count);
821
} catch (const Base::Exception &e) {
823
FC_ERR("Failed to restore string table: full-document recompute strongly recommended.");
825
reader.readEndElement("StringHasher2");
828
if ((count != 0U) && reader.FileVersion > 1) {
829
restoreStream(reader.beginCharStream(), count);
832
for (std::size_t i = 0; i < count; ++i) {
833
reader.readElement("Item");
835
long id = reader.getAttributeAsInteger("id");
836
bool hashed = reader.hasAttribute("hash");
837
if (hashed || reader.hasAttribute("data")) {
839
hashed ? reader.getAttribute("hash") : reader.getAttribute("data");
840
sid = new StringID(id, QByteArray::fromBase64(value), StringID::Flag::Hashed);
843
sid = new StringID(id, QByteArray(reader.getAttribute("text")));
848
reader.readEndElement("StringHasher");
851
unsigned int StringHasher::getMemSize() const
853
return (_hashes->SaveAll ? size() : count()) * 10;
856
PyObject* StringHasher::getPyObject()
858
return new StringHasherPy(this);
861
std::map<long, StringIDRef> StringHasher::getIDMap() const
863
std::map<long, StringIDRef> ret;
864
for (auto& hasher : _hashes->right) {
865
ret.emplace_hint(ret.end(), hasher.first, StringIDRef(hasher.second));
870
void StringHasher::clearMarks() const
872
for (auto& hasher : _hashes->right) {
873
hasher.second->_flags.setFlag(StringID::Flag::Marked, false);