• 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 #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 #include "base/strings/string_piece.h"
15 
16 namespace base {
17 
18 namespace internal {
19 
20 // Scoped HSTRING class to maintain lifetime of HSTRINGs allocated with
21 // WindowsCreateString().
22 struct BASE_EXPORT ScopedHStringTraits {
InvalidValueScopedHStringTraits23   static HSTRING InvalidValue() { return nullptr; }
24   static void Free(HSTRING hstr);
25 };
26 
27 }  // namespace internal
28 
29 namespace win {
30 
31 // ScopedHString is a wrapper around an HSTRING.
32 //
33 // Example use:
34 //
35 //   ScopedHString string = ScopedHString::Create(L"abc");
36 //
37 // Also:
38 //
39 //   HSTRING win_string;
40 //   HRESULT hr = WindowsCreateString(..., &win_string);
41 //   ScopedHString string(win_string);
42 //
43 class BASE_EXPORT ScopedHString
44     : public ScopedGeneric<HSTRING, base::internal::ScopedHStringTraits> {
45  public:
46   // Constructs a ScopedHString from an HSTRING, and takes ownership of |hstr|.
47   explicit ScopedHString(HSTRING hstr);
48 
49   static ScopedHString Create(std::wstring_view str);
50   static ScopedHString Create(StringPiece str);
51 
52   // Returns a view into the memory buffer managed by the instance. The returned
53   // StringPiece is only valid during the lifetime of this ScopedHString
54   // instance.
55   std::wstring_view Get() const;
56 
57   // Returns a copy of the instance as a UTF-8 string.
58   std::string GetAsUTF8() const;
59 };
60 
61 }  // namespace win
62 }  // namespace base
63 
64 #endif  // BASE_WIN_SCOPED_HSTRING_H_
65