1 // Copyright (c) 2016 The WebM project authors. All Rights Reserved. 2 // 3 // Use of this source code is governed by a BSD-style license 4 // that can be found in the LICENSE file in the root of the source 5 // tree. An additional intellectual property rights grant can be found 6 // in the file PATENTS. All contributing project authors may 7 // be found in the AUTHORS file in the root of the source tree. 8 #ifndef INCLUDE_WEBM_ISTREAM_READER_H_ 9 #define INCLUDE_WEBM_ISTREAM_READER_H_ 10 11 #include <cstdint> 12 #include <cstdlib> 13 #include <istream> 14 #include <memory> 15 #include <type_traits> 16 17 #include "./reader.h" 18 #include "./status.h" 19 20 /** 21 \file 22 A `Reader` implementation that reads from a `std::istream`. 23 */ 24 25 namespace webm { 26 27 /** 28 A `Reader` implementation that can read from `std::istream`-based resources. 29 */ 30 class IstreamReader : public Reader { 31 public: 32 /** 33 Constructs a new, empty reader. 34 */ 35 IstreamReader() = default; 36 37 /** 38 Constructs a new reader, using the provided `std::istream` as the data 39 source. 40 41 Ownership of the stream is taken, and it will be moved into a new internal 42 instance. 43 44 \param istream The stream to use as a data source. Must be an rvalue 45 reference derived from `std::istream`. 46 */ 47 template <typename T> IstreamReader(T && istream)48 explicit IstreamReader(T&& istream) : istream_(new T(std::move(istream))) {} 49 50 /** 51 Constructs a new reader by moving the provided reader into the new reader. 52 53 \param other The source reader to move. After moving, it will be reset to an 54 empty stream. 55 */ 56 IstreamReader(IstreamReader&& other); 57 58 /** 59 Moves the provided reader into this reader. 60 61 \param other The source reader to move. After moving, it will be reset to an 62 empty stream. May be equal to `*this`, in which case this is a no-op. 63 \return `*this`. 64 */ 65 IstreamReader& operator=(IstreamReader&& other); 66 67 Status Read(std::size_t num_to_read, std::uint8_t* buffer, 68 std::uint64_t* num_actually_read) override; 69 70 Status Skip(std::uint64_t num_to_skip, 71 std::uint64_t* num_actually_skipped) override; 72 73 std::uint64_t Position() const override; 74 75 /** 76 Constructs a new reader and its data source in place. 77 78 `T` must be derived from `std::istream` and constructible from the provided 79 arguments. 80 81 \param args Arguments that will be forwarded to the `T`'s constructor. 82 \return A new `IstreamReader` backed by the underlying data source equivalent 83 to `T(std::forward<Args>(args)...`. 84 */ 85 template <typename T, typename... Args> Emplace(Args &&...args)86 static IstreamReader Emplace(Args&&... args) { 87 IstreamReader reader; 88 reader.istream_.reset(new T(std::forward<Args>(args)...)); 89 return reader; 90 } 91 92 private: 93 std::unique_ptr<std::istream> istream_; 94 std::uint64_t position_ = 0; 95 }; 96 97 } // namespace webm 98 99 #endif // INCLUDE_WEBM_ISTREAM_READER_H_ 100