aboutsummaryrefslogtreecommitdiff
path: root/src/streams.h
blob: cefcf94d70636db89ec331f165d5e6e35958821d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2015 The Weave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIBWEAVE_SRC_STREAMS_H_
#define LIBWEAVE_SRC_STREAMS_H_

#include <vector>

#include <base/memory/weak_ptr.h>
#include <weave/stream.h>

namespace weave {

namespace provider {
class TaskRunner;
}

class MemoryStream : public InputStream, public OutputStream {
 public:
  MemoryStream(const std::vector<uint8_t>& data,
               provider::TaskRunner* task_runner);

  void Read(void* buffer,
            size_t size_to_read,
            const ReadCallback& callback) override;

  void Write(const void* buffer,
             size_t size_to_write,
             const WriteCallback& callback) override;

  const std::vector<uint8_t>& GetData() const { return data_; }

 private:
  std::vector<uint8_t> data_;
  provider::TaskRunner* task_runner_{nullptr};
  size_t read_position_{0};
};

class StreamCopier {
 public:
  StreamCopier(InputStream* source, OutputStream* destination);

  void Copy(const InputStream::ReadCallback& callback);

 private:
  void OnWriteDone(const InputStream::ReadCallback& callback, ErrorPtr error);
  void OnReadDone(const InputStream::ReadCallback& callback,
                  size_t size,
                  ErrorPtr error);

  InputStream* source_{nullptr};
  OutputStream* destination_{nullptr};

  size_t size_done_{0};
  std::vector<uint8_t> buffer_;

  base::WeakPtrFactory<StreamCopier> weak_ptr_factory_{this};
};

}  // namespace weave

#endif  // LIBWEAVE_SRC_STREAMS_H_