1 // Copyright 2015 The Weave 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 #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, 24 const ReadCallback& callback) override; 25 26 void Write(const void* buffer, 27 size_t size_to_write, 28 const WriteCallback& callback) override; 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 42 void Copy(const InputStream::ReadCallback& callback); 43 44 private: 45 void OnWriteDone(const InputStream::ReadCallback& callback, ErrorPtr error); 46 void OnReadDone(const InputStream::ReadCallback& callback, 47 size_t size, 48 ErrorPtr error); 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_ 62