SFML community forums

Help => System => Topic started by: Garwin on December 02, 2023, 11:52:54 am

Title: std::istream& operator >> for sf::String
Post by: Garwin on December 02, 2023, 11:52:54 am
I overloaded operator >> for std::istream and sf::String to handle UTF8 encoding.
However I can see there are a lot of copies there:
- from stream to std::string (UTF8)
- from std::string (UTF8) to std::basic_string<sf::Uint32> using sfml function decode
- from std::basic_string<sf::Uint32> to sf::String

I need to use the middle step through std::basic_string<sf::Uint32> as there is no std::back_inserter for sf::String. Is there possibility to decrease number of steps.
note: SFML 2.6.1

Some ideas I have:
- making std::basic_string<sf::Uint32> static and add clear at the end of overload so there is no need to for memory allocation each time

std::istream& operator>> (std::istream& in, sf::String& string)
{
    std::string u8string;
    in >> u8string;
    auto begin = u8string.begin();
    auto end = u8string. end();
    std::basic_string<sf::Uint32> stringUint32;
    auto output = std::back_inserter(stringUint32);
    while (begin < end)
    {
        sf::Uint32 codepoint;
        begin = sf::Utf<8>::decode(begin, end, codepoint);
        *output++ = codepoint;
    }
    string = stringUint32;
    return in;
}
 
Title: Re: std::istream& operator >> for sf::String
Post by: eXpl0it3r on December 06, 2023, 01:55:05 pm
Can't you use sf::String::fromUtf8 to at least work around one of the copies?
Title: Re: std::istream& operator >> for sf::String
Post by: Garwin on December 09, 2023, 06:54:28 pm
Thanks, in this case, where I parse whole string, I can.