ServiceWorker: Consolidate version manipulation functions in SWProviderContext
[chromium-blink-merge.git] / mojo / common / data_pipe_utils.cc
blobc99c6668ba46a1d112724e3246821913cdff0377
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"
7 #include <stdio.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"
15 namespace mojo {
16 namespace common {
17 namespace {
19 bool BlockingCopyHelper(ScopedDataPipeConsumerHandle source,
20 const base::Callback<size_t(const void*, uint32_t)>& write_bytes) {
21 for (;;) {
22 const void* buffer;
23 uint32_t num_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)
30 return false;
31 } else if (result == MOJO_RESULT_SHOULD_WAIT) {
32 result = Wait(source.get(),
33 MOJO_HANDLE_SIGNAL_READABLE,
34 MOJO_DEADLINE_INDEFINITE,
35 nullptr);
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.
42 return true;
43 } else {
44 // Some other error occurred.
45 break;
49 return false;
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);
55 return num_bytes;
58 size_t CopyToFileHelper(FILE* fp, const void* buffer, uint32_t num_bytes) {
59 return fwrite(buffer, 1, num_bytes, fp);
62 } // namespace
65 // TODO(hansmuller): Add a max_size parameter.
66 bool BlockingCopyToString(ScopedDataPipeConsumerHandle source,
67 std::string* result) {
68 CHECK(result);
69 result->clear();
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"));
77 if (!fp)
78 return false;
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(
88 task_runner,
89 FROM_HERE,
90 base::Bind(&BlockingCopyToFile, base::Passed(&source), destination),
91 callback);
94 } // namespace common
95 } // namespace mojo