| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
#ifndef CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ |
| 16 |
#define CEREAL_RAPIDJSON_FILEWRITESTREAM_H_ |
| 17 |
|
| 18 |
#include "stream.h" |
| 19 |
#include <cstdio> |
| 20 |
|
| 21 |
#ifdef __clang__ |
| 22 |
CEREAL_RAPIDJSON_DIAG_PUSH |
| 23 |
CEREAL_RAPIDJSON_DIAG_OFF(unreachable-code) |
| 24 |
#endif |
| 25 |
|
| 26 |
CEREAL_RAPIDJSON_NAMESPACE_BEGIN |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
class FileWriteStream { |
| 33 |
public: |
| 34 |
typedef char Ch; |
| 35 |
|
| 36 |
FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) { |
| 37 |
CEREAL_RAPIDJSON_ASSERT(fp_ != 0); |
| 38 |
} |
| 39 |
|
| 40 |
void Put(char c) { |
| 41 |
if (current_ >= bufferEnd_) |
| 42 |
Flush(); |
| 43 |
|
| 44 |
*current_++ = c; |
| 45 |
} |
| 46 |
|
| 47 |
void PutN(char c, size_t n) { |
| 48 |
size_t avail = static_cast<size_t>(bufferEnd_ - current_); |
| 49 |
while (n > avail) { |
| 50 |
std::memset(current_, c, avail); |
| 51 |
current_ += avail; |
| 52 |
Flush(); |
| 53 |
n -= avail; |
| 54 |
avail = static_cast<size_t>(bufferEnd_ - current_); |
| 55 |
} |
| 56 |
|
| 57 |
if (n > 0) { |
| 58 |
std::memset(current_, c, n); |
| 59 |
current_ += n; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
void Flush() { |
| 64 |
if (current_ != buffer_) { |
| 65 |
size_t result = std::fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_); |
| 66 |
if (result < static_cast<size_t>(current_ - buffer_)) { |
| 67 |
|
| 68 |
|
| 69 |
} |
| 70 |
current_ = buffer_; |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
char Peek() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
| 76 |
char Take() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
| 77 |
size_t Tell() const { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
| 78 |
char* PutBegin() { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
| 79 |
size_t PutEnd(char*) { CEREAL_RAPIDJSON_ASSERT(false); return 0; } |
| 80 |
|
| 81 |
private: |
| 82 |
|
| 83 |
FileWriteStream(const FileWriteStream&); |
| 84 |
FileWriteStream& operator=(const FileWriteStream&); |
| 85 |
|
| 86 |
std::FILE* fp_; |
| 87 |
char *buffer_; |
| 88 |
char *bufferEnd_; |
| 89 |
char *current_; |
| 90 |
}; |
| 91 |
|
| 92 |
|
| 93 |
template<> |
| 94 |
inline void PutN(FileWriteStream& stream, char c, size_t n) { |
| 95 |
stream.PutN(c, n); |
| 96 |
} |
| 97 |
|
| 98 |
CEREAL_RAPIDJSON_NAMESPACE_END |
| 99 |
|
| 100 |
#ifdef __clang__ |
| 101 |
CEREAL_RAPIDJSON_DIAG_POP |
| 102 |
#endif |
| 103 |
|
| 104 |
#endif |