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