filewritestream.h
1 #ifndef RAPIDJSON_FILEWRITESTREAM_H_
2 #define RAPIDJSON_FILEWRITESTREAM_H_
3 
4 #include "rapidjson.h"
5 #include <cstdio>
6 
7 namespace rapidjson {
8 
9 //! Wrapper of C file stream for input using fread().
10 /*!
11  \note implements Stream concept
12 */
14 public:
15  typedef char Ch; //!< Character type. Only support char.
16 
17  FileWriteStream(FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) {
18  RAPIDJSON_ASSERT(fp_ != 0);
19  }
20 
21  void Put(char c) {
22  if (current_ >= bufferEnd_)
23  Flush();
24 
25  *current_++ = c;
26  }
27 
28  void PutN(char c, size_t n) {
29  size_t avail = static_cast<size_t>(bufferEnd_ - current_);
30  while (n > avail) {
31  memset(current_, c, avail);
32  current_ += avail;
33  Flush();
34  n -= avail;
35  avail = static_cast<size_t>(bufferEnd_ - current_);
36  }
37 
38  if (n > 0) {
39  memset(current_, c, n);
40  current_ += n;
41  }
42  }
43 
44  void Flush() {
45  if (current_ != buffer_) {
46  fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
47  current_ = buffer_;
48  }
49  }
50 
51  // Not implemented
52  char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
53  char Take() { RAPIDJSON_ASSERT(false); return 0; }
54  size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
55  char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
56  size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
57 
58 private:
59  // Prohibit copy constructor & assignment operator.
60  FileWriteStream(const FileWriteStream&);
61  FileWriteStream& operator=(const FileWriteStream&);
62 
63  FILE* fp_;
64  char *buffer_;
65  char *bufferEnd_;
66  char *current_;
67 };
68 
69 //! Implement specialized version of PutN() with memset() for better performance.
70 template<>
71 inline void PutN(FileWriteStream& stream, char c, size_t n) {
72  stream.PutN(c, n);
73 }
74 
75 } // namespace rapidjson
76 
77 #endif // RAPIDJSON_FILESTREAM_H_
Wrapper of C file stream for input using fread().
Definition: filewritestream.h:13
#define RAPIDJSON_ASSERT(x)
Assertion.
Definition: rapidjson.h:146
char Ch
Character type. Only support char.
Definition: filewritestream.h:15
void PutN(FileWriteStream &stream, char c, size_t n)
Implement specialized version of PutN() with memset() for better performance.
Definition: filewritestream.h:71
main RapidJSON namespace
Definition: allocators.h:6
common definitions and configuration