diff options
author | orivej <orivej@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:01 +0300 |
commit | 2d37894b1b037cf24231090eda8589bbb44fb6fc (patch) | |
tree | be835aa92c6248212e705f25388ebafcf84bc7a1 /contrib/libs/poco/JSON | |
parent | 718c552901d703c502ccbefdfc3c9028d608b947 (diff) | |
download | ydb-2d37894b1b037cf24231090eda8589bbb44fb6fc.tar.gz |
Restoring authorship annotation for <orivej@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/libs/poco/JSON')
28 files changed, 6031 insertions, 6031 deletions
diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Array.h b/contrib/libs/poco/JSON/include/Poco/JSON/Array.h index dcd27005a7..6a61ad39c6 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Array.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Array.h @@ -1,566 +1,566 @@ -// -// Array.h -// -// Library: JSON -// Package: JSON -// Module: Array -// -// Definition of the Array class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_Array_INCLUDED -#define JSON_Array_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include <vector> -#include <sstream> - - -namespace Poco { -namespace JSON { - - -class Object; - - -class JSON_API Array - /// Represents a JSON array. Array provides a representation - /// based on shared pointers and optimized for performance. It is possible to - /// convert Array to Poco::Dynamic::Array. Conversion requires copying and therefore - /// has performance penalty; the benefit is in improved syntax, eg: - /// - /// // use pointers to avoid copying - /// using namespace Poco::JSON; - /// std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]"; - /// Parser parser; - /// Var result = parser.parse(json); - /// Array::Ptr arr = result.extract<Array::Ptr>(); - /// Object::Ptr object = arr->getObject(0); // object == {\"test\" : 0} - /// int i = object->getElement<int>("test"); // i == 0; - /// Object::Ptr subObject = *arr->getObject(1); // subObject == {\"test\" : 0} - /// Array subArr::Ptr = subObject->getArray("test1"); // subArr == [1, 2, 3] - /// i = result = subArr->get(0); // i == 1; - /// - /// // copy/convert to Poco::Dynamic::Array - /// Poco::Dynamic::Array da = *arr; - /// i = da[0]["test"]; // i == 0 - /// i = da[1]["test1"][1]; // i == 2 - /// i = da[1]["test2"]; // i == 4 - /// ---- -{ -public: - typedef std::vector<Dynamic::Var> ValueVec; - typedef std::vector<Dynamic::Var>::iterator Iterator; - typedef std::vector<Dynamic::Var>::const_iterator ConstIterator; - typedef SharedPtr<Array> Ptr; - - Array(int options = 0); - /// Creates an empty Array. - /// - /// If JSON_ESCAPE_UNICODE is specified, when the object is - /// stringified, all unicode characters will be escaped in the - /// resulting string. - - Array(const Array& copy); - /// Creates an Array by copying another one. - -#ifdef POCO_ENABLE_CPP11 - - Array(Array&& other); - /// Move constructor - - Array& operator=(Array&& other); - /// Move assignment operator. - -#endif // POCO_ENABLE_CPP11 - - Array& operator=(const Array& other); - /// Assignment operator. - - virtual ~Array(); - /// Destroys the Array. - - void setEscapeUnicode(bool escape = true); - /// Sets the flag for escaping unicode. - - bool getEscapeUnicode() const; - /// Returns the flag for escaping unicode. - - ValueVec::const_iterator begin() const; - /// Returns the begin iterator for values. - - ValueVec::const_iterator end() const; - /// Returns the end iterator for values. - - Dynamic::Var get(unsigned int index) const; - /// Retrieves the element at the given index. - /// Will return an empty value when the element doesn't exist. - - Array::Ptr getArray(unsigned int index) const; - /// Retrieves an array. When the element is not - /// an Array or doesn't exist, an empty SharedPtr is returned. - - template<typename T> - T getElement(unsigned int index) const - /// Retrieves an element and tries to convert it to the - /// template type. The convert<T> method of - /// Dynamic is called which can also throw - /// exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - Dynamic::Var value = get(index); - return value.convert<T>(); - } - - SharedPtr<Object> getObject(unsigned int index) const; - /// Retrieves an object. When the element is not - /// an object or doesn't exist, an empty SharedPtr is returned. - - std::size_t size() const; - /// Returns the size of the array. - - bool isArray(unsigned int index) const; - /// Returns true when the element is an array. - - bool isArray(const Dynamic::Var& value) const; - /// Returns true when the element is an array. - - bool isArray(ConstIterator& value) const; - /// Returns true when the element is an array. - - bool isNull(unsigned int index) const; - /// Returns true when the element is null or - /// when the element doesn't exist. - - bool isObject(unsigned int index) const; - /// Returns true when the element is an object. - - bool isObject(const Dynamic::Var& value) const; - /// Returns true when the element is an object. - - bool isObject(ConstIterator& value) const; - /// Returns true when the element is an object. - - template<typename T> - T optElement(unsigned int index, const T& def) const - /// Returns the element at the given index. When - /// the element is null, doesn't exist or can't - /// be converted to the given type, the default - /// value will be returned - { - T value = def; - if (index < _values.size()) - { - try - { - value = _values[index].convert<T>(); - } - catch (...) - { - // Default value is returned. - } - } - return value; - } - - void add(const Dynamic::Var& value); - /// Add the given value to the array - - void set(unsigned int index, const Dynamic::Var& value); - /// Update the element on the given index to specified value - - void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; - /// Prints the array to out. When indent has zero value, - /// the array will be printed without newline breaks and spaces between elements. - - void remove(unsigned int index); - /// Removes the element on the given index. - - operator const Poco::Dynamic::Array& () const; - /// Conversion operator to Dynamic::Array. - - static Poco::Dynamic::Array makeArray(const JSON::Array::Ptr& arr); - /// Utility function for creation of array. - - void clear(); - /// Clears the contents of the array. - -private: - void resetDynArray() const; - - typedef SharedPtr<Poco::Dynamic::Array> ArrayPtr; - - ValueVec _values; - mutable ArrayPtr _pArray; - mutable bool _modified; - // Note: - // The reason we have this flag here (rather than as argument to stringify()) - // is because Array can be returned stringified from a Dynamic::Var:toString(), - // so it must know whether to escape unicode or not. - bool _escapeUnicode; -}; - - -// -// inlines -// - -inline void Array::setEscapeUnicode(bool escape) -{ - _escapeUnicode = escape; -} - - -inline bool Array::getEscapeUnicode() const -{ - return _escapeUnicode; -} - - -inline Array::ValueVec::const_iterator Array::begin() const -{ - return _values.begin(); -} - - -inline Array::ValueVec::const_iterator Array::end() const - -{ - return _values.end(); -} - - -inline std::size_t Array::size() const -{ - return static_cast<std::size_t>(_values.size()); -} - - -inline bool Array::isArray(unsigned int index) const -{ - Dynamic::Var value = get(index); - return isArray(value); -} - - -inline bool Array::isArray(const Dynamic::Var& value) const -{ - return value.type() == typeid(Array::Ptr); -} - - -inline bool Array::isArray(ConstIterator& it) const -{ - return it!= end() && isArray(*it); -} - - -inline void Array::add(const Dynamic::Var& value) -{ - _values.push_back(value); - _modified = true; -} - - -inline void Array::set(unsigned int index, const Dynamic::Var& value) -{ - if (index >= _values.size()) _values.resize(index + 1); - _values[index] = value; - _modified = true; -} - - -inline void Array::remove(unsigned int index) -{ - _values.erase(_values.begin() + index); -} - - -} } // namespace Poco::JSON - - -namespace Poco { -namespace Dynamic { - - -template <> -class VarHolderImpl<JSON::Array::Ptr>: public VarHolder -{ -public: - VarHolderImpl(const JSON::Array::Ptr& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Array::Ptr); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = !_val.isNull() && _val->size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val->stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - throw BadCastException("Cannot convert Array to DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - throw BadCastException("Cannot convert Array to LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - throw BadCastException("Cannot convert Array to Timestamp"); - } - - VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Array::Ptr& value() const - { - return _val; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Array::Ptr _val; -}; - - -template <> -class VarHolderImpl<JSON::Array>: public VarHolder -{ -public: - VarHolderImpl(const JSON::Array& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Array); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = _val.size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val.stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - throw BadCastException("Cannot convert Array to DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - throw BadCastException("Cannot convert Array to LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - throw BadCastException("Cannot convert Array to Timestamp"); - } - - VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Array& value() const - { - return _val; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Array _val; -}; - - -} } // namespace Poco::Dynamic - - -#endif // JSON_Array_INCLUDED +// +// Array.h +// +// Library: JSON +// Package: JSON +// Module: Array +// +// Definition of the Array class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_Array_INCLUDED +#define JSON_Array_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/SharedPtr.h" +#include "Poco/Dynamic/Var.h" +#include <vector> +#include <sstream> + + +namespace Poco { +namespace JSON { + + +class Object; + + +class JSON_API Array + /// Represents a JSON array. Array provides a representation + /// based on shared pointers and optimized for performance. It is possible to + /// convert Array to Poco::Dynamic::Array. Conversion requires copying and therefore + /// has performance penalty; the benefit is in improved syntax, eg: + /// + /// // use pointers to avoid copying + /// using namespace Poco::JSON; + /// std::string json = "[ {\"test\" : 0}, { \"test1\" : [1, 2, 3], \"test2\" : 4 } ]"; + /// Parser parser; + /// Var result = parser.parse(json); + /// Array::Ptr arr = result.extract<Array::Ptr>(); + /// Object::Ptr object = arr->getObject(0); // object == {\"test\" : 0} + /// int i = object->getElement<int>("test"); // i == 0; + /// Object::Ptr subObject = *arr->getObject(1); // subObject == {\"test\" : 0} + /// Array subArr::Ptr = subObject->getArray("test1"); // subArr == [1, 2, 3] + /// i = result = subArr->get(0); // i == 1; + /// + /// // copy/convert to Poco::Dynamic::Array + /// Poco::Dynamic::Array da = *arr; + /// i = da[0]["test"]; // i == 0 + /// i = da[1]["test1"][1]; // i == 2 + /// i = da[1]["test2"]; // i == 4 + /// ---- +{ +public: + typedef std::vector<Dynamic::Var> ValueVec; + typedef std::vector<Dynamic::Var>::iterator Iterator; + typedef std::vector<Dynamic::Var>::const_iterator ConstIterator; + typedef SharedPtr<Array> Ptr; + + Array(int options = 0); + /// Creates an empty Array. + /// + /// If JSON_ESCAPE_UNICODE is specified, when the object is + /// stringified, all unicode characters will be escaped in the + /// resulting string. + + Array(const Array& copy); + /// Creates an Array by copying another one. + +#ifdef POCO_ENABLE_CPP11 + + Array(Array&& other); + /// Move constructor + + Array& operator=(Array&& other); + /// Move assignment operator. + +#endif // POCO_ENABLE_CPP11 + + Array& operator=(const Array& other); + /// Assignment operator. + + virtual ~Array(); + /// Destroys the Array. + + void setEscapeUnicode(bool escape = true); + /// Sets the flag for escaping unicode. + + bool getEscapeUnicode() const; + /// Returns the flag for escaping unicode. + + ValueVec::const_iterator begin() const; + /// Returns the begin iterator for values. + + ValueVec::const_iterator end() const; + /// Returns the end iterator for values. + + Dynamic::Var get(unsigned int index) const; + /// Retrieves the element at the given index. + /// Will return an empty value when the element doesn't exist. + + Array::Ptr getArray(unsigned int index) const; + /// Retrieves an array. When the element is not + /// an Array or doesn't exist, an empty SharedPtr is returned. + + template<typename T> + T getElement(unsigned int index) const + /// Retrieves an element and tries to convert it to the + /// template type. The convert<T> method of + /// Dynamic is called which can also throw + /// exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + Dynamic::Var value = get(index); + return value.convert<T>(); + } + + SharedPtr<Object> getObject(unsigned int index) const; + /// Retrieves an object. When the element is not + /// an object or doesn't exist, an empty SharedPtr is returned. + + std::size_t size() const; + /// Returns the size of the array. + + bool isArray(unsigned int index) const; + /// Returns true when the element is an array. + + bool isArray(const Dynamic::Var& value) const; + /// Returns true when the element is an array. + + bool isArray(ConstIterator& value) const; + /// Returns true when the element is an array. + + bool isNull(unsigned int index) const; + /// Returns true when the element is null or + /// when the element doesn't exist. + + bool isObject(unsigned int index) const; + /// Returns true when the element is an object. + + bool isObject(const Dynamic::Var& value) const; + /// Returns true when the element is an object. + + bool isObject(ConstIterator& value) const; + /// Returns true when the element is an object. + + template<typename T> + T optElement(unsigned int index, const T& def) const + /// Returns the element at the given index. When + /// the element is null, doesn't exist or can't + /// be converted to the given type, the default + /// value will be returned + { + T value = def; + if (index < _values.size()) + { + try + { + value = _values[index].convert<T>(); + } + catch (...) + { + // Default value is returned. + } + } + return value; + } + + void add(const Dynamic::Var& value); + /// Add the given value to the array + + void set(unsigned int index, const Dynamic::Var& value); + /// Update the element on the given index to specified value + + void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; + /// Prints the array to out. When indent has zero value, + /// the array will be printed without newline breaks and spaces between elements. + + void remove(unsigned int index); + /// Removes the element on the given index. + + operator const Poco::Dynamic::Array& () const; + /// Conversion operator to Dynamic::Array. + + static Poco::Dynamic::Array makeArray(const JSON::Array::Ptr& arr); + /// Utility function for creation of array. + + void clear(); + /// Clears the contents of the array. + +private: + void resetDynArray() const; + + typedef SharedPtr<Poco::Dynamic::Array> ArrayPtr; + + ValueVec _values; + mutable ArrayPtr _pArray; + mutable bool _modified; + // Note: + // The reason we have this flag here (rather than as argument to stringify()) + // is because Array can be returned stringified from a Dynamic::Var:toString(), + // so it must know whether to escape unicode or not. + bool _escapeUnicode; +}; + + +// +// inlines +// + +inline void Array::setEscapeUnicode(bool escape) +{ + _escapeUnicode = escape; +} + + +inline bool Array::getEscapeUnicode() const +{ + return _escapeUnicode; +} + + +inline Array::ValueVec::const_iterator Array::begin() const +{ + return _values.begin(); +} + + +inline Array::ValueVec::const_iterator Array::end() const + +{ + return _values.end(); +} + + +inline std::size_t Array::size() const +{ + return static_cast<std::size_t>(_values.size()); +} + + +inline bool Array::isArray(unsigned int index) const +{ + Dynamic::Var value = get(index); + return isArray(value); +} + + +inline bool Array::isArray(const Dynamic::Var& value) const +{ + return value.type() == typeid(Array::Ptr); +} + + +inline bool Array::isArray(ConstIterator& it) const +{ + return it!= end() && isArray(*it); +} + + +inline void Array::add(const Dynamic::Var& value) +{ + _values.push_back(value); + _modified = true; +} + + +inline void Array::set(unsigned int index, const Dynamic::Var& value) +{ + if (index >= _values.size()) _values.resize(index + 1); + _values[index] = value; + _modified = true; +} + + +inline void Array::remove(unsigned int index) +{ + _values.erase(_values.begin() + index); +} + + +} } // namespace Poco::JSON + + +namespace Poco { +namespace Dynamic { + + +template <> +class VarHolderImpl<JSON::Array::Ptr>: public VarHolder +{ +public: + VarHolderImpl(const JSON::Array::Ptr& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(JSON::Array::Ptr); + } + + void convert(Int8&) const + { + throw BadCastException(); + } + + void convert(Int16&) const + { + throw BadCastException(); + } + + void convert(Int32&) const + { + throw BadCastException(); + } + + void convert(Int64&) const + { + throw BadCastException(); + } + + void convert(UInt8&) const + { + throw BadCastException(); + } + + void convert(UInt16&) const + { + throw BadCastException(); + } + + void convert(UInt32&) const + { + throw BadCastException(); + } + + void convert(UInt64&) const + { + throw BadCastException(); + } + + void convert(bool& value) const + { + value = !_val.isNull() && _val->size() > 0; + } + + void convert(float&) const + { + throw BadCastException(); + } + + void convert(double&) const + { + throw BadCastException(); + } + + void convert(char&) const + { + throw BadCastException(); + } + + void convert(std::string& s) const + { + std::ostringstream oss; + _val->stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime& /*val*/) const + { + throw BadCastException("Cannot convert Array to DateTime"); + } + + void convert(LocalDateTime& /*ldt*/) const + { + throw BadCastException("Cannot convert Array to LocalDateTime"); + } + + void convert(Timestamp& /*ts*/) const + { + throw BadCastException("Cannot convert Array to Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const JSON::Array::Ptr& value() const + { + return _val; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + JSON::Array::Ptr _val; +}; + + +template <> +class VarHolderImpl<JSON::Array>: public VarHolder +{ +public: + VarHolderImpl(const JSON::Array& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(JSON::Array); + } + + void convert(Int8&) const + { + throw BadCastException(); + } + + void convert(Int16&) const + { + throw BadCastException(); + } + + void convert(Int32&) const + { + throw BadCastException(); + } + + void convert(Int64&) const + { + throw BadCastException(); + } + + void convert(UInt8&) const + { + throw BadCastException(); + } + + void convert(UInt16&) const + { + throw BadCastException(); + } + + void convert(UInt32&) const + { + throw BadCastException(); + } + + void convert(UInt64&) const + { + throw BadCastException(); + } + + void convert(bool& value) const + { + value = _val.size() > 0; + } + + void convert(float&) const + { + throw BadCastException(); + } + + void convert(double&) const + { + throw BadCastException(); + } + + void convert(char&) const + { + throw BadCastException(); + } + + void convert(std::string& s) const + { + std::ostringstream oss; + _val.stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime& /*val*/) const + { + throw BadCastException("Cannot convert Array to DateTime"); + } + + void convert(LocalDateTime& /*ldt*/) const + { + throw BadCastException("Cannot convert Array to LocalDateTime"); + } + + void convert(Timestamp& /*ts*/) const + { + throw BadCastException("Cannot convert Array to Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const JSON::Array& value() const + { + return _val; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + JSON::Array _val; +}; + + +} } // namespace Poco::Dynamic + + +#endif // JSON_Array_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Handler.h b/contrib/libs/poco/JSON/include/Poco/JSON/Handler.h index 1c6ccebffe..8c64f34ff0 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Handler.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Handler.h @@ -1,106 +1,106 @@ -// -// Handler.h -// -// Library: JSON -// Package: JSON -// Module: Handler -// -// Definition of the Handler class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_Handler_INCLUDED -#define JSON_Handler_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/Dynamic/Struct.h" - - -namespace Poco { -namespace JSON { - - -class JSON_API Handler - /// Interface for handling parsing events generated by the JSON Parser. - /// - /// An application can implement a subclass of Handler to implement - /// callback-based parsing of a JSON document, similar to how a SAX - /// parser would handle XML. -{ -public: - typedef SharedPtr<Handler> Ptr; - - Handler(); - /// Creates an empty Handler. - - virtual ~Handler(); - /// Destroys the Handler. - - virtual void reset() = 0; - /// Resets the handler state. - - virtual void startObject() = 0; - /// The parser has read a {, meaning a new object will be read. - - virtual void endObject() = 0; - /// The parser has read a }, meaning the object is read. - - virtual void startArray() = 0; - /// The parser has read a [, meaning a new array will be read. - - virtual void endArray() = 0; - /// The parser has read a ], meaning the array is read. - - virtual void key(const std::string& k) = 0; - /// A key of an object is read. - - virtual void null() = 0; - /// A null value is read. - - virtual void value(int v) = 0; - /// An integer value is read. - - virtual void value(unsigned v) = 0; - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. - -#if defined(POCO_HAVE_INT64) - virtual void value(Int64 v) = 0; - /// A 64-bit integer value is read. - - virtual void value(UInt64 v) = 0; - /// An unsigned 64-bit integer value is read. This will only be - /// triggered if the value cannot fit into a signed 64-bit integer. -#endif - - virtual void value(const std::string& value) = 0; - /// A string value is read. - - virtual void value(double d) = 0; - /// A double value is read. - - virtual void value(bool b) = 0; - /// A boolean value is read. - - virtual Poco::Dynamic::Var asVar() const; - /// Returns the result of the parser (an object, array or string), - /// empty Var if there is no result. - - virtual Poco::DynamicStruct asStruct() const; - /// Returns the result of the parser (an object, array or string), - /// empty Var if there is no result. -}; - - -} } // namespace Poco::JSON - - -#endif // JSON_Handler_INCLUDED +// +// Handler.h +// +// Library: JSON +// Package: JSON +// Module: Handler +// +// Definition of the Handler class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_Handler_INCLUDED +#define JSON_Handler_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/SharedPtr.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/Dynamic/Struct.h" + + +namespace Poco { +namespace JSON { + + +class JSON_API Handler + /// Interface for handling parsing events generated by the JSON Parser. + /// + /// An application can implement a subclass of Handler to implement + /// callback-based parsing of a JSON document, similar to how a SAX + /// parser would handle XML. +{ +public: + typedef SharedPtr<Handler> Ptr; + + Handler(); + /// Creates an empty Handler. + + virtual ~Handler(); + /// Destroys the Handler. + + virtual void reset() = 0; + /// Resets the handler state. + + virtual void startObject() = 0; + /// The parser has read a {, meaning a new object will be read. + + virtual void endObject() = 0; + /// The parser has read a }, meaning the object is read. + + virtual void startArray() = 0; + /// The parser has read a [, meaning a new array will be read. + + virtual void endArray() = 0; + /// The parser has read a ], meaning the array is read. + + virtual void key(const std::string& k) = 0; + /// A key of an object is read. + + virtual void null() = 0; + /// A null value is read. + + virtual void value(int v) = 0; + /// An integer value is read. + + virtual void value(unsigned v) = 0; + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. + +#if defined(POCO_HAVE_INT64) + virtual void value(Int64 v) = 0; + /// A 64-bit integer value is read. + + virtual void value(UInt64 v) = 0; + /// An unsigned 64-bit integer value is read. This will only be + /// triggered if the value cannot fit into a signed 64-bit integer. +#endif + + virtual void value(const std::string& value) = 0; + /// A string value is read. + + virtual void value(double d) = 0; + /// A double value is read. + + virtual void value(bool b) = 0; + /// A boolean value is read. + + virtual Poco::Dynamic::Var asVar() const; + /// Returns the result of the parser (an object, array or string), + /// empty Var if there is no result. + + virtual Poco::DynamicStruct asStruct() const; + /// Returns the result of the parser (an object, array or string), + /// empty Var if there is no result. +}; + + +} } // namespace Poco::JSON + + +#endif // JSON_Handler_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/JSON.h b/contrib/libs/poco/JSON/include/Poco/JSON/JSON.h index b5794eee79..36d7623756 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/JSON.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/JSON.h @@ -1,62 +1,62 @@ -// -// JSON.h -// -// Library: JSON -// Package: JSON -// Module: JSON -// -// Basic definitions for the Poco JSON library. -// This file must be the first file included by every other JSON -// header file. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSON_INCLUDED -#define JSON_JSON_INCLUDED - - -#include "Poco/Foundation.h" - - -// -// The following block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the JSON_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// JSON_API functions as being imported from a DLL, whereas this DLL sees symbols -// defined with this macro as being exported. -// -#if defined(_WIN32) && defined(POCO_DLL) - #if defined(JSON_EXPORTS) - #define JSON_API __declspec(dllexport) - #else - #define JSON_API __declspec(dllimport) - #endif -#endif - - -#if !defined(JSON_API) - #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) - #define JSON_API __attribute__ ((visibility ("default"))) - #else - #define JSON_API - #endif -#endif - - -// -// Automatically link JSON library. -// -#if defined(_MSC_VER) - #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(JSON_EXPORTS) - #pragma comment(lib, "PocoJSON" POCO_LIB_SUFFIX) - #endif -#endif - - -#endif // JSON_JSON_INCLUDED +// +// JSON.h +// +// Library: JSON +// Package: JSON +// Module: JSON +// +// Basic definitions for the Poco JSON library. +// This file must be the first file included by every other JSON +// header file. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSON_INCLUDED +#define JSON_JSON_INCLUDED + + +#include "Poco/Foundation.h" + + +// +// The following block is the standard way of creating macros which make exporting +// from a DLL simpler. All files within this DLL are compiled with the JSON_EXPORTS +// symbol defined on the command line. this symbol should not be defined on any project +// that uses this DLL. This way any other project whose source files include this file see +// JSON_API functions as being imported from a DLL, whereas this DLL sees symbols +// defined with this macro as being exported. +// +#if defined(_WIN32) && defined(POCO_DLL) + #if defined(JSON_EXPORTS) + #define JSON_API __declspec(dllexport) + #else + #define JSON_API __declspec(dllimport) + #endif +#endif + + +#if !defined(JSON_API) + #if !defined(POCO_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4) + #define JSON_API __attribute__ ((visibility ("default"))) + #else + #define JSON_API + #endif +#endif + + +// +// Automatically link JSON library. +// +#if defined(_MSC_VER) + #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(JSON_EXPORTS) + #pragma comment(lib, "PocoJSON" POCO_LIB_SUFFIX) + #endif +#endif + + +#endif // JSON_JSON_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/JSONException.h b/contrib/libs/poco/JSON/include/Poco/JSON/JSONException.h index c32c6e4790..058d36f0ae 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/JSONException.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/JSONException.h @@ -1,35 +1,35 @@ -// -// JSONException.h -// -// Library: JSON -// Package: JSON -// Module: JSONException -// -// Definition of the JSONException class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONException_INCLUDED -#define JSON_JSONException_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/Exception.h" - - -namespace Poco { -namespace JSON { - - -POCO_DECLARE_EXCEPTION(JSON_API, JSONException, Poco::Exception) - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONException_INCLUDED +// +// JSONException.h +// +// Library: JSON +// Package: JSON +// Module: JSONException +// +// Definition of the JSONException class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONException_INCLUDED +#define JSON_JSONException_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/Exception.h" + + +namespace Poco { +namespace JSON { + + +POCO_DECLARE_EXCEPTION(JSON_API, JSONException, Poco::Exception) + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONException_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Object.h b/contrib/libs/poco/JSON/include/Poco/JSON/Object.h index 81193d7aca..8812561a53 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Object.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Object.h @@ -1,715 +1,715 @@ -// -// Object.h -// -// Library: JSON -// Package: JSON -// Module: Object -// -// Definition of the Object class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_Object_INCLUDED -#define JSON_Object_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/Stringifier.h" -#include "Poco/JSONString.h" -#include "Poco/SharedPtr.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/Dynamic/Struct.h" -#include "Poco/Nullable.h" -#include <map> -#include <vector> -#include <deque> -#include <iostream> -#include <sstream> - - -namespace Poco { -namespace JSON { - - -class JSON_API Object - /// Represents a JSON object. Object provides a representation based on - /// shared pointers and optimized for performance. It is possible to - /// convert Object to DynamicStruct. Conversion requires copying and therefore - /// has performance penalty; the benefit is in improved syntax, eg: - /// - /// std::string json = "{ \"test\" : { \"property\" : \"value\" } }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// - /// // use pointers to avoid copying - /// Object::Ptr object = result.extract<Object::Ptr>(); - /// Var test = object->get("test"); // holds { "property" : "value" } - /// Object::Ptr subObject = test.extract<Object::Ptr>(); - /// test = subObject->get("property"); - /// std::string val = test.toString(); // val holds "value" - /// - /// // copy/convert to Poco::DynamicStruct - /// Poco::DynamicStruct ds = *object; - /// val = ds["test"]["property"]; // val holds "value" - /// -{ -public: - typedef SharedPtr<Object> Ptr; - typedef std::map<std::string, Dynamic::Var> ValueMap; - typedef ValueMap::value_type ValueType; - typedef ValueMap::iterator Iterator; - typedef ValueMap::const_iterator ConstIterator; - typedef std::vector<std::string> NameList; - - explicit Object(int options = 0); - /// Creates an empty Object. - /// - /// If JSON_PRESERVE_KEY_ORDER is specified, the object will - /// preserve the items insertion order. Otherwise, items will be - /// sorted by keys. - /// - /// If JSON_ESCAPE_UNICODE is specified, when the object is - /// stringified, all unicode characters will be escaped in the - /// resulting string. - - Object(const Object& copy); - /// Creates an Object by copying another one. - /// - /// Struct is not copied to keep the operation as - /// efficient as possible (when needed, it will be generated upon request). - -#ifdef POCO_ENABLE_CPP11 - - Object(Object&& other); - /// Move constructor - - Object &operator =(Object &&other); - // Move asignment operator - -#endif // POCO_ENABLE_CPP11 - - virtual ~Object(); - /// Destroys the Object. - - Object &operator =(const Object &other); - // Assignment operator - - void setEscapeUnicode(bool escape = true); - /// Sets the flag for escaping unicode. - - bool getEscapeUnicode() const; - /// Returns the flag for escaping unicode. - - Iterator begin(); - /// Returns begin iterator for values. - - ConstIterator begin() const; - /// Returns const begin iterator for values. - - Iterator end(); - /// Returns end iterator for values. - - ConstIterator end() const; - /// Returns const end iterator for values. - - Dynamic::Var get(const std::string& key) const; - /// Retrieves a property. An empty value is - /// returned when the property doesn't exist. - - Array::Ptr getArray(const std::string& key) const; - /// Returns a SharedPtr to an array when the property - /// is an array. An empty SharedPtr is returned when - /// the element doesn't exist or is not an array. - - Object::Ptr getObject(const std::string& key) const; - /// Returns a SharedPtr to an object when the property - /// is an object. An empty SharedPtr is returned when - /// the property doesn't exist or is not an object - - template<typename T> - T getValue(const std::string& key) const - /// Retrieves the property with the given name and will - /// try to convert the value to the given template type. - /// The convert<T>() method of Var is called - /// which can also throw exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - Dynamic::Var value = get(key); - return value.convert<T>(); - } - - template<typename T> - Poco::Nullable<T> getNullableValue(const std::string& key) const - /// Retrieves the property with the given name and will - /// try to convert the value to the given template type. - /// - /// The convert<T> method of Var is called - /// which can also throw exceptions for invalid values. - /// Note: This will not work for an array or an object. - { - if (isNull(key)) - return Poco::Nullable<T>(); - - Dynamic::Var value = get(key); - return value.convert<T>(); - } - - void getNames(NameList& names) const; - /// Fills the supplied vector with all property names. - - NameList getNames() const; - /// Returns all property names. - - bool has(const std::string& key) const; - /// Returns true when the given property exists. - - bool isArray(const std::string& key) const; - /// Returns true when the given property contains an array. - - bool isArray(ConstIterator& it) const; - /// Returns true when the given property contains an array. - - bool isNull(const std::string& key) const; - /// Returns true when the given property contains a null value. - - bool isObject(const std::string& key) const; - /// Returns true when the given property contains an object. - - bool isObject(ConstIterator& it) const; - /// Returns true when the given property contains an object. - - template<typename T> - T optValue(const std::string& key, const T& def) const - /// Returns the value of a property when the property exists - /// and can be converted to the given type. Otherwise - /// def will be returned. - { - T value = def; - ValueMap::const_iterator it = _values.find(key); - if (it != _values.end() && ! it->second.isEmpty()) - { - try - { - value = it->second.convert<T>(); - } - catch (...) - { - // The default value will be returned - } - } - return value; - } - - std::size_t size() const; - /// Returns the number of properties. - - void set(const std::string& key, const Dynamic::Var& value); - /// Sets a new value. - - void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; - /// Prints the object to out stream. - /// - /// When indent is 0, the object will be printed on a single - /// line without indentation. - - void remove(const std::string& key); - /// Removes the property with the given key. - - static Poco::DynamicStruct makeStruct(const Object::Ptr& obj); - /// Utility function for creation of struct. - - operator const Poco::DynamicStruct& () const; - /// Cast operator to Poco::DynamiStruct. - - void clear(); - /// Clears the contents of the object. - /// - /// Insertion order preservation property is left intact. - -private: - typedef std::deque<ValueMap::const_iterator> KeyList; - typedef Poco::DynamicStruct::Ptr StructPtr; - - void resetDynStruct() const; - void syncKeys(const KeyList& keys); - - template <typename C> - void doStringify(const C& container, std::ostream& out, unsigned int indent, unsigned int step) const - { - int options = Poco::JSON_WRAP_STRINGS; - options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; - - out << '{'; - - if (indent > 0) out << std::endl; - - typename C::const_iterator it = container.begin(); - typename C::const_iterator end = container.end(); - for (; it != end;) - { - for (unsigned int i = 0; i < indent; i++) out << ' '; - - Stringifier::stringify(getKey(it), out, indent, step, options); - out << ((indent > 0) ? " : " : ":"); - - Stringifier::stringify(getValue(it), out, indent + step, step, options); - - if (++it != container.end()) out << ','; - - if (step > 0) out << std::endl; - } - - if (indent >= step) indent -= step; - - for (unsigned int i = 0; i < indent; i++) out << ' '; - - out << '}'; - } - - const std::string& getKey(ValueMap::const_iterator& it) const; - const Dynamic::Var& getValue(ValueMap::const_iterator& it) const; - const std::string& getKey(KeyList::const_iterator& it) const; - const Dynamic::Var& getValue(KeyList::const_iterator& it) const; - - ValueMap _values; - KeyList _keys; - bool _preserveInsOrder; - // Note: - // The reason for this flag (rather than as argument to stringify()) is - // because Object can be returned stringified from Dynamic::Var::toString(), - // so it must know whether to escape unicode or not. - bool _escapeUnicode; - mutable StructPtr _pStruct; - mutable bool _modified; -}; - - -// -// inlines -// - -inline void Object::setEscapeUnicode(bool escape) -{ - _escapeUnicode = escape; -} - - -inline bool Object::getEscapeUnicode() const -{ - return _escapeUnicode; -} - - -inline Object::Iterator Object::begin() -{ - return _values.begin(); -} - - -inline Object::ConstIterator Object::begin() const -{ - return _values.begin(); -} - - -inline Object::Iterator Object::end() -{ - return _values.end(); -} - - -inline Object::ConstIterator Object::end() const -{ - return _values.end(); -} - - -inline bool Object::has(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return it != _values.end(); -} - - -inline bool Object::isArray(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return isArray(it); -} - - -inline bool Object::isArray(ConstIterator& it) const -{ - return it != _values.end() && (it->second.type() == typeid(Array::Ptr) || it->second.type() == typeid(Array)); -} - - -inline bool Object::isNull(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return it == _values.end() || it->second.isEmpty(); -} - - -inline bool Object::isObject(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - return isObject(it); -} - - -inline bool Object::isObject(ConstIterator& it) const -{ - return it != _values.end() && (it->second.type() == typeid(Object::Ptr) || it->second.type() == typeid(Object)); -} - - -inline std::size_t Object::size() const -{ - return static_cast<std::size_t>(_values.size()); -} - - -inline void Object::remove(const std::string& key) -{ - _values.erase(key); - if (_preserveInsOrder) - { - KeyList::iterator it = _keys.begin(); - KeyList::iterator end = _keys.end(); - for (; it != end; ++it) - { - if (key == (*it)->first) - { - _keys.erase(it); - break; - } - } - } - _modified = true; -} - - -inline const std::string& Object::getKey(ValueMap::const_iterator& it) const -{ - return it->first; -} - - -inline const Dynamic::Var& Object::getValue(ValueMap::const_iterator& it) const -{ - return it->second; -} - - -inline const Dynamic::Var& Object::getValue(KeyList::const_iterator& it) const -{ - ValueMap::const_iterator itv = _values.find((*it)->first); - if (itv != _values.end()) - return itv->second; - else - throw Poco::NotFoundException(); -} - - -} } // namespace Poco::JSON - - -namespace Poco { -namespace Dynamic { - - -template <> -class VarHolderImpl<JSON::Object::Ptr>: public VarHolder -{ -public: - VarHolderImpl(const JSON::Object::Ptr& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Object::Ptr); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = !_val.isNull() && _val->size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val->stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - //TODO: val = _val; - throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - //TODO: ldt = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - //TODO: ts = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); - } - - VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Object::Ptr& value() const - { - return _val; - } - - bool isArray() const - { - return false; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Object::Ptr _val; -}; - - -template <> -class VarHolderImpl<JSON::Object>: public VarHolder -{ -public: - VarHolderImpl(const JSON::Object& val): _val(val) - { - } - - ~VarHolderImpl() - { - } - - const std::type_info& type() const - { - return typeid(JSON::Object); - } - - void convert(Int8&) const - { - throw BadCastException(); - } - - void convert(Int16&) const - { - throw BadCastException(); - } - - void convert(Int32&) const - { - throw BadCastException(); - } - - void convert(Int64&) const - { - throw BadCastException(); - } - - void convert(UInt8&) const - { - throw BadCastException(); - } - - void convert(UInt16&) const - { - throw BadCastException(); - } - - void convert(UInt32&) const - { - throw BadCastException(); - } - - void convert(UInt64&) const - { - throw BadCastException(); - } - - void convert(bool& value) const - { - value = _val.size() > 0; - } - - void convert(float&) const - { - throw BadCastException(); - } - - void convert(double&) const - { - throw BadCastException(); - } - - void convert(char&) const - { - throw BadCastException(); - } - - void convert(std::string& s) const - { - std::ostringstream oss; - _val.stringify(oss, 2); - s = oss.str(); - } - - void convert(DateTime& /*val*/) const - { - //TODO: val = _val; - throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); - } - - void convert(LocalDateTime& /*ldt*/) const - { - //TODO: ldt = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); - } - - void convert(Timestamp& /*ts*/) const - { - //TODO: ts = _val.timestamp(); - throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); - } - - VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const - { - return cloneHolder(pVarHolder, _val); - } - - const JSON::Object& value() const - { - return _val; - } - - bool isArray() const - { - return false; - } - - bool isInteger() const - { - return false; - } - - bool isSigned() const - { - return false; - } - - bool isNumeric() const - { - return false; - } - - bool isString() const - { - return false; - } - -private: - JSON::Object _val; -}; - - -} } // namespace Poco::Dynamic - - -#endif // JSON_Object_INCLUDED +// +// Object.h +// +// Library: JSON +// Package: JSON +// Module: Object +// +// Definition of the Object class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_Object_INCLUDED +#define JSON_Object_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/Stringifier.h" +#include "Poco/JSONString.h" +#include "Poco/SharedPtr.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/Dynamic/Struct.h" +#include "Poco/Nullable.h" +#include <map> +#include <vector> +#include <deque> +#include <iostream> +#include <sstream> + + +namespace Poco { +namespace JSON { + + +class JSON_API Object + /// Represents a JSON object. Object provides a representation based on + /// shared pointers and optimized for performance. It is possible to + /// convert Object to DynamicStruct. Conversion requires copying and therefore + /// has performance penalty; the benefit is in improved syntax, eg: + /// + /// std::string json = "{ \"test\" : { \"property\" : \"value\" } }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// + /// // use pointers to avoid copying + /// Object::Ptr object = result.extract<Object::Ptr>(); + /// Var test = object->get("test"); // holds { "property" : "value" } + /// Object::Ptr subObject = test.extract<Object::Ptr>(); + /// test = subObject->get("property"); + /// std::string val = test.toString(); // val holds "value" + /// + /// // copy/convert to Poco::DynamicStruct + /// Poco::DynamicStruct ds = *object; + /// val = ds["test"]["property"]; // val holds "value" + /// +{ +public: + typedef SharedPtr<Object> Ptr; + typedef std::map<std::string, Dynamic::Var> ValueMap; + typedef ValueMap::value_type ValueType; + typedef ValueMap::iterator Iterator; + typedef ValueMap::const_iterator ConstIterator; + typedef std::vector<std::string> NameList; + + explicit Object(int options = 0); + /// Creates an empty Object. + /// + /// If JSON_PRESERVE_KEY_ORDER is specified, the object will + /// preserve the items insertion order. Otherwise, items will be + /// sorted by keys. + /// + /// If JSON_ESCAPE_UNICODE is specified, when the object is + /// stringified, all unicode characters will be escaped in the + /// resulting string. + + Object(const Object& copy); + /// Creates an Object by copying another one. + /// + /// Struct is not copied to keep the operation as + /// efficient as possible (when needed, it will be generated upon request). + +#ifdef POCO_ENABLE_CPP11 + + Object(Object&& other); + /// Move constructor + + Object &operator =(Object &&other); + // Move asignment operator + +#endif // POCO_ENABLE_CPP11 + + virtual ~Object(); + /// Destroys the Object. + + Object &operator =(const Object &other); + // Assignment operator + + void setEscapeUnicode(bool escape = true); + /// Sets the flag for escaping unicode. + + bool getEscapeUnicode() const; + /// Returns the flag for escaping unicode. + + Iterator begin(); + /// Returns begin iterator for values. + + ConstIterator begin() const; + /// Returns const begin iterator for values. + + Iterator end(); + /// Returns end iterator for values. + + ConstIterator end() const; + /// Returns const end iterator for values. + + Dynamic::Var get(const std::string& key) const; + /// Retrieves a property. An empty value is + /// returned when the property doesn't exist. + + Array::Ptr getArray(const std::string& key) const; + /// Returns a SharedPtr to an array when the property + /// is an array. An empty SharedPtr is returned when + /// the element doesn't exist or is not an array. + + Object::Ptr getObject(const std::string& key) const; + /// Returns a SharedPtr to an object when the property + /// is an object. An empty SharedPtr is returned when + /// the property doesn't exist or is not an object + + template<typename T> + T getValue(const std::string& key) const + /// Retrieves the property with the given name and will + /// try to convert the value to the given template type. + /// The convert<T>() method of Var is called + /// which can also throw exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + Dynamic::Var value = get(key); + return value.convert<T>(); + } + + template<typename T> + Poco::Nullable<T> getNullableValue(const std::string& key) const + /// Retrieves the property with the given name and will + /// try to convert the value to the given template type. + /// + /// The convert<T> method of Var is called + /// which can also throw exceptions for invalid values. + /// Note: This will not work for an array or an object. + { + if (isNull(key)) + return Poco::Nullable<T>(); + + Dynamic::Var value = get(key); + return value.convert<T>(); + } + + void getNames(NameList& names) const; + /// Fills the supplied vector with all property names. + + NameList getNames() const; + /// Returns all property names. + + bool has(const std::string& key) const; + /// Returns true when the given property exists. + + bool isArray(const std::string& key) const; + /// Returns true when the given property contains an array. + + bool isArray(ConstIterator& it) const; + /// Returns true when the given property contains an array. + + bool isNull(const std::string& key) const; + /// Returns true when the given property contains a null value. + + bool isObject(const std::string& key) const; + /// Returns true when the given property contains an object. + + bool isObject(ConstIterator& it) const; + /// Returns true when the given property contains an object. + + template<typename T> + T optValue(const std::string& key, const T& def) const + /// Returns the value of a property when the property exists + /// and can be converted to the given type. Otherwise + /// def will be returned. + { + T value = def; + ValueMap::const_iterator it = _values.find(key); + if (it != _values.end() && ! it->second.isEmpty()) + { + try + { + value = it->second.convert<T>(); + } + catch (...) + { + // The default value will be returned + } + } + return value; + } + + std::size_t size() const; + /// Returns the number of properties. + + void set(const std::string& key, const Dynamic::Var& value); + /// Sets a new value. + + void stringify(std::ostream& out, unsigned int indent = 0, int step = -1) const; + /// Prints the object to out stream. + /// + /// When indent is 0, the object will be printed on a single + /// line without indentation. + + void remove(const std::string& key); + /// Removes the property with the given key. + + static Poco::DynamicStruct makeStruct(const Object::Ptr& obj); + /// Utility function for creation of struct. + + operator const Poco::DynamicStruct& () const; + /// Cast operator to Poco::DynamiStruct. + + void clear(); + /// Clears the contents of the object. + /// + /// Insertion order preservation property is left intact. + +private: + typedef std::deque<ValueMap::const_iterator> KeyList; + typedef Poco::DynamicStruct::Ptr StructPtr; + + void resetDynStruct() const; + void syncKeys(const KeyList& keys); + + template <typename C> + void doStringify(const C& container, std::ostream& out, unsigned int indent, unsigned int step) const + { + int options = Poco::JSON_WRAP_STRINGS; + options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; + + out << '{'; + + if (indent > 0) out << std::endl; + + typename C::const_iterator it = container.begin(); + typename C::const_iterator end = container.end(); + for (; it != end;) + { + for (unsigned int i = 0; i < indent; i++) out << ' '; + + Stringifier::stringify(getKey(it), out, indent, step, options); + out << ((indent > 0) ? " : " : ":"); + + Stringifier::stringify(getValue(it), out, indent + step, step, options); + + if (++it != container.end()) out << ','; + + if (step > 0) out << std::endl; + } + + if (indent >= step) indent -= step; + + for (unsigned int i = 0; i < indent; i++) out << ' '; + + out << '}'; + } + + const std::string& getKey(ValueMap::const_iterator& it) const; + const Dynamic::Var& getValue(ValueMap::const_iterator& it) const; + const std::string& getKey(KeyList::const_iterator& it) const; + const Dynamic::Var& getValue(KeyList::const_iterator& it) const; + + ValueMap _values; + KeyList _keys; + bool _preserveInsOrder; + // Note: + // The reason for this flag (rather than as argument to stringify()) is + // because Object can be returned stringified from Dynamic::Var::toString(), + // so it must know whether to escape unicode or not. + bool _escapeUnicode; + mutable StructPtr _pStruct; + mutable bool _modified; +}; + + +// +// inlines +// + +inline void Object::setEscapeUnicode(bool escape) +{ + _escapeUnicode = escape; +} + + +inline bool Object::getEscapeUnicode() const +{ + return _escapeUnicode; +} + + +inline Object::Iterator Object::begin() +{ + return _values.begin(); +} + + +inline Object::ConstIterator Object::begin() const +{ + return _values.begin(); +} + + +inline Object::Iterator Object::end() +{ + return _values.end(); +} + + +inline Object::ConstIterator Object::end() const +{ + return _values.end(); +} + + +inline bool Object::has(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + return it != _values.end(); +} + + +inline bool Object::isArray(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + return isArray(it); +} + + +inline bool Object::isArray(ConstIterator& it) const +{ + return it != _values.end() && (it->second.type() == typeid(Array::Ptr) || it->second.type() == typeid(Array)); +} + + +inline bool Object::isNull(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + return it == _values.end() || it->second.isEmpty(); +} + + +inline bool Object::isObject(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + return isObject(it); +} + + +inline bool Object::isObject(ConstIterator& it) const +{ + return it != _values.end() && (it->second.type() == typeid(Object::Ptr) || it->second.type() == typeid(Object)); +} + + +inline std::size_t Object::size() const +{ + return static_cast<std::size_t>(_values.size()); +} + + +inline void Object::remove(const std::string& key) +{ + _values.erase(key); + if (_preserveInsOrder) + { + KeyList::iterator it = _keys.begin(); + KeyList::iterator end = _keys.end(); + for (; it != end; ++it) + { + if (key == (*it)->first) + { + _keys.erase(it); + break; + } + } + } + _modified = true; +} + + +inline const std::string& Object::getKey(ValueMap::const_iterator& it) const +{ + return it->first; +} + + +inline const Dynamic::Var& Object::getValue(ValueMap::const_iterator& it) const +{ + return it->second; +} + + +inline const Dynamic::Var& Object::getValue(KeyList::const_iterator& it) const +{ + ValueMap::const_iterator itv = _values.find((*it)->first); + if (itv != _values.end()) + return itv->second; + else + throw Poco::NotFoundException(); +} + + +} } // namespace Poco::JSON + + +namespace Poco { +namespace Dynamic { + + +template <> +class VarHolderImpl<JSON::Object::Ptr>: public VarHolder +{ +public: + VarHolderImpl(const JSON::Object::Ptr& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(JSON::Object::Ptr); + } + + void convert(Int8&) const + { + throw BadCastException(); + } + + void convert(Int16&) const + { + throw BadCastException(); + } + + void convert(Int32&) const + { + throw BadCastException(); + } + + void convert(Int64&) const + { + throw BadCastException(); + } + + void convert(UInt8&) const + { + throw BadCastException(); + } + + void convert(UInt16&) const + { + throw BadCastException(); + } + + void convert(UInt32&) const + { + throw BadCastException(); + } + + void convert(UInt64&) const + { + throw BadCastException(); + } + + void convert(bool& value) const + { + value = !_val.isNull() && _val->size() > 0; + } + + void convert(float&) const + { + throw BadCastException(); + } + + void convert(double&) const + { + throw BadCastException(); + } + + void convert(char&) const + { + throw BadCastException(); + } + + void convert(std::string& s) const + { + std::ostringstream oss; + _val->stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime& /*val*/) const + { + //TODO: val = _val; + throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); + } + + void convert(LocalDateTime& /*ldt*/) const + { + //TODO: ldt = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); + } + + void convert(Timestamp& /*ts*/) const + { + //TODO: ts = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const JSON::Object::Ptr& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + JSON::Object::Ptr _val; +}; + + +template <> +class VarHolderImpl<JSON::Object>: public VarHolder +{ +public: + VarHolderImpl(const JSON::Object& val): _val(val) + { + } + + ~VarHolderImpl() + { + } + + const std::type_info& type() const + { + return typeid(JSON::Object); + } + + void convert(Int8&) const + { + throw BadCastException(); + } + + void convert(Int16&) const + { + throw BadCastException(); + } + + void convert(Int32&) const + { + throw BadCastException(); + } + + void convert(Int64&) const + { + throw BadCastException(); + } + + void convert(UInt8&) const + { + throw BadCastException(); + } + + void convert(UInt16&) const + { + throw BadCastException(); + } + + void convert(UInt32&) const + { + throw BadCastException(); + } + + void convert(UInt64&) const + { + throw BadCastException(); + } + + void convert(bool& value) const + { + value = _val.size() > 0; + } + + void convert(float&) const + { + throw BadCastException(); + } + + void convert(double&) const + { + throw BadCastException(); + } + + void convert(char&) const + { + throw BadCastException(); + } + + void convert(std::string& s) const + { + std::ostringstream oss; + _val.stringify(oss, 2); + s = oss.str(); + } + + void convert(DateTime& /*val*/) const + { + //TODO: val = _val; + throw NotImplementedException("Conversion not implemented: JSON:Object => DateTime"); + } + + void convert(LocalDateTime& /*ldt*/) const + { + //TODO: ldt = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => LocalDateTime"); + } + + void convert(Timestamp& /*ts*/) const + { + //TODO: ts = _val.timestamp(); + throw NotImplementedException("Conversion not implemented: JSON:Object => Timestamp"); + } + + VarHolder* clone(Placeholder<VarHolder>* pVarHolder = 0) const + { + return cloneHolder(pVarHolder, _val); + } + + const JSON::Object& value() const + { + return _val; + } + + bool isArray() const + { + return false; + } + + bool isInteger() const + { + return false; + } + + bool isSigned() const + { + return false; + } + + bool isNumeric() const + { + return false; + } + + bool isString() const + { + return false; + } + +private: + JSON::Object _val; +}; + + +} } // namespace Poco::Dynamic + + +#endif // JSON_Object_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/ParseHandler.h b/contrib/libs/poco/JSON/include/Poco/JSON/ParseHandler.h index 466113b131..98cd69ed89 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/ParseHandler.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/ParseHandler.h @@ -1,169 +1,169 @@ -// -// ParseHandler.h -// -// Library: JSON -// Package: JSON -// Module: ParseHandler -// -// Definition of the ParseHandler class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_ParseHandler_INCLUDED -#define JSON_ParseHandler_INCLUDED - - -#include "Poco/JSON/Handler.h" -#include <stack> - - -namespace Poco { -namespace JSON { - - -class JSON_API ParseHandler: public Handler - /// ParseHandler is the default handler for the JSON Parser. - /// - /// This handler will construct an Object or Array based - /// on the handlers called by the Parser. -{ -public: - ParseHandler(bool preserveObjectOrder = false); - /// Creates the ParseHandler. - /// - /// If preserveObjectOrder is true, the order of properties - /// inside objects is preserved. Otherwise, items - /// will be sorted by keys. - - virtual ~ParseHandler(); - /// Destroys the ParseHandler. - - virtual void reset(); - /// Resets the handler state. - - void startObject(); - /// Handles a '{'; a new object is started. - - void endObject(); - /// Handles a '}'; the object is closed. - - void startArray(); - /// Handles a '['; a new array is started. - - void endArray(); - /// Handles a ']'; the array is closed. - - void key(const std::string& k); - /// A key is read - - Dynamic::Var asVar() const; - /// Returns the result of the parser (an object or an array). - - virtual void value(int v); - /// An integer value is read - - virtual void value(unsigned v); - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. - -#if defined(POCO_HAVE_INT64) - virtual void value(Int64 v); - /// A 64-bit integer value is read - - virtual void value(UInt64 v); - /// An unsigned 64-bit integer value is read. This will only be - /// triggered if the value cannot fit into a signed 64-bit integer. -#endif - - virtual void value(const std::string& s); - /// A string value is read. - - virtual void value(double d); - /// A double value is read. - - virtual void value(bool b); - /// A boolean value is read. - - virtual void null(); - /// A null value is read. - -private: - void setValue(const Poco::Dynamic::Var& value); - typedef std::stack<Dynamic::Var> Stack; - - Stack _stack; - std::string _key; - Dynamic::Var _result; - bool _preserveObjectOrder; -}; - - -// -// inlines -// -inline Dynamic::Var ParseHandler::asVar() const -{ - return _result; -} - - -inline void ParseHandler::value(int v) -{ - setValue(v); -} - - -inline void ParseHandler::value(unsigned v) -{ - setValue(v); -} - - -#if defined(POCO_HAVE_INT64) -inline void ParseHandler::value(Int64 v) -{ - setValue(v); -} - - -inline void ParseHandler::value(UInt64 v) -{ - setValue(v); -} -#endif - - -inline void ParseHandler::value(const std::string& s) -{ - setValue(s); -} - - -inline void ParseHandler::value(double d) -{ - setValue(d); -} - - -inline void ParseHandler::value(bool b) -{ - setValue(b); -} - - -inline void ParseHandler::null() -{ - Poco::Dynamic::Var empty; - setValue(empty); -} - - -} } // namespace Poco::JSON - - -#endif // JSON_ParseHandler_INCLUDED +// +// ParseHandler.h +// +// Library: JSON +// Package: JSON +// Module: ParseHandler +// +// Definition of the ParseHandler class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_ParseHandler_INCLUDED +#define JSON_ParseHandler_INCLUDED + + +#include "Poco/JSON/Handler.h" +#include <stack> + + +namespace Poco { +namespace JSON { + + +class JSON_API ParseHandler: public Handler + /// ParseHandler is the default handler for the JSON Parser. + /// + /// This handler will construct an Object or Array based + /// on the handlers called by the Parser. +{ +public: + ParseHandler(bool preserveObjectOrder = false); + /// Creates the ParseHandler. + /// + /// If preserveObjectOrder is true, the order of properties + /// inside objects is preserved. Otherwise, items + /// will be sorted by keys. + + virtual ~ParseHandler(); + /// Destroys the ParseHandler. + + virtual void reset(); + /// Resets the handler state. + + void startObject(); + /// Handles a '{'; a new object is started. + + void endObject(); + /// Handles a '}'; the object is closed. + + void startArray(); + /// Handles a '['; a new array is started. + + void endArray(); + /// Handles a ']'; the array is closed. + + void key(const std::string& k); + /// A key is read + + Dynamic::Var asVar() const; + /// Returns the result of the parser (an object or an array). + + virtual void value(int v); + /// An integer value is read + + virtual void value(unsigned v); + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. + +#if defined(POCO_HAVE_INT64) + virtual void value(Int64 v); + /// A 64-bit integer value is read + + virtual void value(UInt64 v); + /// An unsigned 64-bit integer value is read. This will only be + /// triggered if the value cannot fit into a signed 64-bit integer. +#endif + + virtual void value(const std::string& s); + /// A string value is read. + + virtual void value(double d); + /// A double value is read. + + virtual void value(bool b); + /// A boolean value is read. + + virtual void null(); + /// A null value is read. + +private: + void setValue(const Poco::Dynamic::Var& value); + typedef std::stack<Dynamic::Var> Stack; + + Stack _stack; + std::string _key; + Dynamic::Var _result; + bool _preserveObjectOrder; +}; + + +// +// inlines +// +inline Dynamic::Var ParseHandler::asVar() const +{ + return _result; +} + + +inline void ParseHandler::value(int v) +{ + setValue(v); +} + + +inline void ParseHandler::value(unsigned v) +{ + setValue(v); +} + + +#if defined(POCO_HAVE_INT64) +inline void ParseHandler::value(Int64 v) +{ + setValue(v); +} + + +inline void ParseHandler::value(UInt64 v) +{ + setValue(v); +} +#endif + + +inline void ParseHandler::value(const std::string& s) +{ + setValue(s); +} + + +inline void ParseHandler::value(double d) +{ + setValue(d); +} + + +inline void ParseHandler::value(bool b) +{ + setValue(b); +} + + +inline void ParseHandler::null() +{ + Poco::Dynamic::Var empty; + setValue(empty); +} + + +} } // namespace Poco::JSON + + +#endif // JSON_ParseHandler_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Parser.h b/contrib/libs/poco/JSON/include/Poco/JSON/Parser.h index 51820cbf83..592ddabc32 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Parser.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Parser.h @@ -1,203 +1,203 @@ -// -// Parser.h -// -// Library: JSON -// Package: JSON -// Module: Parser -// -// Definition of the Parser class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONParser_INCLUDED -#define JSON_JSONParser_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/ParserImpl.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/ParseHandler.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/Dynamic/Var.h" -#include <string> - - -namespace Poco { -namespace JSON { - - -class JSON_API Parser: private ParserImpl - /// A parser for reading RFC 4627 compliant JSON from strings or streams. - /// - /// Simple usage example: - /// - /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// // ... use result (see next example) - /// parser.reset(); - /// std::ostringstream ostr; - /// PrintHandler::Ptr pHandler = new PrintHandler(ostr); - /// parser.setHandler(pHandler); - /// parser.parse(json); // ostr.str() == json - /// ---- +// +// Parser.h +// +// Library: JSON +// Package: JSON +// Module: Parser +// +// Definition of the Parser class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONParser_INCLUDED +#define JSON_JSONParser_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/ParserImpl.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/ParseHandler.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/Dynamic/Var.h" +#include <string> + + +namespace Poco { +namespace JSON { + + +class JSON_API Parser: private ParserImpl + /// A parser for reading RFC 4627 compliant JSON from strings or streams. /// - /// The result of parsing a valid JSON document will be either an Object - /// or an Array. Therefore the result of parse() is a Poco::Dynamic::Var - /// containing a Poco::SharedPtr to an Object or Array instance. + /// Simple usage example: /// - /// Example: - /// - /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; - /// Parser parser; - /// Var result = parser.parse(json); - /// Object::Ptr object = result.extract<Object::Ptr>(); - /// std::string name = object.getValue<std::string>("name"); - /// Array::Ptr children = object.getArray("children"); - /// ---- -{ -public: - - Parser(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); - /// Creates JSON Parser, using the given Handler and buffer size. - - virtual ~Parser(); - /// Destroys JSON Parser. - - void reset(); - /// Resets the parser. - - void setAllowComments(bool comments); - /// Allow or disallow comments. By default, comments are not allowed. - - bool getAllowComments() const; - /// Returns true if comments are allowed, false otherwise. - /// - /// By default, comments are not allowed. - - void setAllowNullByte(bool nullByte); - /// Allow or disallow null byte in strings. - /// - /// By default, null byte is allowed. - - bool getAllowNullByte() const; - /// Returns true if null byte is allowed, false otherwise. - /// - /// By default, null bytes are allowed. - - void setDepth(std::size_t depth); - /// Sets the allowed JSON depth. - - std::size_t getDepth() const; - /// Returns the allowed JSON depth. - - Dynamic::Var parse(const std::string& json); - /// Parses JSON from a string. - - Dynamic::Var parse(std::istream& in); - /// Parses JSON from an input stream. - - void setHandler(const Handler::Ptr& pHandler); - /// Set the Handler. - - const Handler::Ptr& getHandler(); - /// Returns the Handler. - - Dynamic::Var asVar() const; - /// Returns the result of parsing; - - Dynamic::Var result() const; - /// Returns the result of parsing as Dynamic::Var; - -private: - Parser(const Parser&); - Parser& operator = (const Parser&); -}; - - -// -// inlines -// -inline void Parser::setAllowComments(bool comments) -{ - setAllowCommentsImpl(comments); -} - - -inline bool Parser::getAllowComments() const -{ - return getAllowCommentsImpl(); -} - - -inline void Parser::setAllowNullByte(bool nullByte) -{ - setAllowNullByteImpl(nullByte); -} - - -inline bool Parser::getAllowNullByte() const -{ - return getAllowNullByteImpl(); -} - - -inline void Parser::setDepth(std::size_t depth) -{ - setDepthImpl(depth); -} - - -inline std::size_t Parser::getDepth() const -{ - return getDepthImpl(); -} - - -inline const Handler::Ptr& Parser::getHandler() -{ - return getHandlerImpl(); -} - - -inline Dynamic::Var Parser::result() const -{ - return resultImpl(); -} - - -inline Dynamic::Var Parser::asVar() const -{ - return asVarImpl(); -} - - -inline void Parser::reset() -{ - resetImpl(); -} - - -inline Dynamic::Var Parser::parse(const std::string& json) -{ - return parseImpl(json); -} - - -inline Dynamic::Var Parser::parse(std::istream& in) -{ - return parseImpl(in); -} - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONParser_INCLUDED + /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// // ... use result (see next example) + /// parser.reset(); + /// std::ostringstream ostr; + /// PrintHandler::Ptr pHandler = new PrintHandler(ostr); + /// parser.setHandler(pHandler); + /// parser.parse(json); // ostr.str() == json + /// ---- + /// + /// The result of parsing a valid JSON document will be either an Object + /// or an Array. Therefore the result of parse() is a Poco::Dynamic::Var + /// containing a Poco::SharedPtr to an Object or Array instance. + /// + /// Example: + /// + /// std::string json = "{ \"name\" : \"Franky\", \"children\" : [ \"Jonas\", \"Ellen\" ] }"; + /// Parser parser; + /// Var result = parser.parse(json); + /// Object::Ptr object = result.extract<Object::Ptr>(); + /// std::string name = object.getValue<std::string>("name"); + /// Array::Ptr children = object.getArray("children"); + /// ---- +{ +public: + + Parser(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); + /// Creates JSON Parser, using the given Handler and buffer size. + + virtual ~Parser(); + /// Destroys JSON Parser. + + void reset(); + /// Resets the parser. + + void setAllowComments(bool comments); + /// Allow or disallow comments. By default, comments are not allowed. + + bool getAllowComments() const; + /// Returns true if comments are allowed, false otherwise. + /// + /// By default, comments are not allowed. + + void setAllowNullByte(bool nullByte); + /// Allow or disallow null byte in strings. + /// + /// By default, null byte is allowed. + + bool getAllowNullByte() const; + /// Returns true if null byte is allowed, false otherwise. + /// + /// By default, null bytes are allowed. + + void setDepth(std::size_t depth); + /// Sets the allowed JSON depth. + + std::size_t getDepth() const; + /// Returns the allowed JSON depth. + + Dynamic::Var parse(const std::string& json); + /// Parses JSON from a string. + + Dynamic::Var parse(std::istream& in); + /// Parses JSON from an input stream. + + void setHandler(const Handler::Ptr& pHandler); + /// Set the Handler. + + const Handler::Ptr& getHandler(); + /// Returns the Handler. + + Dynamic::Var asVar() const; + /// Returns the result of parsing; + + Dynamic::Var result() const; + /// Returns the result of parsing as Dynamic::Var; + +private: + Parser(const Parser&); + Parser& operator = (const Parser&); +}; + + +// +// inlines +// +inline void Parser::setAllowComments(bool comments) +{ + setAllowCommentsImpl(comments); +} + + +inline bool Parser::getAllowComments() const +{ + return getAllowCommentsImpl(); +} + + +inline void Parser::setAllowNullByte(bool nullByte) +{ + setAllowNullByteImpl(nullByte); +} + + +inline bool Parser::getAllowNullByte() const +{ + return getAllowNullByteImpl(); +} + + +inline void Parser::setDepth(std::size_t depth) +{ + setDepthImpl(depth); +} + + +inline std::size_t Parser::getDepth() const +{ + return getDepthImpl(); +} + + +inline const Handler::Ptr& Parser::getHandler() +{ + return getHandlerImpl(); +} + + +inline Dynamic::Var Parser::result() const +{ + return resultImpl(); +} + + +inline Dynamic::Var Parser::asVar() const +{ + return asVarImpl(); +} + + +inline void Parser::reset() +{ + resetImpl(); +} + + +inline Dynamic::Var Parser::parse(const std::string& json) +{ + return parseImpl(json); +} + + +inline Dynamic::Var Parser::parse(std::istream& in) +{ + return parseImpl(in); +} + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONParser_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/ParserImpl.h b/contrib/libs/poco/JSON/include/Poco/JSON/ParserImpl.h index 13bf226800..dd92fe84e6 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/ParserImpl.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/ParserImpl.h @@ -1,194 +1,194 @@ -// -// Parser.h -// -// Library: JSON -// Package: JSON -// Module: ParserImpl -// -// Definition of the ParserImpl class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONParserImpl_INCLUDED -#define JSON_JSONParserImpl_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/ParseHandler.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/Dynamic/Var.h" -#include <string> - - -struct json_stream; - - -namespace Poco { -namespace JSON { - - -class JSON_API ParserImpl -{ -protected: - static const std::size_t JSON_PARSE_BUFFER_SIZE = 4096; - static const std::size_t JSON_PARSER_STACK_SIZE = 128; - static const int JSON_UNLIMITED_DEPTH = -1; - - ParserImpl(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); - /// Creates JSON ParserImpl, using the given Handler and buffer size. - - virtual ~ParserImpl(); - /// Destroys JSON ParserImpl. - - void resetImpl(); - /// Resets the parser. - - void setAllowCommentsImpl(bool comments); - /// Allow or disallow comments. By default, comments are not allowed. - - bool getAllowCommentsImpl() const; - /// Returns true if comments are allowed, false otherwise. - /// - /// By default, comments are not allowed. - - void setAllowNullByteImpl(bool nullByte); - /// Allow or disallow null byte in strings. - /// - /// By default, null byte is allowed. - - bool getAllowNullByteImpl() const; - /// Returns true if null byte is allowed, false otherwise. - /// - /// By default, null bytes are allowed. - - void setDepthImpl(std::size_t depth); - /// Sets the allowed JSON depth. - - std::size_t getDepthImpl() const; - /// Returns the allowed JSON depth. - - Dynamic::Var parseImpl(const std::string& json); - /// Parses JSON from a string. - - Dynamic::Var parseImpl(std::istream& in); - /// Parses JSON from an input stream. - - void setHandlerImpl(const Handler::Ptr& pHandler); - /// Set the Handler. - - const Handler::Ptr& getHandlerImpl(); - /// Returns the Handler. - - Dynamic::Var asVarImpl() const; - /// Returns the result of parsing; - - Dynamic::Var resultImpl() const; - /// Returns the result of parsing as Dynamic::Var; - -private: - ParserImpl(const ParserImpl&); - ParserImpl& operator =(const ParserImpl&); - - void handleArray(); - void handleObject(); - void handle(); - void handle(const std::string& json); - void stripComments(std::string& json); - bool checkError(); - - struct json_stream* _pJSON; - Handler::Ptr _pHandler; - int _depth; - char _decimalPoint; - bool _allowNullByte; - bool _allowComments; -}; - - -// -// inlines -// - -inline void ParserImpl::resetImpl() -{ - // currently, json stream is opened and closed on every parse request - // (perhaps there is some optimization room?) - //json_reset(&_json); - if (_pHandler) _pHandler->reset(); -} - - -inline void ParserImpl::setAllowCommentsImpl(bool comments) -{ - _allowComments = comments; -} - - -inline bool ParserImpl::getAllowCommentsImpl() const -{ - return _allowComments; -} - - -inline void ParserImpl::setAllowNullByteImpl(bool nullByte) -{ - _allowNullByte = nullByte; -} - - -inline bool ParserImpl::getAllowNullByteImpl() const -{ - return _allowNullByte; -} - - -inline void ParserImpl::setDepthImpl(std::size_t depth) -{ - _depth = static_cast<int>(depth); -} - - -inline std::size_t ParserImpl::getDepthImpl() const -{ - return static_cast<int>(_depth); -} - - -inline void ParserImpl::setHandlerImpl(const Handler::Ptr& pHandler) -{ - _pHandler = pHandler; -} - - -inline const Handler::Ptr& ParserImpl::getHandlerImpl() -{ - return _pHandler; -} - - -inline Dynamic::Var ParserImpl::resultImpl() const -{ - return asVarImpl(); -} - - -inline Dynamic::Var ParserImpl::asVarImpl() const -{ - if (_pHandler) return _pHandler->asVar(); - - return Dynamic::Var(); -} - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONParserImpl_INCLUDED +// +// Parser.h +// +// Library: JSON +// Package: JSON +// Module: ParserImpl +// +// Definition of the ParserImpl class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONParserImpl_INCLUDED +#define JSON_JSONParserImpl_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/ParseHandler.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/Dynamic/Var.h" +#include <string> + + +struct json_stream; + + +namespace Poco { +namespace JSON { + + +class JSON_API ParserImpl +{ +protected: + static const std::size_t JSON_PARSE_BUFFER_SIZE = 4096; + static const std::size_t JSON_PARSER_STACK_SIZE = 128; + static const int JSON_UNLIMITED_DEPTH = -1; + + ParserImpl(const Handler::Ptr& pHandler = new ParseHandler, std::size_t bufSize = JSON_PARSE_BUFFER_SIZE); + /// Creates JSON ParserImpl, using the given Handler and buffer size. + + virtual ~ParserImpl(); + /// Destroys JSON ParserImpl. + + void resetImpl(); + /// Resets the parser. + + void setAllowCommentsImpl(bool comments); + /// Allow or disallow comments. By default, comments are not allowed. + + bool getAllowCommentsImpl() const; + /// Returns true if comments are allowed, false otherwise. + /// + /// By default, comments are not allowed. + + void setAllowNullByteImpl(bool nullByte); + /// Allow or disallow null byte in strings. + /// + /// By default, null byte is allowed. + + bool getAllowNullByteImpl() const; + /// Returns true if null byte is allowed, false otherwise. + /// + /// By default, null bytes are allowed. + + void setDepthImpl(std::size_t depth); + /// Sets the allowed JSON depth. + + std::size_t getDepthImpl() const; + /// Returns the allowed JSON depth. + + Dynamic::Var parseImpl(const std::string& json); + /// Parses JSON from a string. + + Dynamic::Var parseImpl(std::istream& in); + /// Parses JSON from an input stream. + + void setHandlerImpl(const Handler::Ptr& pHandler); + /// Set the Handler. + + const Handler::Ptr& getHandlerImpl(); + /// Returns the Handler. + + Dynamic::Var asVarImpl() const; + /// Returns the result of parsing; + + Dynamic::Var resultImpl() const; + /// Returns the result of parsing as Dynamic::Var; + +private: + ParserImpl(const ParserImpl&); + ParserImpl& operator =(const ParserImpl&); + + void handleArray(); + void handleObject(); + void handle(); + void handle(const std::string& json); + void stripComments(std::string& json); + bool checkError(); + + struct json_stream* _pJSON; + Handler::Ptr _pHandler; + int _depth; + char _decimalPoint; + bool _allowNullByte; + bool _allowComments; +}; + + +// +// inlines +// + +inline void ParserImpl::resetImpl() +{ + // currently, json stream is opened and closed on every parse request + // (perhaps there is some optimization room?) + //json_reset(&_json); + if (_pHandler) _pHandler->reset(); +} + + +inline void ParserImpl::setAllowCommentsImpl(bool comments) +{ + _allowComments = comments; +} + + +inline bool ParserImpl::getAllowCommentsImpl() const +{ + return _allowComments; +} + + +inline void ParserImpl::setAllowNullByteImpl(bool nullByte) +{ + _allowNullByte = nullByte; +} + + +inline bool ParserImpl::getAllowNullByteImpl() const +{ + return _allowNullByte; +} + + +inline void ParserImpl::setDepthImpl(std::size_t depth) +{ + _depth = static_cast<int>(depth); +} + + +inline std::size_t ParserImpl::getDepthImpl() const +{ + return static_cast<int>(_depth); +} + + +inline void ParserImpl::setHandlerImpl(const Handler::Ptr& pHandler) +{ + _pHandler = pHandler; +} + + +inline const Handler::Ptr& ParserImpl::getHandlerImpl() +{ + return _pHandler; +} + + +inline Dynamic::Var ParserImpl::resultImpl() const +{ + return asVarImpl(); +} + + +inline Dynamic::Var ParserImpl::asVarImpl() const +{ + if (_pHandler) return _pHandler->asVar(); + + return Dynamic::Var(); +} + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONParserImpl_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/PrintHandler.h b/contrib/libs/poco/JSON/include/Poco/JSON/PrintHandler.h index 88239d01f1..620dc52a9a 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/PrintHandler.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/PrintHandler.h @@ -1,139 +1,139 @@ -// -// PrintHandler.h -// -// Library: JSON -// Package: JSON -// Module: PrintHandler -// -// Definition of the PrintHandler class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_PrintHandler_INCLUDED -#define JSON_PrintHandler_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Handler.h" -#include "Poco/JSONString.h" - - -namespace Poco { -namespace JSON { - - -class JSON_API PrintHandler: public Handler - /// PrintHandler formats and prints the JSON object - /// to either user-provided std::ostream or standard output. - /// If indent is zero, the output is a condensed JSON string, - /// otherwise, the proper indentation is applied to elements. -{ -public: - typedef SharedPtr<PrintHandler> Ptr; - - static const unsigned JSON_PRINT_FLAT = 0; - - PrintHandler(unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); - /// Creates the PrintHandler. - - PrintHandler(std::ostream& out, unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); - /// Creates the PrintHandler. - - ~PrintHandler(); - /// Destroys the PrintHandler. - - void reset(); - /// Resets the handler state. - - void startObject(); - /// The parser has read a '{'; a new object is started. - /// If indent is greater than zero, a newline will be appended. - - void endObject(); - /// The parser has read a '}'; the object is closed. - - void startArray(); - /// The parser has read a [; a new array will be started. - /// If indent is greater than zero, a newline will be appended. - - void endArray(); - /// The parser has read a ]; the array is closed. - - void key(const std::string& k); - /// A key of an object is read; it will be written to the output, - /// followed by a ':'. If indent is greater than zero, the colon - /// is padded by a space before and after. - - void null(); - /// A null value is read; "null" will be written to the output. - - void value(int v); - /// An integer value is read. - - void value(unsigned v); - /// An unsigned value is read. This will only be triggered if the - /// value cannot fit into a signed int. - -#if defined(POCO_HAVE_INT64) - void value(Int64 v); - /// A 64-bit integer value is read; it will be written to the output. - - void value(UInt64 v); - /// An unsigned 64-bit integer value is read; it will be written to the output. -#endif - - void value(const std::string& value); - /// A string value is read; it will be formatted and written to the output. - - void value(double d); - /// A double value is read; it will be written to the output. - - void value(bool b); - /// A boolean value is read; it will be written to the output. - - void comma(); - /// A comma is read; it will be written to the output as "true" or "false". - - void setIndent(unsigned indent); - /// Sets indentation. - -private: - const char* endLine() const; - unsigned indent(); - bool printFlat() const; - void arrayValue(); - bool array() const; - - std::ostream& _out; - unsigned _indent; - std::string _tab; - int _array; - bool _objStart; - int _options; -}; - - -// -// inlines -// -inline void PrintHandler::setIndent(unsigned indent) -{ - _indent = indent; -} - - -inline bool PrintHandler::array() const -{ - return _array > 0; -} - - -} } // namespace Poco::JSON - - -#endif // JSON_PrintHandler_INCLUDED +// +// PrintHandler.h +// +// Library: JSON +// Package: JSON +// Module: PrintHandler +// +// Definition of the PrintHandler class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_PrintHandler_INCLUDED +#define JSON_PrintHandler_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Handler.h" +#include "Poco/JSONString.h" + + +namespace Poco { +namespace JSON { + + +class JSON_API PrintHandler: public Handler + /// PrintHandler formats and prints the JSON object + /// to either user-provided std::ostream or standard output. + /// If indent is zero, the output is a condensed JSON string, + /// otherwise, the proper indentation is applied to elements. +{ +public: + typedef SharedPtr<PrintHandler> Ptr; + + static const unsigned JSON_PRINT_FLAT = 0; + + PrintHandler(unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); + /// Creates the PrintHandler. + + PrintHandler(std::ostream& out, unsigned indent = 0, int options = Poco::JSON_WRAP_STRINGS); + /// Creates the PrintHandler. + + ~PrintHandler(); + /// Destroys the PrintHandler. + + void reset(); + /// Resets the handler state. + + void startObject(); + /// The parser has read a '{'; a new object is started. + /// If indent is greater than zero, a newline will be appended. + + void endObject(); + /// The parser has read a '}'; the object is closed. + + void startArray(); + /// The parser has read a [; a new array will be started. + /// If indent is greater than zero, a newline will be appended. + + void endArray(); + /// The parser has read a ]; the array is closed. + + void key(const std::string& k); + /// A key of an object is read; it will be written to the output, + /// followed by a ':'. If indent is greater than zero, the colon + /// is padded by a space before and after. + + void null(); + /// A null value is read; "null" will be written to the output. + + void value(int v); + /// An integer value is read. + + void value(unsigned v); + /// An unsigned value is read. This will only be triggered if the + /// value cannot fit into a signed int. + +#if defined(POCO_HAVE_INT64) + void value(Int64 v); + /// A 64-bit integer value is read; it will be written to the output. + + void value(UInt64 v); + /// An unsigned 64-bit integer value is read; it will be written to the output. +#endif + + void value(const std::string& value); + /// A string value is read; it will be formatted and written to the output. + + void value(double d); + /// A double value is read; it will be written to the output. + + void value(bool b); + /// A boolean value is read; it will be written to the output. + + void comma(); + /// A comma is read; it will be written to the output as "true" or "false". + + void setIndent(unsigned indent); + /// Sets indentation. + +private: + const char* endLine() const; + unsigned indent(); + bool printFlat() const; + void arrayValue(); + bool array() const; + + std::ostream& _out; + unsigned _indent; + std::string _tab; + int _array; + bool _objStart; + int _options; +}; + + +// +// inlines +// +inline void PrintHandler::setIndent(unsigned indent) +{ + _indent = indent; +} + + +inline bool PrintHandler::array() const +{ + return _array > 0; +} + + +} } // namespace Poco::JSON + + +#endif // JSON_PrintHandler_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Query.h b/contrib/libs/poco/JSON/include/Poco/JSON/Query.h index 9e0be050aa..c639a3d7dd 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Query.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Query.h @@ -1,125 +1,125 @@ -// -// Query.h -// -// Library: JSON -// Package: JSON -// Module: Query -// -// Definition of the Query class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONQuery_INCLUDED -#define JSON_JSONQuery_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Array.h" - - -namespace Poco { -namespace JSON { - - -class JSON_API Query - /// Class that can be used to search for a value in a JSON object or array. -{ -public: - Query(const Dynamic::Var& source); - /// Creates a Query/ - /// - /// Source must be JSON Object, Array, Object::Ptr, - /// Array::Ptr or empty Var. Any other type will trigger throwing of - /// InvalidArgumentException. - /// - /// Creating Query holding Ptr will typically result in faster - /// performance. - - virtual ~Query(); - /// Destroys the Query. - - Object::Ptr findObject(const std::string& path) const; - /// Search for an object. - /// - /// When the object can't be found, a zero Ptr is returned; - /// otherwise, a shared pointer to internally held object - /// is returned. - /// If object (as opposed to a pointer to object) is held - /// internally, a shared pointer to new (heap-allocated) Object is - /// returned; this may be expensive operation. - - Object& findObject(const std::string& path, Object& obj) const; - /// Search for an object. - /// - /// If object is found, it is assigned to the - /// Object through the reference passed in. When the object can't be - /// found, the provided Object is emptied and returned. - - Array::Ptr findArray(const std::string& path) const; - /// Search for an array. - /// - /// When the array can't be found, a zero Ptr is returned; - /// otherwise, a shared pointer to internally held array - /// is returned. - /// If array (as opposed to a pointer to array) is held - /// internally, a shared pointer to new (heap-allocated) Object is - /// returned; this may be expensive operation. - - Array& findArray(const std::string& path, Array& obj) const; - /// Search for an array. - /// - /// If array is found, it is assigned to the - /// Object through the reference passed in. When the array can't be - /// found, the provided Object is emptied and returned. - - Dynamic::Var find(const std::string& path) const; - /// Searches a value. - /// - /// Example: "person.children[0].name" will return the - /// the name of the first child. When the value can't be found - /// an empty value is returned. - - template<typename T> - T findValue(const std::string& path, const T& def) const - /// Searches for a value will convert it to the given type. - /// When the value can't be found or has an invalid type - /// the default value will be returned. - { - T result = def; - Dynamic::Var value = find(path); - if (!value.isEmpty()) - { - try +// +// Query.h +// +// Library: JSON +// Package: JSON +// Module: Query +// +// Definition of the Query class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONQuery_INCLUDED +#define JSON_JSONQuery_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/Array.h" + + +namespace Poco { +namespace JSON { + + +class JSON_API Query + /// Class that can be used to search for a value in a JSON object or array. +{ +public: + Query(const Dynamic::Var& source); + /// Creates a Query/ + /// + /// Source must be JSON Object, Array, Object::Ptr, + /// Array::Ptr or empty Var. Any other type will trigger throwing of + /// InvalidArgumentException. + /// + /// Creating Query holding Ptr will typically result in faster + /// performance. + + virtual ~Query(); + /// Destroys the Query. + + Object::Ptr findObject(const std::string& path) const; + /// Search for an object. + /// + /// When the object can't be found, a zero Ptr is returned; + /// otherwise, a shared pointer to internally held object + /// is returned. + /// If object (as opposed to a pointer to object) is held + /// internally, a shared pointer to new (heap-allocated) Object is + /// returned; this may be expensive operation. + + Object& findObject(const std::string& path, Object& obj) const; + /// Search for an object. + /// + /// If object is found, it is assigned to the + /// Object through the reference passed in. When the object can't be + /// found, the provided Object is emptied and returned. + + Array::Ptr findArray(const std::string& path) const; + /// Search for an array. + /// + /// When the array can't be found, a zero Ptr is returned; + /// otherwise, a shared pointer to internally held array + /// is returned. + /// If array (as opposed to a pointer to array) is held + /// internally, a shared pointer to new (heap-allocated) Object is + /// returned; this may be expensive operation. + + Array& findArray(const std::string& path, Array& obj) const; + /// Search for an array. + /// + /// If array is found, it is assigned to the + /// Object through the reference passed in. When the array can't be + /// found, the provided Object is emptied and returned. + + Dynamic::Var find(const std::string& path) const; + /// Searches a value. + /// + /// Example: "person.children[0].name" will return the + /// the name of the first child. When the value can't be found + /// an empty value is returned. + + template<typename T> + T findValue(const std::string& path, const T& def) const + /// Searches for a value will convert it to the given type. + /// When the value can't be found or has an invalid type + /// the default value will be returned. + { + T result = def; + Dynamic::Var value = find(path); + if (!value.isEmpty()) + { + try + { + result = value.convert<T>(); + } + catch (...) { - result = value.convert<T>(); - } - catch (...) - { - } - } - return result; - } - - std::string findValue(const char* path, const char* def) const - /// Searches for a value will convert it to the given type. - /// When the value can't be found or has an invalid type - /// the default value will be returned. - { - return findValue<std::string>(path, def); - } - -private: - Dynamic::Var _source; -}; - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONQuery_INCLUDED + } + } + return result; + } + + std::string findValue(const char* path, const char* def) const + /// Searches for a value will convert it to the given type. + /// When the value can't be found or has an invalid type + /// the default value will be returned. + { + return findValue<std::string>(path, def); + } + +private: + Dynamic::Var _source; +}; + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONQuery_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Stringifier.h b/contrib/libs/poco/JSON/include/Poco/JSON/Stringifier.h index f1bba70cfd..8e3303becf 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Stringifier.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Stringifier.h @@ -1,73 +1,73 @@ -// -// Stringifier.h -// -// Library: JSON -// Package: JSON -// Module: Stringifier -// -// Definition of the Stringifier class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONStringifier_INCLUDED -#define JSON_JSONStringifier_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSONString.h" -#include "Poco/Dynamic/Var.h" -#include <ostream> - - -namespace Poco { -namespace JSON { - - -class JSON_API Stringifier - /// Helper class for creating a string from a JSON object or array. -{ -public: - static void condense(const Dynamic::Var& any, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); - /// Writes a condensed string representation of the value to the output stream while preserving - /// the insertion order. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. - /// - /// This is just a "shortcut" to stringify(any, out) with name indicating the function effect. - - static void stringify(const Dynamic::Var& any, std::ostream& out, - unsigned int indent = 0, int step = -1, int options = Poco::JSON_WRAP_STRINGS); - /// Writes a string representation of the value to the output stream. - /// - /// When indent is 0, the string will be created as small as possible. - /// Indentation is increased/decreased using number of spaces defined in step. - /// The default value -1 for step indicates that step will be equal to the - /// indent size. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. - - static void formatString(const std::string& value, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); - /// Formats the JSON string and streams it into ostream. - /// - /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise - /// only the compulsory ones. -}; - - -inline void Stringifier::condense(const Dynamic::Var& any, std::ostream& out, int options) -{ - stringify(any, out, 0, -1, options); -} - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONStringifier_INCLUDED +// +// Stringifier.h +// +// Library: JSON +// Package: JSON +// Module: Stringifier +// +// Definition of the Stringifier class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONStringifier_INCLUDED +#define JSON_JSONStringifier_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSONString.h" +#include "Poco/Dynamic/Var.h" +#include <ostream> + + +namespace Poco { +namespace JSON { + + +class JSON_API Stringifier + /// Helper class for creating a string from a JSON object or array. +{ +public: + static void condense(const Dynamic::Var& any, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); + /// Writes a condensed string representation of the value to the output stream while preserving + /// the insertion order. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + /// + /// This is just a "shortcut" to stringify(any, out) with name indicating the function effect. + + static void stringify(const Dynamic::Var& any, std::ostream& out, + unsigned int indent = 0, int step = -1, int options = Poco::JSON_WRAP_STRINGS); + /// Writes a string representation of the value to the output stream. + /// + /// When indent is 0, the string will be created as small as possible. + /// Indentation is increased/decreased using number of spaces defined in step. + /// The default value -1 for step indicates that step will be equal to the + /// indent size. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. + + static void formatString(const std::string& value, std::ostream& out, int options = Poco::JSON_WRAP_STRINGS); + /// Formats the JSON string and streams it into ostream. + /// + /// If JSON_ESCAPE_UNICODE is in options, all unicode characters will be escaped, otherwise + /// only the compulsory ones. +}; + + +inline void Stringifier::condense(const Dynamic::Var& any, std::ostream& out, int options) +{ + stringify(any, out, 0, -1, options); +} + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONStringifier_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/Template.h b/contrib/libs/poco/JSON/include/Poco/JSON/Template.h index e971361836..7e8ac51e03 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/Template.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/Template.h @@ -1,151 +1,151 @@ -// -// Template.h -// -// Library: JSON -// Package: JSON -// Module: Template -// -// Definition of the Template class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONTemplate_INCLUDED -#define JSON_JSONTemplate_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/Dynamic/Var.h" -#include "Poco/SharedPtr.h" -#include "Poco/Path.h" -#include "Poco/Timestamp.h" -#include <sstream> -#include <stack> - - -namespace Poco { -namespace JSON { - - -class MultiPart; - - -POCO_DECLARE_EXCEPTION(JSON_API, JSONTemplateException, Poco::Exception) - - -class JSON_API Template - /// Template is a template engine which uses JSON as input - /// for generating output. There are commands for - /// looping over JSON arrays, include other templates, - /// conditional output, etc. +// +// Template.h +// +// Library: JSON +// Package: JSON +// Module: Template +// +// Definition of the Template class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONTemplate_INCLUDED +#define JSON_JSONTemplate_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/Dynamic/Var.h" +#include "Poco/SharedPtr.h" +#include "Poco/Path.h" +#include "Poco/Timestamp.h" +#include <sstream> +#include <stack> + + +namespace Poco { +namespace JSON { + + +class MultiPart; + + +POCO_DECLARE_EXCEPTION(JSON_API, JSONTemplateException, Poco::Exception) + + +class JSON_API Template + /// Template is a template engine which uses JSON as input + /// for generating output. There are commands for + /// looping over JSON arrays, include other templates, + /// conditional output, etc. + /// + /// All text is send to the outputstream. A command is placed + /// between + /// <? + /// and + /// ?> + /// ---- + /// + /// These are the available commands: /// - /// All text is send to the outputstream. A command is placed - /// between - /// <? - /// and - /// ?> - /// ---- + /// <? echo query ?> + /// ---- + /// The result of the query is send to the output stream + /// This command can also be written as <?= query ?> /// - /// These are the available commands: - /// - /// <? echo query ?> - /// ---- - /// The result of the query is send to the output stream - /// This command can also be written as <?= query ?> - /// - /// <? if query ?> <? else ?> <? endif ?> - /// ---- - /// When the result of query is true, all the text between - /// if and else (or endif when there is no else) is send to the - /// output stream. When the result of query is false, all the text - /// between else and endif is send to the output stream. An empty - /// object, an empty array or a null value is considered as a false value. - /// For numbers a zero is false. An empty String is also false. + /// <? if query ?> <? else ?> <? endif ?> + /// ---- + /// When the result of query is true, all the text between + /// if and else (or endif when there is no else) is send to the + /// output stream. When the result of query is false, all the text + /// between else and endif is send to the output stream. An empty + /// object, an empty array or a null value is considered as a false value. + /// For numbers a zero is false. An empty String is also false. + /// + /// <? ifexist query ?> <? else ?> <? endif ?> + /// ---- + /// This can be used to check the existence of the value. + /// Use this for example when a zero value is ok (which returns false for <? if ?>. /// - /// <? ifexist query ?> <? else ?> <? endif ?> - /// ---- - /// This can be used to check the existence of the value. - /// Use this for example when a zero value is ok (which returns false for <? if ?>. - /// - /// <? for variable query ?> <? endfor ?> - /// ---- - /// The result of the query must be an array. For each element - /// in the array the text between for and endfor is send to the - /// output stream. The active element is stored in the variable. - /// - /// <? include "filename" ?> - /// ---- - /// Includes a template. When the filename is relative it will try - /// to resolve the filename against the active template. When this - /// file doesn't exist, it can still be found when the JSONTemplateCache - /// is used. - /// - /// A query is passed to Poco::JSON::Query to get the value. -{ -public: - typedef SharedPtr<Template> Ptr; - - Template(); - /// Creates a Template. - - Template(const Path& templatePath); - /// Creates a Template from the file with the given templatePath. - - virtual ~Template(); - /// Destroys the Template. - - void parse(); - /// Parse a template from a file. - - void parse(const std::string& source); - /// Parse a template from a string. - - void parse(std::istream& in); - /// Parse a template from an input stream. - - Timestamp parseTime() const; - /// Returns the time when the template was parsed. - - void render(const Dynamic::Var& data, std::ostream& out) const; - /// Renders the template and send the output to the stream. - -private: - std::string readText(std::istream& in); - std::string readWord(std::istream& in); - std::string readQuery(std::istream& in); - std::string readTemplateCommand(std::istream& in); - std::string readString(std::istream& in); - void readWhiteSpace(std::istream& in); - - MultiPart* _parts; - std::stack<MultiPart*> _partStack; - MultiPart* _currentPart; - Path _templatePath; - Timestamp _parseTime; -}; - - -// -// inlines -// -inline void Template::parse(const std::string& source) -{ - std::istringstream is(source); - parse(is); -} - - -inline Timestamp Template::parseTime() const -{ - return _parseTime; -} - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONTemplate_INCLUDED + /// <? for variable query ?> <? endfor ?> + /// ---- + /// The result of the query must be an array. For each element + /// in the array the text between for and endfor is send to the + /// output stream. The active element is stored in the variable. + /// + /// <? include "filename" ?> + /// ---- + /// Includes a template. When the filename is relative it will try + /// to resolve the filename against the active template. When this + /// file doesn't exist, it can still be found when the JSONTemplateCache + /// is used. + /// + /// A query is passed to Poco::JSON::Query to get the value. +{ +public: + typedef SharedPtr<Template> Ptr; + + Template(); + /// Creates a Template. + + Template(const Path& templatePath); + /// Creates a Template from the file with the given templatePath. + + virtual ~Template(); + /// Destroys the Template. + + void parse(); + /// Parse a template from a file. + + void parse(const std::string& source); + /// Parse a template from a string. + + void parse(std::istream& in); + /// Parse a template from an input stream. + + Timestamp parseTime() const; + /// Returns the time when the template was parsed. + + void render(const Dynamic::Var& data, std::ostream& out) const; + /// Renders the template and send the output to the stream. + +private: + std::string readText(std::istream& in); + std::string readWord(std::istream& in); + std::string readQuery(std::istream& in); + std::string readTemplateCommand(std::istream& in); + std::string readString(std::istream& in); + void readWhiteSpace(std::istream& in); + + MultiPart* _parts; + std::stack<MultiPart*> _partStack; + MultiPart* _currentPart; + Path _templatePath; + Timestamp _parseTime; +}; + + +// +// inlines +// +inline void Template::parse(const std::string& source) +{ + std::istringstream is(source); + parse(is); +} + + +inline Timestamp Template::parseTime() const +{ + return _parseTime; +} + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONTemplate_INCLUDED diff --git a/contrib/libs/poco/JSON/include/Poco/JSON/TemplateCache.h b/contrib/libs/poco/JSON/include/Poco/JSON/TemplateCache.h index e3c35f0917..0f5fcf095b 100644 --- a/contrib/libs/poco/JSON/include/Poco/JSON/TemplateCache.h +++ b/contrib/libs/poco/JSON/include/Poco/JSON/TemplateCache.h @@ -1,105 +1,105 @@ -// -// TemplateCache.h -// -// Library: JSON -// Package: JSON -// Module: TemplateCache -// -// Definition of the TemplateCache class. -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#ifndef JSON_JSONTemplateCache_INCLUDED -#define JSON_JSONTemplateCache_INCLUDED - - -#include "Poco/JSON/JSON.h" -#include "Poco/JSON/Template.h" -#include "Poco/Path.h" -#include "Poco/SharedPtr.h" -#include "Poco/Logger.h" -#include <vector> -#include <map> - - -namespace Poco { -namespace JSON { - - -class JSON_API TemplateCache - /// Use to cache parsed templates. Templates are - /// stored in a map with the full path as key. - /// When a template file has changed, the cache - /// will remove the old template from the cache - /// and load a new one. -{ -public: - TemplateCache(); - /// Creates an empty TemplateCache. - /// - /// The cache must be created and not destroyed - /// as long as it is used. - - virtual ~TemplateCache(); - /// Destroys the TemplateCache. - - void addPath(const Path& path); - /// Add a path for resolving template paths. - /// The order of check is FIFO. - - Template::Ptr getTemplate(const Path& path); - /// Returns a template from the cache. - /// When the template file is not yet loaded - /// or when the file has changed, the template - /// will be (re)loaded and parsed. A shared pointer - /// is returned, so it is safe to use this template - /// even when the template isn't stored anymore in - /// the cache. - - static TemplateCache* instance(); - /// Returns the only instance of this cache. - - void setLogger(Logger& logger); - /// Sets the logger for the cache. - -private: - void setup(); - Path resolvePath(const Path& path) const; - - static TemplateCache* _pInstance; - std::vector<Path> _includePaths; - std::map<std::string, Template::Ptr> _cache; - Logger* _pLogger; -}; - - -// -// inlines -// -inline void TemplateCache::addPath(const Path& path) -{ - _includePaths.push_back(path); -} - - -inline TemplateCache* TemplateCache::instance() -{ - return _pInstance; -} - - -inline void TemplateCache::setLogger(Logger& logger) -{ - _pLogger = &logger; -} - - -} } // namespace Poco::JSON - - -#endif // JSON_JSONTemplateCache_INCLUDED +// +// TemplateCache.h +// +// Library: JSON +// Package: JSON +// Module: TemplateCache +// +// Definition of the TemplateCache class. +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#ifndef JSON_JSONTemplateCache_INCLUDED +#define JSON_JSONTemplateCache_INCLUDED + + +#include "Poco/JSON/JSON.h" +#include "Poco/JSON/Template.h" +#include "Poco/Path.h" +#include "Poco/SharedPtr.h" +#include "Poco/Logger.h" +#include <vector> +#include <map> + + +namespace Poco { +namespace JSON { + + +class JSON_API TemplateCache + /// Use to cache parsed templates. Templates are + /// stored in a map with the full path as key. + /// When a template file has changed, the cache + /// will remove the old template from the cache + /// and load a new one. +{ +public: + TemplateCache(); + /// Creates an empty TemplateCache. + /// + /// The cache must be created and not destroyed + /// as long as it is used. + + virtual ~TemplateCache(); + /// Destroys the TemplateCache. + + void addPath(const Path& path); + /// Add a path for resolving template paths. + /// The order of check is FIFO. + + Template::Ptr getTemplate(const Path& path); + /// Returns a template from the cache. + /// When the template file is not yet loaded + /// or when the file has changed, the template + /// will be (re)loaded and parsed. A shared pointer + /// is returned, so it is safe to use this template + /// even when the template isn't stored anymore in + /// the cache. + + static TemplateCache* instance(); + /// Returns the only instance of this cache. + + void setLogger(Logger& logger); + /// Sets the logger for the cache. + +private: + void setup(); + Path resolvePath(const Path& path) const; + + static TemplateCache* _pInstance; + std::vector<Path> _includePaths; + std::map<std::string, Template::Ptr> _cache; + Logger* _pLogger; +}; + + +// +// inlines +// +inline void TemplateCache::addPath(const Path& path) +{ + _includePaths.push_back(path); +} + + +inline TemplateCache* TemplateCache::instance() +{ + return _pInstance; +} + + +inline void TemplateCache::setLogger(Logger& logger) +{ + _pLogger = &logger; +} + + +} } // namespace Poco::JSON + + +#endif // JSON_JSONTemplateCache_INCLUDED diff --git a/contrib/libs/poco/JSON/src/Array.cpp b/contrib/libs/poco/JSON/src/Array.cpp index db7c5b48a0..710d0259c6 100644 --- a/contrib/libs/poco/JSON/src/Array.cpp +++ b/contrib/libs/poco/JSON/src/Array.cpp @@ -1,268 +1,268 @@ -// -// Array.cpp -// -// Library: JSON -// Package: JSON -// Module: Array -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Array.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/Stringifier.h" -#include "Poco/JSONString.h" - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -Array::Array(int options): _modified(false), - _escapeUnicode((options & Poco::JSON_ESCAPE_UNICODE) != 0) -{ -} - - -Array::Array(const Array& other) : _values(other._values), - _pArray(other._pArray), - _modified(other._modified) -{ -} - - -Array &Array::operator=(const Array& other) -{ - if (&other != this) - { - _values = other._values; - _pArray = other._pArray; - _modified = other._modified; - } - return *this; -} - -#ifdef POCO_ENABLE_CPP11 - - -Array::Array(Array&& other) : - _values(std::move(other._values)), - _pArray(!other._modified ? other._pArray : 0), - _modified(other._modified) -{ - _pArray = 0; -} - -Array &Array::operator= (Array&& other) -{ - if (&other != this) - { - _values = std::move(other._values); - _pArray = other._pArray; - other._pArray = 0; - _modified = other._modified; - } - return *this; -} - - -#endif // POCO_ENABLE_CPP11 - - -Array::~Array() -{ -} - - -Var Array::get(unsigned int index) const -{ - Var value; - try - { - value = _values.at(index); - } - catch (std::out_of_range&) - { - //Ignore, we return an empty value - } - return value; -} - - -Array::Ptr Array::getArray(unsigned int index) const -{ - Array::Ptr result; - - Var value = get(index); - if (value.type() == typeid(Array::Ptr)) - { - result = value.extract<Array::Ptr>(); - } - return result; -} - - -Object::Ptr Array::getObject(unsigned int index) const -{ - Object::Ptr result; - - Var value = get(index); - if (value.type() == typeid(Object::Ptr)) - { - result = value.extract<Object::Ptr>(); - } - return result; -} - - -bool Array::isNull(unsigned int index) const -{ - if (index < _values.size()) - { - Dynamic::Var value = _values[index]; - return value.isEmpty(); - } - return true; -} - - -bool Array::isObject(unsigned int index) const -{ - Var value = get(index); - return isObject(value); -} - - -bool Array::isObject(const Dynamic::Var& value) const -{ - return value.type() == typeid(Object::Ptr); -} - - -bool Array::isObject(ConstIterator& it) const -{ - return it!= end() && isObject(*it); -} - - -void Array::stringify(std::ostream& out, unsigned int indent, int step) const -{ - int options = Poco::JSON_WRAP_STRINGS; - options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; - - if (step == -1) step = indent; - - out << "["; - - if (indent > 0) out << std::endl; - - for (ValueVec::const_iterator it = _values.begin(); it != _values.end();) - { - for (int i = 0; i < indent; i++) out << ' '; - - Stringifier::stringify(*it, out, indent + step, step, options); - - if (++it != _values.end()) - { - out << ","; - if (step > 0) out << '\n'; - } - } - - if (step > 0) out << '\n'; - - if (indent >= step) indent -= step; - - for (int i = 0; i < indent; i++) out << ' '; - - out << "]"; -} - - -void Array::resetDynArray() const -{ - if (!_pArray) - _pArray = new Poco::Dynamic::Array; - else - _pArray->clear(); -} - - -Array::operator const Poco::Dynamic::Array& () const -{ - if (!_values.size()) - { - resetDynArray(); - } - else if (_modified) - { - ValueVec::const_iterator it = _values.begin(); - ValueVec::const_iterator end = _values.end(); - resetDynArray(); - int index = 0; - for (; it != end; ++it, ++index) - { - if (isObject(it)) - { - _pArray->insert(_pArray->end(), Poco::JSON::Object::makeStruct(getObject(index))); - } - else if (isArray(it)) - { - _pArray->insert(_pArray->end(), makeArray(getArray(index))); - } - else - { - _pArray->insert(_pArray->end(), *it); - } - } - _modified = false; - } - - return *_pArray; -} - - -Poco::Dynamic::Array Array::makeArray(const JSON::Array::Ptr& arr) -{ - Poco::Dynamic::Array vec; - - JSON::Array::ConstIterator it = arr->begin(); - JSON::Array::ConstIterator end = arr->end(); - int index = 0; - for (; it != end; ++it, ++index) - { - if (arr->isObject(it)) - { - Object::Ptr pObj = arr->getObject(index); - DynamicStruct str = Poco::JSON::Object::makeStruct(pObj); - vec.insert(vec.end(), str); - } - else if (arr->isArray(it)) - { - Array::Ptr pArr = arr->getArray(index); - std::vector<Poco::Dynamic::Var> v = makeArray(pArr); - vec.insert(vec.end(), v); - } - else - vec.insert(vec.end(), *it); - } - - return vec; -} - - -void Array::clear() -{ - _values.clear(); - _pArray = 0; -} - - -} } // namespace Poco::JSON +// +// Array.cpp +// +// Library: JSON +// Package: JSON +// Module: Array +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Array.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/Stringifier.h" +#include "Poco/JSONString.h" + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +Array::Array(int options): _modified(false), + _escapeUnicode((options & Poco::JSON_ESCAPE_UNICODE) != 0) +{ +} + + +Array::Array(const Array& other) : _values(other._values), + _pArray(other._pArray), + _modified(other._modified) +{ +} + + +Array &Array::operator=(const Array& other) +{ + if (&other != this) + { + _values = other._values; + _pArray = other._pArray; + _modified = other._modified; + } + return *this; +} + +#ifdef POCO_ENABLE_CPP11 + + +Array::Array(Array&& other) : + _values(std::move(other._values)), + _pArray(!other._modified ? other._pArray : 0), + _modified(other._modified) +{ + _pArray = 0; +} + +Array &Array::operator= (Array&& other) +{ + if (&other != this) + { + _values = std::move(other._values); + _pArray = other._pArray; + other._pArray = 0; + _modified = other._modified; + } + return *this; +} + + +#endif // POCO_ENABLE_CPP11 + + +Array::~Array() +{ +} + + +Var Array::get(unsigned int index) const +{ + Var value; + try + { + value = _values.at(index); + } + catch (std::out_of_range&) + { + //Ignore, we return an empty value + } + return value; +} + + +Array::Ptr Array::getArray(unsigned int index) const +{ + Array::Ptr result; + + Var value = get(index); + if (value.type() == typeid(Array::Ptr)) + { + result = value.extract<Array::Ptr>(); + } + return result; +} + + +Object::Ptr Array::getObject(unsigned int index) const +{ + Object::Ptr result; + + Var value = get(index); + if (value.type() == typeid(Object::Ptr)) + { + result = value.extract<Object::Ptr>(); + } + return result; +} + + +bool Array::isNull(unsigned int index) const +{ + if (index < _values.size()) + { + Dynamic::Var value = _values[index]; + return value.isEmpty(); + } + return true; +} + + +bool Array::isObject(unsigned int index) const +{ + Var value = get(index); + return isObject(value); +} + + +bool Array::isObject(const Dynamic::Var& value) const +{ + return value.type() == typeid(Object::Ptr); +} + + +bool Array::isObject(ConstIterator& it) const +{ + return it!= end() && isObject(*it); +} + + +void Array::stringify(std::ostream& out, unsigned int indent, int step) const +{ + int options = Poco::JSON_WRAP_STRINGS; + options |= _escapeUnicode ? Poco::JSON_ESCAPE_UNICODE : 0; + + if (step == -1) step = indent; + + out << "["; + + if (indent > 0) out << std::endl; + + for (ValueVec::const_iterator it = _values.begin(); it != _values.end();) + { + for (int i = 0; i < indent; i++) out << ' '; + + Stringifier::stringify(*it, out, indent + step, step, options); + + if (++it != _values.end()) + { + out << ","; + if (step > 0) out << '\n'; + } + } + + if (step > 0) out << '\n'; + + if (indent >= step) indent -= step; + + for (int i = 0; i < indent; i++) out << ' '; + + out << "]"; +} + + +void Array::resetDynArray() const +{ + if (!_pArray) + _pArray = new Poco::Dynamic::Array; + else + _pArray->clear(); +} + + +Array::operator const Poco::Dynamic::Array& () const +{ + if (!_values.size()) + { + resetDynArray(); + } + else if (_modified) + { + ValueVec::const_iterator it = _values.begin(); + ValueVec::const_iterator end = _values.end(); + resetDynArray(); + int index = 0; + for (; it != end; ++it, ++index) + { + if (isObject(it)) + { + _pArray->insert(_pArray->end(), Poco::JSON::Object::makeStruct(getObject(index))); + } + else if (isArray(it)) + { + _pArray->insert(_pArray->end(), makeArray(getArray(index))); + } + else + { + _pArray->insert(_pArray->end(), *it); + } + } + _modified = false; + } + + return *_pArray; +} + + +Poco::Dynamic::Array Array::makeArray(const JSON::Array::Ptr& arr) +{ + Poco::Dynamic::Array vec; + + JSON::Array::ConstIterator it = arr->begin(); + JSON::Array::ConstIterator end = arr->end(); + int index = 0; + for (; it != end; ++it, ++index) + { + if (arr->isObject(it)) + { + Object::Ptr pObj = arr->getObject(index); + DynamicStruct str = Poco::JSON::Object::makeStruct(pObj); + vec.insert(vec.end(), str); + } + else if (arr->isArray(it)) + { + Array::Ptr pArr = arr->getArray(index); + std::vector<Poco::Dynamic::Var> v = makeArray(pArr); + vec.insert(vec.end(), v); + } + else + vec.insert(vec.end(), *it); + } + + return vec; +} + + +void Array::clear() +{ + _values.clear(); + _pArray = 0; +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Handler.cpp b/contrib/libs/poco/JSON/src/Handler.cpp index f39beb1e39..e207329ad3 100644 --- a/contrib/libs/poco/JSON/src/Handler.cpp +++ b/contrib/libs/poco/JSON/src/Handler.cpp @@ -1,45 +1,45 @@ -// -// Handler.cpp -// -// Library: JSON -// Package: JSON -// Module: Handler -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Handler.h" -#include "Poco/JSON/Object.h" - - -namespace Poco { -namespace JSON { - - -Handler::Handler() -{ -} - - -Handler::~Handler() -{ -} - - -Dynamic::Var Handler::asVar() const -{ - return Dynamic::Var(); -} - - -Poco::DynamicStruct Handler::asStruct() const -{ - return Poco::DynamicStruct(); -} - - -} } // namespace Poco::JSON +// +// Handler.cpp +// +// Library: JSON +// Package: JSON +// Module: Handler +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Handler.h" +#include "Poco/JSON/Object.h" + + +namespace Poco { +namespace JSON { + + +Handler::Handler() +{ +} + + +Handler::~Handler() +{ +} + + +Dynamic::Var Handler::asVar() const +{ + return Dynamic::Var(); +} + + +Poco::DynamicStruct Handler::asStruct() const +{ + return Poco::DynamicStruct(); +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/JSONException.cpp b/contrib/libs/poco/JSON/src/JSONException.cpp index a3ec4f7588..0ab2a13120 100644 --- a/contrib/libs/poco/JSON/src/JSONException.cpp +++ b/contrib/libs/poco/JSON/src/JSONException.cpp @@ -1,26 +1,26 @@ -// -// JSONException.cpp -// -// Library: JSON -// Package: JSON -// Module: JSONException -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/JSONException.h" -#include <typeinfo> - - -namespace Poco { -namespace JSON { - - -POCO_IMPLEMENT_EXCEPTION(JSONException, Exception, "JSON Exception") - - -} } // namespace Poco::JSON +// +// JSONException.cpp +// +// Library: JSON +// Package: JSON +// Module: JSONException +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/JSONException.h" +#include <typeinfo> + + +namespace Poco { +namespace JSON { + + +POCO_IMPLEMENT_EXCEPTION(JSONException, Exception, "JSON Exception") + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Object.cpp b/contrib/libs/poco/JSON/src/Object.cpp index 217a4638e4..7fca65c5b0 100644 --- a/contrib/libs/poco/JSON/src/Object.cpp +++ b/contrib/libs/poco/JSON/src/Object.cpp @@ -1,298 +1,298 @@ -// -// Object.cpp -// -// Library: JSON -// Package: JSON -// Module: Object -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Object.h" -#include <iostream> -#include <sstream> - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -Object::Object(int options): - _preserveInsOrder((options & Poco::JSON_PRESERVE_KEY_ORDER) != 0), - _escapeUnicode((options & Poco::JSON_ESCAPE_UNICODE) != 0), - _modified(false) -{ -} - - -Object::Object(const Object& other) : _values(other._values), - _preserveInsOrder(other._preserveInsOrder), - _escapeUnicode(other._escapeUnicode), - _pStruct(!other._modified ? other._pStruct : 0), - _modified(other._modified) -{ - syncKeys(other._keys); -} - - -#ifdef POCO_ENABLE_CPP11 - - -Object::Object(Object&& other) : - _values(std::move(other._values)), - _keys(std::move(other._keys)), - _preserveInsOrder(other._preserveInsOrder), - _escapeUnicode(other._escapeUnicode), - _pStruct(!other._modified ? other._pStruct : 0), - _modified(other._modified) -{ - other.clear(); -} - - -Object &Object::operator= (Object &&other) -{ - if (&other != this) - { - _values = other._values; - _preserveInsOrder = other._preserveInsOrder; - syncKeys(other._keys); - _escapeUnicode = other._escapeUnicode; - _pStruct = !other._modified ? other._pStruct : 0; - _modified = other._modified; - other.clear(); - } - return *this; -} - - -#endif // POCO_ENABLE_CPP11 - - -Object::~Object() -{ -} - - -Object &Object::operator= (const Object &other) -{ - if (&other != this) - { - _values = other._values; - _keys = other._keys; - _preserveInsOrder = other._preserveInsOrder; - _escapeUnicode = other._escapeUnicode; - _pStruct = !other._modified ? other._pStruct : 0; - _modified = other._modified; - } - return *this; -} - - -void Object::syncKeys(const KeyList& keys) -{ - if(_preserveInsOrder) - { - // update iterators in _keys to point to copied _values - for(KeyList::const_iterator it = keys.begin(); it != keys.end(); ++it) - { - ValueMap::const_iterator itv = _values.find((*it)->first); - poco_assert (itv != _values.end()); - _keys.push_back(itv); - } - } -} - - -Var Object::get(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - if (it != _values.end()) - { - return it->second; - } - - return Var(); -} - - -Array::Ptr Object::getArray(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - if ((it != _values.end()) && (it->second.type() == typeid(Array::Ptr))) - { - return it->second.extract<Array::Ptr>(); - } - - return 0; -} - - -Object::Ptr Object::getObject(const std::string& key) const -{ - ValueMap::const_iterator it = _values.find(key); - if ((it != _values.end()) && (it->second.type() == typeid(Object::Ptr))) - { - return it->second.extract<Object::Ptr>(); - } - - return 0; -} - - -void Object::getNames(NameList& names) const -{ - names.clear(); - if (_preserveInsOrder) - { - for(KeyList::const_iterator it = _keys.begin(); it != _keys.end(); ++it) - { - names.push_back((*it)->first); - } - } - else - { - for(ValueMap::const_iterator it = _values.begin(); it != _values.end(); ++it) - { - names.push_back(it->first); - } - } -} - - -Object::NameList Object::getNames() const -{ - NameList names; - getNames(names); - return names; -} - - -void Object::stringify(std::ostream& out, unsigned int indent, int step) const -{ - if (step < 0) step = indent; - - if (!_preserveInsOrder) - doStringify(_values, out, indent, step); - else - doStringify(_keys, out, indent, step); -} - - -const std::string& Object::getKey(KeyList::const_iterator& iter) const -{ - ValueMap::const_iterator it = _values.begin(); - ValueMap::const_iterator end = _values.end(); - for (; it != end; ++it) - { - if (it == *iter) return it->first; - } - - throw NotFoundException((*iter)->first); -} - - -void Object::set(const std::string& key, const Dynamic::Var& value) -{ - std::pair<ValueMap::iterator, bool> ret = _values.insert(ValueMap::value_type(key, value)); - if (!ret.second) ret.first->second = value; - if (_preserveInsOrder) - { - KeyList::iterator it = _keys.begin(); - KeyList::iterator end = _keys.end(); - for (; it != end; ++it) - { - if (key == (*it)->first) return; - } - _keys.push_back(ret.first); - } - _modified = true; -} - - -Poco::DynamicStruct Object::makeStruct(const Object::Ptr& obj) -{ - Poco::DynamicStruct ds; - - ConstIterator it = obj->begin(); - ConstIterator end = obj->end(); - for (; it != end; ++it) - { - if (obj->isObject(it)) - { - Object::Ptr pObj = obj->getObject(it->first); - DynamicStruct str = makeStruct(pObj); - ds.insert(it->first, str); - } - else if (obj->isArray(it)) - { - Array::Ptr pArr = obj->getArray(it->first); - std::vector<Poco::Dynamic::Var> v = Poco::JSON::Array::makeArray(pArr); - ds.insert(it->first, v); - } - else - ds.insert(it->first, it->second); - } - - return ds; -} - - -void Object::resetDynStruct() const -{ - if (!_pStruct) - _pStruct = new Poco::DynamicStruct; - else - _pStruct->clear(); -} - - -Object::operator const Poco::DynamicStruct& () const -{ - if (!_values.size()) - { - resetDynStruct(); - } - else if (_modified) - { - ValueMap::const_iterator it = _values.begin(); - ValueMap::const_iterator end = _values.end(); - resetDynStruct(); - for (; it != end; ++it) - { - if (isObject(it)) - { - _pStruct->insert(it->first, makeStruct(getObject(it->first))); - } - else if (isArray(it)) - { - _pStruct->insert(it->first, Poco::JSON::Array::makeArray(getArray(it->first))); - } - else - { - _pStruct->insert(it->first, it->second); - } - } - } - - return *_pStruct; -} - - -void Object::clear() -{ - _values.clear(); - _keys.clear(); - _pStruct = 0; - _modified = true; -} - - -} } // namespace Poco::JSON +// +// Object.cpp +// +// Library: JSON +// Package: JSON +// Module: Object +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Object.h" +#include <iostream> +#include <sstream> + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +Object::Object(int options): + _preserveInsOrder((options & Poco::JSON_PRESERVE_KEY_ORDER) != 0), + _escapeUnicode((options & Poco::JSON_ESCAPE_UNICODE) != 0), + _modified(false) +{ +} + + +Object::Object(const Object& other) : _values(other._values), + _preserveInsOrder(other._preserveInsOrder), + _escapeUnicode(other._escapeUnicode), + _pStruct(!other._modified ? other._pStruct : 0), + _modified(other._modified) +{ + syncKeys(other._keys); +} + + +#ifdef POCO_ENABLE_CPP11 + + +Object::Object(Object&& other) : + _values(std::move(other._values)), + _keys(std::move(other._keys)), + _preserveInsOrder(other._preserveInsOrder), + _escapeUnicode(other._escapeUnicode), + _pStruct(!other._modified ? other._pStruct : 0), + _modified(other._modified) +{ + other.clear(); +} + + +Object &Object::operator= (Object &&other) +{ + if (&other != this) + { + _values = other._values; + _preserveInsOrder = other._preserveInsOrder; + syncKeys(other._keys); + _escapeUnicode = other._escapeUnicode; + _pStruct = !other._modified ? other._pStruct : 0; + _modified = other._modified; + other.clear(); + } + return *this; +} + + +#endif // POCO_ENABLE_CPP11 + + +Object::~Object() +{ +} + + +Object &Object::operator= (const Object &other) +{ + if (&other != this) + { + _values = other._values; + _keys = other._keys; + _preserveInsOrder = other._preserveInsOrder; + _escapeUnicode = other._escapeUnicode; + _pStruct = !other._modified ? other._pStruct : 0; + _modified = other._modified; + } + return *this; +} + + +void Object::syncKeys(const KeyList& keys) +{ + if(_preserveInsOrder) + { + // update iterators in _keys to point to copied _values + for(KeyList::const_iterator it = keys.begin(); it != keys.end(); ++it) + { + ValueMap::const_iterator itv = _values.find((*it)->first); + poco_assert (itv != _values.end()); + _keys.push_back(itv); + } + } +} + + +Var Object::get(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + if (it != _values.end()) + { + return it->second; + } + + return Var(); +} + + +Array::Ptr Object::getArray(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + if ((it != _values.end()) && (it->second.type() == typeid(Array::Ptr))) + { + return it->second.extract<Array::Ptr>(); + } + + return 0; +} + + +Object::Ptr Object::getObject(const std::string& key) const +{ + ValueMap::const_iterator it = _values.find(key); + if ((it != _values.end()) && (it->second.type() == typeid(Object::Ptr))) + { + return it->second.extract<Object::Ptr>(); + } + + return 0; +} + + +void Object::getNames(NameList& names) const +{ + names.clear(); + if (_preserveInsOrder) + { + for(KeyList::const_iterator it = _keys.begin(); it != _keys.end(); ++it) + { + names.push_back((*it)->first); + } + } + else + { + for(ValueMap::const_iterator it = _values.begin(); it != _values.end(); ++it) + { + names.push_back(it->first); + } + } +} + + +Object::NameList Object::getNames() const +{ + NameList names; + getNames(names); + return names; +} + + +void Object::stringify(std::ostream& out, unsigned int indent, int step) const +{ + if (step < 0) step = indent; + + if (!_preserveInsOrder) + doStringify(_values, out, indent, step); + else + doStringify(_keys, out, indent, step); +} + + +const std::string& Object::getKey(KeyList::const_iterator& iter) const +{ + ValueMap::const_iterator it = _values.begin(); + ValueMap::const_iterator end = _values.end(); + for (; it != end; ++it) + { + if (it == *iter) return it->first; + } + + throw NotFoundException((*iter)->first); +} + + +void Object::set(const std::string& key, const Dynamic::Var& value) +{ + std::pair<ValueMap::iterator, bool> ret = _values.insert(ValueMap::value_type(key, value)); + if (!ret.second) ret.first->second = value; + if (_preserveInsOrder) + { + KeyList::iterator it = _keys.begin(); + KeyList::iterator end = _keys.end(); + for (; it != end; ++it) + { + if (key == (*it)->first) return; + } + _keys.push_back(ret.first); + } + _modified = true; +} + + +Poco::DynamicStruct Object::makeStruct(const Object::Ptr& obj) +{ + Poco::DynamicStruct ds; + + ConstIterator it = obj->begin(); + ConstIterator end = obj->end(); + for (; it != end; ++it) + { + if (obj->isObject(it)) + { + Object::Ptr pObj = obj->getObject(it->first); + DynamicStruct str = makeStruct(pObj); + ds.insert(it->first, str); + } + else if (obj->isArray(it)) + { + Array::Ptr pArr = obj->getArray(it->first); + std::vector<Poco::Dynamic::Var> v = Poco::JSON::Array::makeArray(pArr); + ds.insert(it->first, v); + } + else + ds.insert(it->first, it->second); + } + + return ds; +} + + +void Object::resetDynStruct() const +{ + if (!_pStruct) + _pStruct = new Poco::DynamicStruct; + else + _pStruct->clear(); +} + + +Object::operator const Poco::DynamicStruct& () const +{ + if (!_values.size()) + { + resetDynStruct(); + } + else if (_modified) + { + ValueMap::const_iterator it = _values.begin(); + ValueMap::const_iterator end = _values.end(); + resetDynStruct(); + for (; it != end; ++it) + { + if (isObject(it)) + { + _pStruct->insert(it->first, makeStruct(getObject(it->first))); + } + else if (isArray(it)) + { + _pStruct->insert(it->first, Poco::JSON::Array::makeArray(getArray(it->first))); + } + else + { + _pStruct->insert(it->first, it->second); + } + } + } + + return *_pStruct; +} + + +void Object::clear() +{ + _values.clear(); + _keys.clear(); + _pStruct = 0; + _modified = true; +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/ParseHandler.cpp b/contrib/libs/poco/JSON/src/ParseHandler.cpp index 610a203e5d..1b271ff4fa 100644 --- a/contrib/libs/poco/JSON/src/ParseHandler.cpp +++ b/contrib/libs/poco/JSON/src/ParseHandler.cpp @@ -1,148 +1,148 @@ -// -// ParseHandler.cpp -// -// Library: JSON -// Package: JSON -// Module: ParseHandler -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/ParseHandler.h" -#include "Poco/JSON/Object.h" -#include "Poco/JSON/JSONException.h" - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -ParseHandler::ParseHandler(bool preserveObjectOrder) : Handler(), - _preserveObjectOrder(preserveObjectOrder) -{ -} - - -ParseHandler::~ParseHandler() -{ -} - - -void ParseHandler::reset() -{ - while (!_stack.empty()) _stack.pop(); - _key = ""; - _result.empty(); -} - - -void ParseHandler::startObject() -{ - Object::Ptr newObj = new Object(_preserveObjectOrder); - if (_stack.empty()) // The first object - { - _result = newObj; - } - else - { - Var parent = _stack.top(); - - if (parent.type() == typeid(Array::Ptr)) - { - Array::Ptr arr = parent.extract<Array::Ptr>(); - arr->add(newObj); - } - else if (parent.type() == typeid(Object::Ptr)) - { - poco_assert_dbg(!_key.empty()); - Object::Ptr obj = parent.extract<Object::Ptr>(); - obj->set(_key, newObj); - _key.clear(); - } - } - - _stack.push(newObj); -} - - -void ParseHandler::endObject() -{ - if (!_stack.empty()) _stack.pop(); -} - - -void ParseHandler::startArray() -{ - Array::Ptr newArr = new Array(); - - if (_stack.empty()) // The first array - { - _result = newArr; - } - else - { - Var parent = _stack.top(); - - if (parent.type() == typeid(Array::Ptr)) - { - Array::Ptr arr = parent.extract<Array::Ptr>(); - arr->add(newArr); - } - else if (parent.type() == typeid(Object::Ptr)) - { - poco_assert_dbg(!_key.empty()); - Object::Ptr obj = parent.extract<Object::Ptr>(); - obj->set(_key, newArr); - _key.clear(); - } - } - - _stack.push(newArr); -} - - -void ParseHandler::endArray() -{ - if (!_stack.empty()) _stack.pop(); -} - - -void ParseHandler::key(const std::string& k) -{ - _key = k; -} - - -void ParseHandler::setValue(const Var& value) -{ - if (_stack.size()) - { - Var parent = _stack.top(); - - if (parent.type() == typeid(Array::Ptr)) - { - Array::Ptr arr = parent.extract<Array::Ptr>(); - arr->add(value); - } - else if (parent.type() == typeid(Object::Ptr)) - { - Object::Ptr obj = parent.extract<Object::Ptr>(); - obj->set(_key, value); - _key.clear(); - } - } - else - { - throw JSONException("Attempt to set value on an empty stack"); - } -} - - -} } // namespace Poco::JSON +// +// ParseHandler.cpp +// +// Library: JSON +// Package: JSON +// Module: ParseHandler +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/ParseHandler.h" +#include "Poco/JSON/Object.h" +#include "Poco/JSON/JSONException.h" + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +ParseHandler::ParseHandler(bool preserveObjectOrder) : Handler(), + _preserveObjectOrder(preserveObjectOrder) +{ +} + + +ParseHandler::~ParseHandler() +{ +} + + +void ParseHandler::reset() +{ + while (!_stack.empty()) _stack.pop(); + _key = ""; + _result.empty(); +} + + +void ParseHandler::startObject() +{ + Object::Ptr newObj = new Object(_preserveObjectOrder); + if (_stack.empty()) // The first object + { + _result = newObj; + } + else + { + Var parent = _stack.top(); + + if (parent.type() == typeid(Array::Ptr)) + { + Array::Ptr arr = parent.extract<Array::Ptr>(); + arr->add(newObj); + } + else if (parent.type() == typeid(Object::Ptr)) + { + poco_assert_dbg(!_key.empty()); + Object::Ptr obj = parent.extract<Object::Ptr>(); + obj->set(_key, newObj); + _key.clear(); + } + } + + _stack.push(newObj); +} + + +void ParseHandler::endObject() +{ + if (!_stack.empty()) _stack.pop(); +} + + +void ParseHandler::startArray() +{ + Array::Ptr newArr = new Array(); + + if (_stack.empty()) // The first array + { + _result = newArr; + } + else + { + Var parent = _stack.top(); + + if (parent.type() == typeid(Array::Ptr)) + { + Array::Ptr arr = parent.extract<Array::Ptr>(); + arr->add(newArr); + } + else if (parent.type() == typeid(Object::Ptr)) + { + poco_assert_dbg(!_key.empty()); + Object::Ptr obj = parent.extract<Object::Ptr>(); + obj->set(_key, newArr); + _key.clear(); + } + } + + _stack.push(newArr); +} + + +void ParseHandler::endArray() +{ + if (!_stack.empty()) _stack.pop(); +} + + +void ParseHandler::key(const std::string& k) +{ + _key = k; +} + + +void ParseHandler::setValue(const Var& value) +{ + if (_stack.size()) + { + Var parent = _stack.top(); + + if (parent.type() == typeid(Array::Ptr)) + { + Array::Ptr arr = parent.extract<Array::Ptr>(); + arr->add(value); + } + else if (parent.type() == typeid(Object::Ptr)) + { + Object::Ptr obj = parent.extract<Object::Ptr>(); + obj->set(_key, value); + _key.clear(); + } + } + else + { + throw JSONException("Attempt to set value on an empty stack"); + } +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Parser.cpp b/contrib/libs/poco/JSON/src/Parser.cpp index c9c64297f7..368a3a5d69 100644 --- a/contrib/libs/poco/JSON/src/Parser.cpp +++ b/contrib/libs/poco/JSON/src/Parser.cpp @@ -1,49 +1,49 @@ -// -// Parser.cpp -// -// Library: JSON -// Package: JSON -// Module: Parser -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Parser.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/Ascii.h" -#include "Poco/Token.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/String.h" -#undef min -#undef max -#include <limits> -#include <clocale> -#include <istream> - - -namespace Poco { -namespace JSON { - - -Parser::Parser(const Handler::Ptr& pHandler, std::size_t bufSize): - ParserImpl(pHandler, bufSize) -{ -} - - -Parser::~Parser() -{ -} - - -void Parser::setHandler(const Handler::Ptr& pHandler) -{ - setHandlerImpl(pHandler); -} - - -} } // namespace Poco::JSON +// +// Parser.cpp +// +// Library: JSON +// Package: JSON +// Module: Parser +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Parser.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/Ascii.h" +#include "Poco/Token.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/String.h" +#undef min +#undef max +#include <limits> +#include <clocale> +#include <istream> + + +namespace Poco { +namespace JSON { + + +Parser::Parser(const Handler::Ptr& pHandler, std::size_t bufSize): + ParserImpl(pHandler, bufSize) +{ +} + + +Parser::~Parser() +{ +} + + +void Parser::setHandler(const Handler::Ptr& pHandler) +{ + setHandlerImpl(pHandler); +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/ParserImpl.cpp b/contrib/libs/poco/JSON/src/ParserImpl.cpp index 8cd24f9995..ce455ea031 100644 --- a/contrib/libs/poco/JSON/src/ParserImpl.cpp +++ b/contrib/libs/poco/JSON/src/ParserImpl.cpp @@ -1,241 +1,241 @@ -// -// Parser.cpp -// -// Library: JSON -// Package: JSON -// Module: Parser -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Parser.h" -#include "Poco/JSON/JSONException.h" -#include "Poco/Ascii.h" -#include "Poco/Token.h" -#include "Poco/UTF8Encoding.h" -#include "Poco/String.h" -#include "Poco/StreamCopier.h" -#undef min -#undef max -#include <limits> -#include <clocale> -#include <istream> -#include "pdjson.h" - - -typedef struct json_stream json_stream; - - -namespace Poco { -namespace JSON { - - -ParserImpl::ParserImpl(const Handler::Ptr& pHandler, std::size_t /*bufSize*/): - _pJSON(new json_stream), - _pHandler(pHandler), - _depth(JSON_UNLIMITED_DEPTH), - _decimalPoint('.'), - _allowNullByte(true), - _allowComments(false) -{ -} - - -ParserImpl::~ParserImpl() -{ - delete _pJSON; -} - - -void ParserImpl::handle(const std::string& json) -{ - if (!_allowNullByte && json.find("\\u0000") != json.npos) - throw JSONException("Null bytes in strings not allowed."); - - try - { - json_open_buffer(_pJSON, json.data(), json.size()); - checkError(); - ////////////////////////////////// - // Underlying parser is capable of parsing multiple consecutive JSONs; - // we do not currently support this feature; to force error on - // excessive characters past valid JSON end, this MUST be called - // AFTER opening the buffer - otherwise it is overwritten by - // json_open*() call, which calls internal init() - json_set_streaming(_pJSON, false); - ///////////////////////////////// - handle(); checkError(); - if (JSON_DONE != json_next(_pJSON)) - throw JSONException("Excess characters found after JSON end."); - json_close(_pJSON); - } - catch (std::exception&) - { - json_close(_pJSON); - throw; - } -} - - -Dynamic::Var ParserImpl::parseImpl(const std::string& json) -{ - if (_allowComments) - { - std::string str = json; - stripComments(str); - handle(str); - } - else handle(json); - - return asVarImpl(); -} - - -Dynamic::Var ParserImpl::parseImpl(std::istream& in) -{ - std::ostringstream os; - StreamCopier::copyStream(in, os); - return parseImpl(os.str()); -} - - -void ParserImpl::stripComments(std::string& json) -{ - if (_allowComments) - { - bool inString = false; - bool inComment = false; - char prevChar = 0; - std::string::iterator it = json.begin(); - for (; it != json.end();) - { - if (*it == '"' && !inString) inString = true; - else inString = false; - if (!inString) - { - if (*it == '/' && it + 1 != json.end() && *(it + 1) == '*') - inComment = true; - } - if (inComment) - { - char c = *it; - it = json.erase(it); - if (prevChar == '*' && c == '/') - { - inComment = false; - prevChar = 0; - } - else prevChar = c; - } - else ++it; - } - } -} - - -void ParserImpl::handleArray() -{ - json_type tok = json_peek(_pJSON); - while (tok != JSON_ARRAY_END && checkError()) - { - handle(); - tok = json_peek(_pJSON); - } - - if (tok == JSON_ARRAY_END) handle(); - else throw JSONException("JSON array end not found"); -} - - -void ParserImpl::handleObject() -{ - json_type tok = json_peek(_pJSON); - while (tok != JSON_OBJECT_END && checkError()) - { - json_next(_pJSON); - if (_pHandler) _pHandler->key(std::string(json_get_string(_pJSON, NULL))); - handle(); - tok = json_peek(_pJSON); - } - - if (tok == JSON_OBJECT_END) handle(); - else throw JSONException("JSON object end not found"); -} - - -void ParserImpl::handle() -{ - enum json_type type = json_next(_pJSON); - switch (type) - { - case JSON_DONE: - return; - case JSON_NULL: - _pHandler->null(); - break; - case JSON_TRUE: - if (_pHandler) _pHandler->value(true); - break; - case JSON_FALSE: - if (_pHandler) _pHandler->value(false); - break; - case JSON_NUMBER: - { - if (_pHandler) - { - std::string str(json_get_string(_pJSON, NULL)); - if (str.find(_decimalPoint) != str.npos || str.find('e') != str.npos || str.find('E') != str.npos) - { - _pHandler->value(NumberParser::parseFloat(str)); - } - else - { - Poco::Int64 val; - if (NumberParser::tryParse64(str, val)) - _pHandler->value(val); - else - _pHandler->value(NumberParser::parseUnsigned64(str)); - } - } - break; - } - case JSON_STRING: - if (_pHandler) _pHandler->value(std::string(json_get_string(_pJSON, NULL))); - break; - case JSON_OBJECT: - if (_pHandler) _pHandler->startObject(); - handleObject(); - break; - case JSON_OBJECT_END: - if (_pHandler) _pHandler->endObject(); - return; - case JSON_ARRAY: - if (_pHandler) _pHandler->startArray(); - handleArray(); - break; - case JSON_ARRAY_END: - if (_pHandler) _pHandler->endArray(); - return; - case JSON_ERROR: - { - const char* pErr = json_get_error(_pJSON); - std::string err(pErr ? pErr : "JSON parser error."); - throw JSONException(err); - } - } -} - - -bool ParserImpl::checkError() -{ - const char* err = json_get_error(_pJSON); - if (err) throw Poco::JSON::JSONException(err); - return true; -} - - -} } // namespace Poco::JSON +// +// Parser.cpp +// +// Library: JSON +// Package: JSON +// Module: Parser +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Parser.h" +#include "Poco/JSON/JSONException.h" +#include "Poco/Ascii.h" +#include "Poco/Token.h" +#include "Poco/UTF8Encoding.h" +#include "Poco/String.h" +#include "Poco/StreamCopier.h" +#undef min +#undef max +#include <limits> +#include <clocale> +#include <istream> +#include "pdjson.h" + + +typedef struct json_stream json_stream; + + +namespace Poco { +namespace JSON { + + +ParserImpl::ParserImpl(const Handler::Ptr& pHandler, std::size_t /*bufSize*/): + _pJSON(new json_stream), + _pHandler(pHandler), + _depth(JSON_UNLIMITED_DEPTH), + _decimalPoint('.'), + _allowNullByte(true), + _allowComments(false) +{ +} + + +ParserImpl::~ParserImpl() +{ + delete _pJSON; +} + + +void ParserImpl::handle(const std::string& json) +{ + if (!_allowNullByte && json.find("\\u0000") != json.npos) + throw JSONException("Null bytes in strings not allowed."); + + try + { + json_open_buffer(_pJSON, json.data(), json.size()); + checkError(); + ////////////////////////////////// + // Underlying parser is capable of parsing multiple consecutive JSONs; + // we do not currently support this feature; to force error on + // excessive characters past valid JSON end, this MUST be called + // AFTER opening the buffer - otherwise it is overwritten by + // json_open*() call, which calls internal init() + json_set_streaming(_pJSON, false); + ///////////////////////////////// + handle(); checkError(); + if (JSON_DONE != json_next(_pJSON)) + throw JSONException("Excess characters found after JSON end."); + json_close(_pJSON); + } + catch (std::exception&) + { + json_close(_pJSON); + throw; + } +} + + +Dynamic::Var ParserImpl::parseImpl(const std::string& json) +{ + if (_allowComments) + { + std::string str = json; + stripComments(str); + handle(str); + } + else handle(json); + + return asVarImpl(); +} + + +Dynamic::Var ParserImpl::parseImpl(std::istream& in) +{ + std::ostringstream os; + StreamCopier::copyStream(in, os); + return parseImpl(os.str()); +} + + +void ParserImpl::stripComments(std::string& json) +{ + if (_allowComments) + { + bool inString = false; + bool inComment = false; + char prevChar = 0; + std::string::iterator it = json.begin(); + for (; it != json.end();) + { + if (*it == '"' && !inString) inString = true; + else inString = false; + if (!inString) + { + if (*it == '/' && it + 1 != json.end() && *(it + 1) == '*') + inComment = true; + } + if (inComment) + { + char c = *it; + it = json.erase(it); + if (prevChar == '*' && c == '/') + { + inComment = false; + prevChar = 0; + } + else prevChar = c; + } + else ++it; + } + } +} + + +void ParserImpl::handleArray() +{ + json_type tok = json_peek(_pJSON); + while (tok != JSON_ARRAY_END && checkError()) + { + handle(); + tok = json_peek(_pJSON); + } + + if (tok == JSON_ARRAY_END) handle(); + else throw JSONException("JSON array end not found"); +} + + +void ParserImpl::handleObject() +{ + json_type tok = json_peek(_pJSON); + while (tok != JSON_OBJECT_END && checkError()) + { + json_next(_pJSON); + if (_pHandler) _pHandler->key(std::string(json_get_string(_pJSON, NULL))); + handle(); + tok = json_peek(_pJSON); + } + + if (tok == JSON_OBJECT_END) handle(); + else throw JSONException("JSON object end not found"); +} + + +void ParserImpl::handle() +{ + enum json_type type = json_next(_pJSON); + switch (type) + { + case JSON_DONE: + return; + case JSON_NULL: + _pHandler->null(); + break; + case JSON_TRUE: + if (_pHandler) _pHandler->value(true); + break; + case JSON_FALSE: + if (_pHandler) _pHandler->value(false); + break; + case JSON_NUMBER: + { + if (_pHandler) + { + std::string str(json_get_string(_pJSON, NULL)); + if (str.find(_decimalPoint) != str.npos || str.find('e') != str.npos || str.find('E') != str.npos) + { + _pHandler->value(NumberParser::parseFloat(str)); + } + else + { + Poco::Int64 val; + if (NumberParser::tryParse64(str, val)) + _pHandler->value(val); + else + _pHandler->value(NumberParser::parseUnsigned64(str)); + } + } + break; + } + case JSON_STRING: + if (_pHandler) _pHandler->value(std::string(json_get_string(_pJSON, NULL))); + break; + case JSON_OBJECT: + if (_pHandler) _pHandler->startObject(); + handleObject(); + break; + case JSON_OBJECT_END: + if (_pHandler) _pHandler->endObject(); + return; + case JSON_ARRAY: + if (_pHandler) _pHandler->startArray(); + handleArray(); + break; + case JSON_ARRAY_END: + if (_pHandler) _pHandler->endArray(); + return; + case JSON_ERROR: + { + const char* pErr = json_get_error(_pJSON); + std::string err(pErr ? pErr : "JSON parser error."); + throw JSONException(err); + } + } +} + + +bool ParserImpl::checkError() +{ + const char* err = json_get_error(_pJSON); + if (err) throw Poco::JSON::JSONException(err); + return true; +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/PrintHandler.cpp b/contrib/libs/poco/JSON/src/PrintHandler.cpp index b28da5de8d..bf735d0869 100644 --- a/contrib/libs/poco/JSON/src/PrintHandler.cpp +++ b/contrib/libs/poco/JSON/src/PrintHandler.cpp @@ -1,215 +1,215 @@ -// -// PrintHandler.cpp -// -// Library: JSON -// Package: JSON -// Module: PrintHandler -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/PrintHandler.h" -#include "Poco/JSON/Stringifier.h" -#include <iostream> - - -namespace Poco { -namespace JSON { - - -PrintHandler::PrintHandler(unsigned indent, int options): - _out(std::cout), - _indent(indent), - _array(0), - _objStart(true), - _options(options) -{ -} - - -PrintHandler::PrintHandler(std::ostream& out, unsigned indent, int options): - _out(out), - _indent(indent), - _array(0), - _objStart(true), - _options(options) -{ -} - - -PrintHandler::~PrintHandler() -{ -} - - -void PrintHandler::reset() -{ - _out.flush(); - _tab = ""; - _array = 0; - _objStart = true; -} - - -const char* PrintHandler::endLine() const -{ - if (!printFlat()) return "\n"; - else return ""; -} - - -bool PrintHandler::printFlat() const -{ - return _indent == JSON_PRINT_FLAT; -} - - -unsigned PrintHandler::indent() -{ - if (!printFlat()) return _indent; - - return 0; -} - - -void PrintHandler::startObject() -{ - arrayValue(); - _out << '{'; - _out << endLine(); - _tab.append(indent(), ' '); - _objStart = true; -} - - -void PrintHandler::endObject() -{ - if (_tab.length() >= indent()) - _tab.erase(_tab.length() - indent()); - - _out << endLine() << _tab << '}'; - _objStart = false; -} - - -void PrintHandler::startArray() -{ - arrayValue(); - _out << '[' << endLine(); - _tab.append(indent(), ' '); - ++_array; - _objStart = true; -} - - -void PrintHandler::endArray() -{ - _tab.erase(_tab.length() - indent()); - _out << endLine() << _tab << ']'; - --_array; - poco_assert (_array >= 0); - _objStart = false; -} - - -void PrintHandler::key(const std::string& k) -{ - if (!_objStart) comma(); - - _objStart = true; - - _out << _tab; - Stringifier::formatString(k, _out, _options); - if (!printFlat()) _out << ' '; - _out << ':'; - if (!printFlat()) _out << ' '; -} - - -void PrintHandler::null() -{ - arrayValue(); - _out << "null"; - _objStart = false; -} - - -void PrintHandler::value(int v) -{ - arrayValue(); - _out << v; - _objStart = false; -} - - -void PrintHandler::value(unsigned v) -{ - arrayValue(); - _out << v; - _objStart = false; -} - - -#if defined(POCO_HAVE_INT64) -void PrintHandler::value(Int64 v) -{ - arrayValue(); - _out << v; - _objStart = false; -} - - -void PrintHandler::value(UInt64 v) -{ - arrayValue(); - _out << v; - _objStart = false; -} -#endif - - -void PrintHandler::value(const std::string& value) -{ - arrayValue(); - Stringifier::formatString(value, _out, _options); - _objStart = false; -} - - -void PrintHandler::value(double d) -{ - arrayValue(); - _out << d; - _objStart = false; -} - - -void PrintHandler::value(bool b) -{ - arrayValue(); - _out << b; - _objStart = false; -} - - -void PrintHandler::comma() -{ - _out << ',' << endLine(); -} - - -void PrintHandler::arrayValue() -{ - if (!_objStart) comma(); - if (array()) - { - _out << _tab; - } -} - - -} } // namespace Poco::JSON +// +// PrintHandler.cpp +// +// Library: JSON +// Package: JSON +// Module: PrintHandler +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/PrintHandler.h" +#include "Poco/JSON/Stringifier.h" +#include <iostream> + + +namespace Poco { +namespace JSON { + + +PrintHandler::PrintHandler(unsigned indent, int options): + _out(std::cout), + _indent(indent), + _array(0), + _objStart(true), + _options(options) +{ +} + + +PrintHandler::PrintHandler(std::ostream& out, unsigned indent, int options): + _out(out), + _indent(indent), + _array(0), + _objStart(true), + _options(options) +{ +} + + +PrintHandler::~PrintHandler() +{ +} + + +void PrintHandler::reset() +{ + _out.flush(); + _tab = ""; + _array = 0; + _objStart = true; +} + + +const char* PrintHandler::endLine() const +{ + if (!printFlat()) return "\n"; + else return ""; +} + + +bool PrintHandler::printFlat() const +{ + return _indent == JSON_PRINT_FLAT; +} + + +unsigned PrintHandler::indent() +{ + if (!printFlat()) return _indent; + + return 0; +} + + +void PrintHandler::startObject() +{ + arrayValue(); + _out << '{'; + _out << endLine(); + _tab.append(indent(), ' '); + _objStart = true; +} + + +void PrintHandler::endObject() +{ + if (_tab.length() >= indent()) + _tab.erase(_tab.length() - indent()); + + _out << endLine() << _tab << '}'; + _objStart = false; +} + + +void PrintHandler::startArray() +{ + arrayValue(); + _out << '[' << endLine(); + _tab.append(indent(), ' '); + ++_array; + _objStart = true; +} + + +void PrintHandler::endArray() +{ + _tab.erase(_tab.length() - indent()); + _out << endLine() << _tab << ']'; + --_array; + poco_assert (_array >= 0); + _objStart = false; +} + + +void PrintHandler::key(const std::string& k) +{ + if (!_objStart) comma(); + + _objStart = true; + + _out << _tab; + Stringifier::formatString(k, _out, _options); + if (!printFlat()) _out << ' '; + _out << ':'; + if (!printFlat()) _out << ' '; +} + + +void PrintHandler::null() +{ + arrayValue(); + _out << "null"; + _objStart = false; +} + + +void PrintHandler::value(int v) +{ + arrayValue(); + _out << v; + _objStart = false; +} + + +void PrintHandler::value(unsigned v) +{ + arrayValue(); + _out << v; + _objStart = false; +} + + +#if defined(POCO_HAVE_INT64) +void PrintHandler::value(Int64 v) +{ + arrayValue(); + _out << v; + _objStart = false; +} + + +void PrintHandler::value(UInt64 v) +{ + arrayValue(); + _out << v; + _objStart = false; +} +#endif + + +void PrintHandler::value(const std::string& value) +{ + arrayValue(); + Stringifier::formatString(value, _out, _options); + _objStart = false; +} + + +void PrintHandler::value(double d) +{ + arrayValue(); + _out << d; + _objStart = false; +} + + +void PrintHandler::value(bool b) +{ + arrayValue(); + _out << b; + _objStart = false; +} + + +void PrintHandler::comma() +{ + _out << ',' << endLine(); +} + + +void PrintHandler::arrayValue() +{ + if (!_objStart) comma(); + if (array()) + { + _out << _tab; + } +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Query.cpp b/contrib/libs/poco/JSON/src/Query.cpp index 25f2766384..45047a6a05 100644 --- a/contrib/libs/poco/JSON/src/Query.cpp +++ b/contrib/libs/poco/JSON/src/Query.cpp @@ -1,172 +1,172 @@ -// -// Query.cpp -// -// Library: JSON -// Package: JSON -// Module: Query -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Query.h" -#include "Poco/StringTokenizer.h" -#include "Poco/RegularExpression.h" -#include "Poco/NumberParser.h" -#include <sstream> - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -Query::Query(const Var& source): _source(source) -{ - if (!source.isEmpty() && - source.type() != typeid(Object) && - source.type() != typeid(Object::Ptr) && - source.type() != typeid(Array) && - source.type() != typeid(Array::Ptr)) - throw InvalidArgumentException("Only JSON Object, Array or pointers thereof allowed."); -} - - -Query::~Query() -{ -} - - -Object::Ptr Query::findObject(const std::string& path) const -{ - Var result = find(path); - - if (result.type() == typeid(Object::Ptr)) - return result.extract<Object::Ptr>(); - else if (result.type() == typeid(Object)) - return new Object(result.extract<Object>()); - - return 0; -} - - -Object& Query::findObject(const std::string& path, Object& obj) const -{ - obj.clear(); - - Var result = find(path); - - if (result.type() == typeid(Object::Ptr)) - obj = *result.extract<Object::Ptr>(); - else if (result.type() == typeid(Object)) - obj = result.extract<Object>(); - - return obj; -} - - -Array::Ptr Query::findArray(const std::string& path) const -{ - Var result = find(path); - - if (result.type() == typeid(Array::Ptr)) - return result.extract<Array::Ptr>(); - else if (result.type() == typeid(Array)) - return new Array(result.extract<Array>()); - - return 0; -} - - -Array& Query::findArray(const std::string& path, Array& arr) const -{ - arr.clear(); - - Var result = find(path); - - if (result.type() == typeid(Array::Ptr)) - arr = *result.extract<Array::Ptr>(); - else if (result.type() == typeid(Array)) - arr = result.extract<Array>(); - - return arr; -} - - -Var Query::find(const std::string& path) const -{ - Var result = _source; - StringTokenizer tokenizer(path, "."); - for (StringTokenizer::Iterator token = tokenizer.begin(); token != tokenizer.end(); token++) - { - if (!result.isEmpty()) - { - std::vector<int> indexes; - RegularExpression::MatchVec matches; - int firstOffset = -1; - int offset = 0; - RegularExpression regex("\\[([0-9]+)\\]"); - while (regex.match(*token, offset, matches) > 0) - { - if (firstOffset == -1) - { - firstOffset = static_cast<int>(matches[0].offset); - } - std::string num = token->substr(matches[1].offset, matches[1].length); - indexes.push_back(NumberParser::parse(num)); - offset = static_cast<int>(matches[0].offset + matches[0].length); - } - - std::string name(*token); - if (firstOffset != -1) - { - name = name.substr(0, firstOffset); - } - - if (name.length() > 0) - { - if (result.type() == typeid(Object::Ptr)) - { - Object::Ptr o = result.extract<Object::Ptr>(); - result = o->get(name); - } - else if (result.type() == typeid(Object)) - { - Object o = result.extract<Object>(); - result = o.get(name); - } - else - result.empty(); - - } - - if (!result.isEmpty() && !indexes.empty()) - { - for (std::vector<int>::iterator it = indexes.begin(); it != indexes.end(); ++it) - { - if (result.type() == typeid(Array::Ptr)) - { - Array::Ptr array = result.extract<Array::Ptr>(); - result = array->get(*it); - if (result.isEmpty()) break; - } - else if (result.type() == typeid(Array)) - { - Array array = result.extract<Array>(); - result = array.get(*it); - if (result.isEmpty()) break; - } - } - } - } - } - return result; -} - - -} } // namespace Poco::JSON +// +// Query.cpp +// +// Library: JSON +// Package: JSON +// Module: Query +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Query.h" +#include "Poco/StringTokenizer.h" +#include "Poco/RegularExpression.h" +#include "Poco/NumberParser.h" +#include <sstream> + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +Query::Query(const Var& source): _source(source) +{ + if (!source.isEmpty() && + source.type() != typeid(Object) && + source.type() != typeid(Object::Ptr) && + source.type() != typeid(Array) && + source.type() != typeid(Array::Ptr)) + throw InvalidArgumentException("Only JSON Object, Array or pointers thereof allowed."); +} + + +Query::~Query() +{ +} + + +Object::Ptr Query::findObject(const std::string& path) const +{ + Var result = find(path); + + if (result.type() == typeid(Object::Ptr)) + return result.extract<Object::Ptr>(); + else if (result.type() == typeid(Object)) + return new Object(result.extract<Object>()); + + return 0; +} + + +Object& Query::findObject(const std::string& path, Object& obj) const +{ + obj.clear(); + + Var result = find(path); + + if (result.type() == typeid(Object::Ptr)) + obj = *result.extract<Object::Ptr>(); + else if (result.type() == typeid(Object)) + obj = result.extract<Object>(); + + return obj; +} + + +Array::Ptr Query::findArray(const std::string& path) const +{ + Var result = find(path); + + if (result.type() == typeid(Array::Ptr)) + return result.extract<Array::Ptr>(); + else if (result.type() == typeid(Array)) + return new Array(result.extract<Array>()); + + return 0; +} + + +Array& Query::findArray(const std::string& path, Array& arr) const +{ + arr.clear(); + + Var result = find(path); + + if (result.type() == typeid(Array::Ptr)) + arr = *result.extract<Array::Ptr>(); + else if (result.type() == typeid(Array)) + arr = result.extract<Array>(); + + return arr; +} + + +Var Query::find(const std::string& path) const +{ + Var result = _source; + StringTokenizer tokenizer(path, "."); + for (StringTokenizer::Iterator token = tokenizer.begin(); token != tokenizer.end(); token++) + { + if (!result.isEmpty()) + { + std::vector<int> indexes; + RegularExpression::MatchVec matches; + int firstOffset = -1; + int offset = 0; + RegularExpression regex("\\[([0-9]+)\\]"); + while (regex.match(*token, offset, matches) > 0) + { + if (firstOffset == -1) + { + firstOffset = static_cast<int>(matches[0].offset); + } + std::string num = token->substr(matches[1].offset, matches[1].length); + indexes.push_back(NumberParser::parse(num)); + offset = static_cast<int>(matches[0].offset + matches[0].length); + } + + std::string name(*token); + if (firstOffset != -1) + { + name = name.substr(0, firstOffset); + } + + if (name.length() > 0) + { + if (result.type() == typeid(Object::Ptr)) + { + Object::Ptr o = result.extract<Object::Ptr>(); + result = o->get(name); + } + else if (result.type() == typeid(Object)) + { + Object o = result.extract<Object>(); + result = o.get(name); + } + else + result.empty(); + + } + + if (!result.isEmpty() && !indexes.empty()) + { + for (std::vector<int>::iterator it = indexes.begin(); it != indexes.end(); ++it) + { + if (result.type() == typeid(Array::Ptr)) + { + Array::Ptr array = result.extract<Array::Ptr>(); + result = array->get(*it); + if (result.isEmpty()) break; + } + else if (result.type() == typeid(Array)) + { + Array array = result.extract<Array>(); + result = array.get(*it); + if (result.isEmpty()) break; + } + } + } + } + } + return result; +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Stringifier.cpp b/contrib/libs/poco/JSON/src/Stringifier.cpp index eb887eea08..633ddf6753 100644 --- a/contrib/libs/poco/JSON/src/Stringifier.cpp +++ b/contrib/libs/poco/JSON/src/Stringifier.cpp @@ -1,86 +1,86 @@ -// -// Stringifier.cpp -// -// Library: JSON -// Package: JSON -// Module: Stringifier -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Stringifier.h" -#include "Poco/JSON/Array.h" -#include "Poco/JSON/Object.h" -#include <iomanip> - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -void Stringifier::stringify(const Var& any, std::ostream& out, unsigned int indent, int step, int options) -{ - bool escapeUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0); - - if (step == -1) step = indent; - - if (any.type() == typeid(Object)) - { - Object& o = const_cast<Object&>(any.extract<Object>()); - o.setEscapeUnicode(escapeUnicode); - o.stringify(out, indent == 0 ? 0 : indent, step); - } - else if (any.type() == typeid(Array)) - { - Array& a = const_cast<Array&>(any.extract<Array>()); - a.setEscapeUnicode(escapeUnicode); - a.stringify(out, indent == 0 ? 0 : indent, step); - } - else if (any.type() == typeid(Object::Ptr)) - { - Object::Ptr& o = const_cast<Object::Ptr&>(any.extract<Object::Ptr>()); - o->setEscapeUnicode(escapeUnicode); - o->stringify(out, indent == 0 ? 0 : indent, step); - } - else if (any.type() == typeid(Array::Ptr)) - { - Array::Ptr& a = const_cast<Array::Ptr&>(any.extract<Array::Ptr>()); - a->setEscapeUnicode(escapeUnicode); - a->stringify(out, indent == 0 ? 0 : indent, step); - } - else if (any.isEmpty()) - { - out << "null"; - } - else if (any.isNumeric() || any.isBoolean()) - { - std::string value = any.convert<std::string>(); - if (any.type() == typeid(char)) formatString(value, out, options); - else out << value; - } - else if (any.isString() || any.isDateTime() || any.isDate() || any.isTime()) - { - std::string value = any.convert<std::string>(); - formatString(value, out, options); - } - else - { - out << any.convert<std::string>(); - } -} - - -void Stringifier::formatString(const std::string& value, std::ostream& out, int options) -{ - Poco::toJSON(value, out, options); -} - - -} } // namespace Poco::JSON +// +// Stringifier.cpp +// +// Library: JSON +// Package: JSON +// Module: Stringifier +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Stringifier.h" +#include "Poco/JSON/Array.h" +#include "Poco/JSON/Object.h" +#include <iomanip> + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +void Stringifier::stringify(const Var& any, std::ostream& out, unsigned int indent, int step, int options) +{ + bool escapeUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0); + + if (step == -1) step = indent; + + if (any.type() == typeid(Object)) + { + Object& o = const_cast<Object&>(any.extract<Object>()); + o.setEscapeUnicode(escapeUnicode); + o.stringify(out, indent == 0 ? 0 : indent, step); + } + else if (any.type() == typeid(Array)) + { + Array& a = const_cast<Array&>(any.extract<Array>()); + a.setEscapeUnicode(escapeUnicode); + a.stringify(out, indent == 0 ? 0 : indent, step); + } + else if (any.type() == typeid(Object::Ptr)) + { + Object::Ptr& o = const_cast<Object::Ptr&>(any.extract<Object::Ptr>()); + o->setEscapeUnicode(escapeUnicode); + o->stringify(out, indent == 0 ? 0 : indent, step); + } + else if (any.type() == typeid(Array::Ptr)) + { + Array::Ptr& a = const_cast<Array::Ptr&>(any.extract<Array::Ptr>()); + a->setEscapeUnicode(escapeUnicode); + a->stringify(out, indent == 0 ? 0 : indent, step); + } + else if (any.isEmpty()) + { + out << "null"; + } + else if (any.isNumeric() || any.isBoolean()) + { + std::string value = any.convert<std::string>(); + if (any.type() == typeid(char)) formatString(value, out, options); + else out << value; + } + else if (any.isString() || any.isDateTime() || any.isDate() || any.isTime()) + { + std::string value = any.convert<std::string>(); + formatString(value, out, options); + } + else + { + out << any.convert<std::string>(); + } +} + + +void Stringifier::formatString(const std::string& value, std::ostream& out, int options) +{ + Poco::toJSON(value, out, options); +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/Template.cpp b/contrib/libs/poco/JSON/src/Template.cpp index de9d0e00fd..941c5ec5d8 100644 --- a/contrib/libs/poco/JSON/src/Template.cpp +++ b/contrib/libs/poco/JSON/src/Template.cpp @@ -1,701 +1,701 @@ -// -// Template.cpp -// -// Library: JSON -// Package: JSON -// Module: Template -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/JSON/Template.h" -#include "Poco/JSON/TemplateCache.h" -#include "Poco/JSON/Query.h" -#include "Poco/File.h" -#include "Poco/FileStream.h" - - -using Poco::Dynamic::Var; - - -namespace Poco { -namespace JSON { - - -POCO_IMPLEMENT_EXCEPTION(JSONTemplateException, Exception, "Template Exception") - - -class Part -{ -public: - Part() - { - } - - virtual ~Part() - { - } - - virtual void render(const Var& data, std::ostream& out) const = 0; - - typedef std::vector<SharedPtr<Part> > VectorParts; -}; - - -class StringPart: public Part -{ -public: - StringPart(): Part() - { - } - - StringPart(const std::string& content): Part(), _content(content) - { - } - - virtual ~StringPart() - { - } - - void render(const Var& /*data*/, std::ostream& out) const - { - out << _content; - } - - void setContent(const std::string& content) - { - _content = content; - } - - inline std::string getContent() const - { - return _content; - } - -private: - std::string _content; -}; - - -class MultiPart: public Part -{ -public: - MultiPart() - { - } - - virtual ~MultiPart() - { - } - - virtual void addPart(Part* part) - { - _parts.push_back(part); - } - - void render(const Var& data, std::ostream& out) const - { - for (VectorParts::const_iterator it = _parts.begin(); it != _parts.end(); ++it) - { - (*it)->render(data, out); - } - } - -protected: - VectorParts _parts; -}; - - -class EchoPart: public Part -{ -public: - EchoPart(const std::string& query): Part(), _query(query) - { - } - - virtual ~EchoPart() - { - } - - void render(const Var& data, std::ostream& out) const - { - Query query(data); - Var value = query.find(_query); - - if (!value.isEmpty()) - { - out << value.convert<std::string>(); - } - } - -private: - std::string _query; -}; - - -class LogicQuery -{ -public: - LogicQuery(const std::string& query): _queryString(query) - { - } - - virtual ~LogicQuery() - { - } - - virtual bool apply(const Var& data) const - { - bool logic = false; - - Query query(data); - Var value = query.find(_queryString); - - if (!value.isEmpty()) // When empty, logic will be false - { - if (value.isString()) - // An empty string must result in false, otherwise true - // Which is not the case when we convert to bool with Var - { - std::string s = value.convert<std::string>(); - logic = !s.empty(); - } - else - { - // All other values, try to convert to bool - // An empty object or array will turn into false - // all other values depend on the convert<> in Var - logic = value.convert<bool>(); - } - } - - return logic; - } - -protected: - std::string _queryString; -}; - - -class LogicExistQuery: public LogicQuery -{ -public: - LogicExistQuery(const std::string& query): LogicQuery(query) - { - } - - virtual ~LogicExistQuery() - { - } - - virtual bool apply(const Var& data) const - { - Query query(data); - Var value = query.find(_queryString); - - return !value.isEmpty(); - } -}; - - -class LogicElseQuery: public LogicQuery -{ -public: - LogicElseQuery(): LogicQuery("") - { - } - - virtual ~LogicElseQuery() - { - } - - virtual bool apply(const Var& /*data*/) const - { - return true; - } -}; - - -class LogicPart: public MultiPart -{ -public: - LogicPart(): MultiPart() - { - } - - virtual ~LogicPart() - { - } - - void addPart(LogicQuery* query, Part* part) - { - MultiPart::addPart(part); - _queries.push_back(query); - } - - void addPart(Part* part) - { - MultiPart::addPart(part); - _queries.push_back(new LogicElseQuery()); - } - - void render(const Var& data, std::ostream& out) const - { - int count = 0; - for (std::vector<SharedPtr<LogicQuery> >::const_iterator it = _queries.begin(); it != _queries.end(); ++it, ++count) - { - if ((*it)->apply(data) && _parts.size() > count) - { - _parts[count]->render(data, out); - break; - } - } - } - -private: - std::vector<SharedPtr<LogicQuery> > _queries; -}; - - -class LoopPart: public MultiPart -{ -public: - LoopPart(const std::string& name, const std::string& query): MultiPart(), _name(name), _query(query) - { - } - - virtual ~LoopPart() - { - } - - void render(const Var& data, std::ostream& out) const - { - Query query(data); - - if (data.type() == typeid(Object::Ptr)) - { - Object::Ptr dataObject = data.extract<Object::Ptr>(); - Array::Ptr array = query.findArray(_query); - if (!array.isNull()) - { - for (int i = 0; i < array->size(); i++) - { - Var value = array->get(i); - dataObject->set(_name, value); - MultiPart::render(data, out); - } - dataObject->remove(_name); - } - } - } - -private: - std::string _name; - std::string _query; -}; - - -class IncludePart: public Part -{ -public: - - IncludePart(const Path& parentPath, const Path& path): - Part(), - _path(path) - { - // When the path is relative, try to make it absolute based - // on the path of the parent template. When the file doesn't - // exist, we keep it relative and hope that the cache can - // resolve it. - if (_path.isRelative()) - { - Path templatePath(parentPath, _path); - File templateFile(templatePath); - if (templateFile.exists()) - { - _path = templatePath; - } - } - } - - virtual ~IncludePart() - { - } - - void render(const Var& data, std::ostream& out) const - { - TemplateCache* cache = TemplateCache::instance(); - if (cache == 0) - { - Template tpl(_path); - tpl.parse(); - tpl.render(data, out); - } - else - { - Template::Ptr tpl = cache->getTemplate(_path); - tpl->render(data, out); - } - } - -private: - Path _path; -}; - - -Template::Template(const Path& templatePath): - _parts(0), - _currentPart(0), - _templatePath(templatePath) -{ -} - - -Template::Template(): - _parts(0), - _currentPart(0) -{ -} - - -Template::~Template() -{ - delete _parts; -} - - -void Template::parse() -{ - File file(_templatePath); - if (file.exists()) - { - FileInputStream fis(_templatePath.toString()); - parse(fis); - } -} - - -void Template::parse(std::istream& in) -{ - _parseTime.update(); - - _parts = new MultiPart; - _currentPart = _parts; - - while (in.good()) - { - std::string text = readText(in); // Try to read text first - if (text.length() > 0) - { - _currentPart->addPart(new StringPart(text)); - } - - if (in.bad()) - break; // Nothing to do anymore - - std::string command = readTemplateCommand(in); // Try to read a template command - if (command.empty()) - { - break; - } - - readWhiteSpace(in); - - if (command.compare("echo") == 0) - { - std::string query = readQuery(in); - if (query.empty()) - { - throw JSONTemplateException("Missing query in <? echo ?>"); - } - _currentPart->addPart(new EchoPart(query)); - } - else if (command.compare("for") == 0) - { - std::string loopVariable = readWord(in); - if (loopVariable.empty()) - { - throw JSONTemplateException("Missing variable in <? for ?> command"); - } - readWhiteSpace(in); - - std::string query = readQuery(in); - if (query.empty()) - { - throw JSONTemplateException("Missing query in <? for ?> command"); - } - - _partStack.push(_currentPart); - LoopPart* part = new LoopPart(loopVariable, query); - _partStack.push(part); - _currentPart->addPart(part); - _currentPart = part; - } - else if (command.compare("else") == 0) - { - if (_partStack.size() == 0) - { - throw JSONTemplateException("Unexpected <? else ?> found"); - } - _currentPart = _partStack.top(); - LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); - if (lp == 0) - { - throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? else ?>"); - } - MultiPart* part = new MultiPart(); - lp->addPart(part); - _currentPart = part; - } - else if (command.compare("elsif") == 0 || command.compare("elif") == 0) - { - std::string query = readQuery(in); - if (query.empty()) - { - throw JSONTemplateException("Missing query in <? " + command + " ?>"); - } - - if (_partStack.size() == 0) - { - throw JSONTemplateException("Unexpected <? elsif / elif ?> found"); - } - - _currentPart = _partStack.top(); - LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); - if (lp == 0) - { - throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? elsif / elif ?>"); - } - MultiPart* part = new MultiPart(); - lp->addPart(new LogicQuery(query), part); - _currentPart = part; - } - else if (command.compare("endfor") == 0) - { - if (_partStack.size() < 2) - { - throw JSONTemplateException("Unexpected <? endfor ?> found"); - } - MultiPart* loopPart = _partStack.top(); - LoopPart* lp = dynamic_cast<LoopPart*>(loopPart); - if (lp == 0) - { - throw JSONTemplateException("Missing <? for ?> command"); - } - _partStack.pop(); - _currentPart = _partStack.top(); - _partStack.pop(); - } - else if (command.compare("endif") == 0) - { - if (_partStack.size() < 2) - { - throw JSONTemplateException("Unexpected <? endif ?> found"); - } - - _currentPart = _partStack.top(); - LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); - if (lp == 0) - { - throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? endif ?>"); - } - - _partStack.pop(); - _currentPart = _partStack.top(); - _partStack.pop(); - } - else if (command.compare("if") == 0 || command.compare("ifexist") == 0) - { - std::string query = readQuery(in); - if (query.empty()) - { - throw JSONTemplateException("Missing query in <? " + command + " ?>"); - } - _partStack.push(_currentPart); - LogicPart* lp = new LogicPart(); - _partStack.push(lp); - _currentPart->addPart(lp); - _currentPart = new MultiPart(); - if (command.compare("ifexist") == 0) - { - lp->addPart(new LogicExistQuery(query), _currentPart); - } - else - { - lp->addPart(new LogicQuery(query), _currentPart); - } - } - else if (command.compare("include") == 0) - { - readWhiteSpace(in); - std::string filename = readString(in); - if (filename.empty()) - { - throw JSONTemplateException("Missing filename in <? include ?>"); - } - else - { - Path resolvePath(_templatePath); - resolvePath.makeParent(); - _currentPart->addPart(new IncludePart(resolvePath, filename)); - } - } - else - { - throw JSONTemplateException("Unknown command " + command); - } - - readWhiteSpace(in); - - int c = in.get(); - if (c == '?' && in.peek() == '>') - { - in.get(); // forget '>' - - if (command.compare("echo") != 0) - { - if (in.peek() == '\r') - { - in.get(); - } - if (in.peek() == '\n') - { - in.get(); - } - } - } - else - { - throw JSONTemplateException("Missing ?>"); - } - } -} - - -std::string Template::readText(std::istream& in) -{ - std::string text; - int c = in.get(); - while (c != -1) - { - if (c == '<') - { - if (in.peek() == '?') - { - in.get(); // forget '?' - break; - } - } - text += static_cast<char>(c); - - c = in.get(); - } - return text; -} - - -std::string Template::readTemplateCommand(std::istream& in) -{ - std::string command; - - readWhiteSpace(in); - - int c = in.get(); - while (c != -1) - { - if (Ascii::isSpace(c)) - break; - - if (c == '?' && in.peek() == '>') - { - in.putback(static_cast<char>(c)); - break; - } - - if (c == '=' && command.length() == 0) - { - command = "echo"; - break; - } - - command += static_cast<char>(c); - - c = in.get(); - } - - return command; -} - - -std::string Template::readWord(std::istream& in) -{ - std::string word; - int c; - while ((c = in.peek()) != -1 && !Ascii::isSpace(c)) - { - in.get(); - word += static_cast<char>(c); - } - return word; -} - - -std::string Template::readQuery(std::istream& in) -{ - std::string word; - int c; - while ((c = in.get()) != -1) - { - if (c == '?' && in.peek() == '>') - { - in.putback(static_cast<char>(c)); - break; - } - - if (Ascii::isSpace(c)) - { - break; - } - word += static_cast<char>(c); - } - return word; -} - - -void Template::readWhiteSpace(std::istream& in) -{ - int c; - while ((c = in.peek()) != -1 && Ascii::isSpace(c)) - { - in.get(); - } -} - - -std::string Template::readString(std::istream& in) -{ - std::string str; - - int c = in.get(); - if (c == '"') - { - while ((c = in.get()) != -1 && c != '"') - { - str += static_cast<char>(c); - } - } - return str; -} - - -void Template::render(const Var& data, std::ostream& out) const -{ - _parts->render(data, out); -} - - -} } // namespace Poco::JSON +// +// Template.cpp +// +// Library: JSON +// Package: JSON +// Module: Template +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/JSON/Template.h" +#include "Poco/JSON/TemplateCache.h" +#include "Poco/JSON/Query.h" +#include "Poco/File.h" +#include "Poco/FileStream.h" + + +using Poco::Dynamic::Var; + + +namespace Poco { +namespace JSON { + + +POCO_IMPLEMENT_EXCEPTION(JSONTemplateException, Exception, "Template Exception") + + +class Part +{ +public: + Part() + { + } + + virtual ~Part() + { + } + + virtual void render(const Var& data, std::ostream& out) const = 0; + + typedef std::vector<SharedPtr<Part> > VectorParts; +}; + + +class StringPart: public Part +{ +public: + StringPart(): Part() + { + } + + StringPart(const std::string& content): Part(), _content(content) + { + } + + virtual ~StringPart() + { + } + + void render(const Var& /*data*/, std::ostream& out) const + { + out << _content; + } + + void setContent(const std::string& content) + { + _content = content; + } + + inline std::string getContent() const + { + return _content; + } + +private: + std::string _content; +}; + + +class MultiPart: public Part +{ +public: + MultiPart() + { + } + + virtual ~MultiPart() + { + } + + virtual void addPart(Part* part) + { + _parts.push_back(part); + } + + void render(const Var& data, std::ostream& out) const + { + for (VectorParts::const_iterator it = _parts.begin(); it != _parts.end(); ++it) + { + (*it)->render(data, out); + } + } + +protected: + VectorParts _parts; +}; + + +class EchoPart: public Part +{ +public: + EchoPart(const std::string& query): Part(), _query(query) + { + } + + virtual ~EchoPart() + { + } + + void render(const Var& data, std::ostream& out) const + { + Query query(data); + Var value = query.find(_query); + + if (!value.isEmpty()) + { + out << value.convert<std::string>(); + } + } + +private: + std::string _query; +}; + + +class LogicQuery +{ +public: + LogicQuery(const std::string& query): _queryString(query) + { + } + + virtual ~LogicQuery() + { + } + + virtual bool apply(const Var& data) const + { + bool logic = false; + + Query query(data); + Var value = query.find(_queryString); + + if (!value.isEmpty()) // When empty, logic will be false + { + if (value.isString()) + // An empty string must result in false, otherwise true + // Which is not the case when we convert to bool with Var + { + std::string s = value.convert<std::string>(); + logic = !s.empty(); + } + else + { + // All other values, try to convert to bool + // An empty object or array will turn into false + // all other values depend on the convert<> in Var + logic = value.convert<bool>(); + } + } + + return logic; + } + +protected: + std::string _queryString; +}; + + +class LogicExistQuery: public LogicQuery +{ +public: + LogicExistQuery(const std::string& query): LogicQuery(query) + { + } + + virtual ~LogicExistQuery() + { + } + + virtual bool apply(const Var& data) const + { + Query query(data); + Var value = query.find(_queryString); + + return !value.isEmpty(); + } +}; + + +class LogicElseQuery: public LogicQuery +{ +public: + LogicElseQuery(): LogicQuery("") + { + } + + virtual ~LogicElseQuery() + { + } + + virtual bool apply(const Var& /*data*/) const + { + return true; + } +}; + + +class LogicPart: public MultiPart +{ +public: + LogicPart(): MultiPart() + { + } + + virtual ~LogicPart() + { + } + + void addPart(LogicQuery* query, Part* part) + { + MultiPart::addPart(part); + _queries.push_back(query); + } + + void addPart(Part* part) + { + MultiPart::addPart(part); + _queries.push_back(new LogicElseQuery()); + } + + void render(const Var& data, std::ostream& out) const + { + int count = 0; + for (std::vector<SharedPtr<LogicQuery> >::const_iterator it = _queries.begin(); it != _queries.end(); ++it, ++count) + { + if ((*it)->apply(data) && _parts.size() > count) + { + _parts[count]->render(data, out); + break; + } + } + } + +private: + std::vector<SharedPtr<LogicQuery> > _queries; +}; + + +class LoopPart: public MultiPart +{ +public: + LoopPart(const std::string& name, const std::string& query): MultiPart(), _name(name), _query(query) + { + } + + virtual ~LoopPart() + { + } + + void render(const Var& data, std::ostream& out) const + { + Query query(data); + + if (data.type() == typeid(Object::Ptr)) + { + Object::Ptr dataObject = data.extract<Object::Ptr>(); + Array::Ptr array = query.findArray(_query); + if (!array.isNull()) + { + for (int i = 0; i < array->size(); i++) + { + Var value = array->get(i); + dataObject->set(_name, value); + MultiPart::render(data, out); + } + dataObject->remove(_name); + } + } + } + +private: + std::string _name; + std::string _query; +}; + + +class IncludePart: public Part +{ +public: + + IncludePart(const Path& parentPath, const Path& path): + Part(), + _path(path) + { + // When the path is relative, try to make it absolute based + // on the path of the parent template. When the file doesn't + // exist, we keep it relative and hope that the cache can + // resolve it. + if (_path.isRelative()) + { + Path templatePath(parentPath, _path); + File templateFile(templatePath); + if (templateFile.exists()) + { + _path = templatePath; + } + } + } + + virtual ~IncludePart() + { + } + + void render(const Var& data, std::ostream& out) const + { + TemplateCache* cache = TemplateCache::instance(); + if (cache == 0) + { + Template tpl(_path); + tpl.parse(); + tpl.render(data, out); + } + else + { + Template::Ptr tpl = cache->getTemplate(_path); + tpl->render(data, out); + } + } + +private: + Path _path; +}; + + +Template::Template(const Path& templatePath): + _parts(0), + _currentPart(0), + _templatePath(templatePath) +{ +} + + +Template::Template(): + _parts(0), + _currentPart(0) +{ +} + + +Template::~Template() +{ + delete _parts; +} + + +void Template::parse() +{ + File file(_templatePath); + if (file.exists()) + { + FileInputStream fis(_templatePath.toString()); + parse(fis); + } +} + + +void Template::parse(std::istream& in) +{ + _parseTime.update(); + + _parts = new MultiPart; + _currentPart = _parts; + + while (in.good()) + { + std::string text = readText(in); // Try to read text first + if (text.length() > 0) + { + _currentPart->addPart(new StringPart(text)); + } + + if (in.bad()) + break; // Nothing to do anymore + + std::string command = readTemplateCommand(in); // Try to read a template command + if (command.empty()) + { + break; + } + + readWhiteSpace(in); + + if (command.compare("echo") == 0) + { + std::string query = readQuery(in); + if (query.empty()) + { + throw JSONTemplateException("Missing query in <? echo ?>"); + } + _currentPart->addPart(new EchoPart(query)); + } + else if (command.compare("for") == 0) + { + std::string loopVariable = readWord(in); + if (loopVariable.empty()) + { + throw JSONTemplateException("Missing variable in <? for ?> command"); + } + readWhiteSpace(in); + + std::string query = readQuery(in); + if (query.empty()) + { + throw JSONTemplateException("Missing query in <? for ?> command"); + } + + _partStack.push(_currentPart); + LoopPart* part = new LoopPart(loopVariable, query); + _partStack.push(part); + _currentPart->addPart(part); + _currentPart = part; + } + else if (command.compare("else") == 0) + { + if (_partStack.size() == 0) + { + throw JSONTemplateException("Unexpected <? else ?> found"); + } + _currentPart = _partStack.top(); + LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); + if (lp == 0) + { + throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? else ?>"); + } + MultiPart* part = new MultiPart(); + lp->addPart(part); + _currentPart = part; + } + else if (command.compare("elsif") == 0 || command.compare("elif") == 0) + { + std::string query = readQuery(in); + if (query.empty()) + { + throw JSONTemplateException("Missing query in <? " + command + " ?>"); + } + + if (_partStack.size() == 0) + { + throw JSONTemplateException("Unexpected <? elsif / elif ?> found"); + } + + _currentPart = _partStack.top(); + LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); + if (lp == 0) + { + throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? elsif / elif ?>"); + } + MultiPart* part = new MultiPart(); + lp->addPart(new LogicQuery(query), part); + _currentPart = part; + } + else if (command.compare("endfor") == 0) + { + if (_partStack.size() < 2) + { + throw JSONTemplateException("Unexpected <? endfor ?> found"); + } + MultiPart* loopPart = _partStack.top(); + LoopPart* lp = dynamic_cast<LoopPart*>(loopPart); + if (lp == 0) + { + throw JSONTemplateException("Missing <? for ?> command"); + } + _partStack.pop(); + _currentPart = _partStack.top(); + _partStack.pop(); + } + else if (command.compare("endif") == 0) + { + if (_partStack.size() < 2) + { + throw JSONTemplateException("Unexpected <? endif ?> found"); + } + + _currentPart = _partStack.top(); + LogicPart* lp = dynamic_cast<LogicPart*>(_currentPart); + if (lp == 0) + { + throw JSONTemplateException("Missing <? if ?> or <? ifexist ?> for <? endif ?>"); + } + + _partStack.pop(); + _currentPart = _partStack.top(); + _partStack.pop(); + } + else if (command.compare("if") == 0 || command.compare("ifexist") == 0) + { + std::string query = readQuery(in); + if (query.empty()) + { + throw JSONTemplateException("Missing query in <? " + command + " ?>"); + } + _partStack.push(_currentPart); + LogicPart* lp = new LogicPart(); + _partStack.push(lp); + _currentPart->addPart(lp); + _currentPart = new MultiPart(); + if (command.compare("ifexist") == 0) + { + lp->addPart(new LogicExistQuery(query), _currentPart); + } + else + { + lp->addPart(new LogicQuery(query), _currentPart); + } + } + else if (command.compare("include") == 0) + { + readWhiteSpace(in); + std::string filename = readString(in); + if (filename.empty()) + { + throw JSONTemplateException("Missing filename in <? include ?>"); + } + else + { + Path resolvePath(_templatePath); + resolvePath.makeParent(); + _currentPart->addPart(new IncludePart(resolvePath, filename)); + } + } + else + { + throw JSONTemplateException("Unknown command " + command); + } + + readWhiteSpace(in); + + int c = in.get(); + if (c == '?' && in.peek() == '>') + { + in.get(); // forget '>' + + if (command.compare("echo") != 0) + { + if (in.peek() == '\r') + { + in.get(); + } + if (in.peek() == '\n') + { + in.get(); + } + } + } + else + { + throw JSONTemplateException("Missing ?>"); + } + } +} + + +std::string Template::readText(std::istream& in) +{ + std::string text; + int c = in.get(); + while (c != -1) + { + if (c == '<') + { + if (in.peek() == '?') + { + in.get(); // forget '?' + break; + } + } + text += static_cast<char>(c); + + c = in.get(); + } + return text; +} + + +std::string Template::readTemplateCommand(std::istream& in) +{ + std::string command; + + readWhiteSpace(in); + + int c = in.get(); + while (c != -1) + { + if (Ascii::isSpace(c)) + break; + + if (c == '?' && in.peek() == '>') + { + in.putback(static_cast<char>(c)); + break; + } + + if (c == '=' && command.length() == 0) + { + command = "echo"; + break; + } + + command += static_cast<char>(c); + + c = in.get(); + } + + return command; +} + + +std::string Template::readWord(std::istream& in) +{ + std::string word; + int c; + while ((c = in.peek()) != -1 && !Ascii::isSpace(c)) + { + in.get(); + word += static_cast<char>(c); + } + return word; +} + + +std::string Template::readQuery(std::istream& in) +{ + std::string word; + int c; + while ((c = in.get()) != -1) + { + if (c == '?' && in.peek() == '>') + { + in.putback(static_cast<char>(c)); + break; + } + + if (Ascii::isSpace(c)) + { + break; + } + word += static_cast<char>(c); + } + return word; +} + + +void Template::readWhiteSpace(std::istream& in) +{ + int c; + while ((c = in.peek()) != -1 && Ascii::isSpace(c)) + { + in.get(); + } +} + + +std::string Template::readString(std::istream& in) +{ + std::string str; + + int c = in.get(); + if (c == '"') + { + while ((c = in.get()) != -1 && c != '"') + { + str += static_cast<char>(c); + } + } + return str; +} + + +void Template::render(const Var& data, std::ostream& out) const +{ + _parts->render(data, out); +} + + +} } // namespace Poco::JSON diff --git a/contrib/libs/poco/JSON/src/TemplateCache.cpp b/contrib/libs/poco/JSON/src/TemplateCache.cpp index a8bf812e3a..d8df071d45 100644 --- a/contrib/libs/poco/JSON/src/TemplateCache.cpp +++ b/contrib/libs/poco/JSON/src/TemplateCache.cpp @@ -1,157 +1,157 @@ -// -// TemplateCache.cpp -// -// Library: JSON -// Package: JSON -// Module: TemplateCache -// -// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. -// and Contributors. -// -// SPDX-License-Identifier: BSL-1.0 -// - - -#include "Poco/File.h" -#include "Poco/JSON/TemplateCache.h" - - -namespace Poco { -namespace JSON { - - -TemplateCache* TemplateCache::_pInstance = 0; - - -TemplateCache::TemplateCache(): _pLogger(0) -{ - setup(); -} - - -TemplateCache::~TemplateCache() -{ - _pInstance = 0; -} - - -void TemplateCache::setup() -{ - poco_assert (_pInstance == 0); - _pInstance = this; -} - - -Template::Ptr TemplateCache::getTemplate(const Path& path) -{ - if (_pLogger) - { - poco_trace_f1(*_pLogger, "Trying to load %s", path.toString()); - } - - Path templatePath = resolvePath(path); - std::string templatePathname = templatePath.toString(); - - if (_pLogger) - { - poco_trace_f1(*_pLogger, "Path resolved to %s", templatePathname); - } - - File templateFile(templatePathname); - - Template::Ptr tpl; - - std::map<std::string, Template::Ptr>::iterator it = _cache.find(templatePathname); - if (it == _cache.end()) - { - if (templateFile.exists()) - { - if (_pLogger) - { - poco_information_f1(*_pLogger, "Loading template %s", templatePath.toString()); - } - - tpl = new Template(templatePath); - - try - { - tpl->parse(); - _cache[templatePathname] = tpl; - } - catch (JSONTemplateException& jte) - { - if (_pLogger) - { - poco_error_f2(*_pLogger, "Template %s contains an error: %s", templatePath.toString(), jte.message()); - } - } - } - else - { - if (_pLogger) - { - poco_error_f1(*_pLogger, "Template file %s doesn't exist", templatePath.toString()); - } - throw FileNotFoundException(templatePathname); - } - } - else - { - tpl = it->second; - if (tpl->parseTime() < templateFile.getLastModified()) - { - if (_pLogger) - { - poco_information_f1(*_pLogger, "Reloading template %s", templatePath.toString()); - } - - tpl = new Template(templatePath); - - try - { - tpl->parse(); - _cache[templatePathname] = tpl; - } - catch (JSONTemplateException& jte) - { - if (_pLogger) - { - poco_error_f2(*_pLogger, "Template %s contains an error: %s", templatePath.toString(), jte.message()); - } - } - } - } - - return tpl; -} - - -Path TemplateCache::resolvePath(const Path& path) const -{ - if (path.isAbsolute()) - return path; - - for (std::vector<Path>::const_iterator it = _includePaths.begin(); it != _includePaths.end(); ++it) - { - Path templatePath(*it, path); - - File templateFile(templatePath); - if (templateFile.exists()) - { - if (_pLogger) - { - poco_trace_f2(*_pLogger, "%s template file resolved to %s", path.toString(), templatePath.toString()); - } - return templatePath; - } - if (_pLogger) - { - poco_trace_f1(*_pLogger, "%s doesn't exist", templatePath.toString()); - } - } - - throw FileNotFoundException(path.toString()); -} - - -} } // Poco::JSON +// +// TemplateCache.cpp +// +// Library: JSON +// Package: JSON +// Module: TemplateCache +// +// Copyright (c) 2012, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "Poco/File.h" +#include "Poco/JSON/TemplateCache.h" + + +namespace Poco { +namespace JSON { + + +TemplateCache* TemplateCache::_pInstance = 0; + + +TemplateCache::TemplateCache(): _pLogger(0) +{ + setup(); +} + + +TemplateCache::~TemplateCache() +{ + _pInstance = 0; +} + + +void TemplateCache::setup() +{ + poco_assert (_pInstance == 0); + _pInstance = this; +} + + +Template::Ptr TemplateCache::getTemplate(const Path& path) +{ + if (_pLogger) + { + poco_trace_f1(*_pLogger, "Trying to load %s", path.toString()); + } + + Path templatePath = resolvePath(path); + std::string templatePathname = templatePath.toString(); + + if (_pLogger) + { + poco_trace_f1(*_pLogger, "Path resolved to %s", templatePathname); + } + + File templateFile(templatePathname); + + Template::Ptr tpl; + + std::map<std::string, Template::Ptr>::iterator it = _cache.find(templatePathname); + if (it == _cache.end()) + { + if (templateFile.exists()) + { + if (_pLogger) + { + poco_information_f1(*_pLogger, "Loading template %s", templatePath.toString()); + } + + tpl = new Template(templatePath); + + try + { + tpl->parse(); + _cache[templatePathname] = tpl; + } + catch (JSONTemplateException& jte) + { + if (_pLogger) + { + poco_error_f2(*_pLogger, "Template %s contains an error: %s", templatePath.toString(), jte.message()); + } + } + } + else + { + if (_pLogger) + { + poco_error_f1(*_pLogger, "Template file %s doesn't exist", templatePath.toString()); + } + throw FileNotFoundException(templatePathname); + } + } + else + { + tpl = it->second; + if (tpl->parseTime() < templateFile.getLastModified()) + { + if (_pLogger) + { + poco_information_f1(*_pLogger, "Reloading template %s", templatePath.toString()); + } + + tpl = new Template(templatePath); + + try + { + tpl->parse(); + _cache[templatePathname] = tpl; + } + catch (JSONTemplateException& jte) + { + if (_pLogger) + { + poco_error_f2(*_pLogger, "Template %s contains an error: %s", templatePath.toString(), jte.message()); + } + } + } + } + + return tpl; +} + + +Path TemplateCache::resolvePath(const Path& path) const +{ + if (path.isAbsolute()) + return path; + + for (std::vector<Path>::const_iterator it = _includePaths.begin(); it != _includePaths.end(); ++it) + { + Path templatePath(*it, path); + + File templateFile(templatePath); + if (templateFile.exists()) + { + if (_pLogger) + { + poco_trace_f2(*_pLogger, "%s template file resolved to %s", path.toString(), templatePath.toString()); + } + return templatePath; + } + if (_pLogger) + { + poco_trace_f1(*_pLogger, "%s doesn't exist", templatePath.toString()); + } + } + + throw FileNotFoundException(path.toString()); +} + + +} } // Poco::JSON diff --git a/contrib/libs/poco/JSON/src/pdjson.c b/contrib/libs/poco/JSON/src/pdjson.c index 4c6956eac9..a02285e773 100644 --- a/contrib/libs/poco/JSON/src/pdjson.c +++ b/contrib/libs/poco/JSON/src/pdjson.c @@ -1,855 +1,855 @@ -#define _POSIX_C_SOURCE 200112L -#include <stdio.h> -#include <stdbool.h> -#include <stdlib.h> -#include <string.h> -#include <ctype.h> -#include <errno.h> -#include "pdjson.h" - -#define JSON_FLAG_ERROR (1u << 0) -#define JSON_FLAG_STREAMING (1u << 1) - -#define json_error(json, format, ...) \ - if (!(json->flags & JSON_FLAG_ERROR)) { \ - json->flags |= JSON_FLAG_ERROR; \ - snprintf(json->errmsg, sizeof(json->errmsg), \ - "error: %lu: " format, \ - (unsigned long) json->lineno, \ - __VA_ARGS__); \ - } \ - -#define STACK_INC 4 - -#if defined(_MSC_VER) || defined(__MINGW32__) -#define strerror_r(err, buf, len) strerror_s(buf, len, err) -#endif - -const char *json_typename[] = { - [JSON_ERROR] = "ERROR", - [JSON_DONE] = "DONE", - [JSON_OBJECT] = "OBJECT", - [JSON_OBJECT_END] = "OBJECT_END", - [JSON_ARRAY] = "ARRAY", - [JSON_ARRAY_END] = "ARRAY_END", - [JSON_STRING] = "STRING", - [JSON_NUMBER] = "NUMBER", - [JSON_TRUE] = "TRUE", - [JSON_FALSE] = "FALSE", - [JSON_NULL] = "NULL", -}; - -struct json_stack { - enum json_type type; - long count; -}; - -static void json_error_s(json_stream *json, int err) -{ - char errbuf[1024] = {0}; - strerror_r(err, errbuf, sizeof(errbuf)); - json_error(json, "%s", errbuf); -} - -static enum json_type -push(json_stream *json, enum json_type type) -{ - json->stack_top++; - - if (json->stack_top >= json->stack_size) { - struct json_stack *stack; - stack = json->alloc.realloc(json->stack, - (json->stack_size + STACK_INC) * sizeof(*json->stack)); - if (stack == NULL) { - json_error_s(json, errno); - return JSON_ERROR; - } - - json->stack_size += STACK_INC; - json->stack = stack; - } - - json->stack[json->stack_top].type = type; - json->stack[json->stack_top].count = 0; - - return type; -} - -static enum json_type -pop(json_stream *json, int c, enum json_type expected) -{ - if (json->stack == NULL || json->stack[json->stack_top].type != expected) { - json_error(json, "unexpected byte, '%c'", c); - return JSON_ERROR; - } - json->stack_top--; - return expected == JSON_ARRAY ? JSON_ARRAY_END : JSON_OBJECT_END; -} - -static int buffer_peek(struct json_source *source) -{ - if (source->position < source->source.buffer.length) - return source->source.buffer.buffer[source->position]; - else - return EOF; -} - -static int buffer_get(struct json_source *source) -{ - int c = source->peek(source); - source->position++; - return c; -} - -static int stream_get(struct json_source *source) -{ - source->position++; - return fgetc(source->source.stream.stream); -} - -static int stream_peek(struct json_source *source) -{ - int c = fgetc(source->source.stream.stream); - ungetc(c, source->source.stream.stream); - return c; -} - -static void init(json_stream *json) -{ - json->lineno = 1; - json->flags = JSON_FLAG_STREAMING; - json->errmsg[0] = '\0'; - json->ntokens = 0; - json->next = 0; - - json->stack = NULL; - json->stack_top = (size_t)(-1); - json->stack_size = 0; - - json->data.string = NULL; - json->data.string_size = 0; - json->data.string_fill = 0; - json->source.position = 0; - - json->alloc.malloc = malloc; - json->alloc.realloc = realloc; - json->alloc.free = free; -} - -static enum json_type -is_match(json_stream *json, const char *pattern, enum json_type type) -{ - for (const char *p = pattern; *p; p++) - if (*p != json->source.get(&json->source)) - return JSON_ERROR; - return type; -} - -static int pushchar(json_stream *json, int c) -{ - if (json->data.string_fill == json->data.string_size) { - size_t size = json->data.string_size * 2; - char *buffer = json->alloc.realloc(json->data.string, size); - if (buffer == NULL) { - json_error_s(json, errno); - return -1; - } else { - json->data.string_size = size; - json->data.string = buffer; - } - } - json->data.string[json->data.string_fill++] = (char)(c); - return 0; -} - -static int init_string(json_stream *json) -{ - json->data.string_fill = 0; - if (json->data.string == NULL) { - json->data.string_size = 1024; - json->data.string = json->alloc.malloc(json->data.string_size); - if (json->data.string == NULL) { - json_error_s(json, errno); - return -1; - } - } - json->data.string[0] = '\0'; - return 0; -} - -static int encode_utf8(json_stream *json, unsigned long c) -{ - if (c < 0x80UL) { - return pushchar(json, c); - } else if (c < 0x0800UL) { - return !((pushchar(json, (c >> 6 & 0x1F) | 0xC0) == 0) && - (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); - } else if (c < 0x010000UL) { - if (c >= 0xd800 && c <= 0xdfff) { - json_error(json, "invalid codepoint %06lx", c); - return -1; - } - return !((pushchar(json, (c >> 12 & 0x0F) | 0xE0) == 0) && - (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && - (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); - } else if (c < 0x110000UL) { - return !((pushchar(json, (c >> 18 & 0x07) | 0xF0) == 0) && - (pushchar(json, (c >> 12 & 0x3F) | 0x80) == 0) && - (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && - (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); - } else { - json_error(json, "can't encode UTF-8 for %06lx", c); - return -1; - } -} - -static int hexchar(int c) -{ - switch (c) { - case '0': return 0; - case '1': return 1; - case '2': return 2; - case '3': return 3; - case '4': return 4; - case '5': return 5; - case '6': return 6; - case '7': return 7; - case '8': return 8; - case '9': return 9; - case 'a': - case 'A': return 10; - case 'b': - case 'B': return 11; - case 'c': - case 'C': return 12; - case 'd': - case 'D': return 13; - case 'e': - case 'E': return 14; - case 'f': - case 'F': return 15; - default: - return -1; - } -} - -static long -read_unicode_cp(json_stream *json) -{ - long cp = 0; - int shift = 12; - - for (size_t i = 0; i < 4; i++) { - int c = json->source.get(&json->source); - int hc; - - if (c == EOF) { - json_error(json, "%s", "unterminated string literal in unicode"); - return -1; - } else if ((hc = hexchar(c)) == -1) { - json_error(json, "bad escape unicode byte, '%c'", c); - return -1; - } - - cp += hc * (1 << shift); - shift -= 4; - } - - - return cp; -} - -static int read_unicode(json_stream *json) -{ - long cp, h, l; - - if ((cp = read_unicode_cp(json)) == -1) { - return -1; - } - - if (cp >= 0xd800 && cp <= 0xdbff) { - /* This is the high portion of a surrogate pair; we need to read the - * lower portion to get the codepoint - */ - h = cp; - - int c = json->source.get(&json->source); - if (c == EOF) { - json_error(json, "%s", "unterminated string literal in unicode"); - return -1; - } else if (c != '\\') { - json_error(json, "invalid continuation for surrogate pair: '%c', " - "expected '\\'", c); - return -1; - } - - c = json->source.get(&json->source); - if (c == EOF) { - json_error(json, "%s", "unterminated string literal in unicode"); - return -1; - } else if (c != 'u') { - json_error(json, "invalid continuation for surrogate pair: '%c', " - "expected 'u'", c); - return -1; - } - - if ((l = read_unicode_cp(json)) == -1) { - return -1; - } - - if (l < 0xdc00 || l > 0xdfff) { - json_error(json, "invalid surrogate pair continuation \\u%04lx out " - "of range (dc00-dfff)", l); - return -1; - } - - cp = ((h - 0xd800) * 0x400) + ((l - 0xdc00) + 0x10000); - } else if (cp >= 0xdc00 && cp <= 0xdfff) { - json_error(json, "dangling surrogate \\u%04lx", cp); - return -1; - } - - return encode_utf8(json, cp); -} - -int read_escaped(json_stream *json) -{ - int c = json->source.get(&json->source); - if (c == EOF) { - json_error(json, "%s", "unterminated string literal in escape"); - return -1; - } else if (c == 'u') { - if (read_unicode(json) != 0) - return -1; - } else { - switch (c) { - case '\\': - case 'b': - case 'f': - case 'n': - case 'r': - case 't': - case '/': - case '"': - { - const char *codes = "\\bfnrt/\""; - char *p = strchr(codes, c); - if (pushchar(json, "\\\b\f\n\r\t/\""[p - codes]) != 0) - return -1; - } - break; - default: - json_error(json, "bad escaped byte, '%c'", c); - return -1; - } - } - return 0; -} - -static int -char_needs_escaping(int c) -{ - if ((c >= 0) && (c < 0x20 || c == 0x22 || c == 0x5c)) { - return 1; - } - - return 0; -} - -static int -utf8_seq_length(char byte) -{ - unsigned char u = (unsigned char) byte; - if (u < 0x80) return 1; - - if (0x80 <= u && u <= 0xBF) - { - // second, third or fourth byte of a multi-byte - // sequence, i.e. a "continuation byte" - return 0; - } - else if (u == 0xC0 || u == 0xC1) - { - // overlong encoding of an ASCII byte - return 0; - } - else if (0xC2 <= u && u <= 0xDF) - { - // 2-byte sequence - return 2; - } - else if (0xE0 <= u && u <= 0xEF) - { - // 3-byte sequence - return 3; - } - else if (0xF0 <= u && u <= 0xF4) - { - // 4-byte sequence - return 4; - } - else - { - // u >= 0xF5 - // Restricted (start of 4-, 5- or 6-byte sequence) or invalid UTF-8 - return 0; - } -} - -static int -is_legal_utf8(const unsigned char *bytes, int length) -{ - if (0 == bytes || 0 == length) return 0; - - unsigned char a; - const unsigned char* srcptr = bytes + length; - switch (length) - { - default: - return 0; - // Everything else falls through when true. - case 4: - if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; - case 3: - if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; - case 2: - a = (*--srcptr); - switch (*bytes) - { - case 0xE0: - if (a < 0xA0 || a > 0xBF) return 0; - break; - case 0xED: - if (a < 0x80 || a > 0x9F) return 0; - break; - case 0xF0: - if (a < 0x90 || a > 0xBF) return 0; - break; - case 0xF4: - if (a < 0x80 || a > 0x8F) return 0; - break; - default: - if (a < 0x80 || a > 0xBF) return 0; - } - case 1: - if (*bytes >= 0x80 && *bytes < 0xC2) return 0; - } - return *bytes <= 0xF4; -} - -static int -read_utf8(json_stream* json, int next_char) -{ - int count = utf8_seq_length((char)(next_char)); - if (!count) - { - json_error(json, "%s", "Bad character."); - return -1; - } - - char buffer[4]; - buffer[0] = (char)(next_char); - for (int i = 1; i < count; ++i) - { - buffer[i] = (char)(json->source.get(&json->source)); - } - - if (!is_legal_utf8((unsigned char*) buffer, count)) - { - json_error(json, "%s", "No legal UTF8 found"); - return -1; - } - - for (int i = 0; i < count; ++i) - { - if (pushchar(json, buffer[i]) != 0) - return -1; - } - return 0; -} - -static enum json_type -read_string(json_stream *json) -{ - if (init_string(json) != 0) - return JSON_ERROR; - while (1) { - int c = json->source.get(&json->source); - if (c == EOF) { - json_error(json, "%s", "unterminated string literal"); - return JSON_ERROR; - } else if (c == '"') { - if (pushchar(json, '\0') == 0) - return JSON_STRING; - else - return JSON_ERROR; - } else if (c == '\\') { - if (read_escaped(json) != 0) - return JSON_ERROR; - } else if ((unsigned) c >= 0x80) { - if (read_utf8(json, c) != 0) - return JSON_ERROR; - } else { - if (char_needs_escaping(c)) { - json_error(json, "%s", "unescaped control character in string"); - return JSON_ERROR; - } - - if (pushchar(json, c) != 0) - return JSON_ERROR; - } - } - return JSON_ERROR; -} - -static int -is_digit(int c) -{ - return c >= 48 /*0*/ && c <= 57 /*9*/; -} - -static int -read_digits(json_stream *json) -{ - unsigned nread = 0; - while (is_digit(json->source.peek(&json->source))) { - if (pushchar(json, json->source.get(&json->source)) != 0) - return -1; - - nread++; - } - - if (nread == 0) { - return -1; - } - - return 0; -} - -static enum json_type -read_number(json_stream *json, int c) -{ - if (pushchar(json, c) != 0) - return JSON_ERROR; - if (c == '-') { - c = json->source.get(&json->source); - if (is_digit(c)) { - return read_number(json, c); - } else { - json_error(json, "unexpected byte, '%c'", c); - } - } else if (strchr("123456789", c) != NULL) { - c = json->source.peek(&json->source); - if (is_digit(c)) { - if (read_digits(json) != 0) - return JSON_ERROR; - } - } - /* Up to decimal or exponent has been read. */ - c = json->source.peek(&json->source); - if (strchr(".eE", c) == NULL) { - if (pushchar(json, '\0') != 0) - return JSON_ERROR; - else - return JSON_NUMBER; - } - if (c == '.') { - json->source.get(&json->source); // consume . - if (pushchar(json, c) != 0) - return JSON_ERROR; - if (read_digits(json) != 0) - return JSON_ERROR; - } - /* Check for exponent. */ - c = json->source.peek(&json->source); - if (c == 'e' || c == 'E') { - json->source.get(&json->source); // consume e/E - if (pushchar(json, c) != 0) - return JSON_ERROR; - c = json->source.peek(&json->source); - if (c == '+' || c == '-') { - json->source.get(&json->source); // consume - if (pushchar(json, c) != 0) - return JSON_ERROR; - if (read_digits(json) != 0) - return JSON_ERROR; - } else if (is_digit(c)) { - if (read_digits(json) != 0) - return JSON_ERROR; - } else { - json_error(json, "unexpected byte in number, '%c'", c); - return JSON_ERROR; - } - } - if (pushchar(json, '\0') != 0) - return JSON_ERROR; - else - return JSON_NUMBER; -} - -static int -json_isspace(int c) -{ - switch (c) { - case 0x09: - case 0x0a: - case 0x0d: - case 0x20: - return 1; - } - - return 0; -} - -/* Returns the next non-whitespace character in the stream. */ -static int next(json_stream *json) -{ - int c; - while (json_isspace(c = json->source.get(&json->source))) - if (c == '\n') - json->lineno++; - return c; -} - -static enum json_type -read_value(json_stream *json, int c) -{ - json->ntokens++; - switch (c) { - case EOF: - json_error(json, "%s", "unexpected end of data"); - return JSON_ERROR; - case '{': - return push(json, JSON_OBJECT); - case '[': - return push(json, JSON_ARRAY); - case '"': - return read_string(json); - case 'n': - return is_match(json, "ull", JSON_NULL); - case 'f': - return is_match(json, "alse", JSON_FALSE); - case 't': - return is_match(json, "rue", JSON_TRUE); - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '-': - if (init_string(json) != 0) - return JSON_ERROR; - return read_number(json, c); - default: - json_error(json, "unexpected byte, '%c'", c); - return JSON_ERROR; - } -} - -enum json_type json_peek(json_stream *json) -{ - enum json_type next = json_next(json); - json->next = next; - return next; -} - -enum json_type json_next(json_stream *json) -{ - if (json->flags & JSON_FLAG_ERROR) - return JSON_ERROR; - if (json->next != 0) { - enum json_type next = json->next; - json->next = 0; - return next; - } - if (json->ntokens > 0 && json->stack_top == (size_t)-1) { - int c; - - do { - c = json->source.peek(&json->source); - if (json_isspace(c)) { - c = json->source.get(&json->source); - } - } while (json_isspace(c)); - - if (!(json->flags & JSON_FLAG_STREAMING) && c != EOF) { - return JSON_ERROR; - } - - return JSON_DONE; - } - int c = next(json); - if (json->stack_top == (size_t)-1) - return read_value(json, c); - if (json->stack[json->stack_top].type == JSON_ARRAY) { - if (json->stack[json->stack_top].count == 0) { - if (c == ']') { - return pop(json, c, JSON_ARRAY); - } - json->stack[json->stack_top].count++; - return read_value(json, c); - } else if (c == ',') { - json->stack[json->stack_top].count++; - return read_value(json, next(json)); - } else if (c == ']') { - return pop(json, c, JSON_ARRAY); - } else { - json_error(json, "unexpected byte, '%c'", c); - return JSON_ERROR; - } - } else if (json->stack[json->stack_top].type == JSON_OBJECT) { - if (json->stack[json->stack_top].count == 0) { - if (c == '}') { - return pop(json, c, JSON_OBJECT); - } - - /* No property value pairs yet. */ - enum json_type value = read_value(json, c); - if (value != JSON_STRING) { - json_error(json, "%s", "expected property name or '}'"); - return JSON_ERROR; - } else { - json->stack[json->stack_top].count++; - return value; - } - } else if ((json->stack[json->stack_top].count % 2) == 0) { - /* Expecting comma followed by property name. */ - if (c != ',' && c != '}') { - json_error(json, "%s", "expected ',' or '}'"); - return JSON_ERROR; - } else if (c == '}') { - return pop(json, c, JSON_OBJECT); - } else { - enum json_type value = read_value(json, next(json)); - if (value != JSON_STRING) { - json_error(json, "%s", "expected property name"); - return JSON_ERROR; - } else { - json->stack[json->stack_top].count++; - return value; - } - } - } else if ((json->stack[json->stack_top].count % 2) == 1) { - /* Expecting colon followed by value. */ - if (c != ':') { - json_error(json, "%s", "expected ':' after property name"); - return JSON_ERROR; - } else { - json->stack[json->stack_top].count++; - return read_value(json, next(json)); - } - } - } - json_error(json, "%s", "invalid parser state"); - return JSON_ERROR; -} - -void json_reset(json_stream *json) -{ - json->stack_top = (size_t)(-1); - json->ntokens = 0; - json->flags &= ~JSON_FLAG_ERROR; - json->errmsg[0] = '\0'; -} - -const char *json_get_string(json_stream *json, size_t *length) -{ - if (length != NULL) - *length = json->data.string_fill; - if (json->data.string == NULL) - return ""; - else - return json->data.string; -} - -double json_get_number(json_stream *json) -{ - char *p = json->data.string; - return p == NULL ? 0 : strtod(p, NULL); -} - -const char *json_get_error(json_stream *json) -{ - return json->flags & JSON_FLAG_ERROR ? json->errmsg : NULL; -} - -size_t json_get_lineno(json_stream *json) -{ - return json->lineno; -} - -size_t json_get_position(json_stream *json) -{ - return json->source.position; -} - -size_t json_get_depth(json_stream *json) -{ - return json->stack_top + 1; -} - -void json_open_buffer(json_stream *json, const void *buffer, size_t size) -{ - init(json); - json->source.get = buffer_get; - json->source.peek = buffer_peek; - json->source.source.buffer.buffer = buffer; - json->source.source.buffer.length = size; -} - -void json_open_string(json_stream *json, const char *string) -{ - json_open_buffer(json, string, strlen(string)); -} - -void json_open_stream(json_stream *json, FILE * stream) -{ - init(json); - json->source.get = stream_get; - json->source.peek = stream_peek; - json->source.source.stream.stream = stream; -} - -static int user_get(struct json_source *json) -{ - return json->source.user.get(json->source.user.ptr); -} - -static int user_peek(struct json_source *json) -{ - return json->source.user.peek(json->source.user.ptr); -} - -void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user) -{ - init(json); - json->source.get = user_get; - json->source.peek = user_peek; - json->source.source.user.ptr = user; - json->source.source.user.get = get; - json->source.source.user.peek = peek; -} - -void json_set_allocator(json_stream *json, json_allocator *a) -{ - json->alloc = *a; -} - -void json_set_streaming(json_stream *json, bool streaming) -{ - if (streaming) - json->flags |= JSON_FLAG_STREAMING; - else - json->flags &= ~JSON_FLAG_STREAMING; -} - -void json_close(json_stream *json) -{ - json->alloc.free(json->stack); - json->alloc.free(json->data.string); -} +#define _POSIX_C_SOURCE 200112L +#include <stdio.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> +#include <errno.h> +#include "pdjson.h" + +#define JSON_FLAG_ERROR (1u << 0) +#define JSON_FLAG_STREAMING (1u << 1) + +#define json_error(json, format, ...) \ + if (!(json->flags & JSON_FLAG_ERROR)) { \ + json->flags |= JSON_FLAG_ERROR; \ + snprintf(json->errmsg, sizeof(json->errmsg), \ + "error: %lu: " format, \ + (unsigned long) json->lineno, \ + __VA_ARGS__); \ + } \ + +#define STACK_INC 4 + +#if defined(_MSC_VER) || defined(__MINGW32__) +#define strerror_r(err, buf, len) strerror_s(buf, len, err) +#endif + +const char *json_typename[] = { + [JSON_ERROR] = "ERROR", + [JSON_DONE] = "DONE", + [JSON_OBJECT] = "OBJECT", + [JSON_OBJECT_END] = "OBJECT_END", + [JSON_ARRAY] = "ARRAY", + [JSON_ARRAY_END] = "ARRAY_END", + [JSON_STRING] = "STRING", + [JSON_NUMBER] = "NUMBER", + [JSON_TRUE] = "TRUE", + [JSON_FALSE] = "FALSE", + [JSON_NULL] = "NULL", +}; + +struct json_stack { + enum json_type type; + long count; +}; + +static void json_error_s(json_stream *json, int err) +{ + char errbuf[1024] = {0}; + strerror_r(err, errbuf, sizeof(errbuf)); + json_error(json, "%s", errbuf); +} + +static enum json_type +push(json_stream *json, enum json_type type) +{ + json->stack_top++; + + if (json->stack_top >= json->stack_size) { + struct json_stack *stack; + stack = json->alloc.realloc(json->stack, + (json->stack_size + STACK_INC) * sizeof(*json->stack)); + if (stack == NULL) { + json_error_s(json, errno); + return JSON_ERROR; + } + + json->stack_size += STACK_INC; + json->stack = stack; + } + + json->stack[json->stack_top].type = type; + json->stack[json->stack_top].count = 0; + + return type; +} + +static enum json_type +pop(json_stream *json, int c, enum json_type expected) +{ + if (json->stack == NULL || json->stack[json->stack_top].type != expected) { + json_error(json, "unexpected byte, '%c'", c); + return JSON_ERROR; + } + json->stack_top--; + return expected == JSON_ARRAY ? JSON_ARRAY_END : JSON_OBJECT_END; +} + +static int buffer_peek(struct json_source *source) +{ + if (source->position < source->source.buffer.length) + return source->source.buffer.buffer[source->position]; + else + return EOF; +} + +static int buffer_get(struct json_source *source) +{ + int c = source->peek(source); + source->position++; + return c; +} + +static int stream_get(struct json_source *source) +{ + source->position++; + return fgetc(source->source.stream.stream); +} + +static int stream_peek(struct json_source *source) +{ + int c = fgetc(source->source.stream.stream); + ungetc(c, source->source.stream.stream); + return c; +} + +static void init(json_stream *json) +{ + json->lineno = 1; + json->flags = JSON_FLAG_STREAMING; + json->errmsg[0] = '\0'; + json->ntokens = 0; + json->next = 0; + + json->stack = NULL; + json->stack_top = (size_t)(-1); + json->stack_size = 0; + + json->data.string = NULL; + json->data.string_size = 0; + json->data.string_fill = 0; + json->source.position = 0; + + json->alloc.malloc = malloc; + json->alloc.realloc = realloc; + json->alloc.free = free; +} + +static enum json_type +is_match(json_stream *json, const char *pattern, enum json_type type) +{ + for (const char *p = pattern; *p; p++) + if (*p != json->source.get(&json->source)) + return JSON_ERROR; + return type; +} + +static int pushchar(json_stream *json, int c) +{ + if (json->data.string_fill == json->data.string_size) { + size_t size = json->data.string_size * 2; + char *buffer = json->alloc.realloc(json->data.string, size); + if (buffer == NULL) { + json_error_s(json, errno); + return -1; + } else { + json->data.string_size = size; + json->data.string = buffer; + } + } + json->data.string[json->data.string_fill++] = (char)(c); + return 0; +} + +static int init_string(json_stream *json) +{ + json->data.string_fill = 0; + if (json->data.string == NULL) { + json->data.string_size = 1024; + json->data.string = json->alloc.malloc(json->data.string_size); + if (json->data.string == NULL) { + json_error_s(json, errno); + return -1; + } + } + json->data.string[0] = '\0'; + return 0; +} + +static int encode_utf8(json_stream *json, unsigned long c) +{ + if (c < 0x80UL) { + return pushchar(json, c); + } else if (c < 0x0800UL) { + return !((pushchar(json, (c >> 6 & 0x1F) | 0xC0) == 0) && + (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); + } else if (c < 0x010000UL) { + if (c >= 0xd800 && c <= 0xdfff) { + json_error(json, "invalid codepoint %06lx", c); + return -1; + } + return !((pushchar(json, (c >> 12 & 0x0F) | 0xE0) == 0) && + (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && + (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); + } else if (c < 0x110000UL) { + return !((pushchar(json, (c >> 18 & 0x07) | 0xF0) == 0) && + (pushchar(json, (c >> 12 & 0x3F) | 0x80) == 0) && + (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && + (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); + } else { + json_error(json, "can't encode UTF-8 for %06lx", c); + return -1; + } +} + +static int hexchar(int c) +{ + switch (c) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + case 'a': + case 'A': return 10; + case 'b': + case 'B': return 11; + case 'c': + case 'C': return 12; + case 'd': + case 'D': return 13; + case 'e': + case 'E': return 14; + case 'f': + case 'F': return 15; + default: + return -1; + } +} + +static long +read_unicode_cp(json_stream *json) +{ + long cp = 0; + int shift = 12; + + for (size_t i = 0; i < 4; i++) { + int c = json->source.get(&json->source); + int hc; + + if (c == EOF) { + json_error(json, "%s", "unterminated string literal in unicode"); + return -1; + } else if ((hc = hexchar(c)) == -1) { + json_error(json, "bad escape unicode byte, '%c'", c); + return -1; + } + + cp += hc * (1 << shift); + shift -= 4; + } + + + return cp; +} + +static int read_unicode(json_stream *json) +{ + long cp, h, l; + + if ((cp = read_unicode_cp(json)) == -1) { + return -1; + } + + if (cp >= 0xd800 && cp <= 0xdbff) { + /* This is the high portion of a surrogate pair; we need to read the + * lower portion to get the codepoint + */ + h = cp; + + int c = json->source.get(&json->source); + if (c == EOF) { + json_error(json, "%s", "unterminated string literal in unicode"); + return -1; + } else if (c != '\\') { + json_error(json, "invalid continuation for surrogate pair: '%c', " + "expected '\\'", c); + return -1; + } + + c = json->source.get(&json->source); + if (c == EOF) { + json_error(json, "%s", "unterminated string literal in unicode"); + return -1; + } else if (c != 'u') { + json_error(json, "invalid continuation for surrogate pair: '%c', " + "expected 'u'", c); + return -1; + } + + if ((l = read_unicode_cp(json)) == -1) { + return -1; + } + + if (l < 0xdc00 || l > 0xdfff) { + json_error(json, "invalid surrogate pair continuation \\u%04lx out " + "of range (dc00-dfff)", l); + return -1; + } + + cp = ((h - 0xd800) * 0x400) + ((l - 0xdc00) + 0x10000); + } else if (cp >= 0xdc00 && cp <= 0xdfff) { + json_error(json, "dangling surrogate \\u%04lx", cp); + return -1; + } + + return encode_utf8(json, cp); +} + +int read_escaped(json_stream *json) +{ + int c = json->source.get(&json->source); + if (c == EOF) { + json_error(json, "%s", "unterminated string literal in escape"); + return -1; + } else if (c == 'u') { + if (read_unicode(json) != 0) + return -1; + } else { + switch (c) { + case '\\': + case 'b': + case 'f': + case 'n': + case 'r': + case 't': + case '/': + case '"': + { + const char *codes = "\\bfnrt/\""; + char *p = strchr(codes, c); + if (pushchar(json, "\\\b\f\n\r\t/\""[p - codes]) != 0) + return -1; + } + break; + default: + json_error(json, "bad escaped byte, '%c'", c); + return -1; + } + } + return 0; +} + +static int +char_needs_escaping(int c) +{ + if ((c >= 0) && (c < 0x20 || c == 0x22 || c == 0x5c)) { + return 1; + } + + return 0; +} + +static int +utf8_seq_length(char byte) +{ + unsigned char u = (unsigned char) byte; + if (u < 0x80) return 1; + + if (0x80 <= u && u <= 0xBF) + { + // second, third or fourth byte of a multi-byte + // sequence, i.e. a "continuation byte" + return 0; + } + else if (u == 0xC0 || u == 0xC1) + { + // overlong encoding of an ASCII byte + return 0; + } + else if (0xC2 <= u && u <= 0xDF) + { + // 2-byte sequence + return 2; + } + else if (0xE0 <= u && u <= 0xEF) + { + // 3-byte sequence + return 3; + } + else if (0xF0 <= u && u <= 0xF4) + { + // 4-byte sequence + return 4; + } + else + { + // u >= 0xF5 + // Restricted (start of 4-, 5- or 6-byte sequence) or invalid UTF-8 + return 0; + } +} + +static int +is_legal_utf8(const unsigned char *bytes, int length) +{ + if (0 == bytes || 0 == length) return 0; + + unsigned char a; + const unsigned char* srcptr = bytes + length; + switch (length) + { + default: + return 0; + // Everything else falls through when true. + case 4: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 3: + if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 2: + a = (*--srcptr); + switch (*bytes) + { + case 0xE0: + if (a < 0xA0 || a > 0xBF) return 0; + break; + case 0xED: + if (a < 0x80 || a > 0x9F) return 0; + break; + case 0xF0: + if (a < 0x90 || a > 0xBF) return 0; + break; + case 0xF4: + if (a < 0x80 || a > 0x8F) return 0; + break; + default: + if (a < 0x80 || a > 0xBF) return 0; + } + case 1: + if (*bytes >= 0x80 && *bytes < 0xC2) return 0; + } + return *bytes <= 0xF4; +} + +static int +read_utf8(json_stream* json, int next_char) +{ + int count = utf8_seq_length((char)(next_char)); + if (!count) + { + json_error(json, "%s", "Bad character."); + return -1; + } + + char buffer[4]; + buffer[0] = (char)(next_char); + for (int i = 1; i < count; ++i) + { + buffer[i] = (char)(json->source.get(&json->source)); + } + + if (!is_legal_utf8((unsigned char*) buffer, count)) + { + json_error(json, "%s", "No legal UTF8 found"); + return -1; + } + + for (int i = 0; i < count; ++i) + { + if (pushchar(json, buffer[i]) != 0) + return -1; + } + return 0; +} + +static enum json_type +read_string(json_stream *json) +{ + if (init_string(json) != 0) + return JSON_ERROR; + while (1) { + int c = json->source.get(&json->source); + if (c == EOF) { + json_error(json, "%s", "unterminated string literal"); + return JSON_ERROR; + } else if (c == '"') { + if (pushchar(json, '\0') == 0) + return JSON_STRING; + else + return JSON_ERROR; + } else if (c == '\\') { + if (read_escaped(json) != 0) + return JSON_ERROR; + } else if ((unsigned) c >= 0x80) { + if (read_utf8(json, c) != 0) + return JSON_ERROR; + } else { + if (char_needs_escaping(c)) { + json_error(json, "%s", "unescaped control character in string"); + return JSON_ERROR; + } + + if (pushchar(json, c) != 0) + return JSON_ERROR; + } + } + return JSON_ERROR; +} + +static int +is_digit(int c) +{ + return c >= 48 /*0*/ && c <= 57 /*9*/; +} + +static int +read_digits(json_stream *json) +{ + unsigned nread = 0; + while (is_digit(json->source.peek(&json->source))) { + if (pushchar(json, json->source.get(&json->source)) != 0) + return -1; + + nread++; + } + + if (nread == 0) { + return -1; + } + + return 0; +} + +static enum json_type +read_number(json_stream *json, int c) +{ + if (pushchar(json, c) != 0) + return JSON_ERROR; + if (c == '-') { + c = json->source.get(&json->source); + if (is_digit(c)) { + return read_number(json, c); + } else { + json_error(json, "unexpected byte, '%c'", c); + } + } else if (strchr("123456789", c) != NULL) { + c = json->source.peek(&json->source); + if (is_digit(c)) { + if (read_digits(json) != 0) + return JSON_ERROR; + } + } + /* Up to decimal or exponent has been read. */ + c = json->source.peek(&json->source); + if (strchr(".eE", c) == NULL) { + if (pushchar(json, '\0') != 0) + return JSON_ERROR; + else + return JSON_NUMBER; + } + if (c == '.') { + json->source.get(&json->source); // consume . + if (pushchar(json, c) != 0) + return JSON_ERROR; + if (read_digits(json) != 0) + return JSON_ERROR; + } + /* Check for exponent. */ + c = json->source.peek(&json->source); + if (c == 'e' || c == 'E') { + json->source.get(&json->source); // consume e/E + if (pushchar(json, c) != 0) + return JSON_ERROR; + c = json->source.peek(&json->source); + if (c == '+' || c == '-') { + json->source.get(&json->source); // consume + if (pushchar(json, c) != 0) + return JSON_ERROR; + if (read_digits(json) != 0) + return JSON_ERROR; + } else if (is_digit(c)) { + if (read_digits(json) != 0) + return JSON_ERROR; + } else { + json_error(json, "unexpected byte in number, '%c'", c); + return JSON_ERROR; + } + } + if (pushchar(json, '\0') != 0) + return JSON_ERROR; + else + return JSON_NUMBER; +} + +static int +json_isspace(int c) +{ + switch (c) { + case 0x09: + case 0x0a: + case 0x0d: + case 0x20: + return 1; + } + + return 0; +} + +/* Returns the next non-whitespace character in the stream. */ +static int next(json_stream *json) +{ + int c; + while (json_isspace(c = json->source.get(&json->source))) + if (c == '\n') + json->lineno++; + return c; +} + +static enum json_type +read_value(json_stream *json, int c) +{ + json->ntokens++; + switch (c) { + case EOF: + json_error(json, "%s", "unexpected end of data"); + return JSON_ERROR; + case '{': + return push(json, JSON_OBJECT); + case '[': + return push(json, JSON_ARRAY); + case '"': + return read_string(json); + case 'n': + return is_match(json, "ull", JSON_NULL); + case 'f': + return is_match(json, "alse", JSON_FALSE); + case 't': + return is_match(json, "rue", JSON_TRUE); + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + if (init_string(json) != 0) + return JSON_ERROR; + return read_number(json, c); + default: + json_error(json, "unexpected byte, '%c'", c); + return JSON_ERROR; + } +} + +enum json_type json_peek(json_stream *json) +{ + enum json_type next = json_next(json); + json->next = next; + return next; +} + +enum json_type json_next(json_stream *json) +{ + if (json->flags & JSON_FLAG_ERROR) + return JSON_ERROR; + if (json->next != 0) { + enum json_type next = json->next; + json->next = 0; + return next; + } + if (json->ntokens > 0 && json->stack_top == (size_t)-1) { + int c; + + do { + c = json->source.peek(&json->source); + if (json_isspace(c)) { + c = json->source.get(&json->source); + } + } while (json_isspace(c)); + + if (!(json->flags & JSON_FLAG_STREAMING) && c != EOF) { + return JSON_ERROR; + } + + return JSON_DONE; + } + int c = next(json); + if (json->stack_top == (size_t)-1) + return read_value(json, c); + if (json->stack[json->stack_top].type == JSON_ARRAY) { + if (json->stack[json->stack_top].count == 0) { + if (c == ']') { + return pop(json, c, JSON_ARRAY); + } + json->stack[json->stack_top].count++; + return read_value(json, c); + } else if (c == ',') { + json->stack[json->stack_top].count++; + return read_value(json, next(json)); + } else if (c == ']') { + return pop(json, c, JSON_ARRAY); + } else { + json_error(json, "unexpected byte, '%c'", c); + return JSON_ERROR; + } + } else if (json->stack[json->stack_top].type == JSON_OBJECT) { + if (json->stack[json->stack_top].count == 0) { + if (c == '}') { + return pop(json, c, JSON_OBJECT); + } + + /* No property value pairs yet. */ + enum json_type value = read_value(json, c); + if (value != JSON_STRING) { + json_error(json, "%s", "expected property name or '}'"); + return JSON_ERROR; + } else { + json->stack[json->stack_top].count++; + return value; + } + } else if ((json->stack[json->stack_top].count % 2) == 0) { + /* Expecting comma followed by property name. */ + if (c != ',' && c != '}') { + json_error(json, "%s", "expected ',' or '}'"); + return JSON_ERROR; + } else if (c == '}') { + return pop(json, c, JSON_OBJECT); + } else { + enum json_type value = read_value(json, next(json)); + if (value != JSON_STRING) { + json_error(json, "%s", "expected property name"); + return JSON_ERROR; + } else { + json->stack[json->stack_top].count++; + return value; + } + } + } else if ((json->stack[json->stack_top].count % 2) == 1) { + /* Expecting colon followed by value. */ + if (c != ':') { + json_error(json, "%s", "expected ':' after property name"); + return JSON_ERROR; + } else { + json->stack[json->stack_top].count++; + return read_value(json, next(json)); + } + } + } + json_error(json, "%s", "invalid parser state"); + return JSON_ERROR; +} + +void json_reset(json_stream *json) +{ + json->stack_top = (size_t)(-1); + json->ntokens = 0; + json->flags &= ~JSON_FLAG_ERROR; + json->errmsg[0] = '\0'; +} + +const char *json_get_string(json_stream *json, size_t *length) +{ + if (length != NULL) + *length = json->data.string_fill; + if (json->data.string == NULL) + return ""; + else + return json->data.string; +} + +double json_get_number(json_stream *json) +{ + char *p = json->data.string; + return p == NULL ? 0 : strtod(p, NULL); +} + +const char *json_get_error(json_stream *json) +{ + return json->flags & JSON_FLAG_ERROR ? json->errmsg : NULL; +} + +size_t json_get_lineno(json_stream *json) +{ + return json->lineno; +} + +size_t json_get_position(json_stream *json) +{ + return json->source.position; +} + +size_t json_get_depth(json_stream *json) +{ + return json->stack_top + 1; +} + +void json_open_buffer(json_stream *json, const void *buffer, size_t size) +{ + init(json); + json->source.get = buffer_get; + json->source.peek = buffer_peek; + json->source.source.buffer.buffer = buffer; + json->source.source.buffer.length = size; +} + +void json_open_string(json_stream *json, const char *string) +{ + json_open_buffer(json, string, strlen(string)); +} + +void json_open_stream(json_stream *json, FILE * stream) +{ + init(json); + json->source.get = stream_get; + json->source.peek = stream_peek; + json->source.source.stream.stream = stream; +} + +static int user_get(struct json_source *json) +{ + return json->source.user.get(json->source.user.ptr); +} + +static int user_peek(struct json_source *json) +{ + return json->source.user.peek(json->source.user.ptr); +} + +void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user) +{ + init(json); + json->source.get = user_get; + json->source.peek = user_peek; + json->source.source.user.ptr = user; + json->source.source.user.get = get; + json->source.source.user.peek = peek; +} + +void json_set_allocator(json_stream *json, json_allocator *a) +{ + json->alloc = *a; +} + +void json_set_streaming(json_stream *json, bool streaming) +{ + if (streaming) + json->flags |= JSON_FLAG_STREAMING; + else + json->flags &= ~JSON_FLAG_STREAMING; +} + +void json_close(json_stream *json) +{ + json->alloc.free(json->stack); + json->alloc.free(json->data.string); +} diff --git a/contrib/libs/poco/JSON/src/pdjson.h b/contrib/libs/poco/JSON/src/pdjson.h index fc633c137f..dd3d867f51 100644 --- a/contrib/libs/poco/JSON/src/pdjson.h +++ b/contrib/libs/poco/JSON/src/pdjson.h @@ -1,98 +1,98 @@ -#ifndef PDJSON_H -#define PDJSON_H - -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -#include <stdio.h> -#include <stdbool.h> - -enum json_type { - JSON_ERROR = 1, JSON_DONE, - JSON_OBJECT, JSON_OBJECT_END, JSON_ARRAY, JSON_ARRAY_END, - JSON_STRING, JSON_NUMBER, JSON_TRUE, JSON_FALSE, JSON_NULL -}; - -struct json_allocator { - void *(*malloc)(size_t); - void *(*realloc)(void *, size_t); - void (*free)(void *); -}; - -typedef int (*json_user_io) (void *user); - -typedef struct json_stream json_stream; -typedef struct json_allocator json_allocator; - -extern const char *json_typename[]; - -void json_open_buffer(json_stream *json, const void *buffer, size_t size); -void json_open_string(json_stream *json, const char *string); -void json_open_stream(json_stream *json, FILE *stream); -void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user); -void json_close(json_stream *json); - -void json_set_allocator(json_stream *json, json_allocator *a); -void json_set_streaming(json_stream *json, bool strict); - -enum json_type json_next(json_stream *json); -enum json_type json_peek(json_stream *json); -void json_reset(json_stream *json); -const char *json_get_string(json_stream *json, size_t *length); -double json_get_number(json_stream *json); - -size_t json_get_lineno(json_stream *json); -size_t json_get_position(json_stream *json); -size_t json_get_depth(json_stream *json); -const char *json_get_error(json_stream *json); - -/* internal */ - -struct json_source { - int (*get) (struct json_source *); - int (*peek) (struct json_source *); - size_t position; - union { - struct { - FILE *stream; - } stream; - struct { - const char *buffer; - size_t length; - } buffer; - struct { - void *ptr; - json_user_io get; - json_user_io peek; - } user; - } source; -}; - -struct json_stream { - size_t lineno; - - struct json_stack *stack; - size_t stack_top; - size_t stack_size; - enum json_type next; - unsigned flags; - - struct { - char *string; - size_t string_fill; - size_t string_size; - } data; - - size_t ntokens; - - struct json_source source; - struct json_allocator alloc; - char errmsg[128]; -}; - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus - -#endif +#ifndef PDJSON_H +#define PDJSON_H + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include <stdio.h> +#include <stdbool.h> + +enum json_type { + JSON_ERROR = 1, JSON_DONE, + JSON_OBJECT, JSON_OBJECT_END, JSON_ARRAY, JSON_ARRAY_END, + JSON_STRING, JSON_NUMBER, JSON_TRUE, JSON_FALSE, JSON_NULL +}; + +struct json_allocator { + void *(*malloc)(size_t); + void *(*realloc)(void *, size_t); + void (*free)(void *); +}; + +typedef int (*json_user_io) (void *user); + +typedef struct json_stream json_stream; +typedef struct json_allocator json_allocator; + +extern const char *json_typename[]; + +void json_open_buffer(json_stream *json, const void *buffer, size_t size); +void json_open_string(json_stream *json, const char *string); +void json_open_stream(json_stream *json, FILE *stream); +void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user); +void json_close(json_stream *json); + +void json_set_allocator(json_stream *json, json_allocator *a); +void json_set_streaming(json_stream *json, bool strict); + +enum json_type json_next(json_stream *json); +enum json_type json_peek(json_stream *json); +void json_reset(json_stream *json); +const char *json_get_string(json_stream *json, size_t *length); +double json_get_number(json_stream *json); + +size_t json_get_lineno(json_stream *json); +size_t json_get_position(json_stream *json); +size_t json_get_depth(json_stream *json); +const char *json_get_error(json_stream *json); + +/* internal */ + +struct json_source { + int (*get) (struct json_source *); + int (*peek) (struct json_source *); + size_t position; + union { + struct { + FILE *stream; + } stream; + struct { + const char *buffer; + size_t length; + } buffer; + struct { + void *ptr; + json_user_io get; + json_user_io peek; + } user; + } source; +}; + +struct json_stream { + size_t lineno; + + struct json_stack *stack; + size_t stack_top; + size_t stack_size; + enum json_type next; + unsigned flags; + + struct { + char *string; + size_t string_fill; + size_t string_size; + } data; + + size_t ntokens; + + struct json_source source; + struct json_allocator alloc; + char errmsg[128]; +}; + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif diff --git a/contrib/libs/poco/JSON/ya.make b/contrib/libs/poco/JSON/ya.make index d4439cca58..11e0ff72b1 100644 --- a/contrib/libs/poco/JSON/ya.make +++ b/contrib/libs/poco/JSON/ya.make @@ -1,7 +1,7 @@ -# Generated by devtools/yamaker. - -LIBRARY() - +# Generated by devtools/yamaker. + +LIBRARY() + OWNER( orivej g:cpp-contrib @@ -14,34 +14,34 @@ LICENSE( LICENSE_TEXTS(.yandex_meta/licenses.list.txt) -PEERDIR( - contrib/libs/poco/Foundation -) - -ADDINCL( - GLOBAL contrib/libs/poco/JSON/include - contrib/libs/poco/Foundation/include - contrib/libs/poco/JSON/src -) - -NO_COMPILER_WARNINGS() - -NO_UTIL() - -SRCS( - src/Array.cpp - src/Handler.cpp - src/JSONException.cpp - src/Object.cpp - src/ParseHandler.cpp - src/Parser.cpp - src/ParserImpl.cpp - src/PrintHandler.cpp - src/Query.cpp - src/Stringifier.cpp - src/Template.cpp - src/TemplateCache.cpp - src/pdjson.c -) - -END() +PEERDIR( + contrib/libs/poco/Foundation +) + +ADDINCL( + GLOBAL contrib/libs/poco/JSON/include + contrib/libs/poco/Foundation/include + contrib/libs/poco/JSON/src +) + +NO_COMPILER_WARNINGS() + +NO_UTIL() + +SRCS( + src/Array.cpp + src/Handler.cpp + src/JSONException.cpp + src/Object.cpp + src/ParseHandler.cpp + src/Parser.cpp + src/ParserImpl.cpp + src/PrintHandler.cpp + src/Query.cpp + src/Stringifier.cpp + src/Template.cpp + src/TemplateCache.cpp + src/pdjson.c +) + +END() |