[StringIndexer] Fix compare bug and moved strToIndex to private

strToIndex is dangerous because it can increment the use of a string, or
create a new string. This method should only be called by IndexedString.
This commit is contained in:
hsaturn
2022-10-30 21:41:49 +01:00
parent cabb56fc8c
commit f5e9a43461
2 changed files with 36 additions and 25 deletions

View File

@@ -26,32 +26,9 @@ class StringIndexer
#endif #endif
}; };
public: public:
using index_t=uint8_t; using index_t = uint8_t;
static index_t strToIndex(const char* str, uint8_t len) static const std::string& str(const index_t& index)
{
for(auto it=strings.begin(); it!=strings.end(); it++)
{
if (strncmp(it->second.str.c_str(), str, len)==0)
{
it->second.used++;
return it->first;
}
}
for(index_t index=1; index; index++)
{
if (strings.find(index)==strings.end())
{
strings[index].str = std::string(str, len);
strings[index].used++;
// Serial << "Creating index " << index << " for (" << strings[index].str.c_str() << ") len=" << len << endl;
return index;
}
}
return 0; // TODO out of indexes
}
static const std::string& str(const index_t& index)
{ {
static std::string dummy; static std::string dummy;
const auto& it=strings.find(index); const auto& it=strings.find(index);
@@ -82,6 +59,32 @@ class StringIndexer
static uint16_t count() { return strings.size(); } static uint16_t count() { return strings.size(); }
private: private:
friend class IndexedString;
// increment use of str or create a new index
static index_t strToIndex(const char* str, uint8_t len)
{
for(auto it=strings.begin(); it!=strings.end(); it++)
{
if (it->second.str.length() == len && strcmp(it->second.str.c_str(), str)==0)
{
it->second.used++;
return it->first;
}
}
for(index_t index=1; index; index++)
{
if (strings.find(index)==strings.end())
{
strings[index].str = std::string(str, len);
strings[index].used++;
// Serial << "Creating index " << index << " for (" << strings[index].str.c_str() << ") len=" << len << endl;
return index;
}
}
return 0; // TODO out of indexes
}
static std::map<index_t, StringCounter> strings; static std::map<index_t, StringCounter> strings;
}; };

View File

@@ -62,6 +62,14 @@ test(indexer_same_strings_should_equal)
assertTrue(one == two); assertTrue(one == two);
} }
test(indexer_compare_strings_with_same_beginning)
{
IndexedString two("one_two");
IndexedString one("one");
assertNotEqual(one.getIndex(), two.getIndex());
}
test(indexer_indexed_operator_eq) test(indexer_indexed_operator_eq)
{ {
IndexedString one("one"); IndexedString one("one");