1 // Copyright 2017 The Chromium OS 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 SRC_EXTENT_STREAM_H_ 6 #define SRC_EXTENT_STREAM_H_ 7 8 #include <memory> 9 #include <vector> 10 11 #include "puffin/src/include/puffin/common.h" 12 #include "puffin/src/include/puffin/stream.h" 13 14 namespace puffin { 15 16 // A stream object that allows reading and writing into disk extents. This is 17 // only used in main.cc for puffin binary to allow puffpatch on a actual rootfs 18 // and kernel images. 19 class ExtentStream : public StreamInterface { 20 public: 21 // Creates a stream only for writing. 22 static UniqueStreamPtr CreateForWrite(UniqueStreamPtr stream, 23 const std::vector<ByteExtent>& extents); 24 // Creates a stream only for reading. 25 static UniqueStreamPtr CreateForRead(UniqueStreamPtr stream, 26 const std::vector<ByteExtent>& extents); 27 ~ExtentStream() override = default; 28 29 bool GetSize(uint64_t* size) const override; 30 bool GetOffset(uint64_t* offset) const override; 31 bool Seek(uint64_t offset) override; 32 bool Read(void* buffer, size_t length) override; 33 bool Write(const void* buffer, size_t length) override; 34 bool Close() override; 35 36 private: 37 ExtentStream(UniqueStreamPtr stream, 38 const std::vector<ByteExtent>& extents, 39 bool is_for_write); 40 41 // Since both read and write operations are very similar in this class, this 42 // function acts as a common operation that does both write and read based on 43 // the nullability of |read_buffer| or |write_buffer|. 44 bool DoReadOrWrite(void* read_buffer, 45 const void* write_buffer, 46 size_t length); 47 48 // The underlying stream to read from and write into. 49 UniqueStreamPtr stream_; 50 51 std::vector<ByteExtent> extents_; 52 53 // The current |ByteExtent| that is being read from or write into. 54 std::vector<ByteExtent>::iterator cur_extent_; 55 56 // The current offset in the current |ByteExtent| |cur_extent_|. 57 uint64_t cur_extent_offset_; 58 59 // |True| if the stream is write only. |False| if the stream is read only. 60 bool is_for_write_; 61 62 // The size of the stream. It is actually the cumulative size of all the bytes 63 // in |extents_|. 64 uint64_t size_; 65 66 // The current offset. 67 uint64_t offset_; 68 69 // Used for proper and faster seeking. 70 std::vector<uint64_t> extents_upper_bounds_; 71 72 DISALLOW_COPY_AND_ASSIGN(ExtentStream); 73 }; 74 75 } // namespace puffin 76 77 #endif // SRC_EXTENT_STREAM_H_ 78