• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "mojo/public/cpp/system/data_pipe_drainer.h"
6 
7 #include <stdint.h>
8 
9 #include <utility>
10 
11 #include "base/bind.h"
12 
13 namespace mojo {
14 
DataPipeDrainer(Client * client,mojo::ScopedDataPipeConsumerHandle source)15 DataPipeDrainer::DataPipeDrainer(Client* client,
16                                  mojo::ScopedDataPipeConsumerHandle source)
17     : client_(client),
18       source_(std::move(source)),
19       handle_watcher_(FROM_HERE,
20                       SimpleWatcher::ArmingPolicy::AUTOMATIC,
21                       base::SequencedTaskRunnerHandle::Get()),
22       weak_factory_(this) {
23   DCHECK(client_);
24   handle_watcher_.Watch(
25       source_.get(), MOJO_HANDLE_SIGNAL_READABLE,
26       base::Bind(&DataPipeDrainer::WaitComplete, weak_factory_.GetWeakPtr()));
27 }
28 
~DataPipeDrainer()29 DataPipeDrainer::~DataPipeDrainer() {}
30 
ReadData()31 void DataPipeDrainer::ReadData() {
32   const void* buffer = nullptr;
33   uint32_t num_bytes = 0;
34   MojoResult rv =
35       source_->BeginReadData(&buffer, &num_bytes, MOJO_READ_DATA_FLAG_NONE);
36   if (rv == MOJO_RESULT_OK) {
37     client_->OnDataAvailable(buffer, num_bytes);
38     source_->EndReadData(num_bytes);
39   } else if (rv == MOJO_RESULT_FAILED_PRECONDITION) {
40     client_->OnDataComplete();
41   } else if (rv != MOJO_RESULT_SHOULD_WAIT) {
42     DCHECK(false) << "Unhandled MojoResult: " << rv;
43   }
44 }
45 
WaitComplete(MojoResult result)46 void DataPipeDrainer::WaitComplete(MojoResult result) {
47   ReadData();
48 }
49 
50 }  // namespace mojo
51