File size: 22,491 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// SPDX-License-Identifier: LGPL-2.1-or-later

/****************************************************************************

 *                                                                          *

 *   Copyright (c) 2002 Jürgen Riegel <juergen.riegel@web.de>               *

 *   Copyright (c) 2022 Zheng, Lei <realthunder.dev@gmail.com>              *

 *   Copyright (c) 2023 FreeCAD Project Association                         *

 *                                                                          *

 *   This file is part of FreeCAD.                                          *

 *                                                                          *

 *   FreeCAD is free software: you can redistribute it and/or modify it     *

 *   under the terms of the GNU Lesser General Public License as            *

 *   published by the Free Software Foundation, either version 2.1 of the   *

 *   License, or (at your option) any later version.                        *

 *                                                                          *

 *   FreeCAD is distributed in the hope that it will be useful, but         *

 *   WITHOUT ANY WARRANTY; without even the implied warranty of             *

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU       *

 *   Lesser General Public License for more details.                        *

 *                                                                          *

 *   You should have received a copy of the GNU Lesser General Public       *

 *   License along with FreeCAD. If not, see                                *

 *   <https://www.gnu.org/licenses/>.                                       *

 *                                                                          *

 ***************************************************************************/

#include <cstdlib>
#include <limits>

#include <boost/regex.hpp>

#include "ComplexGeoData.h"
#include "ElementMap.h"
#include "ElementNamingUtils.h"

#include <Base/BoundBox.h>
#include <Base/Placement.h>
#include <Base/Reader.h>
#include <Base/Rotation.h>
#include <Base/Writer.h>

#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>


using namespace Data;

TYPESYSTEM_SOURCE_ABSTRACT(Data::Segment, Base::BaseClass)           // NOLINT
TYPESYSTEM_SOURCE_ABSTRACT(Data::ComplexGeoData, Base::Persistence)  // NOLINT

FC_LOG_LEVEL_INIT("ComplexGeoData", true, true)  // NOLINT

namespace bio = boost::iostreams;
using namespace Data;

// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic)

ComplexGeoData::ComplexGeoData() = default;

std::pair<std::string, unsigned long> ComplexGeoData::getTypeAndIndex(const char* Name)

{
    int index = 0;
    std::string element;
    boost::regex ex("^([^0-9]*)([0-9]*)$");
    boost::cmatch what;

    if (Name && boost::regex_match(Name, what, ex)) {
        element = what[1].str();
        index = std::atoi(what[2].str().c_str());
    }

    return std::make_pair(element, index);
}

Data::Segment* ComplexGeoData::getSubElementByName(const char* name) const

{
    auto type = getTypeAndIndex(name);
    return getSubElement(type.first.c_str(), type.second);
}

void ComplexGeoData::applyTransform(const Base::Matrix4D& rclTrf)

{
    setTransform(rclTrf * getTransform());
}

void ComplexGeoData::applyTranslation(const Base::Vector3d& mov)

{
    Base::Matrix4D mat;
    mat.move(mov);
    setTransform(mat * getTransform());
}

void ComplexGeoData::applyRotation(const Base::Rotation& rot)

{
    Base::Matrix4D mat;
    rot.getValue(mat);
    setTransform(mat * getTransform());
}

void ComplexGeoData::setPlacement(const Base::Placement& rclPlacement)

{
    setTransform(rclPlacement.toMatrix());
}

Base::Placement ComplexGeoData::getPlacement() const

{
    Base::Matrix4D mat = getTransform();

    return {Base::Vector3d(mat[0][3], mat[1][3], mat[2][3]), Base::Rotation(mat)};
}

double ComplexGeoData::getAccuracy() const

{
    return 0.0;
}

void ComplexGeoData::getLinesFromSubElement(const Segment* segment,

                                            std::vector<Base::Vector3d>& Points,

                                            std::vector<Line>& lines) const

{
    (void)segment;
    (void)Points;
    (void)lines;
}

void ComplexGeoData::getFacesFromSubElement(const Segment* segment,

                                            std::vector<Base::Vector3d>& Points,

                                            std::vector<Base::Vector3d>& PointNormals,

                                            std::vector<Facet>& faces) const

{
    (void)segment;
    (void)Points;
    (void)PointNormals;
    (void)faces;
}

Base::Vector3d ComplexGeoData::getPointFromLineIntersection(const Base::Vector3f& base,

                                                            const Base::Vector3f& dir) const

{
    (void)base;
    (void)dir;
    return Base::Vector3d();
}

void ComplexGeoData::getPoints(std::vector<Base::Vector3d>& Points,

                               std::vector<Base::Vector3d>& Normals,

                               double Accuracy,

                               uint16_t flags) const

{
    (void)Points;
    (void)Normals;
    (void)Accuracy;
    (void)flags;
}

void ComplexGeoData::getLines(std::vector<Base::Vector3d>& Points,

                              std::vector<Line>& lines,

                              double Accuracy,

                              uint16_t flags) const

{
    (void)Points;
    (void)lines;
    (void)Accuracy;
    (void)flags;
}

void ComplexGeoData::getFaces(std::vector<Base::Vector3d>& Points,

                              std::vector<Facet>& faces,

                              double Accuracy,

                              uint16_t flags) const

{
    (void)Points;
    (void)faces;
    (void)Accuracy;
    (void)flags;
}

bool ComplexGeoData::getCenterOfGravity(Base::Vector3d& unused) const

{
    (void)unused;
    return false;
}

std::optional<Base::Vector3d> ComplexGeoData::centerOfGravity() const

{
    Base::Vector3d centerOfGravity;

    if (getCenterOfGravity(centerOfGravity)) {
        return centerOfGravity;
    }

    return {};
}

const std::string& ComplexGeoData::elementMapPrefix()

{
    static std::string prefix(ELEMENT_MAP_PREFIX);
    return prefix;
}

std::string ComplexGeoData::getElementMapVersion() const

{
    return "5";
}

bool ComplexGeoData::checkElementMapVersion(const char* ver) const

{
    return !boost::ends_with(ver, "5");
}

size_t ComplexGeoData::getElementMapSize(bool flush) const

{
    if (flush) {
        flushElementMap();
#ifdef _FC_MEM_TRACE
        FC_MSG("memory size " << (_MemSize / 1024 / 1024) << "MB, " << (_MemMaxSize / 1024 / 1024));
        for (auto& unit : _MemUnits) {
            FC_MSG("unit " << unit.first << ": " << unit.second.count << ", "
                           << unit.second.maxcount);
        }
#endif
    }
    return _elementMap ? _elementMap->size() : 0;
}

MappedName ComplexGeoData::getMappedName(const IndexedName& element,

                                         bool allowUnmapped,

                                         ElementIDRefs* sid) const

{
    if (!element) {
        return {};
    }
    flushElementMap();
    if (!_elementMap) {
        if (allowUnmapped) {
            return MappedName(element);
        }
        return {};
    }

    MappedName name = _elementMap->find(element, sid);
    if (allowUnmapped && !name) {
        return MappedName(element);
    }
    return name;
}

IndexedName ComplexGeoData::getIndexedName(const MappedName& name, ElementIDRefs* sid) const

{
    flushElementMap();
    if (!name) {
        return IndexedName();
    }
    if (!_elementMap) {
        std::string str;
        return {name.appendToBuffer(str), getElementTypes()};
    }
    return _elementMap->find(name, sid);
}

Data::MappedElement

ComplexGeoData::getElementName(const char* name, ElementIDRefs* sid, bool copy) const

{
    IndexedName element(name, getElementTypes());
    if (element) {
        return {getMappedName(element, false, sid), element};
    }

    const char* mapped = isMappedElement(name);
    if (mapped) {
        name = mapped;
    }

    MappedElement result;
    // Strip out the trailing '.XXXX' if any
    const char* dot = strchr(name, '.');
    if (dot) {
        result.name = MappedName(name, static_cast<int>(dot - name));
    }
    else if (copy) {
        result.name = name;
    }
    else {
        result.name = MappedName(name);
    }
    result.index = getIndexedName(result.name, sid);
    return result;
}

std::vector<std::pair<MappedName, ElementIDRefs>>
ComplexGeoData::getElementMappedNames(const IndexedName& element, bool needUnmapped) const
{
    flushElementMap();
    if (_elementMap) {
        auto res = _elementMap->findAll(element);
        if (!res.empty()) {
            return res;
        }
    }

    if (!needUnmapped) {
        return {};
    }
    return {std::make_pair(MappedName(element), ElementIDRefs())};
}

ElementMapPtr ComplexGeoData::resetElementMap(ElementMapPtr elementMap)

{
    _elementMap.swap(elementMap);
    // We expect that if the ComplexGeoData ( TopoShape ) has a hasher, then its elementMap will
    // have the same one.  Make sure that happens.
    if (_elementMap && !_elementMap->hasher) {
        _elementMap->hasher = Hasher;
    }
    return elementMap;
}

std::vector<MappedElement> ComplexGeoData::getElementMap() const

{
    flushElementMap();
    if (!_elementMap) {
        return {};
    }
    return _elementMap->getAll();
}

ElementMapPtr ComplexGeoData::elementMap(bool flush) const

{
    if (flush) {
        flushElementMap();
    }
    return _elementMap;
}

ElementMapPtr ComplexGeoData::ensureElementMap(bool flush)

{
    if (!_elementMap) {
        resetElementMap(std::make_shared<Data::ElementMap>());
    }
    return elementMap(flush);
}

void ComplexGeoData::flushElementMap() const

{}

void ComplexGeoData::setElementMap(const std::vector<MappedElement>& map)

{
    _elementMap = std::make_shared<Data::ElementMap>();  // Get rid of the old one, if any, but make
                                                         // sure the memory exists for the new data.
    for (auto& element : map) {
        _elementMap->setElementName(element.index, element.name, Tag);
    }
}

char ComplexGeoData::elementType(const Data::MappedName& name) const

{
    if (!name) {
        return 0;
    }
    auto indexedName = getIndexedName(name);
    if (indexedName) {
        return elementType(indexedName);
    }
    char element_type = 0;
    if (name.findTagInElementName(nullptr, nullptr, nullptr, &element_type) < 0) {
        return elementType(name.toIndexedName());
    }
    return element_type;
}

char ComplexGeoData::elementType(const Data::IndexedName& element) const

{
    if (!element) {
        return 0;
    }
    for (auto& type : getElementTypes()) {
        if (boost::equals(element.getType(), type)) {
            return type[0];
        }
    }
    return 0;
}

// The elementType function can take a char *, in which case it tries a sequence of checks to
// see what it got.
// 1) Check to see if it is an indexedName, and if so directly look up the type
// 2) If not:
//    a) Remove any element map prefix that is present
//    b) See if the name contains a dot:
//        i)  If yes, create a MappedName from the part before the dot, and set the type to the
//            part after the dot
//        ii) If no, create a MappedName from the whole name
//    c) Try to get the elementType based on the MappedName. Return it if found
// 3) Check to make sure the discovered type is in the list of types, and return its first
//    character if so.
char ComplexGeoData::elementType(const char* name) const

{
    if (!name) {
        return 0;
    }

    const char* type = nullptr;
    IndexedName element(name, getElementTypes());
    if (element) {
        type = element.getType();
    }
    else {
        const char* mapped = isMappedElement(name);
        if (mapped) {
            name = mapped;
        }

        MappedName mappedName;
        const char* dot = strchr(name, '.');
        if (dot) {
            mappedName = MappedName(name, static_cast<int>(dot - name));
            type = dot + 1;
        }
        else {
            mappedName = MappedName::fromRawData(name);
        }
        char res = elementType(mappedName);
        if (res != 0) {
            return res;
        }
    }

    if (type && (type[0] != 0)) {
        for (auto& elementTypes : getElementTypes()) {
            if (boost::starts_with(type, elementTypes)) {
                return type[0];
            }
        }
    }
    return 0;
}

void ComplexGeoData::setPersistenceFileName(const char* filename) const

{
    if (!filename) {
        filename = "";
    }
    _persistenceName = filename;
}

void ComplexGeoData::Save(Base::Writer& writer) const

{

    if (getElementMapSize() == 0U) {
        writer.Stream() << writer.ind() << "<ElementMap/>\n";
        return;
    }

    // Store some dummy map entry to trigger recompute in older version.
    writer.Stream() << writer.ind() << R"(<ElementMap new="1" count="1">)"
                    << R"(<Element key="Dummy" value="Dummy"/>)"
                    << "</ElementMap>\n";

    // New layout of element map, so we use new xml tag, ElementMap2
    writer.Stream() << writer.ind() << "<ElementMap2";

    if (!_persistenceName.empty()) {
        writer.Stream() << " file=\"" << writer.addFile((_persistenceName + ".txt").c_str(), this)
                        << "\"/>\n";
        return;
    }
    writer.Stream() << " count=\"" << _elementMap->size() << "\">\n";
    _elementMap->save(writer.beginCharStream(Base::CharStreamFormat::Raw) << '\n');
    writer.endCharStream() << '\n';
    writer.Stream() << writer.ind() << "</ElementMap2>\n";
}

void ComplexGeoData::Restore(Base::XMLReader& reader)

{
    resetElementMap();

    reader.readElement("ElementMap");
    bool newTag = false;
    if (reader.hasAttribute("new") && reader.getAttribute<bool>("new")) {
        reader.readEndElement("ElementMap");
        reader.readElement("ElementMap2");
        newTag = true;
    }

    const char* file = "";
    if (reader.hasAttribute("file")) {
        file = reader.getAttribute<const char*>("file");
    }
    if (*file != 0) {
        reader.addFile(file, this);
        return;
    }

    std::size_t count = 0;
    if (reader.hasAttribute("count")) {
        count = reader.getAttribute<unsigned long>("count");
    }
    if (count == 0) {
        return;
    }

    if (newTag) {
        resetElementMap(std::make_shared<ElementMap>());
        _elementMap =
            _elementMap->restore(Hasher, reader.beginCharStream(Base::CharStreamFormat::Raw));
        reader.endCharStream();
        reader.readEndElement("ElementMap2");
        return;
    }

    if (reader.FileVersion > 1) {
        restoreStream(reader.beginCharStream(Base::CharStreamFormat::Raw), count);
        reader.endCharStream();
        return;
    }
    readElements(reader, count);
    reader.readEndElement("ElementMap");
}

void ComplexGeoData::readElements(Base::XMLReader& reader, size_t count)

{
    size_t invalid_count = 0;
    bool warned = false;

    const auto& types = getElementTypes();

    for (size_t i = 0; i < count; ++i) {
        reader.readElement("Element");
        ElementIDRefs sids;
        if (reader.hasAttribute("sid")) {
            if (!Hasher) {
                if (!warned) {
                    warned = true;
                    FC_ERR("missing hasher");  // NOLINT
                }
            }
            else {
                const char* attr = reader.getAttribute<const char*>("sid");
                bio::stream<bio::array_source> iss(attr, std::strlen(attr));
                long id {};
                while ((iss >> id)) {
                    if (id == 0) {
                        continue;
                    }
                    auto sid = Hasher->getID(id);
                    if (!sid) {
                        ++invalid_count;
                    }
                    else {
                        sids.push_back(sid);
                    }
                    char sep {};
                    iss >> sep;
                }
            }
        }
        ensureElementMap()->setElementName(IndexedName(reader.getAttribute<const char*>("value"), types),
                                           MappedName(reader.getAttribute<const char*>("key")),
                                           Tag,
                                           &sids);
    }
    if (invalid_count != 0) {
        FC_ERR("Found " << invalid_count << " invalid string id");  // NOLINT
    }
}

void ComplexGeoData::restoreStream(std::istream& stream, std::size_t count)

{
    resetElementMap();

    size_t invalid_count = 0;
    std::string key;
    std::string value;
    std::string sid;
    bool warned = false;

    const auto& types = getElementTypes();
    try {
        for (size_t i = 0; i < count; ++i) {
            ElementIDRefs sids;
            std::size_t sCount = 0;
            if (!(stream >> value >> key >> sCount)) {
                // NOLINTNEXTLINE
                FC_THROWM(Base::RuntimeError, "Failed to restore element map " << _persistenceName);
            }
            constexpr std::size_t oneGbOfInts {(1 << 30) / sizeof(int)};
            if (sCount > oneGbOfInts) {
                // NOLINTNEXTLINE
                FC_THROWM(Base::RuntimeError, "Failed to restore element map (>1GB) " << _persistenceName);
            }
            sids.reserve(static_cast<int>(sCount));
            for (std::size_t j = 0; j < sCount; ++j) {
                long id = 0;
                if (!(stream >> id)) {
                    // NOLINTNEXTLINE
                    FC_THROWM(Base::RuntimeError,
                              "Failed to restore element map " << _persistenceName);
                }
                if (Hasher) {
                    auto hasherSID = Hasher->getID(id);
                    if (!hasherSID) {
                        ++invalid_count;
                    }
                    else {
                        sids.push_back(hasherSID);
                    }
                }
            }
            if (sCount != 0 && !Hasher) {
                sids.clear();
                if (!warned) {
                    warned = true;
                    FC_ERR("missing hasher");  // NOLINT
                }
            }
            _elementMap->setElementName(IndexedName(value.c_str(), types),
                                        MappedName(key),
                                        Tag,
                                        &sids);
        }
    }
    catch (Base::Exception& e) {
        e.reportException();
        _restoreFailed = true;
        _elementMap.reset();
    }
    if (invalid_count != 0) {
        FC_ERR("Found " << invalid_count << " invalid string id");  // NOLINT
    }
}

void ComplexGeoData::SaveDocFile(Base::Writer& writer) const

{
    flushElementMap();
    if (_elementMap) {
        writer.Stream() << "BeginElementMap v1\n";
        _elementMap->save(writer.Stream());
    }
}

void ComplexGeoData::RestoreDocFile(Base::Reader& reader)

{
    std::string marker;
    std::string ver;
    reader >> marker;
    if (boost::equals(marker, "BeginElementMap")) {
        resetElementMap();
        reader >> ver;
        if (ver != "v1") {
            FC_WARN("Unknown element map format");  // NOLINT
        }
        else {
            resetElementMap(std::make_shared<ElementMap>());
            _elementMap = _elementMap->restore(Hasher, reader);
            return;
        }
    }
    auto count = atoll(marker.c_str());  // Try to prevent UB if the number is unreasonably large
    if (count < 0 || count > std::numeric_limits<int>::max()) {
        FC_THROWM(Base::RuntimeError, "Failed to restore element map " << _persistenceName);
    }
    restoreStream(reader, static_cast<std::size_t>(count));
}

unsigned int ComplexGeoData::getMemSize() const

{
    flushElementMap();
    if (_elementMap) {
        static const int multiplier {10};
        return _elementMap->size() * multiplier;
    }
    return 0;
}

std::vector<IndexedName> ComplexGeoData::getHigherElements(const char*, bool) const

{
    return {};
}

void ComplexGeoData::setMappedChildElements(

    const std::vector<Data::ElementMap::MappedChildElements>& children)

{
    // DO NOT reset element map if there is one. Because we allow mixing child
    // mapping and normal mapping
    if (!_elementMap) {
        resetElementMap(std::make_shared<Data::ElementMap>());
    }
    _elementMap->addChildElements(Tag, children);
}

std::vector<Data::ElementMap::MappedChildElements> ComplexGeoData::getMappedChildElements() const

{
    if (!_elementMap) {
        return {};
    }
    return _elementMap->getChildElements();
}

void ComplexGeoData::beforeSave() const

{
    flushElementMap();
    if (this->_elementMap) {
        this->_elementMap->beforeSave(Hasher);
    }
}

void ComplexGeoData::hashChildMaps()

{
    flushElementMap();
    if (_elementMap) {
        _elementMap->hashChildMaps(Tag);
    }
}

bool ComplexGeoData::hasChildElementMap() const

{
    flushElementMap();
    return _elementMap && _elementMap->hasChildElementMap();
}

void ComplexGeoData::dumpElementMap(std::ostream& stream) const

{
    auto map = getElementMap();
    std::sort(map.begin(), map.end());
    for (auto& element : map) {
        stream << element.index << " : " << element.name << std::endl;
    }
}

const std::string ComplexGeoData::dumpElementMap() const

{
    std::stringstream ss;
    dumpElementMap(ss);
    return ss.str();
}

// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic)