Vitaly Buka | 4615e0d | 2015-10-14 15:35:12 -0700 | [diff] [blame] | 1 | // Copyright 2015 The Weave Authors. All rights reserved. |
Vitaly Buka | ff32458 | 2015-10-08 13:37:53 -0700 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef LIBWEAVE_SRC_STREAMS_H_ |
| 6 | #define LIBWEAVE_SRC_STREAMS_H_ |
| 7 | |
| 8 | #include <base/memory/weak_ptr.h> |
| 9 | #include <weave/stream.h> |
| 10 | |
| 11 | namespace weave { |
| 12 | |
| 13 | namespace provider { |
| 14 | class TaskRunner; |
| 15 | } |
| 16 | |
| 17 | class MemoryStream : public InputStream, public OutputStream { |
| 18 | public: |
| 19 | MemoryStream(const std::vector<uint8_t>& data, |
| 20 | provider::TaskRunner* task_runner); |
| 21 | |
| 22 | void Read(void* buffer, |
| 23 | size_t size_to_read, |
Vitaly Buka | 7476342 | 2015-10-11 00:39:52 -0700 | [diff] [blame] | 24 | const ReadCallback& callback) override; |
Vitaly Buka | ff32458 | 2015-10-08 13:37:53 -0700 | [diff] [blame] | 25 | |
| 26 | void Write(const void* buffer, |
| 27 | size_t size_to_write, |
Vitaly Buka | 7476342 | 2015-10-11 00:39:52 -0700 | [diff] [blame] | 28 | const WriteCallback& callback) override; |
Vitaly Buka | ff32458 | 2015-10-08 13:37:53 -0700 | [diff] [blame] | 29 | |
| 30 | const std::vector<uint8_t>& GetData() const { return data_; } |
| 31 | |
| 32 | private: |
| 33 | std::vector<uint8_t> data_; |
| 34 | provider::TaskRunner* task_runner_{nullptr}; |
| 35 | size_t read_position_{0}; |
| 36 | }; |
| 37 | |
| 38 | class StreamCopier { |
| 39 | public: |
| 40 | StreamCopier(InputStream* source, OutputStream* destination); |
| 41 | |
Vitaly Buka | 7476342 | 2015-10-11 00:39:52 -0700 | [diff] [blame] | 42 | void Copy(const InputStream::ReadCallback& callback); |
Vitaly Buka | ff32458 | 2015-10-08 13:37:53 -0700 | [diff] [blame] | 43 | |
| 44 | private: |
Vitaly Buka | 7476342 | 2015-10-11 00:39:52 -0700 | [diff] [blame] | 45 | void OnWriteDone(const InputStream::ReadCallback& callback, ErrorPtr error); |
| 46 | void OnReadDone(const InputStream::ReadCallback& callback, |
| 47 | size_t size, |
| 48 | ErrorPtr error); |
Vitaly Buka | ff32458 | 2015-10-08 13:37:53 -0700 | [diff] [blame] | 49 | |
| 50 | InputStream* source_{nullptr}; |
| 51 | OutputStream* destination_{nullptr}; |
| 52 | |
| 53 | size_t size_done_{0}; |
| 54 | std::vector<uint8_t> buffer_; |
| 55 | |
| 56 | base::WeakPtrFactory<StreamCopier> weak_ptr_factory_{this}; |
| 57 | }; |
| 58 | |
| 59 | } // namespace weave |
| 60 | |
| 61 | #endif // LIBWEAVE_SRC_STREAMS_H_ |