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/winrt_storage_util.h"
6
7 #include <robuffer.h>
8 #include <string.h>
9 #include <wrl/client.h>
10
11 #include <utility>
12
13 #include "base/strings/string_util.h"
14 #include "base/win/core_winrt_util.h"
15 #include "base/win/scoped_hstring.h"
16
17 namespace base {
18 namespace win {
19
20 using IBuffer = ABI::Windows::Storage::Streams::IBuffer;
21
GetPointerToBufferData(IBuffer * buffer,uint8_t ** out,UINT32 * length)22 HRESULT GetPointerToBufferData(IBuffer* buffer, uint8_t** out, UINT32* length) {
23 *out = nullptr;
24
25 Microsoft::WRL::ComPtr<Windows::Storage::Streams::IBufferByteAccess>
26 buffer_byte_access;
27 HRESULT hr = buffer->QueryInterface(IID_PPV_ARGS(&buffer_byte_access));
28 if (FAILED(hr))
29 return hr;
30
31 hr = buffer->get_Length(length);
32 if (FAILED(hr))
33 return hr;
34
35 // Lifetime of the pointing buffer is controlled by the buffer object.
36 return buffer_byte_access->Buffer(out);
37 }
38
CreateIBufferFromData(const uint8_t * data,UINT32 length,Microsoft::WRL::ComPtr<IBuffer> * buffer)39 HRESULT CreateIBufferFromData(const uint8_t* data,
40 UINT32 length,
41 Microsoft::WRL::ComPtr<IBuffer>* buffer) {
42 *buffer = nullptr;
43
44 Microsoft::WRL::ComPtr<ABI::Windows::Storage::Streams::IBufferFactory>
45 buffer_factory;
46 HRESULT hr = base::win::GetActivationFactory<
47 ABI::Windows::Storage::Streams::IBufferFactory,
48 RuntimeClass_Windows_Storage_Streams_Buffer>(&buffer_factory);
49 if (FAILED(hr))
50 return hr;
51
52 Microsoft::WRL::ComPtr<IBuffer> internal_buffer;
53 hr = buffer_factory->Create(length, &internal_buffer);
54 if (FAILED(hr))
55 return hr;
56
57 hr = internal_buffer->put_Length(length);
58 if (FAILED(hr))
59 return hr;
60
61 uint8_t* p_buffer_data;
62 hr = GetPointerToBufferData(internal_buffer.Get(), &p_buffer_data, &length);
63 if (FAILED(hr))
64 return hr;
65
66 memcpy(p_buffer_data, data, length);
67
68 *buffer = std::move(internal_buffer);
69
70 return S_OK;
71 }
72
73 } // namespace win
74 } // namespace base
75