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