ETLCPP / etl

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

Side effects concern etl::string #875

Closed pinwhell closed 2 months ago

pinwhell commented 2 months ago

Effects of writing .data() ptr directly? can it expect string to keep working properly? is there any mechanism to simply write the buffer internally directly and not having side effects? also what about that repair() does it has something to do with this concern?

jwellbelove commented 2 months ago

Like std::string, you can modify the contents of the string using the pointer returned from data(). BUT, you must not try to change the length of the string by manipulating the null terminator.

If you have a C function that needs to concatenate characters to an etl::string, then you must resize() the string to the maximum, let the C function add the characters using the pointer form data(), and then resize() the string to the new length. The first resize() will fill the new space with null characters.

repair() resets the internal pointer to the buffer after an etl::string has been moved by a byte copy such as memcpy.

jwellbelove commented 2 months ago

There is also trim_to_terminator() which sets the string size to the distance to the first null terminator.

pinwhell commented 2 months ago

Cool, this information is very useful, really appreciated...

jwellbelove commented 2 months ago

There is also data_end() in etl::string, which can make it even simpler.

etl::string<11> text = "Hello";

// C function
strcpy(text.data_end(), " World");

text.trim_to_terminator(); // text contains "Hello World"
jwellbelove commented 2 months ago

There is also a repair() for etl::vector & etl::deque to facilitate copying of them by C functions. This can be useful for copying ETL buffers in an RTOS.

pinwhell commented 2 months ago

yes, very very useful and interesting concept