1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "mojo/common/data_pipe_utils.h"
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_file.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/task_runner_util.h"
19 bool BlockingCopyHelper(ScopedDataPipeConsumerHandle source
,
20 const base::Callback
<size_t(const void*, uint32_t)>& write_bytes
) {
24 MojoResult result
= BeginReadDataRaw(
25 source
.get(), &buffer
, &num_bytes
, MOJO_READ_DATA_FLAG_NONE
);
26 if (result
== MOJO_RESULT_OK
) {
27 size_t bytes_written
= write_bytes
.Run(buffer
, num_bytes
);
28 result
= EndReadDataRaw(source
.get(), num_bytes
);
29 if (bytes_written
< num_bytes
|| result
!= MOJO_RESULT_OK
)
31 } else if (result
== MOJO_RESULT_SHOULD_WAIT
) {
32 result
= Wait(source
.get(),
33 MOJO_HANDLE_SIGNAL_READABLE
,
34 MOJO_DEADLINE_INDEFINITE
,
36 if (result
!= MOJO_RESULT_OK
) {
37 // If the producer handle was closed, then treat as EOF.
38 return result
== MOJO_RESULT_FAILED_PRECONDITION
;
40 } else if (result
== MOJO_RESULT_FAILED_PRECONDITION
) {
41 // If the producer handle was closed, then treat as EOF.
44 // Some other error occurred.
52 size_t CopyToStringHelper(
53 std::string
* result
, const void* buffer
, uint32_t num_bytes
) {
54 result
->append(static_cast<const char*>(buffer
), num_bytes
);
58 size_t CopyToFileHelper(FILE* fp
, const void* buffer
, uint32_t num_bytes
) {
59 return fwrite(buffer
, 1, num_bytes
, fp
);
65 // TODO(hansmuller): Add a max_size parameter.
66 bool BlockingCopyToString(ScopedDataPipeConsumerHandle source
,
67 std::string
* result
) {
70 return BlockingCopyHelper(
71 source
.Pass(), base::Bind(&CopyToStringHelper
, result
));
74 bool BlockingCopyToFile(ScopedDataPipeConsumerHandle source
,
75 const base::FilePath
& destination
) {
76 base::ScopedFILE
fp(base::OpenFile(destination
, "wb"));
79 return BlockingCopyHelper(
80 source
.Pass(), base::Bind(&CopyToFileHelper
, fp
.get()));
83 void CopyToFile(ScopedDataPipeConsumerHandle source
,
84 const base::FilePath
& destination
,
85 base::TaskRunner
* task_runner
,
86 const base::Callback
<void(bool)>& callback
) {
87 base::PostTaskAndReplyWithResult(
90 base::Bind(&BlockingCopyToFile
, base::Passed(&source
), destination
),