3 In RapidJSON, `rapidjson::Stream` is a concept for reading/writing JSON. Here we first show how to use streams provided. And then see how to create a custom stream.
7 # Memory Streams {#MemoryStreams}
9 Memory streams store JSON in memory.
11 ## StringStream (Input) {#StringStream}
13 `StringStream` is the most basic input stream. It represents a complete, read-only JSON stored in memory. It is defined in `rapidjson/rapidjson.h`.
16 #include "rapidjson/document.h" // will include "rapidjson/rapidjson.h"
18 using namespace rapidjson;
21 const char json[] = "[1, 2, 3, 4]";
28 Since this is very common usage, `Document::Parse(const char*)` is provided to do exactly the same as above:
32 const char json[] = "[1, 2, 3, 4]";
37 Note that, `StringStream` is a typedef of `GenericStringStream<UTF8<> >`, user may use another encodings to represent the character set of the stream.
39 ## StringBuffer (Output) {#StringBuffer}
41 `StringBuffer` is a simple output stream. It allocates a memory buffer for writing the whole JSON. Use `GetString()` to obtain the buffer.
44 #include "rapidjson/stringbuffer.h"
47 Writer<StringBuffer> writer(buffer);
50 const char* output = buffer.GetString();
53 When the buffer is full, it will increases the capacity automatically. The default capacity is 256 characters (256 bytes for UTF8, 512 bytes for UTF16, etc.). User can provide an allocator and a initial capacity.
56 StringBuffer buffer1(0, 1024); // Use its allocator, initial size = 1024
57 StringBuffer buffer2(allocator, 1024);
60 By default, `StringBuffer` will instantiate an internal allocator.
62 Similarly, `StringBuffer` is a typedef of `GenericStringBuffer<UTF8<> >`.
64 # File Streams {#FileStreams}
66 When parsing a JSON from file, you may read the whole JSON into memory and use ``StringStream`` above.
68 However, if the JSON is big, or memory is limited, you can use `FileReadStream`. It only read a part of JSON from file into buffer, and then let the part be parsed. If it runs out of characters in the buffer, it will read the next part from file.
70 ## FileReadStream (Input) {#FileReadStream}
72 `FileReadStream` reads the file via a `FILE` pointer. And user need to provide a buffer.
75 #include "rapidjson/filereadstream.h"
78 using namespace rapidjson;
80 FILE* fp = fopen("big.json", "rb"); // non-Windows use "r"
82 char readBuffer[65536];
83 FileReadStream is(fp, readBuffer, sizeof(readBuffer));
91 Different from string streams, `FileReadStream` is byte stream. It does not handle encodings. If the file is not UTF-8, the byte stream can be wrapped in a `EncodedInputStream`. It will be discussed very soon.
93 Apart from reading file, user can also use `FileReadStream` to read `stdin`.
95 ## FileWriteStream (Output) {#FileWriteStream}
97 `FileWriteStream` is buffered output stream. Its usage is very similar to `FileReadStream`.
100 #include "rapidjson/filewritestream.h"
103 using namespace rapidjson;
109 FILE* fp = fopen("output.json", "wb"); // non-Windows use "w"
111 char writeBuffer[65536];
112 FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
114 Writer<FileWriteStream> writer(os);
120 It can also directs the output to `stdout`.
122 # iostream Wrapper {#iostreamWrapper}
124 Due to users' requests, RapidJSON provided official wrappers for `std::basic_istream` and `std::basic_ostream`. However, please note that the performance will be much lower than the other streams above.
126 ## IStreamWrapper {#IStreamWrapper}
128 `IStreamWrapper` wraps any class drived from `std::istream`, such as `std::istringstream`, `std::stringstream`, `std::ifstream`, `std::fstream`, into RapidJSON's input stream.
131 #include <rapidjson/document.h>
132 #include <rapidjson/istreamwrapper.h>
135 using namespace rapidjson;
138 ifstream ifs("test.json");
139 IStreamWrapper isw(ifs);
145 For classes derived from `std::wistream`, use `WIStreamWrapper`.
147 ## OStreamWrapper {#OStreamWrapper}
149 Similarly, `OStreamWrapper` wraps any class derived from `std::ostream`, such as `std::ostringstream`, `std::stringstream`, `std::ofstream`, `std::fstream`, into RapidJSON's input stream.
152 #include <rapidjson/document.h>
153 #include <rapidjson/ostreamwrapper.h>
154 #include <rapidjson/writer.h>
157 using namespace rapidjson;
165 ofstream ofs("output.json");
166 OStreamWrapper osw(ofs);
168 Writer<OStreamWrapper> writer(osw);
172 For classes derived from `std::wostream`, use `WOStreamWrapper`.
174 # Encoded Streams {#EncodedStreams}
176 Encoded streams do not contain JSON itself, but they wrap byte streams to provide basic encoding/decoding function.
178 As mentioned above, UTF-8 byte streams can be read directly. However, UTF-16 and UTF-32 have endian issue. To handle endian correctly, it needs to convert bytes into characters (e.g. `wchar_t` for UTF-16) while reading, and characters into bytes while writing.
180 Besides, it also need to handle [byte order mark (BOM)](http://en.wikipedia.org/wiki/Byte_order_mark). When reading from a byte stream, it is needed to detect or just consume the BOM if exists. When writing to a byte stream, it can optionally write BOM.
182 If the encoding of stream is known in compile-time, you may use `EncodedInputStream` and `EncodedOutputStream`. If the stream can be UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE JSON, and it is only known in runtime, you may use `AutoUTFInputStream` and `AutoUTFOutputStream`. These streams are defined in `rapidjson/encodedstream.h`.
184 Note that, these encoded streams can be applied to streams other than file. For example, you may have a file in memory, or a custom byte stream, be wrapped in encoded streams.
186 ## EncodedInputStream {#EncodedInputStream}
188 `EncodedInputStream` has two template parameters. The first one is a `Encoding` class, such as `UTF8`, `UTF16LE`, defined in `rapidjson/encodings.h`. The second one is the class of stream to be wrapped.
191 #include "rapidjson/document.h"
192 #include "rapidjson/filereadstream.h" // FileReadStream
193 #include "rapidjson/encodedstream.h" // EncodedInputStream
196 using namespace rapidjson;
198 FILE* fp = fopen("utf16le.json", "rb"); // non-Windows use "r"
200 char readBuffer[256];
201 FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
203 EncodedInputStream<UTF16LE<>, FileReadStream> eis(bis); // wraps bis into eis
205 Document d; // Document is GenericDocument<UTF8<> >
206 d.ParseStream<0, UTF16LE<> >(eis); // Parses UTF-16LE file into UTF-8 in memory
211 ## EncodedOutputStream {#EncodedOutputStream}
213 `EncodedOutputStream` is similar but it has a `bool putBOM` parameter in the constructor, controlling whether to write BOM into output byte stream.
216 #include "rapidjson/filewritestream.h" // FileWriteStream
217 #include "rapidjson/encodedstream.h" // EncodedOutputStream
220 Document d; // Document is GenericDocument<UTF8<> >
223 FILE* fp = fopen("output_utf32le.json", "wb"); // non-Windows use "w"
225 char writeBuffer[256];
226 FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer));
228 typedef EncodedOutputStream<UTF32LE<>, FileWriteStream> OutputStream;
229 OutputStream eos(bos, true); // Write BOM
231 Writer<OutputStream, UTF32LE<>, UTF8<>> writer(eos);
232 d.Accept(writer); // This generates UTF32-LE file from UTF-8 in memory
237 ## AutoUTFInputStream {#AutoUTFInputStream}
239 Sometimes an application may want to handle all supported JSON encoding. `AutoUTFInputStream` will detection encoding by BOM first. If BOM is unavailable, it will use characteristics of valid JSON to make detection. If neither method success, it falls back to the UTF type provided in constructor.
241 Since the characters (code units) may be 8-bit, 16-bit or 32-bit. `AutoUTFInputStream` requires a character type which can hold at least 32-bit. We may use `unsigned`, as in the template parameter:
244 #include "rapidjson/document.h"
245 #include "rapidjson/filereadstream.h" // FileReadStream
246 #include "rapidjson/encodedstream.h" // AutoUTFInputStream
249 using namespace rapidjson;
251 FILE* fp = fopen("any.json", "rb"); // non-Windows use "r"
253 char readBuffer[256];
254 FileReadStream bis(fp, readBuffer, sizeof(readBuffer));
256 AutoUTFInputStream<unsigned, FileReadStream> eis(bis); // wraps bis into eis
258 Document d; // Document is GenericDocument<UTF8<> >
259 d.ParseStream<0, AutoUTF<unsigned> >(eis); // This parses any UTF file into UTF-8 in memory
264 When specifying the encoding of stream, uses `AutoUTF<CharType>` as in `ParseStream()` above.
266 You can obtain the type of UTF via `UTFType GetType()`. And check whether a BOM is found by `HasBOM()`
268 ## AutoUTFOutputStream {#AutoUTFOutputStream}
270 Similarly, to choose encoding for output during runtime, we can use `AutoUTFOutputStream`. This class is not automatic *per se*. You need to specify the UTF type and whether to write BOM in runtime.
273 using namespace rapidjson;
275 void WriteJSONFile(FILE* fp, UTFType type, bool putBOM, const Document& d) {
276 char writeBuffer[256];
277 FileWriteStream bos(fp, writeBuffer, sizeof(writeBuffer));
279 typedef AutoUTFOutputStream<unsigned, FileWriteStream> OutputStream;
280 OutputStream eos(bos, type, putBOM);
282 Writer<OutputStream, UTF8<>, AutoUTF<> > writer;
287 `AutoUTFInputStream` and `AutoUTFOutputStream` is more convenient than `EncodedInputStream` and `EncodedOutputStream`. They just incur a little bit runtime overheads.
289 # Custom Stream {#CustomStream}
291 In addition to memory/file streams, user can create their own stream classes which fits RapidJSON's API. For example, you may create network stream, stream from compressed file, etc.
293 RapidJSON combines different types using templates. A class containing all required interface can be a stream. The Stream interface is defined in comments of `rapidjson/rapidjson.h`:
297 typename Ch; //!< Character type of the stream.
299 //! Read the current character from stream without moving the read cursor.
302 //! Read the current character from stream and moving the read cursor to next character.
305 //! Get the current read cursor.
306 //! \return Number of characters read from start.
309 //! Begin writing operation at the current read pointer.
310 //! \return The begin writer pointer.
313 //! Write a character.
316 //! Flush the buffer.
319 //! End the writing operation.
320 //! \param begin The begin write pointer returned by PutBegin().
321 //! \return Number of characters written.
322 size_t PutEnd(Ch* begin);
326 For input stream, they must implement `Peek()`, `Take()` and `Tell()`.
327 For output stream, they must implement `Put()` and `Flush()`.
328 There are two special interface, `PutBegin()` and `PutEnd()`, which are only for *in situ* parsing. Normal streams do not implement them. However, if the interface is not needed for a particular stream, it is still need to a dummy implementation, otherwise will generate compilation error.
330 ## Example: istream wrapper {#ExampleIStreamWrapper}
332 The following example is a simple wrapper of `std::istream`, which only implements 3 functions.
335 class MyIStreamWrapper {
339 MyIStreamWrapper(std::istream& is) : is_(is) {
342 Ch Peek() const { // 1
344 return c == std::char_traits<char>::eof() ? '\0' : (Ch)c;
349 return c == std::char_traits<char>::eof() ? '\0' : (Ch)c;
352 size_t Tell() const { return (size_t)is_.tellg(); } // 3
354 Ch* PutBegin() { assert(false); return 0; }
355 void Put(Ch) { assert(false); }
356 void Flush() { assert(false); }
357 size_t PutEnd(Ch*) { assert(false); return 0; }
360 MyIStreamWrapper(const MyIStreamWrapper&);
361 MyIStreamWrapper& operator=(const MyIStreamWrapper&);
367 User can use it to wrap instances of `std::stringstream`, `std::ifstream`.
370 const char* json = "[1,2,3,4]";
371 std::stringstream ss(json);
372 MyIStreamWrapper is(ss);
378 Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.
380 ## Example: ostream wrapper {#ExampleOStreamWrapper}
382 The following example is a simple wrapper of `std::istream`, which only implements 2 functions.
385 class MyOStreamWrapper {
389 MyOStreamWrapper(std::ostream& os) : os_(os) {
392 Ch Peek() const { assert(false); return '\0'; }
393 Ch Take() { assert(false); return '\0'; }
394 size_t Tell() const { }
396 Ch* PutBegin() { assert(false); return 0; }
397 void Put(Ch c) { os_.put(c); } // 1
398 void Flush() { os_.flush(); } // 2
399 size_t PutEnd(Ch*) { assert(false); return 0; }
402 MyOStreamWrapper(const MyOStreamWrapper&);
403 MyOStreamWrapper& operator=(const MyOStreamWrapper&);
409 User can use it to wrap instances of `std::stringstream`, `std::ofstream`.
415 std::stringstream ss;
416 MyOStreamWrapper os(ss);
418 Writer<MyOStreamWrapper> writer(os);
422 Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.
426 This section describes stream classes available in RapidJSON. Memory streams are simple. File stream can reduce the memory required during JSON parsing and generation, if the JSON is stored in file system. Encoded streams converts between byte streams and character streams. Finally, user may create custom streams using a simple interface.