In 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 streams.
## Memory Streams
Memory streams store JSON in memory.
### StringStream (Input)
`StringStream` is the most basic input stream. It represents a complete, read-only JSON stored in memory. It is defined in `rapidjson/rapidjson.h`.
```cpp
#include "rapidjson/document.h" // will include "rapidjson/rapidjson.h"
usingnamespacerapidjson;
// ...
constcharjson[]="[1, 2, 3, 4]";
StringStreams(json);
Documentd;
d.ParseStream(s);
```
Since this is very common usage, `Document::Parse(const char*)` is provided to do exactly the same as above:
```cpp
// ...
constcharjson[]="[1, 2, 3, 4]";
Documentd;
d.Parse(json);
```
Note that, `StringStream` is a typedef of `GenericStringStream<UTF8<> >`, user may use another encodings to represent the character set of the stream.
### StringBuffer (Output)
`StringBuffer` is a simple output stream. It allocates a memory buffer for writing the whole JSON. Use `GetString()` to obtain the buffer.
```cpp
#include "rapidjson/stringbuffer.h"
StringBufferbuffer;
Writer<StringBuffer>writer(buffer);
d.Accept(writer);
constchar*output=buffer.GetString();
```
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.
```cpp
StringBufferbuffer1(0,1024);// Use its allocator, initial size = 1024
StringBufferbuffer2(allocator,1024);
```
By default, `StringBuffer` will instantiate an internal allocator.
Similarly, `StringBuffer` is a typedef of `GenericStringBuffer<UTF8<> >`.
## File Streams
When parsing a JSON from file, you may read the whole JSON into memory and use ``StringStream`` above.
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.
### FileReadStream (Input)
`FileReadStream` reads the file via a `FILE` pointer. And user need to provide a buffer.
```cpp
#include "rapidjson/filereadstream.h"
#include <cstdio>
FILE*fp=fopen("big.json","rb");// non-Windows use "r"
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.
Apart from reading file, user can also use `FileReadStream` to read `stdin`.
### FileWriteStream (Output)
`FileWriteStream` is buffered output stream. Its usage is very similar to `FileReadStream`.
```cpp
#include "rapidjson/filewritestream.h"
#include <cstdio>
Documentd;
d.Parse(json);
// ...
FILE*fp=fopen("output.json","wb");// non-Windows use "w"
Encoded streams do not contain JSON itself, but they wrap byte streams to provide basic encoding/decoding function.
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.
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.
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`.
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.
### EncodedInputStream
`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.
d.Accept(writer);// This generates UTF32-LE file from UTF-8 in memory
fclose(fp);
```
### AutoUTFInputStream
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.
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:
AutoUTFInputStream<unsigned,FileReadStream>eis(bis);// wraps bis into eis
Documentd;// Document is GenericDocument<UTF8<> >
d.ParseStream<0,AutoUTF<unsigned>>(eis);// This parses any UTF file into UTF-8 in memory
fclose(fp);
```
When specifying the encoding of stream, uses `AutoUTF<CharType>` as in `ParseStream()` above.
You can obtain the type of UTF via `UTFType GetType()`. And check whether a BOM is found by `HasBOM()`
### AutoUTFOutputStream
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.
`AutoUTFInputStream` and `AutoUTFOutputStream` is more convenient than `EncodedInputStream` and `EncodedOutputStream`. They just incur a little bit runtime overheads.
## Custom Stream
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.
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`:
```cpp
conceptStream{
typenameCh;//!< Character type of the stream.
//! Read the current character from stream without moving the read cursor.
ChPeek()const;
//! Read the current character from stream and moving the read cursor to next character.
ChTake();
//! Get the current read cursor.
//! \return Number of characters read from start.
size_tTell();
//! Begin writing operation at the current read pointer.
//! \return The begin writer pointer.
Ch*PutBegin();
//! Write a character.
voidPut(Chc);
//! Flush the buffer.
voidFlush();
//! End the writing operation.
//! \param begin The begin write pointer returned by PutBegin().
//! \return Number of characters written.
size_tPutEnd(Ch*begin);
}
```
For input stream, they must implement `Peek()`, `Take()` and `Tell()`.
For output stream, they must implement `Put()` and `Flush()`.
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.
### Example: istream wrapper
The following example is a wrapper of `std::istream`, which only implements 3 functions.
User can use it to wrap instances of `std::stringstream`, `std::ifstream`.
```cpp
constchar*json="[1,2,3,4]";
std::stringstreamss(json);
IStreamWrapperis(ss);
Documentd;
d.Parse(is);
```
Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.
### Example: ostream wrapper
The following example is a wrapper of `std::istream`, which only implements 2 functions.
```cpp
classOStreamWrapper{
public:
typedefcharCh;
OStreamWrapper(std::ostream&os):os_(os){
}
ChPeek()const{assert(false);return'\0';}
ChTake(){assert(false);return'\0';}
size_tTell()const{}
Ch*PutBegin(){assert(false);return0;}
voidPut(Chc){os_.put(c);}// 1
voidFlush(){os_.flush();}// 2
size_tPutEnd(Ch*){assert(false);return0;}
private:
OStreamWrapper(constOStreamWrapper&);
OStreamWrapper&operator=(constOStreamWrapper&);
std::ostream&os_;
};
```
User can use it to wrap instances of `std::stringstream`, `std::ofstream`.
```cpp
Documentd;
// ...
std::stringstreamss;
OSStreamWrapperos(ss);
Writer<OStreamWrapper>writer(os);
d.Accept(writer);
```
Note that, this implementation may not be as efficient as RapidJSON's memory or file streams, due to internal overheads of the standard library.
## Summary
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.