From 9146c19ccd4243646a5a6415430de9b765c62f94 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Wed, 30 Nov 2022 18:16:47 +0300 Subject: [PATCH] Add util::hstring - both owning & not owning string - for use to emulate heterogeneous containers --- libs/util/include/psemek/util/hstring.hpp | 80 +++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 libs/util/include/psemek/util/hstring.hpp diff --git a/libs/util/include/psemek/util/hstring.hpp b/libs/util/include/psemek/util/hstring.hpp new file mode 100644 index 00000000..7a9775ab --- /dev/null +++ b/libs/util/include/psemek/util/hstring.hpp @@ -0,0 +1,80 @@ +#pragma once + +#include +#include +#include + +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()(str.view()); + } + }; + +}