All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
filereadstream.h
1 #ifndef RAPIDJSON_FILEREADSTREAM_H_
2 #define RAPIDJSON_FILEREADSTREAM_H_
3 
4 #include "rapidjson.h"
5 #include <cstdio>
6 
7 namespace rapidjson {
8 
9 //! File byte stream for input using fread().
10 /*!
11  \note implements Stream concept
12 */
14 public:
15  typedef char Ch; //!< Character type (byte).
16 
17  //! Constructor.
18  /*!
19  \param fp File pointer opened for read.
20  \param buffer user-supplied buffer.
21  \param bufferSize size of buffer in bytes. Must >=4 bytes.
22  */
23  FileReadStream(FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) {
24  RAPIDJSON_ASSERT(fp_ != 0);
25  RAPIDJSON_ASSERT(bufferSize >= 4);
26  Read();
27  }
28 
29  Ch Peek() const { return *current_; }
30  Ch Take() { Ch c = *current_; Read(); return c; }
31  size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); }
32 
33  // Not implemented
34  void Put(Ch) { RAPIDJSON_ASSERT(false); }
35  void Flush() { RAPIDJSON_ASSERT(false); }
36  Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
37  size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
38 
39  // For encoding detection only.
40  const Ch* Peek4() const {
41  return (current_ + 4 <= bufferLast_) ? current_ : 0;
42  }
43 
44 private:
45  void Read() {
46  if (current_ < bufferLast_)
47  ++current_;
48  else if (!eof_) {
49  count_ += readCount_;
50  readCount_ = fread(buffer_, 1, bufferSize_, fp_);
51  bufferLast_ = buffer_ + readCount_ - 1;
52  current_ = buffer_;
53 
54  if (readCount_ < bufferSize_) {
55  buffer_[readCount_] = '\0';
56  ++bufferLast_;
57  eof_ = true;
58  }
59  }
60  }
61 
62  FILE* fp_;
63  Ch *buffer_;
64  size_t bufferSize_;
65  Ch *bufferLast_;
66  Ch *current_;
67  size_t readCount_;
68  size_t count_; //!< Number of characters read
69  bool eof_;
70 };
71 
72 } // namespace rapidjson
73 
74 #endif // RAPIDJSON_FILESTREAM_H_