1 // Copyright 2017 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_WIN_SCOPED_HSTRING_H_ 6 #define BASE_WIN_SCOPED_HSTRING_H_ 7 8 #include <hstring.h> 9 10 #include <string> 11 #include <string_view> 12 13 #include "base/scoped_generic.h" 14 15 namespace base { 16 17 namespace internal { 18 19 // Scoped HSTRING class to maintain lifetime of HSTRINGs allocated with 20 // WindowsCreateString(). 21 struct BASE_EXPORT ScopedHStringTraits { InvalidValueScopedHStringTraits22 static HSTRING InvalidValue() { return nullptr; } 23 static void Free(HSTRING hstr); 24 }; 25 26 } // namespace internal 27 28 namespace win { 29 30 // ScopedHString is a wrapper around an HSTRING. 31 // 32 // Example use: 33 // 34 // ScopedHString string = ScopedHString::Create(L"abc"); 35 // 36 // Also: 37 // 38 // HSTRING win_string; 39 // HRESULT hr = WindowsCreateString(..., &win_string); 40 // ScopedHString string(win_string); 41 // 42 class BASE_EXPORT ScopedHString 43 : public ScopedGeneric<HSTRING, base::internal::ScopedHStringTraits> { 44 public: 45 // Constructs a ScopedHString from an HSTRING, and takes ownership of |hstr|. 46 explicit ScopedHString(HSTRING hstr); 47 48 static ScopedHString Create(std::wstring_view str); 49 static ScopedHString Create(std::string_view str); 50 51 // Returns a view into the memory buffer managed by the instance. The returned 52 // std::string_view is only valid during the lifetime of this ScopedHString 53 // instance. 54 std::wstring_view Get() const; 55 56 // Returns a copy of the instance as a UTF-8 string. 57 std::string GetAsUTF8() const; 58 }; 59 60 } // namespace win 61 } // namespace base 62 63 #endif // BASE_WIN_SCOPED_HSTRING_H_ 64