aboutsummaryrefslogtreecommitdiff
path: root/src/extent_stream.h
blob: 4f39dc59a9c6eb49008895a5bd2b27bdb88c7ea0 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2017 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef SRC_EXTENT_STREAM_H_
#define SRC_EXTENT_STREAM_H_

#include <memory>
#include <vector>

#include "puffin/src/include/puffin/common.h"
#include "puffin/src/include/puffin/stream.h"

namespace puffin {

// A stream object that allows reading and writing into disk extents. This is
// only used in main.cc for puffin binary to allow puffpatch on a actual rootfs
// and kernel images.
class ExtentStream : public StreamInterface {
 public:
  // Creates a stream only for writing.
  static UniqueStreamPtr CreateForWrite(UniqueStreamPtr stream,
                                        const std::vector<ByteExtent>& extents);
  // Creates a stream only for reading.
  static UniqueStreamPtr CreateForRead(UniqueStreamPtr stream,
                                       const std::vector<ByteExtent>& extents);
  ~ExtentStream() override = default;

  bool GetSize(uint64_t* size) const override;
  bool GetOffset(uint64_t* offset) const override;
  bool Seek(uint64_t offset) override;
  bool Read(void* buffer, size_t length) override;
  bool Write(const void* buffer, size_t length) override;
  bool Close() override;

 private:
  ExtentStream(UniqueStreamPtr stream,
               const std::vector<ByteExtent>& extents,
               bool is_for_write);

  // Since both read and write operations are very similar in this class, this
  // function acts as a common operation that does both write and read based on
  // the nullability of |read_buffer| or |write_buffer|.
  bool DoReadOrWrite(void* read_buffer,
                     const void* write_buffer,
                     size_t length);

  // The underlying stream to read from and write into.
  UniqueStreamPtr stream_;

  std::vector<ByteExtent> extents_;

  // The current |ByteExtent| that is being read from or write into.
  std::vector<ByteExtent>::iterator cur_extent_;

  // The current offset in the current |ByteExtent| |cur_extent_|.
  uint64_t cur_extent_offset_;

  // |True| if the stream is write only. |False| if the stream is read only.
  bool is_for_write_;

  // The size of the stream. It is actually the cumulative size of all the bytes
  // in |extents_|.
  uint64_t size_;

  // The current offset.
  uint64_t offset_;

  // Used for proper and faster seeking.
  std::vector<uint64_t> extents_upper_bounds_;

  DISALLOW_COPY_AND_ASSIGN(ExtentStream);
};

}  // namespace puffin

#endif  // SRC_EXTENT_STREAM_H_