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 #ifndef CHROMEOS_DBUS_PIPE_READER_H_
6 #define CHROMEOS_DBUS_PIPE_READER_H_
10 #include "base/callback.h"
11 #include "base/files/file.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/weak_ptr.h"
22 class IOBufferWithSize
;
27 // Simple class to encapsulate collecting data from a pipe into a
29 // - Instantiate the appropriate subclass of PipeReader
30 // - Call StartIO() which will create the appropriate FDs.
31 // - As data is received, the PipeReader will collect this data
32 // as appropriate to the subclass.
33 // - When the there is no more data to read, the PipeReader calls
37 typedef base::Callback
<void(void)> IOCompleteCallback
;
39 PipeReader(const scoped_refptr
<base::TaskRunner
>& task_runner
,
40 const IOCompleteCallback
& callback
);
41 virtual ~PipeReader();
43 // Starts data collection.
44 // Returns the write end of the pipe if stream was setup correctly.
45 // On success data will automatically be accumulated into a string that
46 // can be retrieved with PipeReader::data(). To shutdown collection delete
47 // the instance and/or use PipeReader::OnDataReady(-1).
50 // Called when pipe data are available. Can also be used to shutdown
51 // data collection by passing -1 for |byte_count|.
52 void OnDataReady(int byte_count
);
54 // Virtual function that subclasses will override in order to deal
55 // with incoming data.
56 virtual void AcceptData(const char *data
, int length
) = 0;
59 scoped_ptr
<net::FileStream
> data_stream_
;
60 scoped_refptr
<net::IOBufferWithSize
> io_buffer_
;
61 scoped_refptr
<base::TaskRunner
> task_runner_
;
62 IOCompleteCallback callback_
;
64 // Note: This should remain the last member so it'll be destroyed and
65 // invalidate its weak pointers before any other members are destroyed.
66 base::WeakPtrFactory
<PipeReader
> weak_ptr_factory_
;
68 DISALLOW_COPY_AND_ASSIGN(PipeReader
);
71 // PipeReader subclass which accepts incoming data to a string.
72 class PipeReaderForString
: public PipeReader
{
74 PipeReaderForString(const scoped_refptr
<base::TaskRunner
>& task_runner
,
75 const IOCompleteCallback
& callback
);
77 void AcceptData(const char* data
, int length
) override
;
79 // Destructively returns collected data, by swapping |data_| with |data|.
80 void GetData(std::string
* data
);
85 DISALLOW_COPY_AND_ASSIGN(PipeReaderForString
);
88 } // namespace chromeos
90 #endif // CHROMEOS_DBUS_PIPE_READER_H_