StreamWriter

This commit is contained in:
Christopher Dunn 2015-01-22 14:31:32 -06:00
parent 948f29032e
commit 5fbfe3cdb9
2 changed files with 80 additions and 3 deletions

View File

@ -23,6 +23,35 @@ namespace Json {
class Value;
class JSON_API StreamWriter {
protected:
std::ostream& sout_; // not owned; will not delete
public:
StreamWriter(std::ostream* sout);
virtual ~StreamWriter();
/// Write Value into document as configured in sub-class.
/// \return zero on success
/// \throw std::exception possibly, depending on configuration
virtual int write(Value const& root) const = 0;
};
class JSON_API StreamWriterBuilder {
public:
virtual ~StreamWriterBuilder();
/// Do not delete stream (i.e. not owned), but keep a reference.
virtual StreamWriter* newStreamWriter(std::ostream* stream) const;
};
class JSON_API StreamWriterBuilderFactory {
public:
virtual ~StreamWriterBuilderFactory();
virtual StreamWriterBuilder* newStreamWriterBuilder();
};
/// \brief Write into stringstream, then return string, for convenience.
std::string writeString(Value const& root, StreamWriterBuilder const& builder);
/** \brief Abstract class for writers.
*/
class JSON_API Writer {

View File

@ -7,13 +7,14 @@
#include <json/writer.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
#include <math.h>
#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
#include <float.h>
@ -670,4 +671,51 @@ std::ostream& operator<<(std::ostream& sout, const Value& root) {
return sout;
}
StreamWriter::StreamWriter(std::ostream* sout)
: sout_(*sout)
{
}
StreamWriter::~StreamWriter()
{
}
struct MyStreamWriter : public StreamWriter {
public:
MyStreamWriter(std::ostream* sout);
virtual ~MyStreamWriter();
virtual int write(Value const& root) const = 0;
};
MyStreamWriter::MyStreamWriter(std::ostream* sout)
: StreamWriter(sout)
{
}
MyStreamWriter::~MyStreamWriter()
{
}
int MyStreamWriter::write(Value const& root) const
{
sout_ << root;
return 0;
}
StreamWriterBuilder::~StreamWriterBuilder()
{
}
StreamWriter* StreamWriterBuilder::newStreamWriter(std::ostream* stream) const
{
// return new StyledStreamWriter(stream);
return nullptr;
}
StreamWriterBuilderFactory::~StreamWriterBuilderFactory()
{
}
StreamWriterBuilder* StreamWriterBuilderFactory::newStreamWriterBuilder()
{
return new StreamWriterBuilder;
}
std::string writeString(Value const& root, StreamWriterBuilder const& builder) {
std::ostringstream sout;
std::unique_ptr<StreamWriter> const sw(builder.newStreamWriter(&sout));
sw->write(root);
return sout.str();
}
} // namespace Json