LocIndependent.h (2977B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <string> 5 #include <string_view> 6 7 namespace AppInstaller::Utility 8 { 9 // "I solemnly swear that this string is indeed localization independent." 10 // A localization independent string view. 11 // Used as a wrapper around strings that do not need localization. 12 struct LocIndView : public std::string_view 13 { 14 constexpr LocIndView() = default; 15 explicit constexpr LocIndView(std::string_view sv) : std::string_view(sv) {} 16 }; 17 18 // "I solemnly swear that this string is indeed localization independent." 19 // A localization independent string; either through external localization 20 // or by virtue of not needing to be localized. 21 // Intentionally does not allow the value to be modified to prevent accidental 22 // reintroduction of a localization dependent value. 23 struct LocIndString 24 { 25 LocIndString() = default; 26 27 explicit LocIndString(std::string_view sv) : m_value(sv) {} 28 explicit LocIndString(std::string v) : m_value(std::move(v)) {} 29 30 LocIndString(const LocIndString&) = default; 31 LocIndString& operator=(const LocIndString&) = default; 32 33 LocIndString(LocIndString&&) = default; 34 LocIndString& operator=(LocIndString&&) = default; 35 36 bool empty() const { return m_value.empty(); } 37 38 const std::string& get() const & { return m_value; } 39 std::string&& get() && { return std::move(m_value); } 40 41 operator const std::string& () const { return m_value; } 42 operator std::string_view() const { return m_value; } 43 44 const std::string* operator->() const { return &m_value; } 45 46 bool operator==(std::string_view sv) const { return m_value == sv; } 47 bool operator!=(const LocIndString& other) const { return m_value != other.m_value; } 48 49 bool operator<(const LocIndString& other) const { return m_value < other.m_value; } 50 bool operator<(const std::string& other) const { return m_value < other; } 51 52 friend std::ostream& operator<<(std::ostream& out, const AppInstaller::Utility::LocIndString& lis) 53 { 54 return (out << lis.get()); 55 } 56 57 private: 58 std::string m_value; 59 }; 60 61 namespace literals 62 { 63 // "I solemnly swear that this string is indeed localization independent." 64 // Enable easier use of a localization independent view through literals. 65 inline constexpr LocIndView operator ""_liv(const char* chars, size_t size) 66 { 67 return LocIndView{ std::string_view{ chars, size } }; 68 } 69 70 // "I solemnly swear that this string is indeed localization independent." 71 // Enable easier use of a localization independent string through literals. 72 inline LocIndString operator ""_lis(const char* chars, size_t size) 73 { 74 return LocIndString{ std::string_view{ chars, size } }; 75 } 76 } 77 }