Add util::hstring - both owning & not owning string - for use to emulate heterogeneous containers

This commit is contained in:
Nikita Lisitsa 2022-11-30 18:16:47 +03:00
parent f0ae57a378
commit 9146c19ccd

View file

@ -0,0 +1,80 @@
#pragma once
#include <string>
#include <string_view>
#include <functional>
namespace psemek::util
{
struct hstring
{
hstring(std::string string)
: string_(std::move(string))
, view_(string_)
{}
hstring(std::string_view const & view)
: view_(view)
{}
hstring(hstring const & other)
: string_(other.string_)
, view_(other.owns() ? std::string_view(string_) : other.view_)
{}
hstring(hstring && other)
{
if (other.owns())
{
string_ = std::move(other.string_);
view_ = string_;
}
else
{
view_ = other.view_;
}
other.view_ = std::string_view();
}
std::string_view view() const
{
return view_;
}
bool owns() const
{
return view_.data() == string_.data();
}
private:
std::string string_;
std::string_view view_;
};
inline auto operator == (hstring const & str1, hstring const & str2)
{
return str1.view() == str2.view();
}
inline auto operator <=> (hstring const & str1, hstring const & str2)
{
return str1.view() <=> str2.view();
}
}
namespace std
{
template <>
struct hash<::psemek::util::hstring>
{
std::size_t operator()(::psemek::util::hstring const & str) const
{
return std::hash<std::string_view>()(str.view());
}
};
}