ETLCPP / etl

Embedded Template Library
https://www.etlcpp.com
MIT License
2.17k stars 387 forks source link

string insert vs assign #960

Open KammutierSpule opened 6 days ago

KammutierSpule commented 6 days ago

It looks insert does not "repair" the string. should it? or should put on documentation something about it?

jwellbelove commented 6 days ago

What do you mean by "repair"?

KammutierSpule commented 6 days ago

the test I did, I used insert and it didn't change (update) the size. Does it expects the repair() to be called?

jwellbelove commented 6 days ago

repair() is called by the user when a string has been moved by a low level C copy like memcpy. It just re-attaches the buffer to the internal pointer.

Can you give an example of an insert not updating the size?

KammutierSpule commented 6 days ago
#include <iostream>
#include <etl/string.h>

int main() {
    etl::string<20> test;
    char buffer[20 + 1];
    strncpy(buffer, "ABCDE", sizeof(buffer));
    test.insert(0, buffer, buffer + 5);
    std::cout << "test.size:" << test.length() << "\n";
    test.repair();
    std::cout << "test.size:" << test.length() << "\n";

    return 0;
}
test.size:0
test.size:0

Looks I missed the propose of insert, it works on a string already created and doesn't change the original string size?

jwellbelove commented 6 days ago

When you call test.insert(0, buffer, buffer + 5) you are calling this function

template <typename TIterator>
iterator insert(const_iterator position, TIterator first, TIterator last)

It is expecting the first parameter to be the iterator position where you want the string to be inserted. You are sending it a null iterator.

I assume you meant to call test.insert(0, buffer, 5);