Home | History | Annotate | Download | only in src
      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_MEMORY_STREAM_H_
      6 #define SRC_MEMORY_STREAM_H_
      7 
      8 #include <string>
      9 #include <utility>
     10 
     11 #include "puffin/common.h"
     12 #include "puffin/stream.h"
     13 
     14 namespace puffin {
     15 
     16 // A very simple class for reading and writing into memory.
     17 class MemoryStream : public StreamInterface {
     18  public:
     19   ~MemoryStream() override = default;
     20 
     21   // Creates a stream for reading.
     22   static UniqueStreamPtr CreateForRead(const Buffer& memory);
     23 
     24   // Creates a stream for writing. This function will clear the |memory| if
     25   // |clear| is true. An instance of this class does not retain the ownership of
     26   // the |memory|.
     27   static UniqueStreamPtr CreateForWrite(Buffer* memory);
     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   // Ctor. Exactly one of the |read_memory| or |write_memory| should be nullptr.
     38   MemoryStream(const Buffer* read_memory, Buffer* write_memory);
     39 
     40   // The memory buffer for reading.
     41   const Buffer* read_memory_;
     42 
     43   // The memory buffer for writing. It can grow as we write into it.
     44   Buffer* write_memory_;
     45 
     46   // The current offset.
     47   uint64_t offset_;
     48 
     49   // True if the stream is open.
     50   bool open_;
     51 
     52   DISALLOW_COPY_AND_ASSIGN(MemoryStream);
     53 };
     54 
     55 }  // namespace puffin
     56 
     57 #endif  // SRC_MEMORY_STREAM_H_
     58