• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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)25 void ScopedHStringTraits::Free(HSTRING hstr) {
26   ::WindowsDeleteString(hstr);
27 }
28 
29 }  // namespace internal
30 
31 namespace win {
32 
ScopedHString(HSTRING hstr)33 ScopedHString::ScopedHString(HSTRING hstr) : ScopedGeneric(hstr) {}
34 
35 // static
Create(std::wstring_view str)36 ScopedHString 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 }
53 
54 // static
Create(std::string_view str)55 ScopedHString ScopedHString::Create(std::string_view str) {
56   return Create(UTF8ToWide(str));
57 }
58 
59 // static
Get() const60 std::wstring_view ScopedHString::Get() const {
61   UINT32 length = 0;
62   const wchar_t* buffer = ::WindowsGetStringRawBuffer(get(), &length);
63   return std::wstring_view(buffer, length);
64 }
65 
GetAsUTF8() const66 std::string ScopedHString::GetAsUTF8() const {
67   return WideToUTF8(Get());
68 }
69 
70 }  // namespace win
71 }  // namespace base
72