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_FILE_READER_H_
9 #define INCLUDE_WEBM_FILE_READER_H_
10 
11 #include <cstdint>
12 #include <cstdio>
13 #include <cstdlib>
14 #include <memory>
15 
16 #include "./reader.h"
17 #include "./status.h"
18 
19 /**
20  \file
21  A `Reader` implementation that reads from a `FILE*`.
22  */
23 
24 namespace webm {
25 
26 /**
27  A `Reader` implementation that can read from `FILE*` resources.
28  */
29 class FileReader : public Reader {
30  public:
31   /**
32    Constructs a new, empty reader.
33    */
34   FileReader() = default;
35 
36   /**
37    Constructs a new reader, using the provided file as the data source.
38 
39    Ownership of the file is taken, and `std::fclose()` will be called when the
40    object is destroyed.
41 
42    \param file The file to use as a data source. Must not be null. The file will
43    be closed (via `std::fclose()`) when the `FileReader`'s destructor runs.
44    */
45   explicit FileReader(FILE* file);
46 
47   /**
48    Constructs a new reader by moving the provided reader into the new reader.
49 
50    \param other The source reader to move. After moving, it will be reset to an
51    empty stream.
52    */
53   FileReader(FileReader&& other);
54 
55   /**
56    Moves the provided reader into this reader.
57 
58    \param other The source reader to move. After moving, it will be reset to an
59    empty stream. May be equal to `*this`, in which case this is a no-op.
60    \return `*this`.
61    */
62   FileReader& operator=(FileReader&& other);
63 
64   Status Read(std::size_t num_to_read, std::uint8_t* buffer,
65               std::uint64_t* num_actually_read) override;
66 
67   Status Skip(std::uint64_t num_to_skip,
68               std::uint64_t* num_actually_skipped) override;
69 
70   std::uint64_t Position() const override;
71 
72  private:
73   struct FileCloseFunctor {
operatorFileCloseFunctor74     void operator()(FILE* file) const {
75       if (file)
76         std::fclose(file);
77     }
78   };
79 
80   std::unique_ptr<FILE, FileCloseFunctor> file_;
81 
82   // We can't rely on ftell() for the position (since it only returns long, and
83   // doesn't work on things like pipes); we need to manually track the reading
84   // position.
85   std::uint64_t position_ = 0;
86 };
87 
88 }  // namespace webm
89 
90 #endif  // INCLUDE_WEBM_FILE_READER_H_
91