File indexing completed on 2024-05-12 04:42:19

0001 /*
0002     SPDX-FileCopyrightText: 2020-2021 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "stringpool.h"
0008 
0009 #include <algorithm>
0010 
0011 OSM::StringKeyRegistryBase::StringKeyRegistryBase() = default;
0012 OSM::StringKeyRegistryBase::StringKeyRegistryBase(OSM::StringKeyRegistryBase&&) noexcept = default;
0013 OSM::StringKeyRegistryBase& OSM::StringKeyRegistryBase::operator=(OSM::StringKeyRegistryBase&&) noexcept = default;
0014 
0015 OSM::StringKeyRegistryBase::~StringKeyRegistryBase()
0016 {
0017     std::for_each(m_pool.begin(), m_pool.end(), free);
0018 }
0019 
0020 const char* OSM::StringKeyRegistryBase::makeKeyInternal(const char *name, std::size_t len, OSM::StringMemory memOpt)
0021 {
0022     const auto it = std::lower_bound(m_registry.begin(), m_registry.end(), name, [len](const char *lhs, const char *rhs) {
0023         return std::strncmp(lhs, rhs, len) < 0;
0024     });
0025     if (it == m_registry.end() || std::strncmp((*it), name, len) != 0 || std::strlen(*it) != len) {
0026         if (memOpt == OSM::StringMemory::Transient) {
0027 #ifndef _MSC_VER
0028             auto s = strndup(name, len);
0029 #else
0030             auto s = static_cast<char*>(malloc(len + 1));
0031             std::strncpy(s, name, len);
0032             s[len] = '\0';
0033 #endif
0034             m_pool.push_back(s);
0035             name = s;
0036         }
0037         m_registry.insert(it, name);
0038         return name;
0039     }
0040     return (*it);
0041 }
0042 
0043 const char* OSM::StringKeyRegistryBase::keyInternal(const char *name) const
0044 {
0045     const auto it = std::lower_bound(m_registry.begin(), m_registry.end(), name, [](const char *lhs, const char *rhs) {
0046         return std::strcmp(lhs, rhs) < 0;
0047     });
0048     if (it == m_registry.end() || std::strcmp((*it), name) != 0) {
0049         return {};
0050     }
0051     return (*it);
0052 }