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 #include "base/win/scoped_hstring.h" 6 7 #include <winstring.h> 8 9 #include <ostream> 10 #include <string> 11 #include <string_view> 12 13 #include "base/check.h" 14 #include "base/notreached.h" 15 #include "base/numerics/safe_conversions.h" 16 #include "base/process/memory.h" 17 18 #include "base/strings/utf_string_conversions.h" 19 20 namespace base { 21 22 namespace internal { 23 24 // static Free(HSTRING hstr)25void ScopedHStringTraits::Free(HSTRING hstr) { 26 ::WindowsDeleteString(hstr); 27 } 28 29 } // namespace internal 30 31 namespace win { 32 ScopedHString(HSTRING hstr)33ScopedHString::ScopedHString(HSTRING hstr) : ScopedGeneric(hstr) {} 34 35 // static Create(std::wstring_view str)36ScopedHString ScopedHString::Create(std::wstring_view str) { 37 HSTRING hstr; 38 HRESULT hr = ::WindowsCreateString(str.data(), 39 checked_cast<UINT32>(str.length()), &hstr); 40 if (SUCCEEDED(hr)) 41 return ScopedHString(hstr); 42 43 if (hr == E_OUTOFMEMORY) { 44 // This size is an approximation. The actual size likely includes 45 // sizeof(HSTRING_HEADER) as well. 46 base::TerminateBecauseOutOfMemory((str.length() + 1) * sizeof(wchar_t)); 47 } 48 49 // This should not happen at runtime. Otherwise we could silently pass nullptr 50 // or an empty string to downstream code. 51 NOTREACHED() << "Failed to create HSTRING: " << std::hex << hr; 52 return ScopedHString(nullptr); 53 } 54 55 // static Create(std::string_view str)56ScopedHString ScopedHString::Create(std::string_view str) { 57 return Create(UTF8ToWide(str)); 58 } 59 60 // static Get() const61std::wstring_view ScopedHString::Get() const { 62 UINT32 length = 0; 63 const wchar_t* buffer = ::WindowsGetStringRawBuffer(get(), &length); 64 return std::wstring_view(buffer, length); 65 } 66 GetAsUTF8() const67std::string ScopedHString::GetAsUTF8() const { 68 return WideToUTF8(Get()); 69 } 70 71 } // namespace win 72 } // namespace base 73