smallstring.h 24.3 KB
Newer Older
Marco Bubke's avatar
Marco Bubke committed
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
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#pragma once

#include "utils_global.h"

#include "smallstringliteral.h"
#include "smallstringiterator.h"
#include "smallstringview.h"
#include "smallstringmemory.h"

#include <QByteArray>
#include <QString>

#include <algorithm>
39
#include <cmath>
Marco Bubke's avatar
Marco Bubke committed
40 41 42
#include <cstdlib>
#include <climits>
#include <cstring>
43
#include <string>
Marco Bubke's avatar
Marco Bubke committed
44
#include <unordered_map>
Marco Bubke's avatar
Marco Bubke committed
45
#include <utility>
46
#include <vector>
Marco Bubke's avatar
Marco Bubke committed
47 48

#ifdef UNIT_TESTS
49
#define unitttest_public public
Marco Bubke's avatar
Marco Bubke committed
50
#else
51
#define unitttest_public private
Marco Bubke's avatar
Marco Bubke committed
52 53 54 55
#endif

namespace Utils {

56 57
template<uint Size>
class BasicSmallString
Marco Bubke's avatar
Marco Bubke committed
58 59 60 61 62 63 64 65
{
public:
    using iterator = Internal::SmallStringIterator<std::random_access_iterator_tag, char>;
    using const_iterator = Internal::SmallStringIterator<std::random_access_iterator_tag, const char>;
    using reverse_iterator = std::reverse_iterator<iterator>;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;
    using size_type = std::size_t;

66 67
    BasicSmallString() noexcept
        : m_data(Internal::StringDataLayout<Size>())
Marco Bubke's avatar
Marco Bubke committed
68 69 70 71
    {
    }

    constexpr
72
    BasicSmallString(const BasicSmallStringLiteral<Size> &stringReference)
Marco Bubke's avatar
Marco Bubke committed
73 74 75 76
        : m_data(stringReference.m_data)
    {
    }

77
    template<size_type ArraySize>
Marco Bubke's avatar
Marco Bubke committed
78
    constexpr
79
    BasicSmallString(const char(&string)[ArraySize])
Marco Bubke's avatar
Marco Bubke committed
80 81 82 83
        : m_data(string)
    {
    }

84
    BasicSmallString(const char *string, size_type size, size_type capacity)
Marco Bubke's avatar
Marco Bubke committed
85 86 87 88 89
    {
        if (Q_LIKELY(capacity <= shortStringCapacity())) {
            std::memcpy(m_data.shortString.string, string, size);
            m_data.shortString.string[size] = 0;
            m_data.shortString.shortStringSize = uchar(size);
90
            m_data.shortString.isReference = false;
91
            m_data.shortString.isReadOnlyReference = false;
Marco Bubke's avatar
Marco Bubke committed
92 93 94
        } else {
            m_data.allocated.data.pointer = Memory::allocate(capacity + 1);
            std::memcpy(m_data.allocated.data.pointer, string, size);
95
            initializeLongString(size, capacity);
Marco Bubke's avatar
Marco Bubke committed
96 97 98
        }
    }

99 100 101 102 103
    explicit BasicSmallString(SmallStringView stringView)
        : BasicSmallString(stringView.data(), stringView.size(), stringView.size())
    {
    }

104 105
    BasicSmallString(const char *string, size_type size)
        : BasicSmallString(string, size, size)
Marco Bubke's avatar
Marco Bubke committed
106 107 108
    {
    }

109 110 111
    template<typename Type,
             typename = typename std::enable_if<std::is_pointer<Type>::value>::type
             >
112 113
    BasicSmallString(Type characterPointer)
        : BasicSmallString(characterPointer, std::strlen(characterPointer))
114 115 116 117
    {
        static_assert(!std::is_array<Type>::value, "Input type is array and not char pointer!");
    }

118 119
    BasicSmallString(const QString &qString)
        : BasicSmallString(BasicSmallString::fromQString(qString))
Marco Bubke's avatar
Marco Bubke committed
120 121
    {}

122 123 124
    template<typename Type,
             typename = typename std::enable_if<
                 std::is_same<typename std::decay<Type>::type, std::string>::value>::type>
125 126
    BasicSmallString(Type &&string)
        : BasicSmallString(string.data(), string.size())
127 128
    {}

129 130 131 132
    template<typename BeginIterator,
             typename EndIterator,
             typename = typename std::enable_if<std::is_same<BeginIterator, EndIterator>::value>::type
             >
133 134
    BasicSmallString(BeginIterator begin, EndIterator end)
        : BasicSmallString(&(*begin), size_type(end - begin))
135 136 137 138
    {
    }


139
    ~BasicSmallString() noexcept
Marco Bubke's avatar
Marco Bubke committed
140 141 142 143 144
    {
        if (Q_UNLIKELY(hasAllocatedMemory()))
            Memory::deallocate(m_data.allocated.data.pointer);
    }

145
    BasicSmallString(const BasicSmallString &string)
Marco Bubke's avatar
Marco Bubke committed
146
    {
147
        if (string.isShortString() || string.isReadOnlyReference())
Marco Bubke's avatar
Marco Bubke committed
148 149
            m_data = string.m_data;
        else
150
            new (this) BasicSmallString{string.data(), string.size()};
Marco Bubke's avatar
Marco Bubke committed
151 152
    }

153
    BasicSmallString &operator=(const BasicSmallString &other)
Marco Bubke's avatar
Marco Bubke committed
154
    {
155
        BasicSmallString copy = other;
Marco Bubke's avatar
Marco Bubke committed
156 157 158 159 160 161

        swap(*this, copy);

        return *this;
    }

162
    BasicSmallString(BasicSmallString &&other) noexcept
Marco Bubke's avatar
Marco Bubke committed
163 164
    {
        m_data = other.m_data;
165
        other.m_data = Internal::StringDataLayout<Size>();
Marco Bubke's avatar
Marco Bubke committed
166 167
    }

168
    BasicSmallString &operator=(BasicSmallString &&other) noexcept
Marco Bubke's avatar
Marco Bubke committed
169 170 171 172 173 174
    {
        swap(*this, other);

        return *this;
    }

175
    BasicSmallString clone() const
Marco Bubke's avatar
Marco Bubke committed
176
    {
177
        BasicSmallString clonedString(m_data);
Marco Bubke's avatar
Marco Bubke committed
178 179

        if (Q_UNLIKELY(hasAllocatedMemory()))
180
            new (&clonedString) BasicSmallString{m_data.allocated.data.pointer, m_data.allocated.data.size};
Marco Bubke's avatar
Marco Bubke committed
181 182 183 184 185

        return clonedString;
    }

    friend
186
    void swap(BasicSmallString &first, BasicSmallString &second)
Marco Bubke's avatar
Marco Bubke committed
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
    {
        using std::swap;

        swap(first.m_data, second.m_data);
    }

    QByteArray toQByteArray() const noexcept
    {
        return QByteArray(data(), int(size()));
    }

    QString toQString() const
    {
        return QString::fromUtf8(data(), int(size()));
    }

    operator SmallStringView() const
    {
        return SmallStringView(data(), size());
    }

    operator QString() const
    {
        return toQString();
    }

213 214 215 216 217
    operator std::string() const
    {
        return std::string(data(), size());
    }

Marco Bubke's avatar
Marco Bubke committed
218
    static
219
    BasicSmallString fromUtf8(const char *characterPointer)
Marco Bubke's avatar
Marco Bubke committed
220
    {
221
        return BasicSmallString(characterPointer, std::strlen(characterPointer));
Marco Bubke's avatar
Marco Bubke committed
222 223 224 225 226 227 228 229 230 231 232
    }

    void reserve(size_type newCapacity)
    {
        if (fitsNotInCapacity(newCapacity)) {
            if (Q_UNLIKELY(hasAllocatedMemory())) {
                m_data.allocated.data.pointer = Memory::reallocate(m_data.allocated.data.pointer,
                                                               newCapacity + 1);
                m_data.allocated.data.capacity = newCapacity;
            } else {
                const size_type oldSize = size();
233
                newCapacity = std::max(newCapacity, oldSize);
234
                const char *oldData = data();
Marco Bubke's avatar
Marco Bubke committed
235

236 237 238 239
                char *newData = Memory::allocate(newCapacity + 1);
                std::memcpy(newData, oldData, oldSize);
                m_data.allocated.data.pointer = newData;
                initializeLongString(oldSize, newCapacity);
Marco Bubke's avatar
Marco Bubke committed
240 241 242 243 244 245 246 247 248 249 250 251 252
            }
        }
    }

    void resize(size_type newSize)
    {
        reserve(newSize);
        setSize(newSize);
        at(newSize) = 0;
    }

    void clear() noexcept
    {
253 254
        this->~BasicSmallString();
        m_data = Internal::StringDataLayout<Size>();
Marco Bubke's avatar
Marco Bubke committed
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
    }

    char *data() noexcept
    {
        return Q_LIKELY(isShortString()) ? m_data.shortString.string : m_data.allocated.data.pointer;
    }

    const char *data() const noexcept
    {
        return Q_LIKELY(isShortString()) ? m_data.shortString.string : m_data.allocated.data.pointer;
    }

    const char *constData() const noexcept
    {
        return data();
    }

    iterator begin() noexcept
    {
        return data();
    }

    iterator end() noexcept
    {
        return data() + size();
    }

    reverse_iterator rbegin() noexcept
    {
284
        return reverse_iterator(end() - static_cast<std::size_t>(1));
Marco Bubke's avatar
Marco Bubke committed
285 286 287 288
    }

    reverse_iterator rend() noexcept
    {
289
        return reverse_iterator(begin() - static_cast<std::size_t>(1));
Marco Bubke's avatar
Marco Bubke committed
290 291
    }

292 293 294 295 296 297 298 299 300 301
    const_reverse_iterator rbegin() const noexcept
    {
        return const_reverse_iterator(end() - static_cast<std::size_t>(1));
    }

    const_reverse_iterator rend() const noexcept
    {
        return const_reverse_iterator(begin() - static_cast<std::size_t>(1));
    }

Marco Bubke's avatar
Marco Bubke committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    const_iterator begin() const noexcept
    {
        return constData();
    }

    const_iterator end() const noexcept
    {
        return data() + size();
    }

    const_iterator cbegin() const noexcept
    {
        return begin();
    }

    const_iterator cend() const noexcept
    {
        return end();
    }

    static
323
    BasicSmallString fromQString(const QString &qString)
Marco Bubke's avatar
Marco Bubke committed
324 325 326
    {
        const QByteArray &utf8ByteArray = qString.toUtf8();

327
        return BasicSmallString(utf8ByteArray.constData(), uint(utf8ByteArray.size()));
Marco Bubke's avatar
Marco Bubke committed
328 329 330
    }

    static
331
    BasicSmallString fromQByteArray(const QByteArray &utf8ByteArray)
Marco Bubke's avatar
Marco Bubke committed
332
    {
333
        return BasicSmallString(utf8ByteArray.constData(), uint(utf8ByteArray.size()));
Marco Bubke's avatar
Marco Bubke committed
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
    }

    bool contains(SmallStringView subStringToSearch) const
    {
        auto found = std::search(begin(),
                                 end(),
                                 subStringToSearch.begin(),
                                 subStringToSearch.end());

        return found != end();
    }

    bool contains(char characterToSearch) const
    {
        auto found = std::strchr(data(), characterToSearch);

        return found != nullptr;
    }

    bool startsWith(SmallStringView subStringToSearch) const noexcept
    {
        if (size() >= subStringToSearch.size())
            return !std::memcmp(data(), subStringToSearch.data(), subStringToSearch.size());

        return false;
    }

    bool startsWith(char characterToSearch) const noexcept
    {
        return data()[0] == characterToSearch;
    }

    bool endsWith(SmallStringView subStringToSearch) const noexcept
    {
        if (size() >= subStringToSearch.size()) {
            const int comparison = std::memcmp(end().data() - subStringToSearch.size(),
                                               subStringToSearch.data(),
                                               subStringToSearch.size());
            return comparison == 0;
        }

        return false;
    }

    bool endsWith(char character) const noexcept
    {
        return at(size() - 1) == character;
    }

    size_type size() const noexcept
    {
        if (!isShortString())
            return m_data.allocated.data.size;

        return m_data.shortString.shortStringSize;
    }

    size_type capacity() const noexcept
    {
        if (!isShortString())
            return m_data.allocated.data.capacity;

        return shortStringCapacity();
    }

    bool isEmpty() const noexcept
    {
        return size() == 0;
    }

    bool hasContent() const noexcept
    {
        return size() != 0;
    }

    SmallStringView mid(size_type position) const noexcept
    {
        return SmallStringView(data() + position, size() - position);
    }

    SmallStringView mid(size_type position, size_type length) const noexcept
    {
        return SmallStringView(data() + position, length);
    }

    void append(SmallStringView string) noexcept
    {
        size_type oldSize = size();
        size_type newSize = oldSize + string.size();

        reserve(optimalCapacity(newSize));
        std::memcpy(data() + oldSize, string.data(), string.size());
        at(newSize) = 0;
        setSize(newSize);
    }

430
    BasicSmallString &operator+=(SmallStringView string)
Marco Bubke's avatar
Marco Bubke committed
431 432 433 434 435 436
    {
        append(string);

        return *this;
    }

Marco Bubke's avatar
Marco Bubke committed
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
    void replace(SmallStringView fromText, SmallStringView toText)
    {
        if (toText.size() == fromText.size())
            replaceEqualSized(fromText, toText);
        else if (toText.size() < fromText.size())
            replaceSmallerSized(fromText, toText);
        else
            replaceLargerSized(fromText, toText);
    }

    void replace(size_type position, size_type length, SmallStringView replacementText)
    {
        size_type newSize = size() - length + replacementText.size();

        reserve(optimalCapacity(newSize));

        auto replaceStart = begin() + position;
        auto replaceEnd = replaceStart + length;
        auto replacementEnd = replaceStart + replacementText.size();
        size_type tailSize = size_type(end() - replaceEnd + 1);

        std::memmove(replacementEnd.data(),
                     replaceEnd.data(), tailSize);
        std::memcpy(replaceStart.data(), replacementText.data(), replacementText.size());

        setSize(newSize);
    }

465 466 467 468 469 470 471 472 473
    BasicSmallString toCarriageReturnsStripped() const
    {
        BasicSmallString text = *this;

        text.replace("\r", "");

        return text;
    }

Marco Bubke's avatar
Marco Bubke committed
474 475 476
    constexpr static
    size_type shortStringCapacity() noexcept
    {
477
        return BasicSmallStringLiteral<Size>::shortStringCapacity();
Marco Bubke's avatar
Marco Bubke committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    }

    size_type optimalCapacity(const size_type size)
    {
        if (fitsNotInCapacity(size))
           return optimalHeapCapacity(size + 1) - 1;

        return size;
    }

    size_type shortStringSize() const
    {
        return m_data.shortString.shortStringSize;
    }

    static
494
    BasicSmallString join(std::initializer_list<BasicSmallString> list)
Marco Bubke's avatar
Marco Bubke committed
495 496
    {
        size_type totalSize = 0;
497
        for (const BasicSmallString &string : list)
Marco Bubke's avatar
Marco Bubke committed
498 499
            totalSize += string.size();

500
        BasicSmallString joinedString;
Marco Bubke's avatar
Marco Bubke committed
501 502
        joinedString.reserve(totalSize);

503
        for (const BasicSmallString &string : list)
Marco Bubke's avatar
Marco Bubke committed
504 505 506 507 508
            joinedString.append(string);

        return joinedString;
    }

509
unitttest_public:
Marco Bubke's avatar
Marco Bubke committed
510 511
    bool isShortString() const noexcept
    {
512
        return !m_data.shortString.isReference;
Marco Bubke's avatar
Marco Bubke committed
513 514
    }

515
    bool isReadOnlyReference() const noexcept
Marco Bubke's avatar
Marco Bubke committed
516
    {
517
        return m_data.shortString.isReadOnlyReference;
Marco Bubke's avatar
Marco Bubke committed
518 519 520 521
    }

    bool hasAllocatedMemory() const noexcept
    {
522
        return !isShortString() && !isReadOnlyReference();
Marco Bubke's avatar
Marco Bubke committed
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
    }

    bool fitsNotInCapacity(size_type capacity) const noexcept
    {
        return (isShortString() && capacity > shortStringCapacity())
            || (!isShortString() && capacity > m_data.allocated.data.capacity);
    }

    static
    size_type optimalHeapCapacity(const size_type size)
    {
        const size_type cacheLineSize = 64;

        const auto divisionByCacheLineSize = std::div(int64_t(size), int64_t(cacheLineSize));

        size_type cacheLineBlocks = size_type(divisionByCacheLineSize.quot);
        const size_type supplement = divisionByCacheLineSize.rem ? 1 : 0;

        cacheLineBlocks += supplement;
        int exponent;
        const double significand = std::frexp(cacheLineBlocks, &exponent);
        const double factorOneDotFiveSignificant = std::ceil(significand * 4.) / 4.;
        cacheLineBlocks = size_type(std::ldexp(factorOneDotFiveSignificant, exponent));

        return cacheLineBlocks * cacheLineSize;
    }

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
    template<size_type ArraySize>
    friend bool operator==(const BasicSmallString& first, const char(&second)[ArraySize]) noexcept
    {
        return first == SmallStringView(second);
    }

    template<size_type ArraySize>
    friend bool operator==(const char(&first)[ArraySize], const BasicSmallString& second) noexcept
    {
        return second == first;
    }

    template<typename Type,
             typename = typename std::enable_if<std::is_pointer<Type>::value>::type
             >
    friend bool operator==(const BasicSmallString& first, Type second) noexcept
    {
        return first == SmallStringView(second);
    }

    template<typename Type,
             typename = typename std::enable_if<std::is_pointer<Type>::value>::type
             >
    friend bool operator==(Type first, const BasicSmallString& second) noexcept
    {
        return second == first;
    }

    friend bool operator==(const BasicSmallString& first, const BasicSmallString& second) noexcept
    {
        return first.size() == second.size()
            && std::memcmp(first.data(), second.data(), first.size()) == 0;
    }

    friend bool operator==(const BasicSmallString& first, const SmallStringView& second) noexcept
    {
        return first.size() == second.size()
            && std::memcmp(first.data(), second.data(), first.size()) == 0;
    }

    friend bool operator==(const SmallStringView& first, const BasicSmallString& second) noexcept
    {
        return second == first;
    }

    friend bool operator!=(const BasicSmallString& first, const SmallStringView& second) noexcept
    {
        return !(first == second);
    }

    friend bool operator!=(const SmallStringView& first, const BasicSmallString& second) noexcept
    {
        return second == first;
    }

    friend bool operator!=(const BasicSmallString& first, const BasicSmallString& second) noexcept
    {
        return !(first == second);
    }

    template<size_type ArraySize>
    friend bool operator!=(const BasicSmallString& first, const char(&second)[ArraySize]) noexcept
    {
        return !(first == second);
    }

    template<size_type ArraySize>
    friend bool operator!=(const char(&first)[ArraySize], const BasicSmallString& second) noexcept
    {
        return second != first;
    }

    template<typename Type,
             typename = typename std::enable_if<std::is_pointer<Type>::value>::type
             >
    friend bool operator!=(const BasicSmallString& first, Type second) noexcept
    {
        return !(first == second);
    }

    template<typename Type,
             typename = typename std::enable_if<std::is_pointer<Type>::value>::type
             >
    friend bool operator!=(Type first, const BasicSmallString& second) noexcept
    {
        return second != first;
    }

    friend bool operator<(const BasicSmallString& first, const BasicSmallString& second) noexcept
    {
640 641
        if (first.size() != second.size())
            return first.size() < second.size();
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        const int comparison = std::memcmp(first.data(), second.data(), first.size() + 1);

        return comparison < 0;
    }

    friend bool operator<(const BasicSmallString& first, SmallStringView second) noexcept
    {
        if (first.size() != second.size())
            return first.size() < second.size();

        const int comparison = std::memcmp(first.data(), second.data(), first.size());

        return comparison < 0;
    }

    friend bool operator<(SmallStringView first, const BasicSmallString& second) noexcept
    {
        if (first.size() != second.size())
            return first.size() < second.size();

        const int comparison = std::memcmp(first.data(), second.data(), first.size());
664 665 666 667

        return comparison < 0;
    }

Marco Bubke's avatar
Marco Bubke committed
668
private:
669
    BasicSmallString(Internal::StringDataLayout<Size> data) noexcept
Marco Bubke's avatar
Marco Bubke committed
670 671 672 673
        : m_data(data)
    {
    }

674 675 676 677 678 679 680 681 682 683
    void initializeLongString(size_type size, size_type capacity)
    {
        m_data.allocated.data.pointer[size] = 0;
        m_data.allocated.data.size = size;
        m_data.allocated.data.capacity = capacity;
        m_data.allocated.shortStringSize = 0;
        m_data.allocated.isReference = true;
        m_data.allocated.isReadOnlyReference = false;
    }

Marco Bubke's avatar
Marco Bubke committed
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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
    char &at(size_type index)
    {
        return *(data() + index);
    }

    const char &at(size_type index) const
    {
        return *(data() + index);
    }

    void replaceEqualSized(SmallStringView fromText, SmallStringView toText)
    {
        reserve(size());

        auto start = begin();
        auto found = std::search(start,
                                 end(),
                                 fromText.begin(),
                                 fromText.end());

        while (found != end()) {
            start = found + toText.size();

            std::memcpy(found.data(), toText.data(), toText.size());

            found = std::search(start,
                                     end(),
                                     fromText.begin(),
                                     fromText.end());

        }
    }

    void replaceSmallerSized(SmallStringView fromText, SmallStringView toText)
    {
        size_type newSize = size();
        reserve(newSize);

        auto start = begin();

        auto found = std::search(start,
                                 end(),
                                 fromText.begin(),
                                 fromText.end());

        size_type sizeDifference = 0;

        while (found != end()) {
            start = found + fromText.size();

            auto nextFound = std::search(start,
                                         end(),
                                         fromText.begin(),
                                         fromText.end());

            auto replacedTextEndPosition = found + fromText.size();
            auto replacementTextEndPosition = found + toText.size() - sizeDifference;
            auto replacementTextStartPosition = found - sizeDifference;

            std::memmove(replacementTextEndPosition.data(),
                         replacedTextEndPosition.data(),
                         nextFound - start);
            std::memcpy(replacementTextStartPosition.data(), toText.data(), toText.size());

            sizeDifference += fromText.size() - toText.size();
            found = nextFound;
        }
        newSize -= sizeDifference;
        setSize(newSize);
        *end() = 0;
    }

    iterator replaceLargerSizedRecursive(size_type startIndex,
                                         SmallStringView fromText,
                                         SmallStringView toText,
                                         size_type sizeDifference)
    {
        auto found = std::search(begin() + startIndex,
                                 end(),
                                 fromText.begin(),
                                 fromText.end());

        auto foundIndex = found - begin();

        if (found != end()) {
            startIndex = foundIndex + fromText.size();

            size_type newSizeDifference = sizeDifference + toText.size() - fromText.size();

            auto nextFound = replaceLargerSizedRecursive(startIndex,
                                                         fromText,
                                                         toText,
                                                         newSizeDifference);

            found = begin() + foundIndex;
            auto start = begin() + startIndex;

            auto replacedTextEndPosition = found + fromText.size();
            auto replacementTextEndPosition = found + fromText.size() + newSizeDifference;
            auto replacementTextStartPosition = found + sizeDifference;


            std::memmove(replacementTextEndPosition.data(),
                         replacedTextEndPosition.data(),
                         nextFound - start);
            std::memcpy(replacementTextStartPosition.data(), toText.data(), toText.size());
        } else {
            size_type newSize = size() + sizeDifference;
            reserve(optimalCapacity(newSize));
            setSize(newSize);
            found = end();
            *end() = 0;
        }

        return found;
    }

    void replaceLargerSized(SmallStringView fromText, SmallStringView toText)
    {
        size_type sizeDifference = 0;
        size_type startIndex = 0;

        replaceLargerSizedRecursive(startIndex, fromText, toText, sizeDifference);
    }

    void setSize(size_type size)
    {
        if (isShortString())
            m_data.shortString.shortStringSize = uchar(size);
        else
            m_data.allocated.data.size = size;
    }

private:
818
    Internal::StringDataLayout<Size> m_data;
Marco Bubke's avatar
Marco Bubke committed
819 820
};

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
template<typename Key,
         typename Value,
         typename Hash = std::hash<Key>,
         typename KeyEqual = std::equal_to<Key>,
         typename Allocator = std::allocator<std::pair<const Key, Value>>>
std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>
clone(const std::unordered_map<Key, Value, Hash, KeyEqual, Allocator> &map)
{
    std::unordered_map<Key, Value, Hash, KeyEqual, Allocator> clonedMap;
    clonedMap.reserve(clonedMap.size());

    for (auto &&entry : map)
        clonedMap.emplace(entry.first, entry.second.clone());

    return clonedMap;
}

template <typename Type>
std::vector<Type> clone(const std::vector<Type> &vector)
{
    std::vector<Type> clonedVector;
    clonedVector.reserve(vector.size());

    for (auto &&entry : vector)
        clonedVector.push_back(entry.clone());

    return clonedVector;
}

850
using SmallString = BasicSmallString<31>;
851
using PathString = BasicSmallString<191>;
852

853
} // namespace Utils