Rapidjson: std::string_view support

Created on 1 Feb 2017  路  6Comments  路  Source: Tencent/rapidjson

Could you add support for the C++17 std::string_view type?

enhancement

Most helpful comment

I would also like to see std::string_view replace StringRef, or more realistically, have a string_view-to-StringRef converter as suggested by a few people above.
However, as I reported in issue #1649 some of the existing code (e.g., FindMember(), RemoveMember()) has trouble dealing with non-null terminated strings - it simply ignores the length of the StringRef's length. This assumption is wrong, and can break a lot of uses of std::string_view (it broke mine) - so before we recommend people can use std::string_view, we need to fix issue #1649.

All 6 comments

in the meantime you can use something like :

rapidjson::GenericStringRef<char> StringRef(std::string_view s) const
{ return rapidjson::GenericStringRef<char>(s.data(), s.size()); }

or

template<typename Ch>
rapidjson::GenericStringRef<char> StringRef(std::basic_string_view<Ch> s) const
{ return rapidjson::GenericStringRef<Ch>(s.data(), s.size()); }

I suggest to replace the current const std::string& interfaces by a fallback chain that consists of std::string_view, std::experimental::string_view and const std::string&, because all of them are non-owning, and all accepts std::string.

@jcelerier data() might return NULL (if !size) and rapidjson can't handle that so it's not quite that easy.

howdy :( maybe have a static empty string in this case then ?

rapidjson::GenericStringRef<char> StringRef(std::string_view s) const
{ 
    static const constexpr auto empty = "";
    if(s.data())
        return rapidjson::GenericStringRef<char>(s.data(), s.size()); 
    else
        return rapidjson::GenericStringRef<char>(empty, 0); 
}

Just "" is fine ;)

return rapidjson::GenericStringRef<char>(s.data() ? s.data() : "", s.size());

I would also like to see std::string_view replace StringRef, or more realistically, have a string_view-to-StringRef converter as suggested by a few people above.
However, as I reported in issue #1649 some of the existing code (e.g., FindMember(), RemoveMember()) has trouble dealing with non-null terminated strings - it simply ignores the length of the StringRef's length. This assumption is wrong, and can break a lot of uses of std::string_view (it broke mine) - so before we recommend people can use std::string_view, we need to fix issue #1649.

Was this page helpful?
0 / 5 - 0 ratings